as3525v2: check if SD transfers fit with the card capacity
[kugel-rb.git] / firmware / target / arm / as3525 / sd-as3525v2.c
blob887a84fb90d106a3453f5c40c11c40b1cd8b5397
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 #include "config.h" /* for HAVE_MULTIVOLUME */
24 #include "fat.h"
25 #include "thread.h"
26 #include "led.h"
27 #include "hotswap.h"
28 #include "system.h"
29 #include "kernel.h"
30 #include "cpu.h"
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include "as3525v2.h"
35 #include "pl081.h" /* DMA controller */
36 #include "dma-target.h" /* DMA request lines */
37 #include "clock-target.h"
38 #include "panic.h"
39 #include "stdbool.h"
40 #include "ata_idle_notify.h"
41 #include "sd.h"
42 #include "usb.h"
44 #ifdef HAVE_HOTSWAP
45 #include "disk.h"
46 #endif
48 #include "lcd.h"
49 #include <stdarg.h>
50 #include "sysfont.h"
52 #define INTERNAL_AS3525 0 /* embedded SD card */
53 #define SD_SLOT_AS3525 1 /* SD slot if present */
55 /* Clipv2 Clip+ and Fuzev2 OF all occupy the same size */
56 #define AMS_OF_SIZE 0xf000
58 /* command flags */
59 #define MCI_NO_RESP (0<<0)
60 #define MCI_RESP (1<<0)
61 #define MCI_LONG_RESP (1<<1)
63 /* controller registers */
64 #define SD_BASE 0xC6070000
66 #define SD_REG(x) (*(volatile unsigned long *) (SD_BASE+x))
68 #define MCI_CTRL SD_REG(0x00)
70 /* control bits */
71 #define CTRL_RESET (1<<0)
72 #define FIFO_RESET (1<<1)
73 #define DMA_RESET (1<<2)
74 #define INT_ENABLE (1<<4)
75 #define DMA_ENABLE (1<<5)
76 #define READ_WAIT (1<<6)
77 #define SEND_IRQ_RESP (1<<7)
78 #define ABRT_READ_DATA (1<<8)
79 #define SEND_CCSD (1<<9)
80 #define SEND_AS_CCSD (1<<10)
81 #define EN_OD_PULLUP (1<<24)
84 #define MCI_PWREN SD_REG(0x04) /* power enable */
86 #define PWR_CRD_0 (1<<0)
87 #define PWR_CRD_1 (1<<1)
88 #define PWR_CRD_2 (1<<2)
89 #define PWR_CRD_3 (1<<3)
91 #define MCI_CLKDIV SD_REG(0x08) /* clock divider */
92 /* CLK_DIV_0 : bits 7:0
93 * CLK_DIV_1 : bits 15:8
94 * CLK_DIV_2 : bits 23:16
95 * CLK_DIV_3 : bits 31:24
98 #define MCI_CLKSRC SD_REG(0x0C) /* clock source */
99 /* CLK_SRC_CRD0: bits 1:0
100 * CLK_SRC_CRD1: bits 3:2
101 * CLK_SRC_CRD2: bits 5:4
102 * CLK_SRC_CRD3: bits 7:6
105 #define MCI_CLKENA SD_REG(0x10) /* clock enable */
107 #define CCLK_ENA_CRD0 (1<<0)
108 #define CCLK_ENA_CRD1 (1<<1)
109 #define CCLK_ENA_CRD2 (1<<2)
110 #define CCLK_ENA_CRD3 (1<<3)
111 #define CCLK_LP_CRD0 (1<<16) /* LP --> Low Power Mode? */
112 #define CCLK_LP_CRD1 (1<<17)
113 #define CCLK_LP_CRD2 (1<<18)
114 #define CCLK_LP_CRD3 (1<<19)
116 #define MCI_TMOUT SD_REG(0x14) /* timeout */
117 /* response timeout bits 0:7
118 * data timeout bits 8:31
121 #define MCI_CTYPE SD_REG(0x18) /* card type */
122 /* 1 bit per card, set = wide bus */
123 #define WIDTH4_CRD0 (1<<0)
124 #define WIDTH4_CRD1 (1<<1)
125 #define WIDTH4_CRD2 (1<<2)
126 #define WIDTH4_CRD3 (1<<3)
128 #define MCI_BLKSIZ SD_REG(0x1C) /* block size bits 0:15*/
129 #define MCI_BYTCNT SD_REG(0x20) /* byte count bits 0:31*/
130 #define MCI_MASK SD_REG(0x24) /* interrupt mask */
134 #define MCI_ARGUMENT SD_REG(0x28)
135 #define MCI_COMMAND SD_REG(0x2C)
137 /* command bits (bits 5:0 are the command index) */
138 #define CMD_RESP_EXP_BIT (1<<6)
139 #define CMD_RESP_LENGTH_BIT (1<<7)
140 #define CMD_CHECK_CRC_BIT (1<<8)
141 #define CMD_DATA_EXP_BIT (1<<9)
142 #define CMD_RW_BIT (1<<10)
143 #define CMD_TRANSMODE_BIT (1<<11)
144 #define CMD_SENT_AUTO_STOP_BIT (1<<12)
145 #define CMD_WAIT_PRV_DAT_BIT (1<<13)
146 #define CMD_ABRT_CMD_BIT (1<<14)
147 #define CMD_SEND_INIT_BIT (1<<15)
148 #define CMD_CARD_NO(x) ((x)<<16) /* 5 bits wide */
149 #define CMD_SEND_CLK_ONLY (1<<21)
150 #define CMD_READ_CEATA (1<<22)
151 #define CMD_CCS_EXPECTED (1<<23)
152 #define CMD_DONE_BIT (1<<31)
154 #define TRANSFER_CMD (cmd == SD_READ_MULTIPLE_BLOCK || \
155 cmd == SD_WRITE_MULTIPLE_BLOCK)
157 #define MCI_RESP0 SD_REG(0x30)
158 #define MCI_RESP1 SD_REG(0x34)
159 #define MCI_RESP2 SD_REG(0x38)
160 #define MCI_RESP3 SD_REG(0x3C)
162 #define MCI_MASK_STATUS SD_REG(0x40) /* masked interrupt status */
163 #define MCI_RAW_STATUS SD_REG(0x44) /* raw interrupt status, also used as
164 * status clear */
166 /* interrupt bits */ /* C D E (Cmd) (Data) (End) */
167 #define MCI_INT_CRDDET (1<<0) /* card detect */
168 #define MCI_INT_RE (1<<1) /* x response error */
169 #define MCI_INT_CD (1<<2) /* x command done */
170 #define MCI_INT_DTO (1<<3) /* x data transfer over */
171 #define MCI_INT_TXDR (1<<4) /* tx fifo data request */
172 #define MCI_INT_RXDR (1<<5) /* rx fifo data request */
173 #define MCI_INT_RCRC (1<<6) /* x response crc error */
174 #define MCI_INT_DCRC (1<<7) /* x data crc error */
175 #define MCI_INT_RTO (1<<8) /* x response timeout */
176 #define MCI_INT_DRTO (1<<9) /* x data read timeout */
177 #define MCI_INT_HTO (1<<10) /* x data starv timeout */
178 #define MCI_INT_FRUN (1<<11) /* x fifo over/underrun */
179 #define MCI_INT_HLE (1<<12) /* x x hw locked while error */
180 #define MCI_INT_SBE (1<<13) /* x start bit error */
181 #define MCI_INT_ACD (1<<14) /* auto command done */
182 #define MCI_INT_EBE (1<<15) /* x end bit error */
183 #define MCI_INT_SDIO (0xf<<16)
186 * STATUS register
187 * & 0xBA80 = MCI_INT_DCRC | MCI_INT_DRTO | MCI_INT_FRUN | \
188 * MCI_INT_HLE | MCI_INT_SBE | MCI_INT_EBE
189 * & 8 = MCI_INT_DTO
190 * & 0x428 = MCI_INT_DTO | MCI_INT_RXDR | MCI_INT_HTO
191 * & 0x418 = MCI_INT_DTO | MCI_INT_TXDR | MCI_INT_HTO
194 #define MCI_CMD_ERROR \
195 (MCI_INT_RE | \
196 MCI_INT_RCRC | \
197 MCI_INT_RTO | \
198 MCI_INT_HLE)
200 #define MCI_DATA_ERROR \
201 ( MCI_INT_DCRC | \
202 MCI_INT_DRTO | \
203 MCI_INT_HTO | \
204 MCI_INT_FRUN | \
205 MCI_INT_HLE | \
206 MCI_INT_SBE | \
207 MCI_INT_EBE)
209 #define MCI_STATUS SD_REG(0x48)
211 #define FIFO_RX_WM (1<<0)
212 #define FIFO_TX_WM (1<<1)
213 #define FIFO_EMPTY (1<<2)
214 #define FIFO_FULL (1<<3)
215 #define CMD_FSM_STATE_B0 (1<<4)
216 #define CMD_FSM_STATE_B1 (1<<5)
217 #define CMD_FSM_STATE_B2 (1<<6)
218 #define CMD_FSM_STATE_B3 (1<<7)
219 #define DATA_3_STAT (1<<8)
220 #define DATA_BUSY (1<<9)
221 #define DATA_STAT_MC_BUSY (1<<10)
222 #define RESP_IDX_B0 (1<<11)
223 #define RESP_IDX_B1 (1<<12)
224 #define RESP_IDX_B2 (1<<13)
225 #define RESP_IDX_B3 (1<<14)
226 #define RESP_IDX_B4 (1<<15)
227 #define RESP_IDX_B5 (1<<16)
228 #define FIFO_CNT_B00 (1<<17)
229 #define FIFO_CNT_B01 (1<<18)
230 #define FIFO_CNT_B02 (1<<19)
231 #define FIFO_CNT_B03 (1<<20)
232 #define FIFO_CNT_B04 (1<<21)
233 #define FIFO_CNT_B05 (1<<22)
234 #define FIFO_CNT_B06 (1<<23)
235 #define FIFO_CNT_B07 (1<<24)
236 #define FIFO_CNT_B08 (1<<25)
237 #define FIFO_CNT_B09 (1<<26)
238 #define FIFO_CNT_B10 (1<<27)
239 #define FIFO_CNT_B11 (1<<28)
240 #define FIFO_CNT_B12 (1<<29)
241 #define DMA_ACK (1<<30)
242 #define START_CMD (1<<31)
244 #define MCI_FIFOTH SD_REG(0x4C) /* FIFO threshold */
245 /* TX watermark : bits 11:0
246 * RX watermark : bits 27:16
247 * DMA MTRANS SIZE : bits 30:28
248 * bits 31, 15:12 : unused
250 #define MCI_FIFOTH_MASK 0x8000f000
252 #define MCI_CDETECT SD_REG(0x50) /* card detect */
254 #define CDETECT_CRD_0 (1<<0)
255 #define CDETECT_CRD_1 (1<<1)
256 #define CDETECT_CRD_2 (1<<2)
257 #define CDETECT_CRD_3 (1<<3)
259 #define MCI_WRTPRT SD_REG(0x54) /* write protect */
260 #define MCI_GPIO SD_REG(0x58)
261 #define MCI_TCBCNT SD_REG(0x5C) /* transferred CIU byte count (card)*/
262 #define MCI_TBBCNT SD_REG(0x60) /* transferred host/DMA to/from bytes (FIFO)*/
263 #define MCI_DEBNCE SD_REG(0x64) /* card detect debounce bits 23:0*/
264 #define MCI_USRID SD_REG(0x68) /* user id */
265 #define MCI_VERID SD_REG(0x6C) /* version id */
267 #define MCI_HCON SD_REG(0x70) /* hardware config */
268 /* bit 0 : card type
269 * bits 5:1 : maximum card index
270 * bit 6 : BUS TYPE
271 * bits 9:7 : DATA WIDTH
272 * bits 15:10 : ADDR WIDTH
273 * bits 17:16 : DMA IF
274 * bits 20:18 : DMA WIDTH
275 * bit 21 : FIFO RAM INSIDE
276 * bit 22 : IMPL HOLD REG
277 * bit 23 : SET CLK FALSE
278 * bits 25:24 : MAX CLK DIV IDX
279 * bit 26 : AREA OPTIM
282 #define MCI_BMOD SD_REG(0x80) /* bus mode */
283 /* bit 0 : SWR
284 * bit 1 : FB
285 * bits 6:2 : DSL
286 * bit 7 : DE
287 * bit 10:8 : PBL
290 #define MCI_PLDMND SD_REG(0x84) /* poll demand */
291 #define MCI_DBADDR SD_REG(0x88) /* descriptor base address */
292 #define MCI_IDSTS SD_REG(0x8C) /* internal DMAC status */
293 /* bit 0 : TI
294 * bit 1 : RI
295 * bit 2 : FBE
296 * bit 3 : unused
297 * bit 4 : DU
298 * bit 5 : CES
299 * bits 7:6 : unused
300 * bits 8 : NIS
301 * bit 9 : AIS
302 * bits 12:10 : EB
303 * bits 16:13 : FSM
306 #define MCI_IDINTEN SD_REG(0x90) /* internal DMAC interrupt enable */
307 /* bit 0 : TI
308 * bit 1 : RI
309 * bit 2 : FBE
310 * bit 3 : unused
311 * bit 4 : DU
312 * bit 5 : CES
313 * bits 7:6 : unused
314 * bits 8 : NI
315 * bit 9 : AI
317 #define MCI_DSCADDR SD_REG(0x94) /* current host descriptor address */
318 #define MCI_BUFADDR SD_REG(0x98) /* current host buffer address */
320 #define MCI_FIFO ((unsigned long *) (SD_BASE+0x100))
322 #define UNALIGNED_NUM_SECTORS 10
323 static unsigned char aligned_buffer[UNALIGNED_NUM_SECTORS* SD_BLOCK_SIZE] __attribute__((aligned(32))); /* align on cache line size */
324 static unsigned char *uncached_buffer = UNCACHED_ADDR(&aligned_buffer[0]);
326 static void init_controller(void);
327 static int sd_wait_for_state(const int drive, unsigned int state);
329 static tCardInfo card_info[NUM_DRIVES];
331 /* for compatibility */
332 static long last_disk_activity = -1;
334 #define MIN_YIELD_PERIOD 5 /* ticks */
335 static long next_yield = 0;
337 static long sd_stack [(DEFAULT_STACK_SIZE*2 + 0x200)/sizeof(long)];
338 static const char sd_thread_name[] = "ata/sd";
339 static struct mutex sd_mtx SHAREDBSS_ATTR;
340 static struct event_queue sd_queue;
341 #ifndef BOOTLOADER
342 bool sd_enabled = false;
343 #endif
345 static struct wakeup transfer_completion_signal;
346 static struct wakeup command_completion_signal;
347 static volatile bool retry;
348 static volatile int cmd_error;
350 #if defined(HAVE_MULTIDRIVE)
351 int active_card = 0;
352 #define EXT_SD_BITS (1<<2)
353 #endif
355 static inline void mci_delay(void) { udelay(1000); }
357 void INT_NAND(void)
359 MCI_CTRL &= ~INT_ENABLE;
360 /* use raw status here as we need to check some Ints that are masked */
361 const int status = MCI_RAW_STATUS;
363 MCI_RAW_STATUS = status; /* clear status */
365 if(status & MCI_DATA_ERROR)
366 retry = true;
368 if( status & (MCI_INT_DTO|MCI_DATA_ERROR))
369 wakeup_signal(&transfer_completion_signal);
371 cmd_error = status & MCI_CMD_ERROR;
373 if(status & MCI_INT_CD)
374 wakeup_signal(&command_completion_signal);
376 MCI_CTRL |= INT_ENABLE;
379 static inline bool card_detect_target(void)
381 #if defined(HAVE_MULTIDRIVE)
382 #if defined(SANSA_FUZEV2)
383 return GPIOA_PIN(2);
384 #elif defined(SANSA_CLIPPLUS)
385 return !(GPIOA_PIN(2));
386 #else
387 #error "microSD pin not defined for your target"
388 #endif
389 #else
390 return false;
391 #endif
394 static bool send_cmd(const int drive, const int cmd, const int arg, const int flags,
395 unsigned long *response)
397 #if defined(HAVE_MULTIDRIVE)
398 /* Check to see if we need to switch cards */
399 if(sd_present(SD_SLOT_AS3525))
400 if(active_card != drive)
402 GPIOB_PIN(5) = (1-drive) << 5;
403 active_card = drive;
405 #endif
407 /* RCRC & RTO interrupts should be set together with the CD interrupt but
408 * in practice sometimes incorrectly precede the CD interrupt. If we leave
409 * them masked for now we can check them in the isr by reading raw status when
410 * the CD int is triggered.
412 MCI_MASK |= MCI_INT_CD;
413 MCI_ARGUMENT = arg;
415 /* Construct MCI_COMMAND */
416 MCI_COMMAND =
417 /*b5:0*/ cmd
418 /*b6 */ | ((flags & MCI_RESP) ? CMD_RESP_EXP_BIT: 0)
419 /*b7 */ | ((flags & MCI_LONG_RESP) ? CMD_RESP_LENGTH_BIT: 0)
420 /*b8 | CMD_CHECK_CRC_BIT unused */
421 /*b9 */ | (TRANSFER_CMD ? CMD_DATA_EXP_BIT: 0)
422 /*b10 */ | ((cmd == SD_WRITE_MULTIPLE_BLOCK) ? CMD_RW_BIT: 0)
423 /*b11 | CMD_TRANSMODE_BIT unused */
424 /*b12 | CMD_SENT_AUTO_STOP_BIT unused */
425 /*b13 */ | (TRANSFER_CMD ? CMD_WAIT_PRV_DAT_BIT: 0)
426 /*b14 | CMD_ABRT_CMD_BIT unused */
427 /*b15 | CMD_SEND_INIT_BIT unused */
428 /*b20:16 */ | CMD_CARD_NO(drive)
429 /*b21 | CMD_SEND_CLK_ONLY unused */
430 /*b22 | CMD_READ_CEATA unused */
431 /*b23 | CMD_CCS_EXPECTED unused */
432 /*b31 */ | CMD_DONE_BIT;
434 wakeup_wait(&command_completion_signal, TIMEOUT_BLOCK);
436 MCI_MASK &= ~MCI_INT_CD;
438 /* Handle command responses & errors */
439 if(flags & MCI_RESP)
441 if(cmd_error & (MCI_INT_RCRC | MCI_INT_RTO))
442 return false;
444 if(flags & MCI_LONG_RESP)
446 response[0] = MCI_RESP3;
447 response[1] = MCI_RESP2;
448 response[2] = MCI_RESP1;
449 response[3] = MCI_RESP0;
451 else
452 response[0] = MCI_RESP0;
454 return true;
457 static int sd_init_card(const int drive)
459 unsigned long response;
460 long init_timeout;
461 bool sd_v2 = false;
463 /* assume 24 MHz clock / 60 = 400 kHz */
464 MCI_CLKDIV = (MCI_CLKDIV & ~(0xFF)) | 0x3C; /* CLK_DIV_0 : bits 7:0 */
466 /* 100 - 400kHz clock required for Identification Mode */
467 /* Start of Card Identification Mode ************************************/
469 /* CMD0 Go Idle */
470 if(!send_cmd(drive, SD_GO_IDLE_STATE, 0, MCI_NO_RESP, NULL))
471 return -1;
472 mci_delay();
474 /* CMD8 Check for v2 sd card. Must be sent before using ACMD41
475 Non v2 cards will not respond to this command*/
476 if(send_cmd(drive, SD_SEND_IF_COND, 0x1AA, MCI_RESP, &response))
477 if((response & 0xFFF) == 0x1AA)
478 sd_v2 = true;
480 /* timeout for initialization is 1sec, from SD Specification 2.00 */
481 init_timeout = current_tick + HZ;
483 do {
484 /* this timeout is the only valid error for this loop*/
485 if(TIME_AFTER(current_tick, init_timeout))
486 return -2;
488 /* app_cmd */
489 send_cmd(drive, SD_APP_CMD, 0, MCI_RESP, &response);
491 /* ACMD41 For v2 cards set HCS bit[30] & send host voltage range to all */
492 if(!send_cmd(drive, SD_APP_OP_COND, (0x00FF8000 | (sd_v2 ? 1<<30 : 0)),
493 MCI_RESP, &card_info[drive].ocr))
494 return -3;
495 } while(!(card_info[drive].ocr & (1<<31)) );
497 /* CMD2 send CID */
498 if(!send_cmd(drive, SD_ALL_SEND_CID, 0, MCI_RESP|MCI_LONG_RESP, card_info[drive].cid))
499 return -4;
501 /* CMD3 send RCA */
502 if(!send_cmd(drive, SD_SEND_RELATIVE_ADDR, 0, MCI_RESP, &card_info[drive].rca))
503 return -5;
505 #ifdef HAVE_MULTIDRIVE
506 /* Make sure we have 2 unique rca numbers */
507 if(card_info[INTERNAL_AS3525].rca == card_info[SD_SLOT_AS3525].rca)
508 if(!send_cmd(drive, SD_SEND_RELATIVE_ADDR, 0, MCI_RESP, &card_info[drive].rca))
509 return -6;
510 #endif
511 /* End of Card Identification Mode ************************************/
513 /* Attempt to switch cards to HS timings, non HS cards just ignore this */
514 /* CMD7 w/rca: Select card to put it in TRAN state */
515 if(!send_cmd(drive, SD_SELECT_CARD, card_info[drive].rca, MCI_NO_RESP, NULL))
516 return -7;
518 if(sd_wait_for_state(drive, SD_TRAN))
519 return -8;
521 /* CMD6 */
522 if(!send_cmd(drive, SD_SWITCH_FUNC, 0x80fffff1, MCI_NO_RESP, NULL))
523 return -9;
524 mci_delay();
526 /* We need to go back to STBY state now so we can read csd */
527 /* CMD7 w/rca=0: Deselect card to put it in STBY state */
528 if(!send_cmd(drive, SD_DESELECT_CARD, 0, MCI_NO_RESP, NULL))
529 return -10;
531 /* CMD9 send CSD */
532 if(!send_cmd(drive, SD_SEND_CSD, card_info[drive].rca,
533 MCI_RESP|MCI_LONG_RESP, card_info[drive].csd))
534 return -11;
536 sd_parse_csd(&card_info[drive]);
538 if(drive == INTERNAL_AS3525) /* The OF is stored in the first blocks */
539 card_info[INTERNAL_AS3525].numblocks -= AMS_OF_SIZE;
541 /* Card back to full speed */
542 MCI_CLKDIV &= ~(0xFF); /* CLK_DIV_0 : bits 7:0 = 0x00 */
544 /* CMD7 w/rca: Select card to put it in TRAN state */
545 if(!send_cmd(drive, SD_SELECT_CARD, card_info[drive].rca, MCI_NO_RESP, NULL))
546 return -12;
548 #ifndef BOOTLOADER
549 /* Switch to to 4 bit widebus mode */
550 if(sd_wait_for_state(drive, SD_TRAN) < 0)
551 return -13;
552 /* CMD55 */ /* Response is requested due to timing issue */
553 if(!send_cmd(drive, SD_APP_CMD, card_info[drive].rca, MCI_RESP, &response))
554 return -14;
555 /* ACMD6 */
556 if(!send_cmd(drive, SD_SET_BUS_WIDTH, 2, MCI_NO_RESP, NULL))
557 return -15;
558 mci_delay();
559 /* CMD55 */ /* Response is requested due to timing issue */
560 if(!send_cmd(drive, SD_APP_CMD, card_info[drive].rca, MCI_RESP, &response))
561 return -16;
562 /* ACMD42 */
563 if(!send_cmd(drive, SD_SET_CLR_CARD_DETECT, 0, MCI_NO_RESP, NULL))
564 return -17;
565 /* Now that card is widebus make controller aware */
566 MCI_CTYPE |= (1<<drive);
567 #endif
569 card_info[drive].initialized = 1;
571 MCI_CLKENA |= 1<<(drive + 16); /* Set low power mode */
573 return 0;
576 static void sd_thread(void) __attribute__((noreturn));
577 static void sd_thread(void)
579 struct queue_event ev;
580 bool idle_notified = false;
582 while (1)
584 queue_wait_w_tmo(&sd_queue, &ev, HZ);
586 switch ( ev.id )
588 #ifdef HAVE_HOTSWAP
589 case SYS_HOTSWAP_INSERTED:
590 case SYS_HOTSWAP_EXTRACTED:
592 int microsd_init = 1;
593 fat_lock(); /* lock-out FAT activity first -
594 prevent deadlocking via disk_mount that
595 would cause a reverse-order attempt with
596 another thread */
597 mutex_lock(&sd_mtx); /* lock-out card activity - direct calls
598 into driver that bypass the fat cache */
600 /* We now have exclusive control of fat cache and ata */
602 disk_unmount(SD_SLOT_AS3525); /* release "by force", ensure file
603 descriptors aren't leaked and any busy
604 ones are invalid if mounting */
605 /* Force card init for new card, re-init for re-inserted one or
606 * clear if the last attempt to init failed with an error. */
607 card_info[SD_SLOT_AS3525].initialized = 0;
609 if (ev.id == SYS_HOTSWAP_INSERTED)
611 sd_enable(true);
612 microsd_init = sd_init_card(SD_SLOT_AS3525);
613 if (microsd_init < 0) /* initialisation failed */
614 panicf("microSD init failed : %d", microsd_init);
616 microsd_init = disk_mount(SD_SLOT_AS3525); /* 0 if fail */
620 * Mount succeeded, or this was an EXTRACTED event,
621 * in both cases notify the system about the changed filesystems
623 if (microsd_init)
624 queue_broadcast(SYS_FS_CHANGED, 0);
625 /* Access is now safe */
626 mutex_unlock(&sd_mtx);
627 fat_unlock();
628 sd_enable(false);
630 break;
631 #endif
632 case SYS_TIMEOUT:
633 if (TIME_BEFORE(current_tick, last_disk_activity+(3*HZ)))
635 idle_notified = false;
637 else
639 /* never let a timer wrap confuse us */
640 next_yield = current_tick;
642 if (!idle_notified)
644 call_storage_idle_notifys(false);
645 idle_notified = true;
648 break;
650 case SYS_USB_CONNECTED:
651 usb_acknowledge(SYS_USB_CONNECTED_ACK);
652 /* Wait until the USB cable is extracted again */
653 usb_wait_for_disconnect(&sd_queue);
655 break;
656 case SYS_USB_DISCONNECTED:
657 usb_acknowledge(SYS_USB_DISCONNECTED_ACK);
658 break;
663 static void init_controller(void)
665 int hcon_numcards = ((MCI_HCON>>1) & 0x1F) + 1;
666 int card_mask = (1 << hcon_numcards) - 1;
668 MCI_PWREN &= ~card_mask; /* power off all cards */
670 MCI_CLKSRC = 0x00; /* All CLK_SRC_CRD set to 0*/
671 MCI_CLKDIV = 0x00; /* CLK_DIV_0 : bits 7:0 */
673 MCI_PWREN |= card_mask; /* power up cards */
674 mci_delay();
676 MCI_CTRL |= CTRL_RESET;
677 while(MCI_CTRL & CTRL_RESET)
680 MCI_RAW_STATUS = 0xffffffff; /* Clear all MCI Interrupts */
682 MCI_TMOUT = 0xffffffff; /* data b31:8, response b7:0 */
684 MCI_CTYPE = 0x0; /* all cards 1 bit bus for now */
686 MCI_CLKENA = card_mask; /* Enables card clocks */
688 MCI_ARGUMENT = 0;
689 MCI_COMMAND = CMD_DONE_BIT|CMD_SEND_CLK_ONLY|CMD_WAIT_PRV_DAT_BIT;
690 while(MCI_COMMAND & CMD_DONE_BIT)
693 MCI_DEBNCE = 0xfffff; /* default value */
695 /* Rx watermark = 63(sd reads) Tx watermark = 128 (sd writes) */
696 MCI_FIFOTH = (MCI_FIFOTH & MCI_FIFOTH_MASK) | 0x503f0080;
698 GPIOB_DIR |= (1<<5); /* Set pin B5 to output */
700 /* Mask all MCI Interrupts initially */
701 MCI_MASK = 0;
703 MCI_CTRL |= INT_ENABLE;
706 int sd_init(void)
708 int ret;
710 CGU_PERI |= CGU_MCI_CLOCK_ENABLE;
712 CGU_IDE = (1<<7) /* AHB interface enable */
713 | (AS3525_IDE_DIV << 2)
714 | 1; /* clock source = PLLA */
716 CGU_MEMSTICK = (1<<7) /* interface enable */
717 | (AS3525_MS_DIV << 2)
718 | 1; /* clock source = PLLA */
720 CGU_SDSLOT = (1<<7) /* interface enable */
721 | (AS3525_SDSLOT_DIV << 2)
722 | 1; /* clock source = PLLA */
724 wakeup_init(&transfer_completion_signal);
725 wakeup_init(&command_completion_signal);
726 #ifdef HAVE_MULTIDRIVE
727 /* clear previous irq */
728 GPIOA_IC = EXT_SD_BITS;
729 /* enable edge detecting */
730 GPIOA_IS &= ~EXT_SD_BITS;
731 /* detect both raising and falling edges */
732 GPIOA_IBE |= EXT_SD_BITS;
733 /* Configure XPD for SD-MCI interface */
734 CCU_IO |= (1<<2);
735 #endif
737 VIC_INT_ENABLE = INTERRUPT_NAND;
739 init_controller();
740 ret = sd_init_card(INTERNAL_AS3525);
741 if(ret < 0)
742 return ret;
744 /* init mutex */
745 mutex_init(&sd_mtx);
747 queue_init(&sd_queue, true);
748 create_thread(sd_thread, sd_stack, sizeof(sd_stack), 0,
749 sd_thread_name IF_PRIO(, PRIORITY_USER_INTERFACE) IF_COP(, CPU));
751 #ifndef BOOTLOADER
752 sd_enabled = true;
753 sd_enable(false);
754 #endif
755 return 0;
758 static int sd_wait_for_state(const int drive, unsigned int state)
760 unsigned long response;
761 unsigned int timeout = 100; /* ticks */
762 long t = current_tick;
764 while (1)
766 long tick;
768 while(!(send_cmd(drive, SD_SEND_STATUS, card_info[drive].rca, MCI_RESP, &response)));
770 if (((response >> 9) & 0xf) == state)
771 return 0;
773 if(TIME_AFTER(current_tick, t + timeout))
774 return -10 * ((response >> 9) & 0xf);
776 if (TIME_AFTER((tick = current_tick), next_yield))
778 yield();
779 timeout += current_tick - tick;
780 next_yield = tick + MIN_YIELD_PERIOD;
785 static int sd_transfer_sectors(IF_MD2(int drive,) unsigned long start,
786 int count, void* buf, bool write)
788 int ret = 0;
789 #ifndef HAVE_MULTIDRIVE
790 const int drive = 0;
791 #endif
793 /* skip SanDisk OF */
794 if (drive == INTERNAL_AS3525)
795 start += AMS_OF_SIZE;
797 mutex_lock(&sd_mtx);
798 #ifndef BOOTLOADER
799 sd_enable(true);
800 led(true);
801 #endif
803 if (card_info[drive].initialized <= 0)
805 ret = sd_init_card(drive);
806 if (!(card_info[drive].initialized))
808 panicf("card not initialised (%d)", ret);
809 goto sd_transfer_error;
813 if((start+count) > card_info[drive].numblocks)
815 ret = -18;
816 goto sd_transfer_error;
819 /* CMD7 w/rca: Select card to put it in TRAN state */
820 if(!send_cmd(drive, SD_SELECT_CARD, card_info[drive].rca, MCI_NO_RESP, NULL))
821 return -19;
823 last_disk_activity = current_tick;
824 dma_retain();
826 const int cmd = write ? SD_WRITE_MULTIPLE_BLOCK : SD_READ_MULTIPLE_BLOCK;
830 void *dma_buf = aligned_buffer;
831 unsigned int transfer = count;
832 if(transfer > UNALIGNED_NUM_SECTORS)
833 transfer = UNALIGNED_NUM_SECTORS;
835 if(write)
836 memcpy(uncached_buffer, buf, transfer * SD_BLOCK_SIZE);
838 /* Interrupt handler might set this to true during transfer */
839 retry = false;
841 MCI_BLKSIZ = SD_BLOCK_SIZE;
842 MCI_BYTCNT = transfer * SD_BLOCK_SIZE;
844 ret = sd_wait_for_state(drive, SD_TRAN);
845 if (ret < 0)
847 static const char *st[9] = {
848 "IDLE", "RDY", "IDENT", "STBY", "TRAN", "DATA", "RCV",
849 "PRG", "DIS"};
850 if(ret <= -10)
851 panicf("wait for TRAN state failed (%s) %d",
852 st[(-ret / 10) % 9], drive);
853 else
854 panicf("wait for state failed");
855 goto sd_transfer_error;
858 int arg = start;
859 if(!(card_info[drive].ocr & (1<<30))) /* not SDHC */
860 arg *= SD_BLOCK_SIZE;
862 if(write)
863 dma_enable_channel(0, dma_buf, MCI_FIFO, DMA_PERI_SD,
864 DMAC_FLOWCTRL_PERI_MEM_TO_PERI, true, false, 0, DMA_S8, NULL);
865 else
866 dma_enable_channel(0, MCI_FIFO, dma_buf, DMA_PERI_SD,
867 DMAC_FLOWCTRL_PERI_PERI_TO_MEM, false, true, 0, DMA_S8, NULL);
869 MCI_MASK |= (MCI_DATA_ERROR | MCI_INT_DTO);
870 MCI_CTRL |= DMA_ENABLE;
872 unsigned long dummy; /* if we don't ask for a response, writing fails */
873 if(!send_cmd(drive, cmd, arg, MCI_RESP, &dummy))
874 panicf("%s multiple blocks failed", write ? "write" : "read");
876 wakeup_wait(&transfer_completion_signal, TIMEOUT_BLOCK);
878 MCI_MASK &= ~(MCI_DATA_ERROR | MCI_INT_DTO);
880 last_disk_activity = current_tick;
882 if(!send_cmd(drive, SD_STOP_TRANSMISSION, 0, MCI_NO_RESP, NULL))
884 ret = -666;
885 panicf("STOP TRANSMISSION failed");
886 goto sd_transfer_error;
889 if(!retry)
891 if(!write)
892 memcpy(buf, uncached_buffer, transfer * SD_BLOCK_SIZE);
893 buf += transfer * SD_BLOCK_SIZE;
894 start += transfer;
895 count -= transfer;
897 else /* reset controller if we had an error */
899 MCI_CTRL |= (FIFO_RESET|DMA_RESET);
900 while(MCI_CTRL & (FIFO_RESET|DMA_RESET))
904 } while(retry || count);
906 dma_release();
908 /* CMD lines are separate, not common, so we need to actively deselect */
909 /* CMD7 w/rca =0 : deselects card & puts it in STBY state */
910 if(!send_cmd(drive, SD_DESELECT_CARD, 0, MCI_NO_RESP, NULL))
911 return -20;
913 #ifndef BOOTLOADER
914 sd_enable(false);
915 led(false);
916 #endif
917 mutex_unlock(&sd_mtx);
918 return 0;
920 sd_transfer_error:
921 panicf("transfer error : %d",ret);
922 card_info[drive].initialized = 0;
923 return ret;
926 int sd_read_sectors(IF_MD2(int drive,) unsigned long start, int count,
927 void* buf)
929 return sd_transfer_sectors(IF_MD2(drive,) start, count, buf, false);
932 int sd_write_sectors(IF_MD2(int drive,) unsigned long start, int count,
933 const void* buf)
935 #if defined(BOOTLOADER) /* we don't need write support in bootloader */
936 #ifdef HAVE_MULTIDRIVE
937 (void) drive;
938 #endif
939 (void) start;
940 (void) count;
941 (void) buf;
942 return -1;
943 #else
944 return sd_transfer_sectors(IF_MD2(drive,) start, count, (void*)buf, true);
945 #endif /* defined(BOOTLOADER) */
948 #ifndef BOOTLOADER
949 long sd_last_disk_activity(void)
951 return last_disk_activity;
954 void sd_enable(bool on)
956 /* TODO */
957 (void) on;
960 tCardInfo *card_get_info_target(int card_no)
962 return &card_info[card_no];
964 #endif /* BOOTLOADER */
966 #ifdef HAVE_HOTSWAP
967 bool sd_removable(IF_MD_NONVOID(int drive))
969 return (drive==1);
972 bool sd_present(IF_MD_NONVOID(int drive))
974 return (drive == 0) ? true : card_detect_target();
977 static int sd1_oneshot_callback(struct timeout *tmo)
979 (void)tmo;
981 /* This is called only if the state was stable for 300ms - check state
982 * and post appropriate event. */
983 if (card_detect_target())
985 queue_broadcast(SYS_HOTSWAP_INSERTED, 0);
987 else
988 queue_broadcast(SYS_HOTSWAP_EXTRACTED, 0);
990 return 0;
993 void sd_gpioa_isr(void)
995 static struct timeout sd1_oneshot;
996 if (GPIOA_MIS & EXT_SD_BITS)
997 timeout_register(&sd1_oneshot, sd1_oneshot_callback, (3*HZ/10), 0);
998 /* acknowledge interrupt */
999 GPIOA_IC = EXT_SD_BITS;
1002 void card_enable_monitoring_target(bool on)
1004 if (on) /* enable interrupt */
1005 GPIOA_IE |= EXT_SD_BITS;
1006 else /* disable interrupt */
1007 GPIOA_IE &= ~EXT_SD_BITS;
1009 #endif /* HAVE_HOTSWAP */
1011 #ifdef CONFIG_STORAGE_MULTI
1012 int sd_num_drives(int first_drive)
1014 /* We don't care which logical drive number(s) we have been assigned */
1015 (void)first_drive;
1017 return NUM_DRIVES;
1019 #endif /* CONFIG_STORAGE_MULTI */