summaryrefslogtreecommitdiffstats
path: root/firmware/target/arm/tcc780x/sd-tcc780x.c
blob: 8b0ac8a8a6dcc1f3bf46feea2d85808b9fc93acc (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
/***************************************************************************
 *             __________               __   ___.
 *   Open      \______   \ ____   ____ |  | _\_ |__   _______  ___
 *   Source     |       _//  _ \_/ ___\|  |/ /| __ \ /  _ \  \/  /
 *   Jukebox    |    |   (  <_> )  \___|    < | \_\ (  <_> > <  <
 *   Firmware   |____|_  /\____/ \___  >__|_ \|___  /\____/__/\_ \
 *                     \/            \/     \/    \/            \/
 * $Id$
 *
 * Copyright (C) 2006 Daniel Ankers
 * Copyright (C) 2009 Rob Purchase
 *
 * 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 software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
 * KIND, either express or implied.
 *
 ****************************************************************************/
#include "sd.h"
#include "system.h"
#include <string.h>
#include "hotswap.h"
#include "storage.h"
#include "led.h"
#include "thread.h"
#include "disk.h"
#include "fat.h"
#include "ata_idle_notify.h"
#include "usb.h"

#if defined(HAVE_INTERNAL_SD) && defined(HAVE_HOTSWAP)
#define CARD_NUM_INTERNAL 0
#define CARD_NUM_SLOT     1
#elif !defined(HAVE_INTERNAL_SD) && defined(HAVE_HOTSWAP)
#define CARD_NUM_SLOT     0
#endif

#define EC_OK                    0
#define EC_FAILED                1
#define EC_NOCARD                2
#define EC_WAIT_STATE_FAILED     3
#define EC_POWER_UP              4
#define EC_FIFO_WR_EMPTY         5
#define EC_FIFO_WR_DONE          6
#define EC_TRAN_READ_ENTRY       7
#define EC_TRAN_READ_EXIT        8
#define EC_TRAN_WRITE_ENTRY      9
#define EC_TRAN_WRITE_EXIT       10
#define EC_COMMAND               11

/* for compatibility */
static long last_disk_activity = -1;

/** static, private data **/ 
static bool initialized = false;

static long next_yield = 0;
#define MIN_YIELD_PERIOD 1000

static tCardInfo card_info[NUM_DRIVES];
static tCardInfo *currcard = NULL; /* current active card */

struct sd_card_status
{
    int retry;
    int retry_max;
};

static struct sd_card_status sd_status[NUM_DRIVES] =
{
#ifdef HAVE_INTERNAL_SD
    { 0, 1  },
#endif
#ifdef HAVE_HOTSWAP
    { 0, 10 }
#endif
};

/* Shoot for around 75% usage */
static long sd_stack [(DEFAULT_STACK_SIZE*2 + 0x1c0)/sizeof(long)];
static const char         sd_thread_name[] = "sd";
static struct mutex       sd_mtx SHAREDBSS_ATTR;
static struct event_queue sd_queue;

static int sd_first_drive = 0;


static bool sd_poll_status(unsigned int trigger, long timeout)
{
    long t = USEC_TIMER;

    while ((SDISTATUS & trigger) != trigger)
    {
        long time = USEC_TIMER;

        if (TIME_AFTER(time, next_yield))
        {
            long ty = USEC_TIMER;
            yield();
            timeout += USEC_TIMER - ty;
            next_yield = ty + MIN_YIELD_PERIOD;
        }

        if (TIME_AFTER(time, t + timeout))
            return false;
    }

    return true;
}

static int sd_command(unsigned int cmd, unsigned int arg, 
                      unsigned long* response, unsigned int resp_type)
{
    int sdi_cmd = cmd;
    
    sdi_cmd |= (127<<12) | (1<<11); /* max wait time | enable */
    
    if (resp_type)
    {
        /* response type & response required flag */
        sdi_cmd |= (resp_type<<7) | (1<<6);
    }
    
    if (cmd == SD_READ_SINGLE_BLOCK ||
        cmd == SD_READ_MULTIPLE_BLOCK ||
        cmd == SD_WRITE_BLOCK ||
        cmd == SD_WRITE_MULTIPLE_BLOCK)
    {
        sdi_cmd |= (1<<10); /* request data transfer */
    }
    
    if (!sd_poll_status(SDISTATUS_CMD_PATH_RDY, 100000))
        return -EC_COMMAND;
    
    SDIARGU = arg;
    SDICMD = sdi_cmd;
    
    udelay(10);
    
    if (response == NULL)
        return 0;
    
    if (!sd_poll_status(SDISTATUS_RESP_RCVD, 100000))
        return -EC_COMMAND;

    if (resp_type == SDICMD_RES_TYPE2)
    {
        response[0] = SDIRSPARGU0;
        response[1] = SDIRSPARGU1;
        response[2] = SDIRSPARGU2;
        response[3] = SDIRSPARGU3;
    }
    else
    {
        response[0] = SDIRSPARGU0;
    }
    
    return 0;
}

static int sd_wait_for_state(unsigned int state, int id)
{
    unsigned long response = 0;
    unsigned int timeout = 0x80000;

    long start_time = USEC_TIMER;

    while (1)
    {
        int ret = sd_command
            (SD_SEND_STATUS, currcard->rca, &response, SDICMD_RES_TYPE1);

        long us;

        if (ret < 0)
            return ret*100 - id;

        if (((response >> 9) & 0xf) == state)
        {
            return 0;
        }

        if (TIME_AFTER(USEC_TIMER, start_time + timeout))
            return -EC_WAIT_STATE_FAILED*100 - id;

        us = USEC_TIMER;
        if (TIME_AFTER(us, next_yield))
        {
            yield();
            timeout += USEC_TIMER - us;
            next_yield = us + MIN_YIELD_PERIOD;
        }
    }
}

static void sd_card_mux(int card_no)
{
    /* We only support the default card */
    (void)card_no;
}

#ifdef HAVE_HOTSWAP

bool card_detect_target(void)
{
    return (GPIOB & (1<<26)) == 0; /* low active */
}

void card_enable_monitoring_target(bool on)
{
    if (on)
    {
        IEN |= EXT0_IRQ_MASK;
    }
    else
    {
        IEN &= ~EXT0_IRQ_MASK;
    }
}

static int sd1_oneshot_callback(struct timeout *tmo)
{
    (void)tmo;

    /* This is called only if the state was stable for 300ms - check state
     * and post appropriate event. */
    if (card_detect_target())
        queue_broadcast(SYS_HOTSWAP_INSERTED, 0);
    else
        queue_broadcast(SYS_HOTSWAP_EXTRACTED, 0);

    return 0;
}

void EXT0(void)
{
    static struct timeout sd1_oneshot;
    
    timeout_register(&sd1_oneshot, sd1_oneshot_callback, (3*HZ/10), 0);
}

bool sd_removable(IF_MD_NONVOID(int card_no))
{
#ifndef HAVE_MULTIDRIVE
    const int card_no = 0;
#endif
    return (card_no == CARD_NUM_SLOT);
}

bool sd_present(IF_MD_NONVOID(int card_no))
{
#ifndef HAVE_MULTIDRIVE
    const int card_no = 0;
#endif
    return (card_info[card_no].initialized &&
            card_info[card_no].numblocks > 0);
}

#else

bool card_detect_target(void)
{
    return false;
}

bool sd_removable(IF_MD_NONVOID(int card_no))
{
#ifndef HAVE_MULTIDRIVE
    const int card_no = 0;
#endif
    (void)card_no;
    
    return false;
}

#endif /* HAVE_HOTSWAP */


static void sd_init_device(int card_no)
{
    int ret;
    unsigned long response;
    
    /* Initialise card data as blank */
    memset(currcard, 0, sizeof(*currcard));

    /* Switch card mux to card to initialize */
    sd_card_mux(card_no);

#ifdef HAVE_HOTSWAP
    /* Check card is inserted */
    if (card_no == CARD_NUM_SLOT)
    {
        if (GPIOB & (1<<26))
        {
            ret = -EC_NOCARD;
            goto card_init_error;
        }

        /* Card will not power up unless this is done */
        GPIOC_CLEAR = (1<<24);
    }
#endif

    ret = sd_command(SD_GO_IDLE_STATE, 0, NULL, SDICMD_RES_TYPE1);
    
    if (ret < 0)
        goto card_init_error;

    /* Use slow clock during identification (24MHz / 60 = 400kHz) */
    SDICLK = (1<<12) | 59;

    sd_command(SD_SEND_IF_COND, 0x1aa, &response, SDICMD_RES_TYPE3);
    
    if (!sd_poll_status(SDISTATUS_CMD_PATH_RDY, 100000))
        goto card_init_error;
    
    currcard->ocr = 0;
    
    long start_tick = current_tick;
    
    while ((currcard->ocr & (1<<31)) == 0
            && TIME_BEFORE(current_tick, start_tick + HZ))
    {
        udelay(100);
        sd_command(SD_APP_CMD, 0, NULL, SDICMD_RES_TYPE1);
        
        int arg = 0x100000 | ((response == 0x1aa) ? (1<<30):0);
        sd_command(SD_APP_OP_COND, arg, &currcard->ocr, SDICMD_RES_TYPE3);
    }
    
    if ((currcard->ocr & (1<<31)) == 0)
    {
        ret = -EC_POWER_UP;
        goto card_init_error;
    }
    
    ret = sd_command
        (SD_ALL_SEND_CID, 0, currcard->cid, SDICMD_RES_TYPE2);

    if (ret < 0)
        goto card_init_error;

    ret = sd_command
        (SD_SEND_RELATIVE_ADDR, 0, &currcard->rca, SDICMD_RES_TYPE1);
    
    if (ret < 0)
        goto card_init_error;
    
    ret = sd_command
        (SD_SEND_CSD, currcard->rca, currcard->csd, SDICMD_RES_TYPE2);
    
    if (ret < 0)
        goto card_init_error;
    
    sd_parse_csd(currcard);

    ret = sd_command
        (SD_SELECT_CARD, currcard->rca, NULL, SDICMD_RES_TYPE1);
    
    if (ret < 0)
        goto card_init_error;

    ret = sd_command
        (SD_APP_CMD, currcard->rca, NULL, SDICMD_RES_TYPE1);
    
    if (ret < 0)
        goto card_init_error;

    ret = sd_command             /* 4 bit */
        (SD_SET_BUS_WIDTH, currcard->rca | 2, NULL, SDICMD_RES_TYPE1);
    
    if (ret < 0)
        goto card_init_error;

    ret = sd_command
        (SD_SET_BLOCKLEN, currcard->blocksize, NULL, SDICMD_RES_TYPE1);
    
    if (ret < 0)
        goto card_init_error;

    currcard->initialized = 1;
    return;

    /* Card failed to initialize so disable it */
card_init_error:
    currcard->initialized = ret;
    return;
}

/* lock must already be acquired */
static void sd_select_device(int card_no)
{
    currcard = &card_info[card_no];

    if (currcard->initialized > 0)
    {
        /* This card is already initialized - switch to it */
        sd_card_mux(card_no);
        return;
    }

    if (currcard->initialized == 0)
    {
        /* Card needs (re)init */
        sd_init_device(card_no);
    }
}

int sd_read_sectors(IF_MD2(int card_no,) unsigned long start, int incount,
                     void* inbuf)
{
#ifndef HAVE_MULTIDRIVE
    const int card_no = 0;
#endif

    int ret = 0;
    bool aligned;
    unsigned char* buf_end;

    mutex_lock(&sd_mtx);
    sd_enable(true);
    led(true);

sd_read_retry:
    if ((card_no == CARD_NUM_SLOT) && !card_detect_target())
    {
        /* no external sd-card inserted */
        ret = -EC_NOCARD;
        goto sd_read_error;
    }

    sd_select_device(card_no);

    if (currcard->initialized < 0)
    {
        ret = currcard->initialized;
        goto sd_read_error;
    }
    
    last_disk_activity = current_tick;

    ret = sd_wait_for_state(SD_TRAN, EC_TRAN_READ_ENTRY);
    
    if (ret < 0)
        goto sd_read_error;
    
    /* Use full SD clock for data transfer (PCK_SDMMC) */
    SDICLK = (1<<13) | (1<<12); /* bypass divider | enable */
            
    /*  Block count | FIFO count | Block size (2^9) | 4-bit bus */
    SDIDCTRL = (incount << 13) | (4<<8) | (9<<4) | (1<<2);
    SDIDCTRL |= (1<<12);    /* nReset */
    
    SDIDCTRL2 = (1<<2); /* multi block, read */

    if (currcard->ocr & (1<<30))
        ret = sd_command(SD_READ_MULTIPLE_BLOCK, start, NULL, SDICMD_RES_TYPE1);
    else
        ret = sd_command(SD_READ_MULTIPLE_BLOCK, start * 512, NULL, SDICMD_RES_TYPE1);

    if (ret < 0)
        goto sd_read_error;

    aligned = (((int)inbuf & 3) == 0);

    buf_end = (unsigned char *)inbuf + incount * currcard->blocksize;

    while (inbuf < (void*)buf_end)
    {
        if (!sd_poll_status(SDISTATUS_FIFO_FETCH_REQ, 100000))
            goto sd_read_error;

        if (aligned)
        {
            unsigned int* ptr = (unsigned int*)inbuf;
            *ptr++ = SDIRDATA;
            *ptr++ = SDIRDATA;
            *ptr++ = SDIRDATA;
            *ptr   = SDIRDATA;

        }
        else
        {
            int tmp_buf[4];

            tmp_buf[0] = SDIRDATA;
            tmp_buf[1] = SDIRDATA;
            tmp_buf[2] = SDIRDATA;
            tmp_buf[3] = SDIRDATA;

            memcpy(inbuf, tmp_buf, 16);
        }
        inbuf += 16;
    }

    ret = sd_command(SD_STOP_TRANSMISSION, 0, NULL, SDICMD_RES_TYPE1);
    if (ret < 0)
        goto sd_read_error;

    ret = sd_wait_for_state(SD_TRAN, EC_TRAN_READ_EXIT);
    if (ret < 0)
        goto sd_read_error;

    while (1)
    {
        led(false);
        sd_enable(false);
        mutex_unlock(&sd_mtx);

        return ret;

sd_read_error:
        if (sd_status[card_no].retry < sd_status[card_no].retry_max
            && ret != -EC_NOCARD)
        {
            sd_status[card_no].retry++;
            currcard->initialized = 0;
            goto sd_read_retry;
        }
    }
}

int sd_write_sectors(IF_MD2(int card_no,) unsigned long start, int count,
                      const void* outbuf)
{
/* Write support is not finished yet */
/* TODO: The standard suggests using ACMD23 prior to writing multiple blocks
   to improve performance */
#ifndef HAVE_MULTIDRIVE
    const int card_no = 0;
#endif
    int ret;
    const unsigned char *buf_end;
    bool aligned;

    mutex_lock(&sd_mtx);
    sd_enable(true);
    led(true);

sd_write_retry:
    if ((card_no == CARD_NUM_SLOT) && !card_detect_target())
    {
        /* no external sd-card inserted */
        ret = -EC_NOCARD;
        goto sd_write_error;
    }

    sd_select_device(card_no);

    if (currcard->initialized < 0)
    {
        ret = currcard->initialized;
        goto sd_write_error;
    }
    
    ret = sd_wait_for_state(SD_TRAN, EC_TRAN_WRITE_ENTRY);
    
    if (ret < 0)
        goto sd_write_error;

    /* Use full SD clock for data transfer (PCK_SDMMC) */
    SDICLK = (1<<13) | (1<<12); /* bypass divider | enable */
            
    /* Block count | FIFO count | Block size (2^9) | 4-bit bus */
    SDIDCTRL = (count<<13) | (4<<8) | (9<<4) | (1<<2);
    SDIDCTRL |= (1<<12);    /* nReset */
    
    SDIDCTRL2 = (1<<2) | (1<<1); /* multi block, write */

    if (currcard->ocr & (1<<30))
        ret = sd_command(SD_WRITE_MULTIPLE_BLOCK, start, NULL, SDICMD_RES_TYPE1);
    else
        ret = sd_command(SD_WRITE_MULTIPLE_BLOCK, start * 512, NULL, SDICMD_RES_TYPE1);

    if (ret < 0)
        goto sd_write_error;

    aligned = (((int)outbuf & 3) == 0);

    buf_end = (unsigned char *)outbuf + count * currcard->blocksize;

    while (outbuf < (void*)buf_end)
    {
        if (aligned)
        {
            unsigned int* ptr = (unsigned int*)outbuf;
            SDIWDATA = *ptr++;
            SDIWDATA = *ptr++;
            SDIWDATA = *ptr++;
            SDIWDATA = *ptr;
        }
        else
        {
            int tmp_buf[4];
            
            memcpy(tmp_buf, outbuf, 16);

            SDIWDATA = tmp_buf[0];
            SDIWDATA = tmp_buf[1];
            SDIWDATA = tmp_buf[2];
            SDIWDATA = tmp_buf[3];
        }
        outbuf += 16;

        /* Wait for the FIFO to empty */
        if (!sd_poll_status(SDISTATUS_FIFO_LOAD_REQ, 0x80000))
        {
            ret = -EC_FIFO_WR_EMPTY;
            goto sd_write_error;
        }
    }

    last_disk_activity = current_tick;

    if (!sd_poll_status(SDISTATUS_MULTIBLOCK_END, 0x80000))
    {
        ret = -EC_FIFO_WR_DONE;
        goto sd_write_error;
    }

    ret = sd_command(SD_STOP_TRANSMISSION, 0, NULL, SDICMD_RES_TYPE1);
    if (ret < 0)
        goto sd_write_error;

    ret = sd_wait_for_state(SD_TRAN, EC_TRAN_WRITE_EXIT);
    if (ret < 0)
        goto sd_write_error;

    while (1)
    {
        led(false);
        sd_enable(false);
        mutex_unlock(&sd_mtx);

        return ret;

sd_write_error:
        if (sd_status[card_no].retry < sd_status[card_no].retry_max
            && ret != -EC_NOCARD)
        {
            sd_status[card_no].retry++;
            currcard->initialized = 0;
            goto sd_write_retry;
        }
    }
}

static void sd_thread(void) __attribute__((noreturn));
static void sd_thread(void)
{
    struct queue_event ev;
    bool idle_notified = false;
    
    while (1)
    {
        queue_wait_w_tmo(&sd_queue, &ev, HZ);

        switch ( ev.id ) 
        {
#ifdef HAVE_HOTSWAP
        case SYS_HOTSWAP_INSERTED:
        case SYS_HOTSWAP_EXTRACTED:
            fat_lock();          /* lock-out FAT activity first -
                                    prevent deadlocking via disk_mount that
                                    would cause a reverse-order attempt with
                                    another thread */
            mutex_lock(&sd_mtx); /* lock-out card activity - direct calls
                                    into driver that bypass the fat cache */

            /* We now have exclusive control of fat cache and ata */

            /* Release "by force", ensure file descriptors aren't leaked and
               any busy ones are invalid if mounting */
            disk_unmount(sd_first_drive + CARD_NUM_SLOT); 

            /* Force card init for new card, re-init for re-inserted one or
             * clear if the last attempt to init failed with an error. */
            card_info[CARD_NUM_SLOT].initialized = 0;
            sd_status[CARD_NUM_SLOT].retry = 0; 

            if (ev.id == SYS_HOTSWAP_INSERTED)
                disk_mount(sd_first_drive + CARD_NUM_SLOT);

            queue_broadcast(SYS_FS_CHANGED, 0);

            /* Access is now safe */
            mutex_unlock(&sd_mtx);
            fat_unlock();
            break;
#endif
        case SYS_TIMEOUT:
            if (TIME_BEFORE(current_tick, last_disk_activity+(3*HZ)))
            {
                idle_notified = false;
            }
            else
            {
                /* never let a timer wrap confuse us */
                next_yield = USEC_TIMER;

                if (!idle_notified)
                {
                    call_storage_idle_notifys(false);
                    idle_notified = true;
                }
            }
            break;

        case SYS_USB_CONNECTED:
            usb_acknowledge(SYS_USB_CONNECTED_ACK);
            /* Wait until the USB cable is extracted again */
            usb_wait_for_disconnect(&sd_queue);
            break;

        case SYS_USB_DISCONNECTED:
            usb_acknowledge(SYS_USB_DISCONNECTED_ACK);
            break;
        }
    }
}

void sd_enable(bool on)
{
    if(on)
    {
        /* Enable controller & clock */
        BCLKCTR |= DEV_SDMMC;
        PCLK_SDMMC = PCK_EN | (CKSEL_PLL0<<24) | 7; /* 192/8 = 24MHz */
    }
    else
    {
        /* Disable controller & clock */
        BCLKCTR &= ~DEV_SDMMC;
        PCLK_SDMMC &= ~PCK_EN;
    }
}
    
int sd_init(void)
{
    int ret = 0;
    
    if (!initialized)
        mutex_init(&sd_mtx);

    mutex_lock(&sd_mtx);

    led(false);

    if (!initialized)
    {
        initialized = true;

        SWRESET |= DEV_SDMMC;
        SWRESET &= ~DEV_SDMMC;

        /* Configure dual-purpose pins for SD usage */
        PORTCFG0 &= ~(3<<16);
        PORTCFG0 |= (1<<16);              /* SD_D0 & SD_D1 */

        PORTCFG2 &= ~((3<<2) | (3<<0));
        PORTCFG2 |= ((1<<2) | (1<<0));    /* SD_D2/D3/CK/CMD */

        /* Configure card detection GPIO as input */
        GPIOB_DIR &= ~(1<<26);

        /* Configure card power(?) GPIO as output */
        GPIOC_DIR |= (1<<24);

        queue_init(&sd_queue, true);
        create_thread(sd_thread, sd_stack, sizeof(sd_stack), 0,
            sd_thread_name IF_PRIO(, PRIORITY_USER_INTERFACE)
            IF_COP(, CPU));
        
        sleep(HZ/10);
        
#ifdef HAVE_HOTSWAP
        /* Configure interrupts for the card slot */
        TMODE &= ~EXT0_IRQ_MASK; /* edge-triggered */
        TMODEA |= EXT0_IRQ_MASK; /* trigger on both edges */
#endif
    }

    mutex_unlock(&sd_mtx);

    return ret;
}

long sd_last_disk_activity(void)
{
    return last_disk_activity;
}

tCardInfo *card_get_info_target(int card_no)
{    
    return &card_info[card_no];
}

#ifdef CONFIG_STORAGE_MULTI

int sd_num_drives(int first_drive)
{
    /* Store which logical drive number(s) we have been assigned */
    sd_first_drive = first_drive;
    
#if defined(HAVE_INTERNAL_SD) && defined(HAVE_HOTSWAP)
    return 2;
#else
    return 1;
#endif
}

void sd_sleepnow(void)
{
}

bool sd_disk_is_active(void)
{
    return false;
}

int sd_soft_reset(void)
{
    return 0;
}

int sd_spinup_time(void)
{
    return 0;
}

#endif /* CONFIG_STORAGE_MULTI */