summaryrefslogtreecommitdiff
path: root/board/st/u8500/mmc_utils.c
blob: 8e868bbb50e68e79cbb02f8d5b060af7fd001acf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
/*
 * (C) Copyright 2009
 * ST-Ericsson, <www.stericsson.com>
 *
 * See file CREDITS for list of people who contributed to this
 * project.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of
 * the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 * MA 02111-1307 USA
 */
#include <linux/ctype.h>

#include <common.h>
#include <command.h>
#include "gpio.h"
#include "mmc.h"                // MMC api
#include "mmc_utils.h"          // to access MMC
#include "mmc_p.h"              // t_mmc_register definition

u32       MMCBuffer[1024] ;
static int              IS_SD_CARD;

/* --- exported from other modules ---------------------------------------- */
static  u8               selected_card = 0;
extern  t_mmc_error           mmc_cmderror_2            (void);
extern  t_mmc_error           mmc_cmdresp2error_2       (void);
extern  t_mmc_error           mmc_cmdresp3error_2       (void);
extern  t_mmc_error           mmc_cmdresp145error_2     (u8 cmd);
extern  t_mmc_error           mmc_cmdreadresp           (u32 * tempbuff);
extern  t_mmc_error           mmc_waitcmdreadresp       (void);
extern  t_mmc_error           mmc_cmdwriteresp          (u8 cardno, u32 * tempbuff, u16 total_num_of_bytes);
extern  t_mmc_error           mmc_waitcmdwriteresp      (u8 cardno, u32 * tempbuff, u16 total_num_of_bytes);

extern  t_mmc_register  *t_mmc0;
extern  u32         t_mmc_rel_addr;

t_mmc_boot_record             mmc_boot_record;

void mmc_copyByteH (u8 * sourceAddr, u8 * destAddress, int size)
{
    int                           i;
    for (i = 0; i < size; i++)
    {
        *(destAddress + i) = *(sourceAddr + i);
    }
}

void mmc_shift_memH (int num_of_words, u32 * start_address, u32 * dest_address, u32 shift)
{
    u32                     *address;
    int                           word = 0;
    u32                      high;
    int                           i, word_offset, bit_offset;

    word_offset = (int) (shift / 32);
    bit_offset  = (int) (shift % 32);
    for (i = 0; i < num_of_words; i++)
    {
        *(dest_address + i) = 0;
    }
    for (i = word_offset; i < num_of_words; i++)
    {
        *(dest_address + i - word_offset) = *(start_address + i);
    }
    address = dest_address;
    for (word = 0; word < num_of_words - 1; word++)
    {
        *address = (*address) >> bit_offset;
        address++;
        high = (*address << (32 - bit_offset));
        *(address - 1) |= high;
    }
    *address = (*address) >> bit_offset;
}

u8 convert_from_bytes_to_power_of_two (u16 no_of_bytes)
{
    u8                       count = 0;
    while (no_of_bytes != 1)
    {
        no_of_bytes >>= 1;
        count++;
    }
    return count;
}

t_mmc_error mmc_enable ()
{
    t_mmc_error                   error = MMC_OK;
    t_mmc_command_control         commcontrol;
    t_bool                        validvoltage = FALSE;
    u32                      arg, response;
    int i;

    IS_SD_CARD = 0;

    selected_card       = 0;

    t_mmc0->mmc_Power = 0x1BF;
    t_mmc0->mmc_Clock = 0x41FF;

    commcontrol.IsRespExpected  = FALSE;
    commcontrol.IsLongResp      = FALSE;
    commcontrol.IsInterruptMode = FALSE;
    commcontrol.IsPending       = FALSE;
    commcontrol.cmdpath         = MMC_ENABLE;

    error   = mmc_sendcommand (MMC_GO_IDLE_STATE, 0x00000000, commcontrol);

    error   = mmc_cmderror_2 ();

    //// Added by Chris Sebastian for SD Card support:
    //// Send ACMD41.  If we do not get a response, it is not an SD card.
    ////               If we do get a response, loop until card is not busy.

    commcontrol.IsRespExpected  = TRUE;
    commcontrol.IsLongResp      = FALSE;
    commcontrol.IsInterruptMode = FALSE;
    commcontrol.IsPending       = FALSE;
    commcontrol.cmdpath         = MMC_ENABLE;

    for(i = 200; i; i--) {
        error = mmc_sendcommand (MMC_APP_CMD, 0x00000000, commcontrol);      // Let the card know that the next command is an app-cmd.
        error = mmc_cmdresp145error_2(MMC_APP_CMD);
        error = mmc_sendcommand (SD_SEND_OP_COND, 0x00060000, commcontrol);  // I got the 0x00060000 from Linux kernel source.
        error = mmc_cmdresp3error_2 ();
        t_mmc0->mmc_Clear = ClrStaticFlags; //clear all the static status flags.  CmdResp3Error_2 leaves some bits set.
        if (t_mmc0->mmc_Response0 & 0x80000000) {
            printf("SD card detected \n");
            IS_SD_CARD = 1;
            return MMC_OK; // SD CARD DETECTED.  Do not continue with MMC init logic.  Quick escape!
        }
    }

    commcontrol.IsRespExpected  = FALSE;
    commcontrol.IsLongResp      = FALSE;
    commcontrol.IsInterruptMode = FALSE;
    commcontrol.IsPending       = FALSE;
    commcontrol.cmdpath         = MMC_ENABLE;

    error   = mmc_sendcommand (MMC_GO_IDLE_STATE, 0x00000000, commcontrol);
    error   = mmc_cmderror_2 ();

    arg     = 0x00060000;  // High Voltage MMC, byte mode.  Was 0x00FFC000, but that writes to reserved bits...
    while (!validvoltage)
    {
        // send CMD1 (SEND_OP_COND)
        commcontrol.IsRespExpected = TRUE;
        error   = mmc_sendcommand (MMC_SEND_OP_COND, arg, commcontrol);

        error   = mmc_cmdresp3error_2 ();

        if (error != MMC_OK)
        {
            goto end;
        }
        mmc_getresponse (MMC_SHORT_RESP, &response);

        arg = response;
        validvoltage = (t_bool) (((response >> 31) == 1) ? 1 : 0);

    }
end:
    return error;
}

t_mmc_error  mmc_disable ()
{
    t_mmc_error                   error = MMC_OK;
    t_mmc_power_state             powerstate = MMC_POWER_OFF;

    error   = mmc_setpowerstate (powerstate);
    return error;
}

t_mmc_error                   mmc_initCard ()
{
    t_mmc_error                   error = MMC_OK;
    t_mmc_command_control         commcontrol;
    t_mmc_bus_configuration       busconfig;
    t_mmc_clock_control           clockcontrol;

    // send CMD2 (ALL_SEND_CID)
    commcontrol.IsRespExpected  = TRUE;
    commcontrol.IsLongResp      = TRUE;
    commcontrol.IsInterruptMode = FALSE;
    commcontrol.IsPending       = FALSE;
    commcontrol.cmdpath         = MMC_ENABLE;

    error = mmc_sendcommand (MMC_ALL_SEND_CID, 0x00000000, commcontrol);
    error = mmc_cmdresp2error_2 ();
    // error is MMC_CMD_CRC_FAIL on COB board ?!
    // if( error != MMC_OK)
    // goto end;

    // send CMD3 (SET_RELATIVE_ADDR)

    commcontrol.IsLongResp      = FALSE;
    error               = mmc_sendcommand       (MMC_SET_REL_ADDR, t_mmc_rel_addr, commcontrol);
    error               = mmc_cmdresp145error_2 (MMC_SET_REL_ADDR);
    if(IS_SD_CARD) {
        t_mmc_rel_addr = t_mmc0->mmc_Response0 & 0xFFFF0000;
    }

    if (error != MMC_OK)
    {
        goto end;
    }
    busconfig.mode      = MMC_PUSH_PULL;
    busconfig.rodctrl   = MMC_DISABLE;
    error               = mmc_configbus (busconfig);
    clockcontrol.pwrsave= MMC_DISABLE;
    clockcontrol.bypass = MMC_DISABLE;
    clockcontrol.widebus= MMC_DISABLE;
    error = mmc_setclockfrequency(0x00);	/* 26 MHz */
    if (error != MMC_OK)
    {
        goto end;
    }
    error = mmc_configclockcontrol (clockcontrol);
    if (error != MMC_OK)
    {
        goto end;
    }
end:
    return error;
}

t_mmc_error mmc_readblock (u8 cardno, u32 addr, u32 * readbuff, u16 blocksize, t_mmc_transfer_mode mmc_transfer_mode)
{
    t_mmc_error                   error = MMC_OK;
    u8                       power;
    t_mmc_command_control         commcontrol;
    u32                      response;

    commcontrol.IsRespExpected  = TRUE              ;
    commcontrol.IsLongResp      = FALSE             ;
    commcontrol.IsInterruptMode = FALSE             ;
    commcontrol.IsPending       = FALSE             ;
    commcontrol.cmdpath         = MMC_ENABLE        ;
    error                       = mmc_setdatapath   (MMC_DISABLE);
    error                       = mmc_handledma     (MMC_DISABLE);
    if (error != MMC_OK)
    {
        goto end;
    }
    // send command for selecting the card
    if (cardno != selected_card)
    {
        error   = mmc_sendcommand       (MMC_SEL_DESEL_CARD, t_mmc_rel_addr, commcontrol);
        error   = mmc_cmdresp145error_2 (MMC_SEL_DESEL_CARD);
        if (error != MMC_OK)
        {
            goto end;
        }
        else
        {
            selected_card = cardno;
        }
    }
    error       = mmc_getresponse (MMC_SHORT_RESP, &response);
    if (response & 0x02000000)
    {
        return MMC_LOCK_UNLOCK_FAILED;
    }
    // set the block size,both on controller and card
    if ((blocksize > 0) && (blocksize <= 2048) && ((blocksize & (blocksize - 1)) == 0))
    {
        power = convert_from_bytes_to_power_of_two (blocksize);
        error = mmc_setdatablocklength  (power);
        error = mmc_sendcommand         (MMC_SET_BLOCKLEN, (u32) blocksize, commcontrol);
        error = mmc_cmdresp145error_2   (MMC_SET_BLOCKLEN);
        if (error != MMC_OK)
        {
            return error;
        }
    }
    else
    {
        error = MMC_INVALID_PARAMETER;
        goto end;
    }
    error = mmc_setdatalength           (blocksize  );
    error = mmc_setdatatimeout          (0xefffffff );
    error = mmc_settransferdirection    (MMC_READ   );
    error = mmc_settransfertype         (MMC_BLOCK  );
    error = mmc_setdatapath             (MMC_ENABLE);
    //t_mmc0->mmc_DataCtrl	|=             (ReadDir & ~StreamMode) | DataPathEnable;
    error = mmc_sendcommand             (MMC_READ_SINGLE_BLOCK, addr, commcontrol);
    error = mmc_cmdresp145error_2       (MMC_READ_SINGLE_BLOCK);
    if (error != MMC_OK)
    {
        goto end;
    }
    if (mmc_transfer_mode == MMCDMA)
    {
        error = mmc_waitcmdreadresp ();
    }
    else
    {
        error = mmc_cmdreadresp (readbuff);
    }
    if (error != MMC_OK)
    {
        goto end;
    }
end:
    return error;
}

t_mmc_error mmc_writeblock (u8 cardno, u32 addr, u32 * writebuff, u16 blocksize, t_mmc_transfer_mode mmc_transfer_mode)
{
    t_mmc_error                   error = MMC_OK;
    u8                       power;
    t_mmc_command_control         commcontrol;
    u32                      response;

    commcontrol.IsRespExpected  = TRUE;
    commcontrol.IsLongResp      = FALSE;
    commcontrol.IsInterruptMode = FALSE;
    commcontrol.IsPending       = FALSE;
    commcontrol.cmdpath         = MMC_ENABLE;

    error = mmc_setdatapath         (MMC_DISABLE);
    error = mmc_handledma           (MMC_DISABLE);
    error = mmc_settransferdirection(MMC_WRITE);
    error = mmc_settransfertype     (MMC_BLOCK);

    if (cardno != selected_card)
    {
        error = mmc_sendcommand (MMC_SEL_DESEL_CARD, t_mmc_rel_addr, commcontrol);
        error = mmc_cmdresp145error_2 (MMC_SEL_DESEL_CARD);
        if (error != MMC_OK)
        {
            goto end;
        }
        else
        {
            selected_card = cardno;
        }
    }

    mmc_getresponse (MMC_SHORT_RESP, &response);
    if (response & 0x02000000)
    {
        return MMC_LOCK_UNLOCK_FAILED;
    }
    // set the block size,both on controller and card
    if ((blocksize > 0) && (blocksize <= 2048) && (((blocksize & (blocksize - 1)) == 0)))
    {
        power = convert_from_bytes_to_power_of_two (blocksize);
        error = mmc_setdatablocklength (power);
        error = mmc_sendcommand (MMC_SET_BLOCKLEN, (u32) blocksize, commcontrol);
        error = mmc_cmdresp145error_2 (MMC_SET_BLOCKLEN);
        if (error != MMC_OK)
        {
            goto end;
        }
    }
    else
    {
        error = MMC_INVALID_PARAMETER;
        goto end;
    }

    error = mmc_setdatalength           (blocksize);
    error = mmc_setdatatimeout          (0xefffffff);
    error = mmc_settransferdirection    (MMC_WRITE);
    error = mmc_settransfertype         (MMC_BLOCK);
    error = mmc_setdatapath         (MMC_ENABLE);
    error = mmc_sendcommand         (MMC_WRITE_SINGLE_BLOCK, addr, commcontrol);
    error = mmc_cmdresp145error_2   (MMC_WRITE_SINGLE_BLOCK);
    if (error != MMC_OK)
    {
        goto end;
    }
    if (mmc_transfer_mode == MMCDMA)
    {
        error = mmc_waitcmdwriteresp (cardno, writebuff, blocksize);
    }
    else
    {
        error = mmc_cmdwriteresp (cardno, writebuff, blocksize);
    }
    if (error != MMC_OK)
    {
        goto end;
    }
end:
    return error;
}

t_mmc_error mmc_readcsd (u32 * CSD)
{
    t_mmc_error                   error = MMC_OK;
    t_mmc_command_control         commcontrol;
    u32                      buf[4];

    // send CMD9 (SEND CSD)
    commcontrol.IsRespExpected  = TRUE;
    commcontrol.IsLongResp      = TRUE;
    commcontrol.IsInterruptMode = FALSE;
    commcontrol.IsPending       = FALSE;
    commcontrol.cmdpath         = MMC_ENABLE;

    error = mmc_sendcommand     (MMC_SEND_CSD,  t_mmc_rel_addr, commcontrol);
    error = mmc_cmdresp2error_2 ();
    if (error != MMC_OK)
    {
        goto end;
    }
    error = mmc_getresponse (MMC_LONG_RESP, buf);
    CSD[0] = buf[3];
    CSD[1] = buf[2];
    CSD[2] = buf[1];
    CSD[3] = buf[0];
end:
    return error;
}

t_mmc_error mmc_select_n_switch(void)
{
    t_mmc_error                   error = MMC_OK;
    t_mmc_command_control         commcontrol;
    /* t_mmc_clock_control           clockcontrol; */
    u32                           response;
    u8                            cardno = 1;

    commcontrol.IsRespExpected  = TRUE;
    commcontrol.IsLongResp      = FALSE;
    commcontrol.IsInterruptMode = FALSE;
    commcontrol.IsPending       = FALSE;
    commcontrol.cmdpath         = MMC_ENABLE;

    // send command for selecting the card
    if (cardno != selected_card)
    {
        error = mmc_sendcommand(MMC_SEL_DESEL_CARD, t_mmc_rel_addr, commcontrol);
        error = mmc_cmdresp145error_2(MMC_SEL_DESEL_CARD);
        if (error != MMC_OK)
        {
            goto end;
        }
        else
        {
            selected_card = cardno;
        }
    }
    error = mmc_getresponse(MMC_SHORT_RESP, &response);
    if (response & 0x02000000)
    {
        error =  MMC_LOCK_UNLOCK_FAILED;
        goto end;
    }
    /* XXX: what is this, why is it commented out, why is it here at all? */
    /*
    error = mmc_sendcommand (MMC_APP_CMD, 0x00000000, commcontrol);
    error = mmc_cmdresp145error_2(MMC_APP_CMD);
    error = mmc_sendcommand (6, 0x2, commcontrol);
    error = mmc_cmdresp145error_2(6);
    if (error != MMC_OK)
    {
        goto end;
    }
    clockcontrol.pwrsave= MMC_DISABLE;
    clockcontrol.bypass = MMC_DISABLE;
    clockcontrol.widebus= MMC_ENABLE;
    error = mmc_configclockcontrol (clockcontrol);
    if (error != MMC_OK)
    {
        goto end;
    }
    */
end:
    return error;
}

t_mmc_error mmc_readcid (u32 * CID)
{
    t_mmc_error                   error = MMC_OK;
    t_mmc_command_control         commcontrol;
    u32                      buf[4];

    // send CMD9 (SEND CSD)
    commcontrol.IsRespExpected  = TRUE;
    commcontrol.IsLongResp      = TRUE;
    commcontrol.IsInterruptMode = FALSE;
    commcontrol.IsPending       = FALSE;
    commcontrol.cmdpath         = MMC_ENABLE;

    error = mmc_sendcommand     (MMC_SEND_CID, t_mmc_rel_addr, commcontrol);
    error = mmc_cmdresp2error_2 ();
    if (error != MMC_OK)
    {
        goto end;
    }
    error = mmc_getresponse (MMC_LONG_RESP, buf);
    CID[0] = buf[3];
    CID[1] = buf[2];
    CID[2] = buf[1];
    CID[3] = buf[0];
end:
    return error;
}

t_mmc_error mmc_read_file (char *filename, u32 address, u32 * FileSize)
{
    u8                      *mem_address = (u8 *) address;
    u8                       sector[512];
    u16                      BytesPerSector;
    u32                      BRStartSector;
    u32                      FATStartSector;
    u32                      DataStartSector;
    u32                      FileStartSector;
    u16                      SectorsPerFAT;
    u8                       SectorsPerCluster;
    u8                       k;
    u16                      MaxRDEntries;
    u16                      ReservedSectors;
    u32                      RDStartSector, j;
    char                          nomefile[12] = "           ";
    int                           filelength;
    u16                      FileStartCluster = 0;
    t_mmc_error                   response, response2;
    int                           i, goout, found, result = PASS;
    u32                      CSD[4];
    char                          mmcfilename[] = "           ";
    char                         *dotpos;

    /////////// Attention please:  /////////////////////
    //                                                //
    // if other Alternate function apart from MMCI    //
    // are selected, the MMCI I/F has some problems   //
    //                                                //
    ////////////////////////////////////////////////////

    gpio_altfuncenable(GPIO_ALT_SD_CARD0, "MMC");
    // Power-on the controller
    response = mmc_enable ();

    if (response != MMC_OK)
    {

        response = mmc_enable (); // This actually IS necessary because it takes time for newly-inserted cards initialize.  ~Chris S.
        if (response != MMC_OK)
        {
            printf ("Error in card power on\n");
            result = FAIL;
            goto end;
        }
    }
    // Initialise the cards on the bus, if any
    response = mmc_initCard ();

    if (response != MMC_OK)
    {
        printf ("Error in card initialization\n");
        result = FAIL;
        goto end;
    }
    // Get card info: CID, CSD, RCA registers
    response = mmc_readcsd (CSD);

    if (response != MMC_OK)
    {
        printf ("Error while fetching card info\n");
        result = FAIL;
        goto end;
    }

    // Select card and switch to 4-Bit, TODO HS if possible
    response = mmc_select_n_switch ();

    if (response != MMC_OK)
    {
        printf ("Error while select or switching to 4-bit/HS\n");
        goto end;
    }

    // Read the MBR
    response = mmc_readblock (1, 0, (u32 *) sector, 512, MMCPOLLING);

    if (response != MMC_OK)
    {
        printf ("Error while reading boot record\n");
        result = FAIL;
        goto end;
    }
    if (sector[446] == 0x00 || sector[446] == 0x80)
    {                           // found a MBR at the beginning of card
        BRStartSector = sector[454];
    }
    else
    {                           // BR at the beginning of card
        BRStartSector = 0x00;
    }
    // Read the BR
    response = mmc_readblock (1, (u32) (512 * BRStartSector), (u32 *) & mmc_boot_record, 512, MMCPOLLING);

    k = 0;
    while (response == MMC_DATA_CRC_FAIL && (k < 2))
    {
        response = mmc_readblock (1, (u32) (512 * BRStartSector), (u32 *) & mmc_boot_record, 512, MMCPOLLING);
        k++;
    }
    if (response != MMC_OK)
    {
        printf ("Error while reading boot record\n");
        result = FAIL;
        goto end;
    }
    mmc_copyByteH        (mmc_boot_record.BytesPerSector, (u8 *) & BytesPerSector, 2);
    mmc_copyByteH        (mmc_boot_record.ReservedSectors, (u8 *) & ReservedSectors, 2);
    FATStartSector      = BRStartSector + ReservedSectors;   // the field at offset 15 contains the number of reserved sectors at
    // the beginning of the media including the boot sector
    mmc_copyByteH        (mmc_boot_record.SectorsPerFat, (u8 *) & SectorsPerFAT, 2);
    SectorsPerCluster   = mmc_boot_record.SectorsPerCluster[0];
    mmc_copyByteH        (mmc_boot_record.NumOfRootEntries, (u8 *) & MaxRDEntries, 2);
    FATStartSector      += SectorsPerFAT;
    RDStartSector       = FATStartSector + SectorsPerFAT;
    DataStartSector     = RDStartSector + (u32) ((MaxRDEntries * 32) / 512);



    // convert filename into mmc compatible file name (upper case , <= 8+3 char, no dot, no extension)
    filelength = strlen (filename);
    dotpos = strchr (filename, '.');
    if (dotpos == NULL)
    {
        // no dot
        if (filelength <= 8)
        {
            for (j = 0; j < filelength; j++)
            {
                mmcfilename[j] = (char) toupper (filename[j]);
            }
        }
        else
        {
            for (j = 0; j < 6; j++)
            {
                mmcfilename[j] = (char) toupper (filename[j]);
            }
            mmcfilename[7] = '~';
            mmcfilename[8] = '1';
            filelength = 8;
        }
    }
    else
    {
        // dot
        if ((dotpos - filename) <= 8)
        {
            for (j = 0; j < (dotpos - filename); j++)
            {
                mmcfilename[j] = (char) toupper (filename[j]);
            }
            for (; j < 8; j++)
            {
                mmcfilename[j] = ' ';
            }
            // copy 3 char after .
            mmcfilename[j++] = (char) toupper (dotpos[1]);
            mmcfilename[j++] = (char) toupper (dotpos[2]);
            mmcfilename[j++] = (char) toupper (dotpos[3]);

        }
        else
        {
            for (j = 0; j < 6; j++)
            {
                mmcfilename[j] = (char) toupper (filename[j]);
            }
            mmcfilename[6] = '~';
            mmcfilename[7] = '1';
            // copy 3 char after .
            mmcfilename[8] = (char) toupper (dotpos[1]);
            mmcfilename[9] = (char) toupper (dotpos[2]);
            mmcfilename[10] = (char) toupper (dotpos[3]);
        }
        filelength = 11;
    }
    mmcfilename[11] = '\0';


    // search Root Directory for entry filename
    goout = 0;
    found = 0;
    for (j = 0; j < (DataStartSector - RDStartSector); j++)
    {
        if (goout == 1)
            break;
        response = mmc_readblock (1, (u32) ((RDStartSector + j) * 512), (u32 *) sector, 512, MMCPOLLING);
        if (response != MMC_OK)
        {
            printf ("Error while reading root directory\n");
            result = FAIL;
            goto end;
        }

        for (i = 0; i < 512; i += 32)
        {
            strncpy (nomefile, (char *) &sector[i], filelength);
            if (strcmp (nomefile, mmcfilename) == 0)
            {
                mmc_copyByteH (&sector[i + 26], (u8 *) & FileStartCluster, 2);
                mmc_copyByteH (&sector[i + 28], (u8 *) FileSize, 4);
                FileStartCluster -= 2;
                goout = 1;
                found = 1;
                break;
            }
            if (nomefile[0] == 0)
            {                   // end of Root Directory
                goout = 1;
                break;
            }
        }
    }

    // size of file                : *FileSize ( 32 bits quantum)
    // number of bytes per sector  : BytesPerSector
    // Beginning of file           : FileStartSector

    printf ("Bytes per sector    : %d \n", BytesPerSector    );
    printf ("Sectors per cluster : %d \n", SectorsPerCluster );
    if (found)
    {
        u32    remaining =  *FileSize     ;
        u32    count;
        u32    burstsize = BytesPerSector ;

        FileStartSector     = ( DataStartSector + (u32)(FileStartCluster * SectorsPerCluster))  ;
        printf                 ("Reading file %s from MMC ..., start sector = %d, address 0x%x \n",filename,FileStartSector,address);
        count               = SectorsPerCluster - (FileStartSector % SectorsPerCluster) ;
        FileStartSector     = FileStartSector * BytesPerSector; // the first burst might be different to align of clusters

        do
        {
            if ( remaining >= burstsize )
            {   // read straight burst

                k = 0;
                do
                {
                    response = mmc_readblock (1, (u32) FileStartSector ,  (u32 *) mem_address, burstsize , MMCPOLLING);
                    k++;

                }   while ((response==MMC_DATA_CRC_FAIL)&&(k<4));
                if ( k != 1) printf ("!");
                FileStartSector += burstsize;
                mem_address     += burstsize;
                remaining       -= burstsize;
            }
            else
            {   // read burst +1 and perform memcpy

                burstsize = ((remaining + (BytesPerSector-1))/BytesPerSector) * BytesPerSector ;
                k = 0;
                do
                {
                    response = mmc_readblock (1, (u32) FileStartSector ,  (u32 *) MMCBuffer , burstsize , MMCPOLLING);
                    k++;
                }   while ((response==MMC_DATA_CRC_FAIL)&&(k<4));
                if ( k != 1) printf ("!");
                memcpy ((char *) mem_address, (char *)MMCBuffer,remaining);
                remaining = 0;
            }
            if (response != MMC_OK)
            {
                printf ("Error while reading file %s\n", filename);
                result = FAIL;
                goto end;
            }
        }   while ( remaining );

    }
    else
    {
        printf ("Unable to find %s on Multi Media Card\n", filename);
        response = MMC_INVALID_PARAMETER;
        result = FAIL;
        goto end;
    }

end:

    return response;
}

/*
 * command line commands
 */

static char       mmc_cmdbuffer[1024] ;

int copy_file_mmc (cmd_tbl_t *cmdtp, int flag, int argc, char *argv[])
{
	unsigned long	address;
	u32		filesize;
	int		load_result;
	char		filename[30];

	strcpy(filename , argv[1]);
        address  = simple_strtoul (argv[2], 0, 16);

	printf("copy_file_mmc : filename = %s\n", filename);
	printf("copy_file_mmc : address = %lx\n", address);

        load_result      = mmc_read_file(filename, address, &filesize);
        if (load_result != 0)
        {
            printf("copy_file_mmc error : in loading file \n");
        }
        return(load_result);
}

int mmc_read_cmd_file (cmd_tbl_t *cmdtp, int flag, int argc, char *argv[])
{
	u32	filesize;
	int	load_result;

        load_result      = mmc_read_file("command.txt",
			(unsigned long)&mmc_cmdbuffer, &filesize);
        if (load_result != 0) {
            printf("mmc_read_cmd_file error : in loading file \n");
        } else {
	    setenv ("bootcmd", mmc_cmdbuffer);
	}
        return(load_result);
}


U_BOOT_CMD(
	copy_file_mmc,	3,	0,	copy_file_mmc,
	"- copy file from mmc card\n",
	"filename address\n"
	"    - load binary file from the MMC/SD card to a memory address\n"
);


U_BOOT_CMD(
	mmc_read_cmd_file,	1,	0,	mmc_read_cmd_file,
	"- copy command file from mmc card\n",
	NULL
);

/* ------------------------------- End of file ---------------------------- */