These changes are the raw update to qemu-2.6.
[kvmfornfv.git] / qemu / roms / seabios / src / hw / sdcard.c
1 // PCI SD Host Controller Interface
2 //
3 // Copyright (C) 2014  Kevin O'Connor <kevin@koconnor.net>
4 //
5 // This file may be distributed under the terms of the GNU LGPLv3 license.
6
7 #include "block.h" // struct drive_s
8 #include "malloc.h" // malloc_fseg
9 #include "output.h" // znprintf
10 #include "pci.h" // pci_config_readl
11 #include "pci_ids.h" // PCI_CLASS_SYSTEM_SDHCI
12 #include "pci_regs.h" // PCI_BASE_ADDRESS_0
13 #include "romfile.h" // romfile_findprefix
14 #include "stacks.h" // wait_preempt
15 #include "std/disk.h" // DISK_RET_SUCCESS
16 #include "string.h" // memset
17 #include "util.h" // boot_add_hd
18 #include "x86.h" // writel
19
20 // SDHCI MMIO registers
21 struct sdhci_s {
22     u32 sdma_addr;
23     u16 block_size;
24     u16 block_count;
25     u32 arg;
26     u16 transfer_mode;
27     u16 cmd;
28     u32 response[4];
29     u32 data;
30     u32 present_state;
31     u8 host_control;
32     u8 power_control;
33     u8 block_gap_control;
34     u8 wakeup_control;
35     u16 clock_control;
36     u8 timeout_control;
37     u8 software_reset;
38     u16 irq_status;
39     u16 error_irq_status;
40     u16 irq_enable;
41     u16 error_irq_enable;
42     u16 irq_signal;
43     u16 error_signal;
44     u16 auto_cmd12;
45     u16 host_control2;
46     u32 cap_lo, cap_hi;
47     u64 max_current;
48     u16 force_auto_cmd12;
49     u16 force_error;
50     u8 adma_error;
51     u8 pad_55[3];
52     u64 adma_addr;
53     u8 pad_60[156];
54     u16 slot_irq;
55     u16 controller_version;
56 } PACKED;
57
58 // SDHCI commands
59 #define SCB_R0   0x00 // No response
60 #define SCB_R48  0x1a // Response R1 (no data), R5, R6, R7
61 #define SCB_R48d 0x3a // Response R1 (with data)
62 #define SCB_R48b 0x1b // Response R1b, R5b
63 #define SCB_R48o 0x02 // Response R3, R4
64 #define SCB_R136 0x09 // Response R2
65 #define SC_GO_IDLE_STATE        ((0<<8) | SCB_R0)
66 #define SC_SEND_OP_COND         ((1<<8) | SCB_R48o)
67 #define SC_ALL_SEND_CID         ((2<<8) | SCB_R136)
68 #define SC_SEND_RELATIVE_ADDR   ((3<<8) | SCB_R48)
69 #define SC_SELECT_DESELECT_CARD ((7<<8) | SCB_R48b)
70 #define SC_SEND_IF_COND         ((8<<8) | SCB_R48)
71 #define SC_SEND_EXT_CSD         ((8<<8) | SCB_R48d)
72 #define SC_SEND_CSD             ((9<<8) | SCB_R136)
73 #define SC_READ_SINGLE          ((17<<8) | SCB_R48d)
74 #define SC_READ_MULTIPLE        ((18<<8) | SCB_R48d)
75 #define SC_WRITE_SINGLE         ((24<<8) | SCB_R48d)
76 #define SC_WRITE_MULTIPLE       ((25<<8) | SCB_R48d)
77 #define SC_APP_CMD              ((55<<8) | SCB_R48)
78 #define SC_APP_SEND_OP_COND ((41<<8) | SCB_R48o)
79
80 // SDHCI irqs
81 #define SI_CMD_COMPLETE (1<<0)
82 #define SI_TRANS_DONE   (1<<1)
83 #define SI_WRITE_READY  (1<<4)
84 #define SI_READ_READY   (1<<5)
85 #define SI_ERROR        (1<<15)
86
87 // SDHCI present_state flags
88 #define SP_CMD_INHIBIT   (1<<0)
89 #define SP_DAT_INHIBIT   (1<<1)
90 #define SP_CARD_INSERTED (1<<16)
91
92 // SDHCI transfer_mode flags
93 #define ST_BLOCKCOUNT (1<<1)
94 #define ST_AUTO_CMD12 (1<<2)
95 #define ST_READ       (1<<4)
96 #define ST_MULTIPLE   (1<<5)
97
98 // SDHCI capabilities flags
99 #define SD_CAPLO_V33             (1<<24)
100 #define SD_CAPLO_V30             (1<<25)
101 #define SD_CAPLO_V18             (1<<26)
102 #define SD_CAPLO_BASECLOCK_SHIFT 8
103 #define SD_CAPLO_BASECLOCK_MASK  0xff
104
105 // SDHCI clock control flags
106 #define SCC_INTERNAL_ENABLE (1<<0)
107 #define SCC_STABLE          (1<<1)
108 #define SCC_CLOCK_ENABLE    (1<<2)
109 #define SCC_SDCLK_MASK      0xff
110 #define SCC_SDCLK_SHIFT     8
111 #define SCC_SDCLK_HI_MASK   0x300
112 #define SCC_SDCLK_HI_RSHIFT 2
113
114 // SDHCI power control flags
115 #define SPC_POWER_ON (1<<0)
116 #define SPC_V18      0x0a
117 #define SPC_V30      0x0c
118 #define SPC_V33      0x0e
119
120 // SDHCI software reset flags
121 #define SRF_ALL  0x01
122 #define SRF_CMD  0x02
123 #define SRF_DATA 0x04
124
125 // SDHCI result flags
126 #define SR_OCR_CCS     (1<<30)
127 #define SR_OCR_NOTBUSY (1<<31)
128
129 // SDHCI timeouts
130 #define SDHCI_POWER_OFF_TIME   1
131 #define SDHCI_POWER_ON_TIME    1
132 #define SDHCI_CLOCK_ON_TIME    1 // 74 clock cycles
133 #define SDHCI_POWERUP_TIMEOUT  1000
134 #define SDHCI_PIO_TIMEOUT      1000  // XXX - this is just made up
135
136 // Internal 'struct drive_s' storage for a detected card
137 struct sddrive_s {
138     struct drive_s drive;
139     struct sdhci_s *regs;
140     int card_type;
141 };
142
143 // SD card types
144 #define SF_MMC          (1<<0)
145 #define SF_HIGHCAPACITY (1<<1)
146
147 // Repeatedly read a u16 register until any bit in a given mask is set
148 static int
149 sdcard_waitw(u16 *reg, u16 mask)
150 {
151     u32 end = timer_calc(SDHCI_PIO_TIMEOUT);
152     for (;;) {
153         u16 v = readw(reg);
154         if (v & mask)
155             return v;
156         if (timer_check(end)) {
157             warn_timeout();
158             return -1;
159         }
160         yield();
161     }
162 }
163
164 // Send an sdhci reset
165 static int
166 sdcard_reset(struct sdhci_s *regs, int flags)
167 {
168     writeb(&regs->software_reset, flags);
169     u32 end = timer_calc(SDHCI_PIO_TIMEOUT);
170     while (readb(&regs->software_reset))
171         if (timer_check(end)) {
172             warn_timeout();
173             return -1;
174         }
175     return 0;
176 }
177
178 // Send a command to the card.
179 static int
180 sdcard_pio(struct sdhci_s *regs, int cmd, u32 *param)
181 {
182     u32 state = readl(&regs->present_state);
183     dprintf(9, "sdcard_pio cmd %x %x %x\n", cmd, *param, state);
184     if ((state & SP_CMD_INHIBIT)
185         || ((cmd & 0x03) == 0x03 && state & SP_DAT_INHIBIT)) {
186         dprintf(1, "sdcard_pio not ready %x\n", state);
187         return -1;
188     }
189     // Send command
190     writel(&regs->arg, *param);
191     writew(&regs->cmd, cmd);
192     int ret = sdcard_waitw(&regs->irq_status, SI_ERROR|SI_CMD_COMPLETE);
193     if (ret < 0)
194         return ret;
195     if (ret & SI_ERROR) {
196         u16 err = readw(&regs->error_irq_status);
197         dprintf(3, "sdcard_pio command stop (code=%x)\n", err);
198         sdcard_reset(regs, SRF_CMD|SRF_DATA);
199         writew(&regs->error_irq_status, err);
200         return -1;
201     }
202     writew(&regs->irq_status, SI_CMD_COMPLETE);
203     // Read response
204     memcpy(param, regs->response, sizeof(regs->response));
205     dprintf(9, "sdcard cmd %x response %x %x %x %x\n"
206             , cmd, param[0], param[1], param[2], param[3]);
207     return 0;
208 }
209
210 // Send an "app specific" command to the card.
211 static int
212 sdcard_pio_app(struct sdhci_s *regs, int cmd, u32 *param)
213 {
214     u32 aparam[4] = {};
215     int ret = sdcard_pio(regs, SC_APP_CMD, aparam);
216     if (ret)
217         return ret;
218     return sdcard_pio(regs, cmd, param);
219 }
220
221 // Send a command to the card which transfers data.
222 static int
223 sdcard_pio_transfer(struct sddrive_s *drive, int cmd, u32 addr
224                     , void *data, int count)
225 {
226     // Send command
227     writew(&drive->regs->block_size, DISK_SECTOR_SIZE);
228     writew(&drive->regs->block_count, count);
229     int isread = cmd != SC_WRITE_SINGLE && cmd != SC_WRITE_MULTIPLE;
230     u16 tmode = ((count > 1 ? ST_MULTIPLE|ST_AUTO_CMD12|ST_BLOCKCOUNT : 0)
231                  | (isread ? ST_READ : 0));
232     writew(&drive->regs->transfer_mode, tmode);
233     if (!(drive->card_type & SF_HIGHCAPACITY))
234         addr *= DISK_SECTOR_SIZE;
235     u32 param[4] = { addr };
236     int ret = sdcard_pio(drive->regs, cmd, param);
237     if (ret)
238         return ret;
239     // Read/write data
240     u16 cbit = isread ? SI_READ_READY : SI_WRITE_READY;
241     while (count--) {
242         ret = sdcard_waitw(&drive->regs->irq_status, cbit);
243         if (ret < 0)
244             return ret;
245         writew(&drive->regs->irq_status, cbit);
246         int i;
247         for (i=0; i<DISK_SECTOR_SIZE/4; i++) {
248             if (isread)
249                 *(u32*)data = readl(&drive->regs->data);
250             else
251                 writel(&drive->regs->data, *(u32*)data);
252             data += 4;
253         }
254     }
255     // Complete command
256     ret = sdcard_waitw(&drive->regs->irq_status, SI_TRANS_DONE);
257     if (ret < 0)
258         return ret;
259     writew(&drive->regs->irq_status, SI_TRANS_DONE);
260     return 0;
261 }
262
263 // Read/write a block of data to/from the card.
264 static int
265 sdcard_readwrite(struct disk_op_s *op, int iswrite)
266 {
267     struct sddrive_s *drive = container_of(
268         op->drive_gf, struct sddrive_s, drive);
269     int cmd = iswrite ? SC_WRITE_SINGLE : SC_READ_SINGLE;
270     if (op->count > 1)
271         cmd = iswrite ? SC_WRITE_MULTIPLE : SC_READ_MULTIPLE;
272     int ret = sdcard_pio_transfer(drive, cmd, op->lba, op->buf_fl, op->count);
273     if (ret)
274         return DISK_RET_EBADTRACK;
275     return DISK_RET_SUCCESS;
276 }
277
278 int
279 sdcard_process_op(struct disk_op_s *op)
280 {
281     if (!CONFIG_SDCARD)
282         return 0;
283     switch (op->command) {
284     case CMD_READ:
285         return sdcard_readwrite(op, 0);
286     case CMD_WRITE:
287         return sdcard_readwrite(op, 1);
288     default:
289         return default_process_op(op);
290     }
291 }
292
293
294 /****************************************************************
295  * Setup
296  ****************************************************************/
297
298 static int
299 sdcard_set_power(struct sdhci_s *regs)
300 {
301     u32 cap = readl(&regs->cap_lo);
302     u32 volt, vbits;
303     if (cap & SD_CAPLO_V33) {
304         volt = 1<<20;
305         vbits = SPC_V33;
306     } else if (cap & SD_CAPLO_V30) {
307         volt = 1<<18;
308         vbits = SPC_V30;
309     } else if (cap & SD_CAPLO_V18) {
310         volt = 1<<7;
311         vbits = SPC_V18;
312     } else {
313         dprintf(1, "SD controller unsupported volt range (%x)\n", cap);
314         return -1;
315     }
316     writeb(&regs->power_control, 0);
317     msleep(SDHCI_POWER_OFF_TIME);
318     writeb(&regs->power_control, vbits | SPC_POWER_ON);
319     msleep(SDHCI_POWER_ON_TIME);
320     return volt;
321 }
322
323 static int
324 sdcard_set_frequency(struct sdhci_s *regs, u32 khz)
325 {
326     u16 ver = readw(&regs->controller_version);
327     u32 cap = readl(&regs->cap_lo);
328     u32 base_freq = (cap >> SD_CAPLO_BASECLOCK_SHIFT) & SD_CAPLO_BASECLOCK_MASK;
329     if (!base_freq) {
330         dprintf(1, "Unknown base frequency for SD controller\n");
331         return -1;
332     }
333     // Set new frequency
334     u32 divisor = DIV_ROUND_UP(base_freq * 1000, khz);
335     u16 creg;
336     if ((ver & 0xff) <= 0x01) {
337         divisor = divisor > 1 ? 1 << __fls(divisor-1) : 0;
338         creg = (divisor & SCC_SDCLK_MASK) << SCC_SDCLK_SHIFT;
339     } else {
340         divisor = DIV_ROUND_UP(divisor, 2);
341         creg = (divisor & SCC_SDCLK_MASK) << SCC_SDCLK_SHIFT;
342         creg |= (divisor & SCC_SDCLK_HI_MASK) >> SCC_SDCLK_HI_RSHIFT;
343     }
344     dprintf(3, "sdcard_set_frequency %d %d %x\n", base_freq, khz, creg);
345     writew(&regs->clock_control, 0);
346     writew(&regs->clock_control, creg | SCC_INTERNAL_ENABLE);
347     // Wait for frequency to become active
348     int ret = sdcard_waitw(&regs->clock_control, SCC_STABLE);
349     if (ret < 0)
350         return ret;
351     // Enable SD clock
352     writew(&regs->clock_control, creg | SCC_INTERNAL_ENABLE | SCC_CLOCK_ENABLE);
353     return 0;
354 }
355
356 // Obtain the disk size of an SD card
357 static int
358 sdcard_get_capacity(struct sddrive_s *drive, u8 *csd)
359 {
360     // Original MMC/SD card capacity formula
361     u16 C_SIZE = (csd[6] >> 6) | (csd[7] << 2) | ((csd[8] & 0x03) << 10);
362     u8 C_SIZE_MULT = (csd[4] >> 7) | ((csd[5] & 0x03) << 1);
363     u8 READ_BL_LEN = csd[9] & 0x0f;
364     u32 count = (C_SIZE+1) << (C_SIZE_MULT + 2 + READ_BL_LEN - 9);
365     // Check for newer encoding formats.
366     u8 CSD_STRUCTURE = csd[14] >> 6;
367     if ((drive->card_type & SF_MMC) && CSD_STRUCTURE >= 2) {
368         // Get capacity from EXT_CSD register
369         u8 ext_csd[512];
370         int ret = sdcard_pio_transfer(drive, SC_SEND_EXT_CSD, 0, ext_csd, 1);
371         if (ret)
372             return ret;
373         count = *(u32*)&ext_csd[212];
374     } else if (!(drive->card_type & SF_MMC) && CSD_STRUCTURE >= 1) {
375         // High capacity SD card
376         u32 C_SIZE2 = csd[5] | (csd[6] << 8) | ((csd[7] & 0x3f) << 16);
377         count = (C_SIZE2+1) << (19-9);
378     }
379     // Fill drive struct and return
380     drive->drive.blksize = DISK_SECTOR_SIZE;
381     drive->drive.sectors = count;
382     return 0;
383 }
384
385 // Initialize an SD card
386 static int
387 sdcard_card_setup(struct sddrive_s *drive, int volt, int prio)
388 {
389     struct sdhci_s *regs = drive->regs;
390     // Set controller to initialization clock rate
391     int ret = sdcard_set_frequency(regs, 400);
392     if (ret)
393         return ret;
394     msleep(SDHCI_CLOCK_ON_TIME);
395     // Reset card
396     u32 param[4] = { };
397     ret = sdcard_pio(regs, SC_GO_IDLE_STATE, param);
398     if (ret)
399         return ret;
400     // Let card know SDHC/SDXC is supported and confirm voltage
401     u32 hcs = 0, vrange = (volt >= (1<<15) ? 0x100 : 0x200) | 0xaa;
402     param[0] = vrange;
403     ret = sdcard_pio(regs, SC_SEND_IF_COND, param);
404     if (!ret && param[0] == vrange)
405         hcs = (1<<30);
406     // Verify SD card (instead of MMC or SDIO)
407     param[0] = 0x00;
408     ret = sdcard_pio_app(regs, SC_APP_SEND_OP_COND, param);
409     if (ret) {
410         // Check for MMC card
411         param[0] = 0x00;
412         ret = sdcard_pio(regs, SC_SEND_OP_COND, param);
413         if (ret)
414             return ret;
415         drive->card_type |= SF_MMC;
416         hcs = (1<<30);
417     }
418     // Init card
419     u32 end = timer_calc(SDHCI_POWERUP_TIMEOUT);
420     for (;;) {
421         param[0] = hcs | volt; // high-capacity support and voltage level
422         if (drive->card_type & SF_MMC)
423             ret = sdcard_pio(regs, SC_SEND_OP_COND, param);
424         else
425             ret = sdcard_pio_app(regs, SC_APP_SEND_OP_COND, param);
426         if (ret)
427             return ret;
428         if (param[0] & SR_OCR_NOTBUSY)
429             break;
430         if (timer_check(end)) {
431             warn_timeout();
432             return -1;
433         }
434         msleep(5); // Avoid flooding log when debugging
435     }
436     drive->card_type |= (param[0] & SR_OCR_CCS) ? SF_HIGHCAPACITY : 0;
437     // Select card (get cid, set rca, get csd, select card)
438     param[0] = 0x00;
439     ret = sdcard_pio(regs, SC_ALL_SEND_CID, param);
440     if (ret)
441         return ret;
442     u8 cid[16];
443     memcpy(cid, param, sizeof(cid));
444     param[0] = drive->card_type & SF_MMC ? 0x0001 << 16 : 0x00;
445     ret = sdcard_pio(regs, SC_SEND_RELATIVE_ADDR, param);
446     if (ret)
447         return ret;
448     u16 rca = drive->card_type & SF_MMC ? 0x0001 : param[0] >> 16;
449     param[0] = rca << 16;
450     ret = sdcard_pio(regs, SC_SEND_CSD, param);
451     if (ret)
452         return ret;
453     u8 csd[16];
454     memcpy(csd, param, sizeof(csd));
455     param[0] = rca << 16;
456     ret = sdcard_pio(regs, SC_SELECT_DESELECT_CARD, param);
457     if (ret)
458         return ret;
459     // Set controller to data transfer clock rate
460     ret = sdcard_set_frequency(regs, 25000);
461     if (ret)
462         return ret;
463     // Register drive
464     ret = sdcard_get_capacity(drive, csd);
465     if (ret)
466         return ret;
467     char pnm[7] = {};
468     int i;
469     for (i=0; i < (drive->card_type & SF_MMC ? 6 : 5); i++)
470         pnm[i] = cid[11-i];
471     char *desc = znprintf(MAXDESCSIZE, "%s %s %dMiB"
472                           , drive->card_type & SF_MMC ? "MMC drive" : "SD card"
473                           , pnm, (u32)(drive->drive.sectors >> 11));
474     dprintf(1, "Found sdcard at %p: %s\n", regs, desc);
475     boot_add_hd(&drive->drive, desc, prio);
476     return 0;
477 }
478
479 // Setup and configure an SD card controller
480 static void
481 sdcard_controller_setup(struct sdhci_s *regs, int prio)
482 {
483     // Initialize controller
484     u32 present_state = readl(&regs->present_state);
485     if (!(present_state & SP_CARD_INSERTED))
486         // No card present
487         return;
488     dprintf(3, "sdhci@%p ver=%x cap=%x %x\n", regs
489             , readw(&regs->controller_version)
490             , readl(&regs->cap_lo), readl(&regs->cap_hi));
491     sdcard_reset(regs, SRF_ALL);
492     writew(&regs->irq_signal, 0);
493     writew(&regs->irq_enable, 0x01ff);
494     writew(&regs->irq_status, readw(&regs->irq_status));
495     writew(&regs->error_signal, 0);
496     writew(&regs->error_irq_enable, 0x01ff);
497     writew(&regs->error_irq_status, readw(&regs->error_irq_status));
498     writeb(&regs->timeout_control, 0x0e); // Set to max timeout
499     int volt = sdcard_set_power(regs);
500     if (volt < 0)
501         return;
502
503     // Initialize card
504     struct sddrive_s *drive = malloc_fseg(sizeof(*drive));
505     if (!drive) {
506         warn_noalloc();
507         goto fail;
508     }
509     memset(drive, 0, sizeof(*drive));
510     drive->drive.type = DTYPE_SDCARD;
511     drive->regs = regs;
512     int ret = sdcard_card_setup(drive, volt, prio);
513     if (ret) {
514         free(drive);
515         goto fail;
516     }
517     return;
518 fail:
519     writeb(&regs->power_control, 0);
520     writew(&regs->clock_control, 0);
521 }
522
523 static void
524 sdcard_pci_setup(void *data)
525 {
526     struct pci_device *pci = data;
527     wait_preempt();  // Avoid pci_config_readl when preempting
528     // XXX - bars dependent on slot index register in pci config space
529     u32 regs = pci_config_readl(pci->bdf, PCI_BASE_ADDRESS_0);
530     regs &= PCI_BASE_ADDRESS_MEM_MASK;
531     pci_config_maskw(pci->bdf, PCI_COMMAND, 0,
532                      PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER);
533     int prio = bootprio_find_pci_device(pci);
534     sdcard_controller_setup((void*)regs, prio);
535 }
536
537 static void
538 sdcard_romfile_setup(void *data)
539 {
540     struct romfile_s *file = data;
541     int prio = bootprio_find_named_rom(file->name, 0);
542     u32 addr = romfile_loadint(file->name, 0);
543     dprintf(1, "Starting sdcard controller check at addr %x\n", addr);
544     sdcard_controller_setup((void*)addr, prio);
545 }
546
547 void
548 sdcard_setup(void)
549 {
550     if (!CONFIG_SDCARD)
551         return;
552
553     struct romfile_s *file = NULL;
554     for (;;) {
555         file = romfile_findprefix("etc/sdcard", file);
556         if (!file)
557             break;
558         run_thread(sdcard_romfile_setup, file);
559     }
560
561     struct pci_device *pci;
562     foreachpci(pci) {
563         if (pci->class != PCI_CLASS_SYSTEM_SDHCI || pci->prog_if >= 2)
564             // Not an SDHCI controller following SDHCI spec
565             continue;
566         run_thread(sdcard_pci_setup, pci);
567     }
568 }