FS#11765: Improve AMSv1 Battery Life by Lowering CPU and Peripheral clocks. Unboosted...
[kugel-rb.git] / firmware / target / arm / as3525 / sd-as3525.c
blob6f11145ee6e44fdf1e8b7856869ed140fbf40cc7
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2006 Daniel Ankers
11 * Copyright © 2008-2009 Rafaël Carré
13 * This program is free software; you can redistribute it and/or
14 * modify it under the terms of the GNU General Public License
15 * as published by the Free Software Foundation; either version 2
16 * of the License, or (at your option) any later version.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 ****************************************************************************/
23 /* Driver for the ARM PL180 SD/MMC controller inside AS3525 SoC */
25 #include "config.h" /* for HAVE_MULTIDRIVE & AMS_OF_SIZE */
26 #include "fat.h"
27 #include "thread.h"
28 #include "led.h"
29 #include "sdmmc.h"
30 #include "system.h"
31 #include "cpu.h"
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include "gcc_extensions.h"
36 #include "as3525.h"
37 #include "pl180.h" /* SD controller */
38 #include "pl081.h" /* DMA controller */
39 #include "dma-target.h" /* DMA request lines */
40 #include "clock-target.h"
41 #include "panic.h"
42 #ifdef HAVE_BUTTON_LIGHT
43 #include "backlight-target.h"
44 #endif
45 #include "stdbool.h"
46 #include "ata_idle_notify.h"
47 #include "sd.h"
48 #include "usb.h"
49 /*#define LOGF_ENABLE*/
50 #include "logf.h"
52 #ifdef HAVE_HOTSWAP
53 #include "disk.h"
54 #endif
56 //#define VERIFY_WRITE 1
58 /* command flags */
59 #define MCI_NO_RESP (0<<0)
60 #define MCI_RESP (1<<0)
61 #define MCI_LONG_RESP (1<<1)
62 #define MCI_ACMD (1<<2)
63 #define MCI_NOCRC (1<<3)
65 /* ARM PL180 registers */
66 #define MCI_POWER(i) (*(volatile unsigned char *) (pl180_base[i]+0x00))
67 #define MCI_CLOCK(i) (*(volatile unsigned long *) (pl180_base[i]+0x04))
68 #define MCI_ARGUMENT(i) (*(volatile unsigned long *) (pl180_base[i]+0x08))
69 #define MCI_COMMAND(i) (*(volatile unsigned long *) (pl180_base[i]+0x0C))
70 #define MCI_RESPCMD(i) (*(volatile unsigned long *) (pl180_base[i]+0x10))
71 #define MCI_RESP0(i) (*(volatile unsigned long *) (pl180_base[i]+0x14))
72 #define MCI_RESP1(i) (*(volatile unsigned long *) (pl180_base[i]+0x18))
73 #define MCI_RESP2(i) (*(volatile unsigned long *) (pl180_base[i]+0x1C))
74 #define MCI_RESP3(i) (*(volatile unsigned long *) (pl180_base[i]+0x20))
75 #define MCI_DATA_TIMER(i) (*(volatile unsigned long *) (pl180_base[i]+0x24))
76 #define MCI_DATA_LENGTH(i) (*(volatile unsigned short*) (pl180_base[i]+0x28))
77 #define MCI_DATA_CTRL(i) (*(volatile unsigned char *) (pl180_base[i]+0x2C))
78 #define MCI_DATA_CNT(i) (*(volatile unsigned short*) (pl180_base[i]+0x30))
79 #define MCI_STATUS(i) (*(volatile unsigned long *) (pl180_base[i]+0x34))
80 #define MCI_CLEAR(i) (*(volatile unsigned long *) (pl180_base[i]+0x38))
81 #define MCI_MASK0(i) (*(volatile unsigned long *) (pl180_base[i]+0x3C))
82 #define MCI_MASK1(i) (*(volatile unsigned long *) (pl180_base[i]+0x40))
83 #define MCI_SELECT(i) (*(volatile unsigned long *) (pl180_base[i]+0x44))
84 #define MCI_FIFO_CNT(i) (*(volatile unsigned long *) (pl180_base[i]+0x48))
86 #define MCI_DATA_ERROR \
87 ( MCI_DATA_CRC_FAIL \
88 | MCI_DATA_TIMEOUT \
89 | MCI_TX_UNDERRUN \
90 | MCI_RX_OVERRUN \
91 | MCI_START_BIT_ERR)
93 #define MCI_RESPONSE_ERROR \
94 ( MCI_CMD_TIMEOUT \
95 | MCI_CMD_CRC_FAIL)
97 #define MCI_FIFO(i) ((unsigned long *) (pl180_base[i]+0x80))
98 /* volumes */
99 #define INTERNAL_AS3525 0 /* embedded SD card */
100 #define SD_SLOT_AS3525 1 /* SD slot if present */
102 static const int pl180_base[NUM_DRIVES] = {
103 NAND_FLASH_BASE
104 #ifdef HAVE_MULTIDRIVE
105 , SD_MCI_BASE
106 #endif
109 static int sd_wait_for_tran_state(const int drive);
110 static int sd_select_bank(signed char bank);
111 static int sd_init_card(const int drive);
112 static void init_pl180_controller(const int drive);
114 #define BLOCKS_PER_BANK 0x7a7800u
116 static tCardInfo card_info[NUM_DRIVES];
118 /* maximum timeouts recommanded in the SD Specification v2.00 */
119 #define SD_MAX_READ_TIMEOUT ((AS3525_PCLK_FREQ*(cpu_frequency==CPUFREQ_MAX?2:1)) / 1000 * 100) /* 100 ms */
120 #define SD_MAX_WRITE_TIMEOUT ((AS3525_PCLK_FREQ*(cpu_frequency==CPUFREQ_MAX?2:1)) / 1000 * 250) /* 250 ms */
121 /* for compatibility */
122 static long last_disk_activity = -1;
124 #define MIN_YIELD_PERIOD 5 /* ticks */
125 static long next_yield = 0;
127 static long sd_stack [(DEFAULT_STACK_SIZE*2 + 0x200)/sizeof(long)];
128 static const char sd_thread_name[] = "ata/sd";
129 static struct mutex sd_mtx;
130 static struct event_queue sd_queue;
131 bool sd_enabled = false;
133 #if defined(HAVE_MULTIDRIVE)
134 static bool hs_card = false;
135 #define EXT_SD_BITS (1<<2)
136 #endif
138 static struct wakeup transfer_completion_signal;
139 static volatile unsigned int transfer_error[NUM_VOLUMES];
140 #define PL180_MAX_TRANSFER_ERRORS 10
142 extern long cpu_frequency;
144 #define UNALIGNED_NUM_SECTORS 10
145 static unsigned char aligned_buffer[UNALIGNED_NUM_SECTORS* SD_BLOCK_SIZE] __attribute__((aligned(32))); /* align on cache line size */
146 static unsigned char *uncached_buffer = AS3525_UNCACHED_ADDR(&aligned_buffer[0]);
149 static inline void mci_delay(void) { udelay(1000) ; }
152 static inline bool card_detect_target(void)
154 #if defined(HAVE_MULTIDRIVE)
155 return !(GPIOA_PIN(2));
156 #else
157 return false;
158 #endif
162 #ifdef HAVE_HOTSWAP
163 static int sd1_oneshot_callback(struct timeout *tmo)
165 (void)tmo;
167 /* This is called only if the state was stable for 300ms - check state
168 * and post appropriate event. */
169 if (card_detect_target())
171 queue_broadcast(SYS_HOTSWAP_INSERTED, 0);
173 else
174 queue_broadcast(SYS_HOTSWAP_EXTRACTED, 0);
176 return 0;
179 void sd_gpioa_isr(void)
181 static struct timeout sd1_oneshot;
182 if (GPIOA_MIS & EXT_SD_BITS)
183 timeout_register(&sd1_oneshot, sd1_oneshot_callback, (3*HZ/10), 0);
184 /* acknowledge interrupt */
185 GPIOA_IC = EXT_SD_BITS;
187 #endif /* HAVE_HOTSWAP */
189 void INT_NAND(void)
191 const int status = MCI_STATUS(INTERNAL_AS3525);
193 transfer_error[INTERNAL_AS3525] = status & MCI_DATA_ERROR;
195 wakeup_signal(&transfer_completion_signal);
196 MCI_CLEAR(INTERNAL_AS3525) = status;
199 #ifdef HAVE_MULTIDRIVE
200 void INT_MCI0(void)
202 const int status = MCI_STATUS(SD_SLOT_AS3525);
204 transfer_error[SD_SLOT_AS3525] = status & MCI_DATA_ERROR;
206 wakeup_signal(&transfer_completion_signal);
207 MCI_CLEAR(SD_SLOT_AS3525) = status;
209 #endif
211 static bool send_cmd(const int drive, const int cmd, const int arg,
212 const int flags, long *response)
214 int status;
216 unsigned cmd_retries = 6;
217 while(cmd_retries--)
219 if ((flags & MCI_ACMD) && /* send SD_APP_CMD before each try */
220 !send_cmd(drive, SD_APP_CMD, card_info[drive].rca, MCI_RESP, response))
221 return false;
223 /* Clear old status flags */
224 MCI_CLEAR(drive) = 0x7ff;
226 /* Load command argument or clear if none */
227 MCI_ARGUMENT(drive) = arg;
229 /* Construct MCI_COMMAND & enable CPSM */
230 MCI_COMMAND(drive) =
231 /*b0:5*/ cmd
232 /* b6 */| ((flags & (MCI_RESP|MCI_LONG_RESP)) ? MCI_COMMAND_RESPONSE : 0)
233 /* b7 */| ((flags & MCI_LONG_RESP) ? MCI_COMMAND_LONG_RESPONSE : 0)
234 /* b8 | MCI_COMMAND_INTERRUPT */
235 /* b9 | MCI_COMMAND_PENDING */ /*Only used with stream data transfer*/
236 /* b10*/| MCI_COMMAND_ENABLE; /* Enables CPSM */
238 /* Wait while cmd completes then disable CPSM */
239 while(MCI_STATUS(drive) & MCI_CMD_ACTIVE);
240 MCI_COMMAND(drive) = 0;
242 status = MCI_STATUS(drive);
244 /* Handle command responses */
245 if(flags & MCI_RESP) /* CMD expects response */
247 response[0] = MCI_RESP0(drive); /* Always prepare short response */
249 if(status & MCI_RESPONSE_ERROR) {/* timeout or crc failure */
250 if ((status & MCI_CMD_CRC_FAIL) &&
251 (flags & MCI_NOCRC))
252 break;
253 logf("sd cmd error: drive %d cmd %d arg %08x sd_status %08x resp0 %08lx",
254 drive, cmd, arg, status, response[0]);
255 continue;
258 if((flags & MCI_RESP) &&
259 !(flags & MCI_LONG_RESP) &&
260 (response[0] & SD_R1_CARD_ERROR)) {
261 logf("sd card error: drive %d cmd %d arg %08x r1 %08lx",
262 drive, cmd, arg, response[0]);
265 if(status & MCI_CMD_RESP_END) /* Response passed CRC check */
267 if(flags & MCI_LONG_RESP)
268 { /* response[0] has already been read */
269 response[1] = MCI_RESP1(drive);
270 response[2] = MCI_RESP2(drive);
271 response[3] = MCI_RESP3(drive);
273 return true;
276 else if(status & MCI_CMD_SENT) /* CMD sent, no response required */
277 return true;
280 return false;
283 #define MCI_FULLSPEED (MCI_CLOCK_ENABLE | MCI_CLOCK_BYPASS) /* MCLK */
284 #define MCI_HALFSPEED (MCI_CLOCK_ENABLE) /* MCLK/2 */
285 #define MCI_QUARTERSPEED (MCI_CLOCK_ENABLE | 1) /* MCLK/4 */
286 #define MCI_IDENTSPEED (MCI_CLOCK_ENABLE | AS3525_SD_IDENT_DIV) /* IDENT */
287 #define MCI_IDENTSPEED_BOOSTED (MCI_CLOCK_ENABLE | AS3525_SD_IDENT_DIV_BOOSTED)
288 static int sd_init_card(const int drive)
290 unsigned long response;
291 long init_timeout;
292 bool sd_v2 = false;
294 card_info[drive].rca = 0;
296 /* MCLCK on and set to 400kHz ident frequency */
297 if (cpu_frequency == CPUFREQ_MAX)
298 MCI_CLOCK(drive) = MCI_IDENTSPEED_BOOSTED;
299 else
300 MCI_CLOCK(drive) = MCI_IDENTSPEED;
302 /* 100 - 400kHz clock required for Identification Mode */
303 /* Start of Card Identification Mode ************************************/
305 /* CMD0 Go Idle */
306 if(!send_cmd(drive, SD_GO_IDLE_STATE, 0, MCI_NO_RESP, NULL))
307 return -1;
308 mci_delay();
310 /* CMD8 Check for v2 sd card. Must be sent before using ACMD41
311 Non v2 cards will not respond to this command*/
312 if(send_cmd(drive, SD_SEND_IF_COND, 0x1AA, MCI_RESP, &response))
313 if((response & 0xFFF) == 0x1AA)
314 sd_v2 = true;
316 /* timeout for initialization is 1sec, from SD Specification 2.00 */
317 init_timeout = current_tick + HZ;
319 do {
320 /* this timeout is the only valid error for this loop*/
321 if(TIME_AFTER(current_tick, init_timeout))
322 return -2;
324 /* ACMD41 For v2 cards set HCS bit[30] & send host voltage range to all */
325 send_cmd(drive, SD_APP_OP_COND, (0x00FF8000 | (sd_v2 ? 1<<30 : 0)),
326 MCI_ACMD|MCI_NOCRC|MCI_RESP, &card_info[drive].ocr);
328 } while(!(card_info[drive].ocr & (1<<31)));
330 /* CMD2 send CID */
331 if(!send_cmd(drive, SD_ALL_SEND_CID, 0, MCI_RESP|MCI_LONG_RESP,
332 card_info[drive].cid))
333 return -3;
335 /* CMD3 send RCA */
336 if(!send_cmd(drive, SD_SEND_RELATIVE_ADDR, 0, MCI_RESP,
337 &card_info[drive].rca))
338 return -4;
340 /* End of Card Identification Mode ************************************/
342 #ifdef HAVE_MULTIDRIVE /* The internal SDs are v1 */
344 /* Try to switch V2 cards to HS timings, non HS seem to ignore this */
345 if(sd_v2)
347 /* CMD7 w/rca: Select card to put it in TRAN state */
348 if(!send_cmd(drive, SD_SELECT_CARD, card_info[drive].rca, MCI_RESP, &response))
349 return -5;
351 if(sd_wait_for_tran_state(drive))
352 return -6;
353 /* CMD6 */
354 if(!send_cmd(drive, SD_SWITCH_FUNC, 0x80fffff1, MCI_NO_RESP, NULL))
355 return -7;
356 mci_delay();
358 /* go back to STBY state so we can read csd */
359 /* CMD7 w/rca=0: Deselect card to put it in STBY state */
360 if(!send_cmd(drive, SD_DESELECT_CARD, 0, MCI_NO_RESP, NULL))
361 return -8;
362 mci_delay();
364 #endif /* HAVE_MULTIDRIVE */
366 /* CMD9 send CSD */
367 if(!send_cmd(drive, SD_SEND_CSD, card_info[drive].rca,
368 MCI_RESP|MCI_LONG_RESP, card_info[drive].csd))
369 return -9;
371 sd_parse_csd(&card_info[drive]);
373 #if defined(HAVE_MULTIDRIVE)
374 hs_card = (card_info[drive].speed == 50000000);
375 #endif
377 /* Boost MCICLK to operating speed */
378 if(drive == INTERNAL_AS3525)
379 MCI_CLOCK(drive) = MCI_HALFSPEED; /* MCICLK = IDE_CLK/2 = 25 MHz */
380 #if defined(HAVE_MULTIDRIVE)
381 else
382 { /* PCLK = 31Mhz (62 boosted) MCI = 31Mhz(hs) or 15.5 */
383 if (cpu_frequency == CPUFREQ_MAX )
384 MCI_CLOCK(drive) = (hs_card ? MCI_HALFSPEED : MCI_QUARTERSPEED);
385 else
386 MCI_CLOCK(drive) = (hs_card ? MCI_FULLSPEED : MCI_HALFSPEED);
388 #endif
390 /* CMD7 w/rca: Select card to put it in TRAN state */
391 if(!send_cmd(drive, SD_SELECT_CARD, card_info[drive].rca, MCI_RESP, &response))
392 return -10;
394 #if 0 /* FIXME : it seems that reading fails on some models */
395 /* Switch to to 4 bit widebus mode */
396 if(sd_wait_for_tran_state(drive) < 0)
397 return -11;
398 /* ACMD42 */
399 if(!send_cmd(drive, SD_SET_CLR_CARD_DETECT, 0, MCI_ACMD|MCI_RESP, &response))
400 return -15;
401 /* ACMD6 */
402 if(!send_cmd(drive, SD_SET_BUS_WIDTH, 2, MCI_ACMD|MCI_RESP, &response))
403 return -13;
404 /* Now that card is widebus make controller aware */
405 MCI_CLOCK(drive) |= MCI_CLOCK_WIDEBUS;
406 #endif
409 * enable bank switching
410 * without issuing this command, we only have access to 1/4 of the blocks
411 * of the first bank (0x1E9E00 blocks, which is the size reported in the
412 * CSD register)
414 if(drive == INTERNAL_AS3525)
416 const int ret = sd_select_bank(-1);
417 if(ret < 0)
418 return ret -16;
420 /* CMD7 w/rca = 0: Unselect card to put it in STBY state */
421 if(!send_cmd(drive, SD_SELECT_CARD, 0, MCI_NO_RESP, NULL))
422 return -17;
423 mci_delay();
425 /* CMD9 send CSD again, so we got the correct number of blocks */
426 if(!send_cmd(drive, SD_SEND_CSD, card_info[drive].rca,
427 MCI_RESP|MCI_LONG_RESP, card_info[drive].csd))
428 return -18;
430 sd_parse_csd(&card_info[drive]);
431 /* The OF is stored in the first blocks */
432 card_info[INTERNAL_AS3525].numblocks -= AMS_OF_SIZE;
434 /* CMD7 w/rca: Select card to put it in TRAN state */
435 if(!send_cmd(drive, SD_SELECT_CARD, card_info[drive].rca, MCI_RESP, &response))
436 return -19;
439 card_info[drive].initialized = 1;
441 return 0;
444 static void sd_thread(void) NORETURN_ATTR;
445 static void sd_thread(void)
447 struct queue_event ev;
448 bool idle_notified = false;
450 while (1)
452 queue_wait_w_tmo(&sd_queue, &ev, HZ);
454 switch ( ev.id )
456 #ifdef HAVE_HOTSWAP
457 case SYS_HOTSWAP_INSERTED:
458 case SYS_HOTSWAP_EXTRACTED:
460 int microsd_init = 1;
461 fat_lock(); /* lock-out FAT activity first -
462 prevent deadlocking via disk_mount that
463 would cause a reverse-order attempt with
464 another thread */
465 mutex_lock(&sd_mtx); /* lock-out card activity - direct calls
466 into driver that bypass the fat cache */
468 /* We now have exclusive control of fat cache and ata */
470 disk_unmount(SD_SLOT_AS3525); /* release "by force", ensure file
471 descriptors aren't leaked and any busy
472 ones are invalid if mounting */
474 /* Force card init for new card, re-init for re-inserted one or
475 * clear if the last attempt to init failed with an error. */
476 card_info[SD_SLOT_AS3525].initialized = 0;
478 if (ev.id == SYS_HOTSWAP_INSERTED)
480 sd_enable(true);
481 init_pl180_controller(SD_SLOT_AS3525);
482 microsd_init = sd_init_card(SD_SLOT_AS3525);
483 if (microsd_init < 0) /* initialisation failed */
484 panicf("microSD init failed : %d", microsd_init);
486 microsd_init = disk_mount(SD_SLOT_AS3525); /* 0 if fail */
490 * Mount succeeded, or this was an EXTRACTED event,
491 * in both cases notify the system about the changed filesystems
493 if (microsd_init)
494 queue_broadcast(SYS_FS_CHANGED, 0);
496 /* Access is now safe */
497 mutex_unlock(&sd_mtx);
498 fat_unlock();
499 sd_enable(false);
501 break;
502 #endif
503 case SYS_TIMEOUT:
504 if (TIME_BEFORE(current_tick, last_disk_activity+(3*HZ)))
506 idle_notified = false;
508 else
510 /* never let a timer wrap confuse us */
511 next_yield = current_tick;
513 if (!idle_notified)
515 call_storage_idle_notifys(false);
516 idle_notified = true;
519 break;
521 case SYS_USB_CONNECTED:
522 usb_acknowledge(SYS_USB_CONNECTED_ACK);
523 /* Wait until the USB cable is extracted again */
524 usb_wait_for_disconnect(&sd_queue);
526 break;
527 case SYS_USB_DISCONNECTED:
528 usb_acknowledge(SYS_USB_DISCONNECTED_ACK);
529 break;
534 #ifdef HAVE_MULTIDRIVE
535 void sd_set_boosted_divider(void)
537 if ( !sd_enabled )
538 return;
539 /* 62Mhz/2 - 62/4 */
540 MCI_CLOCK(SD_SLOT_AS3525) = (hs_card ?
541 MCI_HALFSPEED : MCI_QUARTERSPEED);
544 void sd_set_unboosted_divider(void)
546 if ( !sd_enabled )
547 return;
548 /* 31Mhz/1 - 31/2 */
549 MCI_CLOCK(SD_SLOT_AS3525) = (hs_card ?
550 MCI_FULLSPEED : MCI_HALFSPEED);
552 #endif
554 static void init_pl180_controller(const int drive)
556 MCI_COMMAND(drive) = MCI_DATA_CTRL(drive) = 0;
557 MCI_CLEAR(drive) = 0x7ff;
559 MCI_MASK0(drive) = MCI_DATA_ERROR | MCI_DATA_END;
560 MCI_MASK1(drive) = 0;
561 #ifdef HAVE_MULTIDRIVE
562 VIC_INT_ENABLE =
563 (drive == INTERNAL_AS3525) ? INTERRUPT_NAND : INTERRUPT_MCI0;
564 /* clear previous irq */
565 GPIOA_IC = EXT_SD_BITS;
566 /* enable edge detecting */
567 GPIOA_IS &= ~EXT_SD_BITS;
568 /* detect both raising and falling edges */
569 GPIOA_IBE |= EXT_SD_BITS;
570 /* enable the card detect interrupt */
571 GPIOA_IE |= EXT_SD_BITS;
573 #else
574 VIC_INT_ENABLE = INTERRUPT_NAND;
575 #endif
577 MCI_POWER(drive) = MCI_POWER_UP | (MCI_VDD_3_0); /* OF Setting */
578 mci_delay();
580 MCI_POWER(drive) |= MCI_POWER_ON;
581 mci_delay();
583 MCI_SELECT(drive) = 0;
585 /* Pl180 clocks get turned on at start of card init */
588 int sd_init(void)
590 int ret;
591 CGU_IDE = (1<<6) /* enable non AHB interface*/
592 | (AS3525_IDE_DIV << 2)
593 | AS3525_CLK_PLLA; /* clock source = PLLA */
595 bitset32(&CGU_PERI, CGU_NAF_CLOCK_ENABLE);
596 #ifdef HAVE_MULTIDRIVE
597 bitset32(&CGU_PERI, CGU_MCI_CLOCK_ENABLE);
598 bitclr32(&CCU_IO, 1<<3); /* bits 3:2 = 01, xpd is SD interface */
599 bitset32(&CCU_IO, 1<<2);
600 #endif
602 wakeup_init(&transfer_completion_signal);
604 init_pl180_controller(INTERNAL_AS3525);
605 ret = sd_init_card(INTERNAL_AS3525);
606 if(ret < 0)
607 return ret;
608 #ifdef HAVE_MULTIDRIVE
609 init_pl180_controller(SD_SLOT_AS3525);
610 #endif
612 /* init mutex */
613 mutex_init(&sd_mtx);
615 queue_init(&sd_queue, true);
616 create_thread(sd_thread, sd_stack, sizeof(sd_stack), 0,
617 sd_thread_name IF_PRIO(, PRIORITY_USER_INTERFACE) IF_COP(, CPU));
619 sd_enabled = true;
620 sd_enable(false);
622 return 0;
625 #ifdef HAVE_HOTSWAP
626 bool sd_removable(IF_MD_NONVOID(int drive))
628 return (drive==1);
631 bool sd_present(IF_MD_NONVOID(int drive))
633 return (drive == 0) ? true : card_detect_target();
635 #endif /* HAVE_HOTSWAP */
637 static int sd_wait_for_tran_state(const int drive)
639 unsigned long response = 0;
640 unsigned int timeout = current_tick + 5 * HZ;
642 while (1)
644 if(!send_cmd(drive, SD_SEND_STATUS, card_info[drive].rca, MCI_RESP,
645 &response))
646 return -1;
648 if (((response >> 9) & 0xf) == SD_TRAN)
649 return 0;
651 if(TIME_AFTER(current_tick, timeout))
652 return -2;
654 if (TIME_AFTER(current_tick, next_yield))
656 yield();
657 next_yield = current_tick + MIN_YIELD_PERIOD;
662 static int sd_select_bank(signed char bank)
664 int ret;
665 unsigned loops = 0;
667 memset(uncached_buffer, 0, 512);
668 if(bank == -1)
669 { /* enable bank switching */
670 uncached_buffer[0] = 16;
671 uncached_buffer[1] = 1;
672 uncached_buffer[2] = 10;
674 else
675 uncached_buffer[0] = bank;
677 do {
678 if(loops++ > PL180_MAX_TRANSFER_ERRORS)
679 panicf("SD bank %d error : 0x%x", bank,
680 transfer_error[INTERNAL_AS3525]);
682 ret = sd_wait_for_tran_state(INTERNAL_AS3525);
683 if (ret < 0)
684 return ret - 2;
686 if(!send_cmd(INTERNAL_AS3525, SD_SWITCH_FUNC, 0x80ffffef, MCI_NO_RESP,
687 NULL))
688 return -1;
690 mci_delay();
692 if(!send_cmd(INTERNAL_AS3525, 35, 0, MCI_NO_RESP, NULL))
693 return -2;
695 mci_delay();
697 dma_retain();
698 /* we don't use the uncached buffer here, because we need the
699 * physical memory address for DMA transfers */
700 dma_enable_channel(0, AS3525_PHYSICAL_ADDR(&aligned_buffer[0]),
701 MCI_FIFO(INTERNAL_AS3525), DMA_PERI_SD,
702 DMAC_FLOWCTRL_PERI_MEM_TO_PERI, true, false, 0, DMA_S8, NULL);
704 MCI_DATA_TIMER(INTERNAL_AS3525) = SD_MAX_WRITE_TIMEOUT;
705 MCI_DATA_LENGTH(INTERNAL_AS3525) = 512;
706 MCI_DATA_CTRL(INTERNAL_AS3525) = (1<<0) /* enable */ |
707 (0<<1) /* transfer direction */ |
708 (1<<3) /* DMA */ |
709 (9<<4) /* 2^9 = 512 */ ;
711 /* Wakeup signal from NAND/MCIO isr on MCI_DATA_ERROR | MCI_DATA_END */
712 wakeup_wait(&transfer_completion_signal, TIMEOUT_BLOCK);
714 /* Wait for FIFO to empty, card may still be in PRG state */
715 while(MCI_STATUS(INTERNAL_AS3525) & MCI_TX_ACTIVE );
717 dma_release();
719 } while(transfer_error[INTERNAL_AS3525]);
721 card_info[INTERNAL_AS3525].current_bank = (bank == -1) ? 0 : bank;
723 return 0;
726 static int sd_transfer_sectors(IF_MD2(int drive,) unsigned long start,
727 int count, void* buf, const bool write)
729 #ifndef HAVE_MULTIDRIVE
730 const int drive = 0;
731 #endif
732 int ret = 0;
733 unsigned loops = 0;
734 unsigned long response;
735 bool aligned = !((uintptr_t)buf & (CACHEALIGN_SIZE - 1));
737 sd_enable(true);
738 led(true);
740 if (card_info[drive].initialized <= 0)
742 ret = sd_init_card(drive);
743 if (!(card_info[drive].initialized))
744 goto sd_transfer_error_nodma;
747 if(count < 0) /* XXX: why is it signed ? */
749 ret = -20;
750 goto sd_transfer_error_nodma;
752 if((start+count) > card_info[drive].numblocks)
754 ret = -21;
755 goto sd_transfer_error_nodma;
758 /* skip SanDisk OF */
759 if (drive == INTERNAL_AS3525)
760 start += AMS_OF_SIZE;
762 last_disk_activity = current_tick;
764 dma_retain();
766 if(aligned)
767 { /* direct transfer, indirect is always uncached */
768 if(write)
769 commit_dcache_range(buf, count * SECTOR_SIZE);
770 else
771 discard_dcache_range(buf, count * SECTOR_SIZE);
774 while(count)
776 /* 128 * 512 = 2^16, and doesn't fit in the 16 bits of DATA_LENGTH
777 * register, so we have to transfer maximum 127 sectors at a time. */
778 unsigned int transfer = (count >= 128) ? 127 : count; /* sectors */
779 void *dma_buf;
780 const int cmd =
781 write ? SD_WRITE_MULTIPLE_BLOCK : SD_READ_MULTIPLE_BLOCK;
782 unsigned long bank_start = start;
783 unsigned long status;
785 /* Only switch banks for internal storage */
786 if(drive == INTERNAL_AS3525)
788 unsigned int bank = 0;
789 while(bank_start >= BLOCKS_PER_BANK)
791 bank_start -= BLOCKS_PER_BANK;
792 bank++;
795 /* Switch bank if needed */
796 if(card_info[INTERNAL_AS3525].current_bank != bank)
798 ret = sd_select_bank(bank);
799 if (ret < 0)
801 ret -= 20;
802 goto sd_transfer_error;
806 /* Do not cross a bank boundary in a single transfer loop */
807 if((transfer + bank_start) > BLOCKS_PER_BANK)
808 transfer = BLOCKS_PER_BANK - bank_start;
811 /* Set bank_start to the correct unit (blocks or bytes) */
812 if(!(card_info[drive].ocr & (1<<30))) /* not SDHC */
813 bank_start *= SD_BLOCK_SIZE;
815 if(aligned)
817 dma_buf = AS3525_PHYSICAL_ADDR(buf);
819 else
821 dma_buf = AS3525_PHYSICAL_ADDR(&aligned_buffer[0]);
822 if(transfer > UNALIGNED_NUM_SECTORS)
823 transfer = UNALIGNED_NUM_SECTORS;
825 if(write)
826 memcpy(uncached_buffer, buf, transfer * SD_BLOCK_SIZE);
829 ret = sd_wait_for_tran_state(drive);
830 if (ret < 0)
832 ret -= 2*20;
833 goto sd_transfer_error;
836 if(!send_cmd(drive, cmd, bank_start, MCI_RESP, &response))
838 ret -= 3*20;
839 goto sd_transfer_error;
842 if(write)
844 dma_enable_channel(0, dma_buf, MCI_FIFO(drive),
845 (drive == INTERNAL_AS3525) ? DMA_PERI_SD : DMA_PERI_SD_SLOT,
846 DMAC_FLOWCTRL_PERI_MEM_TO_PERI, true, false, 0, DMA_S8, NULL);
848 /*Small delay for writes prevents data crc failures at lower freqs*/
849 #ifdef HAVE_MULTIDRIVE
850 if((drive == SD_SLOT_AS3525) && !hs_card)
852 int write_delay = 125;
853 while(write_delay--);
855 #endif
857 else
858 dma_enable_channel(0, MCI_FIFO(drive), dma_buf,
859 (drive == INTERNAL_AS3525) ? DMA_PERI_SD : DMA_PERI_SD_SLOT,
860 DMAC_FLOWCTRL_PERI_PERI_TO_MEM, false, true, 0, DMA_S8, NULL);
862 MCI_DATA_TIMER(drive) = write ?
863 SD_MAX_WRITE_TIMEOUT : SD_MAX_READ_TIMEOUT;
864 MCI_DATA_LENGTH(drive) = transfer * SD_BLOCK_SIZE;
865 MCI_DATA_CTRL(drive) = (1<<0) /* enable */ |
866 (!write<<1) /* transfer direction */ |
867 (1<<3) /* DMA */ |
868 (9<<4) /* 2^9 = 512 */ ;
870 /* Wakeup signal from NAND/MCIO isr on MCI_DATA_ERROR | MCI_DATA_END */
871 wakeup_wait(&transfer_completion_signal, TIMEOUT_BLOCK);
873 /* Wait for FIFO to empty, card may still be in PRG state for writes */
874 while(MCI_STATUS(drive) & MCI_TX_ACTIVE);
877 * If the write aborted early due to a tx underrun, disable the
878 * dma channel here, otherwise there are still 4 words in the fifo
879 * and the retried write will get corrupted.
881 dma_disable_channel(0);
883 last_disk_activity = current_tick;
885 if(!send_cmd(drive, SD_STOP_TRANSMISSION, 0, MCI_RESP, &status))
887 ret = -4*20;
888 goto sd_transfer_error;
891 if(!transfer_error[drive])
893 if(!write && !aligned)
894 memcpy(buf, uncached_buffer, transfer * SD_BLOCK_SIZE);
895 buf += transfer * SD_BLOCK_SIZE;
896 start += transfer;
897 count -= transfer;
898 loops = 0; /* reset errors counter */
900 else if(loops++ > PL180_MAX_TRANSFER_ERRORS)
901 panicf("SD Xfer %s err:0x%x Disk%d", (write? "write": "read"),
902 transfer_error[drive], drive);
905 sd_transfer_error:
907 dma_release();
909 sd_transfer_error_nodma:
911 led(false);
912 sd_enable(false);
914 if (ret) /* error */
915 card_info[drive].initialized = 0;
917 return ret;
920 int sd_read_sectors(IF_MD2(int drive,) unsigned long start, int count,
921 void* buf)
923 int ret;
925 mutex_lock(&sd_mtx);
926 ret = sd_transfer_sectors(IF_MD2(drive,) start, count, buf, false);
927 mutex_unlock(&sd_mtx);
929 return ret;
932 int sd_write_sectors(IF_MD2(int drive,) unsigned long start, int count,
933 const void* buf)
935 #ifdef VERIFY_WRITE
936 unsigned long saved_start = start;
937 int saved_count = count;
938 void *saved_buf = (void*)buf;
939 #endif
940 int ret;
942 mutex_lock(&sd_mtx);
944 ret = sd_transfer_sectors(IF_MD2(drive,) start, count, (void*)buf, true);
946 #ifdef VERIFY_WRITE
947 if (ret) {
948 /* write failed, no point in verifying */
949 mutex_unlock(&sd_mtx);
950 return ret;
953 count = saved_count;
954 buf = saved_buf;
955 start = saved_start;
956 while (count) {
957 int transfer = count;
958 if(transfer > UNALIGNED_NUM_SECTORS)
959 transfer = UNALIGNED_NUM_SECTORS;
961 sd_transfer_sectors(IF_MD2(drive,) start, transfer, aligned_buffer, false);
962 if (memcmp(buf, aligned_buffer, transfer * 512) != 0) {
963 /* try the write again in the hope to repair the damage */
964 sd_transfer_sectors(IF_MD2(drive,) saved_start, saved_count, saved_buf, true);
965 panicf("sd: verify failed: sec=%ld n=%d!", start, transfer);
968 buf += transfer * 512;
969 count -= transfer;
970 start += transfer;
972 #endif
974 mutex_unlock(&sd_mtx);
976 return ret;
979 long sd_last_disk_activity(void)
981 return last_disk_activity;
984 void sd_enable(bool on)
986 #if defined(HAVE_BUTTON_LIGHT) && defined(HAVE_MULTIDRIVE)
987 extern int buttonlight_is_on;
988 #endif
990 #if defined(HAVE_HOTSWAP) && defined (HAVE_ADJUSTABLE_CPU_VOLTAGE)
991 static bool cpu_boosted = false;
992 #endif
994 if (sd_enabled == on)
995 return; /* nothing to do */
997 sd_enabled = on;
999 if(on)
1001 #if defined(HAVE_BUTTON_LIGHT) && defined(HAVE_MULTIDRIVE)
1002 /* buttonlight AMSes need a bit of special handling for the buttonlight
1003 * here due to the dual mapping of GPIOD and XPD */
1004 bitset32(&CCU_IO, 1<<2); /* XPD is SD-MCI interface (b3:2 = 01) */
1005 if (buttonlight_is_on)
1006 GPIOD_DIR &= ~(1<<7);
1007 else
1008 _buttonlight_off();
1009 #endif
1011 #if defined(HAVE_HOTSWAP) && defined (HAVE_ADJUSTABLE_CPU_VOLTAGE)
1012 if(card_detect_target()) /* If SD card present Boost cpu for voltage */
1014 cpu_boosted = true;
1015 cpu_boost(true);
1017 #endif /* defined(HAVE_HOTSWAP) && defined (HAVE_ADJUSTABLE_CPU_VOLTAGE) */
1019 else
1021 #if defined(HAVE_HOTSWAP) && defined (HAVE_ADJUSTABLE_CPU_VOLTAGE)
1022 if(cpu_boosted)
1024 cpu_boost(false);
1025 cpu_boosted = false;
1027 #endif /* defined(HAVE_HOTSWAP) && defined (HAVE_ADJUSTABLE_CPU_VOLTAGE) */
1029 #if defined(HAVE_BUTTON_LIGHT) && defined(HAVE_MULTIDRIVE)
1030 bitclr32(&CCU_IO, 1<<2); /* XPD is general purpose IO (b3:2 = 00) */
1031 if (buttonlight_is_on)
1032 _buttonlight_on();
1033 #endif
1037 tCardInfo *card_get_info_target(int card_no)
1039 return &card_info[card_no];
1042 #ifdef CONFIG_STORAGE_MULTI
1043 int sd_num_drives(int first_drive)
1045 /* We don't care which logical drive number(s) we have been assigned */
1046 (void)first_drive;
1048 return NUM_DRIVES;
1050 #endif /* CONFIG_STORAGE_MULTI */