xref: /openbmc/qemu/hw/sd/sdhci.c (revision f1f7e4bf)
1 /*
2  * SD Association Host Standard Specification v2.0 controller emulation
3  *
4  * Copyright (c) 2011 Samsung Electronics Co., Ltd.
5  * Mitsyanko Igor <i.mitsyanko@samsung.com>
6  * Peter A.G. Crosthwaite <peter.crosthwaite@petalogix.com>
7  *
8  * Based on MMC controller for Samsung S5PC1xx-based board emulation
9  * by Alexey Merkulov and Vladimir Monakhov.
10  *
11  * This program is free software; you can redistribute it and/or modify it
12  * under the terms of the GNU General Public License as published by the
13  * Free Software Foundation; either version 2 of the License, or (at your
14  * option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
19  * See the GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License along
22  * with this program; if not, see <http://www.gnu.org/licenses/>.
23  */
24 
25 #include <inttypes.h>
26 #include "hw/hw.h"
27 #include "sysemu/block-backend.h"
28 #include "sysemu/blockdev.h"
29 #include "sysemu/dma.h"
30 #include "qemu/timer.h"
31 #include "qemu/bitops.h"
32 #include "sdhci-internal.h"
33 
34 /* host controller debug messages */
35 #ifndef SDHC_DEBUG
36 #define SDHC_DEBUG                        0
37 #endif
38 
39 #define DPRINT_L1(fmt, args...) \
40     do { \
41         if (SDHC_DEBUG) { \
42             fprintf(stderr, "QEMU SDHC: " fmt, ## args); \
43         } \
44     } while (0)
45 #define DPRINT_L2(fmt, args...) \
46     do { \
47         if (SDHC_DEBUG > 1) { \
48             fprintf(stderr, "QEMU SDHC: " fmt, ## args); \
49         } \
50     } while (0)
51 #define ERRPRINT(fmt, args...) \
52     do { \
53         if (SDHC_DEBUG) { \
54             fprintf(stderr, "QEMU SDHC ERROR: " fmt, ## args); \
55         } \
56     } while (0)
57 
58 /* Default SD/MMC host controller features information, which will be
59  * presented in CAPABILITIES register of generic SD host controller at reset.
60  * If not stated otherwise:
61  * 0 - not supported, 1 - supported, other - prohibited.
62  */
63 #define SDHC_CAPAB_64BITBUS       0ul        /* 64-bit System Bus Support */
64 #define SDHC_CAPAB_18V            1ul        /* Voltage support 1.8v */
65 #define SDHC_CAPAB_30V            0ul        /* Voltage support 3.0v */
66 #define SDHC_CAPAB_33V            1ul        /* Voltage support 3.3v */
67 #define SDHC_CAPAB_SUSPRESUME     0ul        /* Suspend/resume support */
68 #define SDHC_CAPAB_SDMA           1ul        /* SDMA support */
69 #define SDHC_CAPAB_HIGHSPEED      1ul        /* High speed support */
70 #define SDHC_CAPAB_ADMA1          1ul        /* ADMA1 support */
71 #define SDHC_CAPAB_ADMA2          1ul        /* ADMA2 support */
72 /* Maximum host controller R/W buffers size
73  * Possible values: 512, 1024, 2048 bytes */
74 #define SDHC_CAPAB_MAXBLOCKLENGTH 512ul
75 /* Maximum clock frequency for SDclock in MHz
76  * value in range 10-63 MHz, 0 - not defined */
77 #define SDHC_CAPAB_BASECLKFREQ    52ul
78 #define SDHC_CAPAB_TOUNIT         1ul  /* Timeout clock unit 0 - kHz, 1 - MHz */
79 /* Timeout clock frequency 1-63, 0 - not defined */
80 #define SDHC_CAPAB_TOCLKFREQ      52ul
81 
82 /* Now check all parameters and calculate CAPABILITIES REGISTER value */
83 #if SDHC_CAPAB_64BITBUS > 1 || SDHC_CAPAB_18V > 1 || SDHC_CAPAB_30V > 1 ||     \
84     SDHC_CAPAB_33V > 1 || SDHC_CAPAB_SUSPRESUME > 1 || SDHC_CAPAB_SDMA > 1 ||  \
85     SDHC_CAPAB_HIGHSPEED > 1 || SDHC_CAPAB_ADMA2 > 1 || SDHC_CAPAB_ADMA1 > 1 ||\
86     SDHC_CAPAB_TOUNIT > 1
87 #error Capabilities features can have value 0 or 1 only!
88 #endif
89 
90 #if SDHC_CAPAB_MAXBLOCKLENGTH == 512
91 #define MAX_BLOCK_LENGTH 0ul
92 #elif SDHC_CAPAB_MAXBLOCKLENGTH == 1024
93 #define MAX_BLOCK_LENGTH 1ul
94 #elif SDHC_CAPAB_MAXBLOCKLENGTH == 2048
95 #define MAX_BLOCK_LENGTH 2ul
96 #else
97 #error Max host controller block size can have value 512, 1024 or 2048 only!
98 #endif
99 
100 #if (SDHC_CAPAB_BASECLKFREQ > 0 && SDHC_CAPAB_BASECLKFREQ < 10) || \
101     SDHC_CAPAB_BASECLKFREQ > 63
102 #error SDclock frequency can have value in range 0, 10-63 only!
103 #endif
104 
105 #if SDHC_CAPAB_TOCLKFREQ > 63
106 #error Timeout clock frequency can have value in range 0-63 only!
107 #endif
108 
109 #define SDHC_CAPAB_REG_DEFAULT                                 \
110    ((SDHC_CAPAB_64BITBUS << 28) | (SDHC_CAPAB_18V << 26) |     \
111     (SDHC_CAPAB_30V << 25) | (SDHC_CAPAB_33V << 24) |          \
112     (SDHC_CAPAB_SUSPRESUME << 23) | (SDHC_CAPAB_SDMA << 22) |  \
113     (SDHC_CAPAB_HIGHSPEED << 21) | (SDHC_CAPAB_ADMA1 << 20) |  \
114     (SDHC_CAPAB_ADMA2 << 19) | (MAX_BLOCK_LENGTH << 16) |      \
115     (SDHC_CAPAB_BASECLKFREQ << 8) | (SDHC_CAPAB_TOUNIT << 7) | \
116     (SDHC_CAPAB_TOCLKFREQ))
117 
118 #define MASKED_WRITE(reg, mask, val)  (reg = (reg & (mask)) | (val))
119 
120 static uint8_t sdhci_slotint(SDHCIState *s)
121 {
122     return (s->norintsts & s->norintsigen) || (s->errintsts & s->errintsigen) ||
123          ((s->norintsts & SDHC_NIS_INSERT) && (s->wakcon & SDHC_WKUP_ON_INS)) ||
124          ((s->norintsts & SDHC_NIS_REMOVE) && (s->wakcon & SDHC_WKUP_ON_RMV));
125 }
126 
127 static inline void sdhci_update_irq(SDHCIState *s)
128 {
129     qemu_set_irq(s->irq, sdhci_slotint(s));
130 }
131 
132 static void sdhci_raise_insertion_irq(void *opaque)
133 {
134     SDHCIState *s = (SDHCIState *)opaque;
135 
136     if (s->norintsts & SDHC_NIS_REMOVE) {
137         timer_mod(s->insert_timer,
138                        qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + SDHC_INSERTION_DELAY);
139     } else {
140         s->prnsts = 0x1ff0000;
141         if (s->norintstsen & SDHC_NISEN_INSERT) {
142             s->norintsts |= SDHC_NIS_INSERT;
143         }
144         sdhci_update_irq(s);
145     }
146 }
147 
148 static void sdhci_insert_eject_cb(void *opaque, int irq, int level)
149 {
150     SDHCIState *s = (SDHCIState *)opaque;
151     DPRINT_L1("Card state changed: %s!\n", level ? "insert" : "eject");
152 
153     if ((s->norintsts & SDHC_NIS_REMOVE) && level) {
154         /* Give target some time to notice card ejection */
155         timer_mod(s->insert_timer,
156                        qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + SDHC_INSERTION_DELAY);
157     } else {
158         if (level) {
159             s->prnsts = 0x1ff0000;
160             if (s->norintstsen & SDHC_NISEN_INSERT) {
161                 s->norintsts |= SDHC_NIS_INSERT;
162             }
163         } else {
164             s->prnsts = 0x1fa0000;
165             s->pwrcon &= ~SDHC_POWER_ON;
166             s->clkcon &= ~SDHC_CLOCK_SDCLK_EN;
167             if (s->norintstsen & SDHC_NISEN_REMOVE) {
168                 s->norintsts |= SDHC_NIS_REMOVE;
169             }
170         }
171         sdhci_update_irq(s);
172     }
173 }
174 
175 static void sdhci_card_readonly_cb(void *opaque, int irq, int level)
176 {
177     SDHCIState *s = (SDHCIState *)opaque;
178 
179     if (level) {
180         s->prnsts &= ~SDHC_WRITE_PROTECT;
181     } else {
182         /* Write enabled */
183         s->prnsts |= SDHC_WRITE_PROTECT;
184     }
185 }
186 
187 static void sdhci_reset(SDHCIState *s)
188 {
189     timer_del(s->insert_timer);
190     timer_del(s->transfer_timer);
191     /* Set all registers to 0. Capabilities registers are not cleared
192      * and assumed to always preserve their value, given to them during
193      * initialization */
194     memset(&s->sdmasysad, 0, (uintptr_t)&s->capareg - (uintptr_t)&s->sdmasysad);
195 
196     sd_set_cb(s->card, s->ro_cb, s->eject_cb);
197     s->data_count = 0;
198     s->stopped_state = sdhc_not_stopped;
199 }
200 
201 static void sdhci_data_transfer(void *opaque);
202 
203 static void sdhci_send_command(SDHCIState *s)
204 {
205     SDRequest request;
206     uint8_t response[16];
207     int rlen;
208 
209     s->errintsts = 0;
210     s->acmd12errsts = 0;
211     request.cmd = s->cmdreg >> 8;
212     request.arg = s->argument;
213     DPRINT_L1("sending CMD%u ARG[0x%08x]\n", request.cmd, request.arg);
214     rlen = sd_do_command(s->card, &request, response);
215 
216     if (s->cmdreg & SDHC_CMD_RESPONSE) {
217         if (rlen == 4) {
218             s->rspreg[0] = (response[0] << 24) | (response[1] << 16) |
219                            (response[2] << 8)  |  response[3];
220             s->rspreg[1] = s->rspreg[2] = s->rspreg[3] = 0;
221             DPRINT_L1("Response: RSPREG[31..0]=0x%08x\n", s->rspreg[0]);
222         } else if (rlen == 16) {
223             s->rspreg[0] = (response[11] << 24) | (response[12] << 16) |
224                            (response[13] << 8) |  response[14];
225             s->rspreg[1] = (response[7] << 24) | (response[8] << 16) |
226                            (response[9] << 8)  |  response[10];
227             s->rspreg[2] = (response[3] << 24) | (response[4] << 16) |
228                            (response[5] << 8)  |  response[6];
229             s->rspreg[3] = (response[0] << 16) | (response[1] << 8) |
230                             response[2];
231             DPRINT_L1("Response received:\n RSPREG[127..96]=0x%08x, RSPREG[95.."
232                   "64]=0x%08x,\n RSPREG[63..32]=0x%08x, RSPREG[31..0]=0x%08x\n",
233                   s->rspreg[3], s->rspreg[2], s->rspreg[1], s->rspreg[0]);
234         } else {
235             ERRPRINT("Timeout waiting for command response\n");
236             if (s->errintstsen & SDHC_EISEN_CMDTIMEOUT) {
237                 s->errintsts |= SDHC_EIS_CMDTIMEOUT;
238                 s->norintsts |= SDHC_NIS_ERR;
239             }
240         }
241 
242         if ((s->norintstsen & SDHC_NISEN_TRSCMP) &&
243             (s->cmdreg & SDHC_CMD_RESPONSE) == SDHC_CMD_RSP_WITH_BUSY) {
244             s->norintsts |= SDHC_NIS_TRSCMP;
245         }
246     } else if (rlen != 0 && (s->errintstsen & SDHC_EISEN_CMDIDX)) {
247         s->errintsts |= SDHC_EIS_CMDIDX;
248         s->norintsts |= SDHC_NIS_ERR;
249     }
250 
251     if (s->norintstsen & SDHC_NISEN_CMDCMP) {
252         s->norintsts |= SDHC_NIS_CMDCMP;
253     }
254 
255     sdhci_update_irq(s);
256 
257     if (s->blksize && (s->cmdreg & SDHC_CMD_DATA_PRESENT)) {
258         s->data_count = 0;
259         sdhci_data_transfer(s);
260     }
261 }
262 
263 static void sdhci_end_transfer(SDHCIState *s)
264 {
265     /* Automatically send CMD12 to stop transfer if AutoCMD12 enabled */
266     if ((s->trnmod & SDHC_TRNS_ACMD12) != 0) {
267         SDRequest request;
268         uint8_t response[16];
269 
270         request.cmd = 0x0C;
271         request.arg = 0;
272         DPRINT_L1("Automatically issue CMD%d %08x\n", request.cmd, request.arg);
273         sd_do_command(s->card, &request, response);
274         /* Auto CMD12 response goes to the upper Response register */
275         s->rspreg[3] = (response[0] << 24) | (response[1] << 16) |
276                 (response[2] << 8) | response[3];
277     }
278 
279     s->prnsts &= ~(SDHC_DOING_READ | SDHC_DOING_WRITE |
280             SDHC_DAT_LINE_ACTIVE | SDHC_DATA_INHIBIT |
281             SDHC_SPACE_AVAILABLE | SDHC_DATA_AVAILABLE);
282 
283     if (s->norintstsen & SDHC_NISEN_TRSCMP) {
284         s->norintsts |= SDHC_NIS_TRSCMP;
285     }
286 
287     sdhci_update_irq(s);
288 }
289 
290 /*
291  * Programmed i/o data transfer
292  */
293 
294 /* Fill host controller's read buffer with BLKSIZE bytes of data from card */
295 static void sdhci_read_block_from_card(SDHCIState *s)
296 {
297     int index = 0;
298 
299     if ((s->trnmod & SDHC_TRNS_MULTI) &&
300             (s->trnmod & SDHC_TRNS_BLK_CNT_EN) && (s->blkcnt == 0)) {
301         return;
302     }
303 
304     for (index = 0; index < (s->blksize & 0x0fff); index++) {
305         s->fifo_buffer[index] = sd_read_data(s->card);
306     }
307 
308     /* New data now available for READ through Buffer Port Register */
309     s->prnsts |= SDHC_DATA_AVAILABLE;
310     if (s->norintstsen & SDHC_NISEN_RBUFRDY) {
311         s->norintsts |= SDHC_NIS_RBUFRDY;
312     }
313 
314     /* Clear DAT line active status if that was the last block */
315     if ((s->trnmod & SDHC_TRNS_MULTI) == 0 ||
316             ((s->trnmod & SDHC_TRNS_MULTI) && s->blkcnt == 1)) {
317         s->prnsts &= ~SDHC_DAT_LINE_ACTIVE;
318     }
319 
320     /* If stop at block gap request was set and it's not the last block of
321      * data - generate Block Event interrupt */
322     if (s->stopped_state == sdhc_gap_read && (s->trnmod & SDHC_TRNS_MULTI) &&
323             s->blkcnt != 1)    {
324         s->prnsts &= ~SDHC_DAT_LINE_ACTIVE;
325         if (s->norintstsen & SDHC_EISEN_BLKGAP) {
326             s->norintsts |= SDHC_EIS_BLKGAP;
327         }
328     }
329 
330     sdhci_update_irq(s);
331 }
332 
333 /* Read @size byte of data from host controller @s BUFFER DATA PORT register */
334 static uint32_t sdhci_read_dataport(SDHCIState *s, unsigned size)
335 {
336     uint32_t value = 0;
337     int i;
338 
339     /* first check that a valid data exists in host controller input buffer */
340     if ((s->prnsts & SDHC_DATA_AVAILABLE) == 0) {
341         ERRPRINT("Trying to read from empty buffer\n");
342         return 0;
343     }
344 
345     for (i = 0; i < size; i++) {
346         value |= s->fifo_buffer[s->data_count] << i * 8;
347         s->data_count++;
348         /* check if we've read all valid data (blksize bytes) from buffer */
349         if ((s->data_count) >= (s->blksize & 0x0fff)) {
350             DPRINT_L2("All %u bytes of data have been read from input buffer\n",
351                     s->data_count);
352             s->prnsts &= ~SDHC_DATA_AVAILABLE; /* no more data in a buffer */
353             s->data_count = 0;  /* next buff read must start at position [0] */
354 
355             if (s->trnmod & SDHC_TRNS_BLK_CNT_EN) {
356                 s->blkcnt--;
357             }
358 
359             /* if that was the last block of data */
360             if ((s->trnmod & SDHC_TRNS_MULTI) == 0 ||
361                 ((s->trnmod & SDHC_TRNS_BLK_CNT_EN) && (s->blkcnt == 0)) ||
362                  /* stop at gap request */
363                 (s->stopped_state == sdhc_gap_read &&
364                  !(s->prnsts & SDHC_DAT_LINE_ACTIVE))) {
365                 sdhci_end_transfer(s);
366             } else { /* if there are more data, read next block from card */
367                 sdhci_read_block_from_card(s);
368             }
369             break;
370         }
371     }
372 
373     return value;
374 }
375 
376 /* Write data from host controller FIFO to card */
377 static void sdhci_write_block_to_card(SDHCIState *s)
378 {
379     int index = 0;
380 
381     if (s->prnsts & SDHC_SPACE_AVAILABLE) {
382         if (s->norintstsen & SDHC_NISEN_WBUFRDY) {
383             s->norintsts |= SDHC_NIS_WBUFRDY;
384         }
385         sdhci_update_irq(s);
386         return;
387     }
388 
389     if (s->trnmod & SDHC_TRNS_BLK_CNT_EN) {
390         if (s->blkcnt == 0) {
391             return;
392         } else {
393             s->blkcnt--;
394         }
395     }
396 
397     for (index = 0; index < (s->blksize & 0x0fff); index++) {
398         sd_write_data(s->card, s->fifo_buffer[index]);
399     }
400 
401     /* Next data can be written through BUFFER DATORT register */
402     s->prnsts |= SDHC_SPACE_AVAILABLE;
403 
404     /* Finish transfer if that was the last block of data */
405     if ((s->trnmod & SDHC_TRNS_MULTI) == 0 ||
406             ((s->trnmod & SDHC_TRNS_MULTI) &&
407             (s->trnmod & SDHC_TRNS_BLK_CNT_EN) && (s->blkcnt == 0))) {
408         sdhci_end_transfer(s);
409     } else if (s->norintstsen & SDHC_NISEN_WBUFRDY) {
410         s->norintsts |= SDHC_NIS_WBUFRDY;
411     }
412 
413     /* Generate Block Gap Event if requested and if not the last block */
414     if (s->stopped_state == sdhc_gap_write && (s->trnmod & SDHC_TRNS_MULTI) &&
415             s->blkcnt > 0) {
416         s->prnsts &= ~SDHC_DOING_WRITE;
417         if (s->norintstsen & SDHC_EISEN_BLKGAP) {
418             s->norintsts |= SDHC_EIS_BLKGAP;
419         }
420         sdhci_end_transfer(s);
421     }
422 
423     sdhci_update_irq(s);
424 }
425 
426 /* Write @size bytes of @value data to host controller @s Buffer Data Port
427  * register */
428 static void sdhci_write_dataport(SDHCIState *s, uint32_t value, unsigned size)
429 {
430     unsigned i;
431 
432     /* Check that there is free space left in a buffer */
433     if (!(s->prnsts & SDHC_SPACE_AVAILABLE)) {
434         ERRPRINT("Can't write to data buffer: buffer full\n");
435         return;
436     }
437 
438     for (i = 0; i < size; i++) {
439         s->fifo_buffer[s->data_count] = value & 0xFF;
440         s->data_count++;
441         value >>= 8;
442         if (s->data_count >= (s->blksize & 0x0fff)) {
443             DPRINT_L2("write buffer filled with %u bytes of data\n",
444                     s->data_count);
445             s->data_count = 0;
446             s->prnsts &= ~SDHC_SPACE_AVAILABLE;
447             if (s->prnsts & SDHC_DOING_WRITE) {
448                 sdhci_write_block_to_card(s);
449             }
450         }
451     }
452 }
453 
454 /*
455  * Single DMA data transfer
456  */
457 
458 /* Multi block SDMA transfer */
459 static void sdhci_sdma_transfer_multi_blocks(SDHCIState *s)
460 {
461     bool page_aligned = false;
462     unsigned int n, begin;
463     const uint16_t block_size = s->blksize & 0x0fff;
464     uint32_t boundary_chk = 1 << (((s->blksize & 0xf000) >> 12) + 12);
465     uint32_t boundary_count = boundary_chk - (s->sdmasysad % boundary_chk);
466 
467     /* XXX: Some sd/mmc drivers (for example, u-boot-slp) do not account for
468      * possible stop at page boundary if initial address is not page aligned,
469      * allow them to work properly */
470     if ((s->sdmasysad % boundary_chk) == 0) {
471         page_aligned = true;
472     }
473 
474     if (s->trnmod & SDHC_TRNS_READ) {
475         s->prnsts |= SDHC_DOING_READ | SDHC_DATA_INHIBIT |
476                 SDHC_DAT_LINE_ACTIVE;
477         while (s->blkcnt) {
478             if (s->data_count == 0) {
479                 for (n = 0; n < block_size; n++) {
480                     s->fifo_buffer[n] = sd_read_data(s->card);
481                 }
482             }
483             begin = s->data_count;
484             if (((boundary_count + begin) < block_size) && page_aligned) {
485                 s->data_count = boundary_count + begin;
486                 boundary_count = 0;
487              } else {
488                 s->data_count = block_size;
489                 boundary_count -= block_size - begin;
490                 if (s->trnmod & SDHC_TRNS_BLK_CNT_EN) {
491                     s->blkcnt--;
492                 }
493             }
494             dma_memory_write(&address_space_memory, s->sdmasysad,
495                              &s->fifo_buffer[begin], s->data_count - begin);
496             s->sdmasysad += s->data_count - begin;
497             if (s->data_count == block_size) {
498                 s->data_count = 0;
499             }
500             if (page_aligned && boundary_count == 0) {
501                 break;
502             }
503         }
504     } else {
505         s->prnsts |= SDHC_DOING_WRITE | SDHC_DATA_INHIBIT |
506                 SDHC_DAT_LINE_ACTIVE;
507         while (s->blkcnt) {
508             begin = s->data_count;
509             if (((boundary_count + begin) < block_size) && page_aligned) {
510                 s->data_count = boundary_count + begin;
511                 boundary_count = 0;
512              } else {
513                 s->data_count = block_size;
514                 boundary_count -= block_size - begin;
515             }
516             dma_memory_read(&address_space_memory, s->sdmasysad,
517                             &s->fifo_buffer[begin], s->data_count);
518             s->sdmasysad += s->data_count - begin;
519             if (s->data_count == block_size) {
520                 for (n = 0; n < block_size; n++) {
521                     sd_write_data(s->card, s->fifo_buffer[n]);
522                 }
523                 s->data_count = 0;
524                 if (s->trnmod & SDHC_TRNS_BLK_CNT_EN) {
525                     s->blkcnt--;
526                 }
527             }
528             if (page_aligned && boundary_count == 0) {
529                 break;
530             }
531         }
532     }
533 
534     if (s->blkcnt == 0) {
535         sdhci_end_transfer(s);
536     } else {
537         if (s->norintstsen & SDHC_NISEN_DMA) {
538             s->norintsts |= SDHC_NIS_DMA;
539         }
540         sdhci_update_irq(s);
541     }
542 }
543 
544 /* single block SDMA transfer */
545 
546 static void sdhci_sdma_transfer_single_block(SDHCIState *s)
547 {
548     int n;
549     uint32_t datacnt = s->blksize & 0x0fff;
550 
551     if (s->trnmod & SDHC_TRNS_READ) {
552         for (n = 0; n < datacnt; n++) {
553             s->fifo_buffer[n] = sd_read_data(s->card);
554         }
555         dma_memory_write(&address_space_memory, s->sdmasysad, s->fifo_buffer,
556                          datacnt);
557     } else {
558         dma_memory_read(&address_space_memory, s->sdmasysad, s->fifo_buffer,
559                         datacnt);
560         for (n = 0; n < datacnt; n++) {
561             sd_write_data(s->card, s->fifo_buffer[n]);
562         }
563     }
564 
565     if (s->trnmod & SDHC_TRNS_BLK_CNT_EN) {
566         s->blkcnt--;
567     }
568 
569     sdhci_end_transfer(s);
570 }
571 
572 typedef struct ADMADescr {
573     hwaddr addr;
574     uint16_t length;
575     uint8_t attr;
576     uint8_t incr;
577 } ADMADescr;
578 
579 static void get_adma_description(SDHCIState *s, ADMADescr *dscr)
580 {
581     uint32_t adma1 = 0;
582     uint64_t adma2 = 0;
583     hwaddr entry_addr = (hwaddr)s->admasysaddr;
584     switch (SDHC_DMA_TYPE(s->hostctl)) {
585     case SDHC_CTRL_ADMA2_32:
586         dma_memory_read(&address_space_memory, entry_addr, (uint8_t *)&adma2,
587                         sizeof(adma2));
588         adma2 = le64_to_cpu(adma2);
589         /* The spec does not specify endianness of descriptor table.
590          * We currently assume that it is LE.
591          */
592         dscr->addr = (hwaddr)extract64(adma2, 32, 32) & ~0x3ull;
593         dscr->length = (uint16_t)extract64(adma2, 16, 16);
594         dscr->attr = (uint8_t)extract64(adma2, 0, 7);
595         dscr->incr = 8;
596         break;
597     case SDHC_CTRL_ADMA1_32:
598         dma_memory_read(&address_space_memory, entry_addr, (uint8_t *)&adma1,
599                         sizeof(adma1));
600         adma1 = le32_to_cpu(adma1);
601         dscr->addr = (hwaddr)(adma1 & 0xFFFFF000);
602         dscr->attr = (uint8_t)extract32(adma1, 0, 7);
603         dscr->incr = 4;
604         if ((dscr->attr & SDHC_ADMA_ATTR_ACT_MASK) == SDHC_ADMA_ATTR_SET_LEN) {
605             dscr->length = (uint16_t)extract32(adma1, 12, 16);
606         } else {
607             dscr->length = 4096;
608         }
609         break;
610     case SDHC_CTRL_ADMA2_64:
611         dma_memory_read(&address_space_memory, entry_addr,
612                         (uint8_t *)(&dscr->attr), 1);
613         dma_memory_read(&address_space_memory, entry_addr + 2,
614                         (uint8_t *)(&dscr->length), 2);
615         dscr->length = le16_to_cpu(dscr->length);
616         dma_memory_read(&address_space_memory, entry_addr + 4,
617                         (uint8_t *)(&dscr->addr), 8);
618         dscr->attr = le64_to_cpu(dscr->attr);
619         dscr->attr &= 0xfffffff8;
620         dscr->incr = 12;
621         break;
622     }
623 }
624 
625 /* Advanced DMA data transfer */
626 
627 static void sdhci_do_adma(SDHCIState *s)
628 {
629     unsigned int n, begin, length;
630     const uint16_t block_size = s->blksize & 0x0fff;
631     ADMADescr dscr;
632     int i;
633 
634     for (i = 0; i < SDHC_ADMA_DESCS_PER_DELAY; ++i) {
635         s->admaerr &= ~SDHC_ADMAERR_LENGTH_MISMATCH;
636 
637         get_adma_description(s, &dscr);
638         DPRINT_L2("ADMA loop: addr=" TARGET_FMT_plx ", len=%d, attr=%x\n",
639                 dscr.addr, dscr.length, dscr.attr);
640 
641         if ((dscr.attr & SDHC_ADMA_ATTR_VALID) == 0) {
642             /* Indicate that error occurred in ST_FDS state */
643             s->admaerr &= ~SDHC_ADMAERR_STATE_MASK;
644             s->admaerr |= SDHC_ADMAERR_STATE_ST_FDS;
645 
646             /* Generate ADMA error interrupt */
647             if (s->errintstsen & SDHC_EISEN_ADMAERR) {
648                 s->errintsts |= SDHC_EIS_ADMAERR;
649                 s->norintsts |= SDHC_NIS_ERR;
650             }
651 
652             sdhci_update_irq(s);
653             return;
654         }
655 
656         length = dscr.length ? dscr.length : 65536;
657 
658         switch (dscr.attr & SDHC_ADMA_ATTR_ACT_MASK) {
659         case SDHC_ADMA_ATTR_ACT_TRAN:  /* data transfer */
660 
661             if (s->trnmod & SDHC_TRNS_READ) {
662                 while (length) {
663                     if (s->data_count == 0) {
664                         for (n = 0; n < block_size; n++) {
665                             s->fifo_buffer[n] = sd_read_data(s->card);
666                         }
667                     }
668                     begin = s->data_count;
669                     if ((length + begin) < block_size) {
670                         s->data_count = length + begin;
671                         length = 0;
672                      } else {
673                         s->data_count = block_size;
674                         length -= block_size - begin;
675                     }
676                     dma_memory_write(&address_space_memory, dscr.addr,
677                                      &s->fifo_buffer[begin],
678                                      s->data_count - begin);
679                     dscr.addr += s->data_count - begin;
680                     if (s->data_count == block_size) {
681                         s->data_count = 0;
682                         if (s->trnmod & SDHC_TRNS_BLK_CNT_EN) {
683                             s->blkcnt--;
684                             if (s->blkcnt == 0) {
685                                 break;
686                             }
687                         }
688                     }
689                 }
690             } else {
691                 while (length) {
692                     begin = s->data_count;
693                     if ((length + begin) < block_size) {
694                         s->data_count = length + begin;
695                         length = 0;
696                      } else {
697                         s->data_count = block_size;
698                         length -= block_size - begin;
699                     }
700                     dma_memory_read(&address_space_memory, dscr.addr,
701                                     &s->fifo_buffer[begin],
702                                     s->data_count - begin);
703                     dscr.addr += s->data_count - begin;
704                     if (s->data_count == block_size) {
705                         for (n = 0; n < block_size; n++) {
706                             sd_write_data(s->card, s->fifo_buffer[n]);
707                         }
708                         s->data_count = 0;
709                         if (s->trnmod & SDHC_TRNS_BLK_CNT_EN) {
710                             s->blkcnt--;
711                             if (s->blkcnt == 0) {
712                                 break;
713                             }
714                         }
715                     }
716                 }
717             }
718             s->admasysaddr += dscr.incr;
719             break;
720         case SDHC_ADMA_ATTR_ACT_LINK:   /* link to next descriptor table */
721             s->admasysaddr = dscr.addr;
722             DPRINT_L1("ADMA link: admasysaddr=0x%" PRIx64 "\n",
723                       s->admasysaddr);
724             break;
725         default:
726             s->admasysaddr += dscr.incr;
727             break;
728         }
729 
730         if (dscr.attr & SDHC_ADMA_ATTR_INT) {
731             DPRINT_L1("ADMA interrupt: admasysaddr=0x%" PRIx64 "\n",
732                       s->admasysaddr);
733             if (s->norintstsen & SDHC_NISEN_DMA) {
734                 s->norintsts |= SDHC_NIS_DMA;
735             }
736 
737             sdhci_update_irq(s);
738         }
739 
740         /* ADMA transfer terminates if blkcnt == 0 or by END attribute */
741         if (((s->trnmod & SDHC_TRNS_BLK_CNT_EN) &&
742                     (s->blkcnt == 0)) || (dscr.attr & SDHC_ADMA_ATTR_END)) {
743             DPRINT_L2("ADMA transfer completed\n");
744             if (length || ((dscr.attr & SDHC_ADMA_ATTR_END) &&
745                 (s->trnmod & SDHC_TRNS_BLK_CNT_EN) &&
746                 s->blkcnt != 0)) {
747                 ERRPRINT("SD/MMC host ADMA length mismatch\n");
748                 s->admaerr |= SDHC_ADMAERR_LENGTH_MISMATCH |
749                         SDHC_ADMAERR_STATE_ST_TFR;
750                 if (s->errintstsen & SDHC_EISEN_ADMAERR) {
751                     ERRPRINT("Set ADMA error flag\n");
752                     s->errintsts |= SDHC_EIS_ADMAERR;
753                     s->norintsts |= SDHC_NIS_ERR;
754                 }
755 
756                 sdhci_update_irq(s);
757             }
758             sdhci_end_transfer(s);
759             return;
760         }
761 
762     }
763 
764     /* we have unfinished business - reschedule to continue ADMA */
765     timer_mod(s->transfer_timer,
766                    qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + SDHC_TRANSFER_DELAY);
767 }
768 
769 /* Perform data transfer according to controller configuration */
770 
771 static void sdhci_data_transfer(void *opaque)
772 {
773     SDHCIState *s = (SDHCIState *)opaque;
774 
775     if (s->trnmod & SDHC_TRNS_DMA) {
776         switch (SDHC_DMA_TYPE(s->hostctl)) {
777         case SDHC_CTRL_SDMA:
778             if ((s->trnmod & SDHC_TRNS_MULTI) &&
779                     (!(s->trnmod & SDHC_TRNS_BLK_CNT_EN) || s->blkcnt == 0)) {
780                 break;
781             }
782 
783             if ((s->blkcnt == 1) || !(s->trnmod & SDHC_TRNS_MULTI)) {
784                 sdhci_sdma_transfer_single_block(s);
785             } else {
786                 sdhci_sdma_transfer_multi_blocks(s);
787             }
788 
789             break;
790         case SDHC_CTRL_ADMA1_32:
791             if (!(s->capareg & SDHC_CAN_DO_ADMA1)) {
792                 ERRPRINT("ADMA1 not supported\n");
793                 break;
794             }
795 
796             sdhci_do_adma(s);
797             break;
798         case SDHC_CTRL_ADMA2_32:
799             if (!(s->capareg & SDHC_CAN_DO_ADMA2)) {
800                 ERRPRINT("ADMA2 not supported\n");
801                 break;
802             }
803 
804             sdhci_do_adma(s);
805             break;
806         case SDHC_CTRL_ADMA2_64:
807             if (!(s->capareg & SDHC_CAN_DO_ADMA2) ||
808                     !(s->capareg & SDHC_64_BIT_BUS_SUPPORT)) {
809                 ERRPRINT("64 bit ADMA not supported\n");
810                 break;
811             }
812 
813             sdhci_do_adma(s);
814             break;
815         default:
816             ERRPRINT("Unsupported DMA type\n");
817             break;
818         }
819     } else {
820         if ((s->trnmod & SDHC_TRNS_READ) && sd_data_ready(s->card)) {
821             s->prnsts |= SDHC_DOING_READ | SDHC_DATA_INHIBIT |
822                     SDHC_DAT_LINE_ACTIVE;
823             sdhci_read_block_from_card(s);
824         } else {
825             s->prnsts |= SDHC_DOING_WRITE | SDHC_DAT_LINE_ACTIVE |
826                     SDHC_SPACE_AVAILABLE | SDHC_DATA_INHIBIT;
827             sdhci_write_block_to_card(s);
828         }
829     }
830 }
831 
832 static bool sdhci_can_issue_command(SDHCIState *s)
833 {
834     if (!SDHC_CLOCK_IS_ON(s->clkcon) || !(s->pwrcon & SDHC_POWER_ON) ||
835         (((s->prnsts & SDHC_DATA_INHIBIT) || s->stopped_state) &&
836         ((s->cmdreg & SDHC_CMD_DATA_PRESENT) ||
837         ((s->cmdreg & SDHC_CMD_RESPONSE) == SDHC_CMD_RSP_WITH_BUSY &&
838         !(SDHC_COMMAND_TYPE(s->cmdreg) == SDHC_CMD_ABORT))))) {
839         return false;
840     }
841 
842     return true;
843 }
844 
845 /* The Buffer Data Port register must be accessed in sequential and
846  * continuous manner */
847 static inline bool
848 sdhci_buff_access_is_sequential(SDHCIState *s, unsigned byte_num)
849 {
850     if ((s->data_count & 0x3) != byte_num) {
851         ERRPRINT("Non-sequential access to Buffer Data Port register"
852                 "is prohibited\n");
853         return false;
854     }
855     return true;
856 }
857 
858 static uint64_t sdhci_read(void *opaque, hwaddr offset, unsigned size)
859 {
860     SDHCIState *s = (SDHCIState *)opaque;
861     uint32_t ret = 0;
862 
863     switch (offset & ~0x3) {
864     case SDHC_SYSAD:
865         ret = s->sdmasysad;
866         break;
867     case SDHC_BLKSIZE:
868         ret = s->blksize | (s->blkcnt << 16);
869         break;
870     case SDHC_ARGUMENT:
871         ret = s->argument;
872         break;
873     case SDHC_TRNMOD:
874         ret = s->trnmod | (s->cmdreg << 16);
875         break;
876     case SDHC_RSPREG0 ... SDHC_RSPREG3:
877         ret = s->rspreg[((offset & ~0x3) - SDHC_RSPREG0) >> 2];
878         break;
879     case  SDHC_BDATA:
880         if (sdhci_buff_access_is_sequential(s, offset - SDHC_BDATA)) {
881             ret = sdhci_read_dataport(s, size);
882             DPRINT_L2("read %ub: addr[0x%04x] -> %u(0x%x)\n", size, (int)offset,
883                       ret, ret);
884             return ret;
885         }
886         break;
887     case SDHC_PRNSTS:
888         ret = s->prnsts;
889         break;
890     case SDHC_HOSTCTL:
891         ret = s->hostctl | (s->pwrcon << 8) | (s->blkgap << 16) |
892               (s->wakcon << 24);
893         break;
894     case SDHC_CLKCON:
895         ret = s->clkcon | (s->timeoutcon << 16);
896         break;
897     case SDHC_NORINTSTS:
898         ret = s->norintsts | (s->errintsts << 16);
899         break;
900     case SDHC_NORINTSTSEN:
901         ret = s->norintstsen | (s->errintstsen << 16);
902         break;
903     case SDHC_NORINTSIGEN:
904         ret = s->norintsigen | (s->errintsigen << 16);
905         break;
906     case SDHC_ACMD12ERRSTS:
907         ret = s->acmd12errsts;
908         break;
909     case SDHC_CAPAREG:
910         ret = s->capareg;
911         break;
912     case SDHC_MAXCURR:
913         ret = s->maxcurr;
914         break;
915     case SDHC_ADMAERR:
916         ret =  s->admaerr;
917         break;
918     case SDHC_ADMASYSADDR:
919         ret = (uint32_t)s->admasysaddr;
920         break;
921     case SDHC_ADMASYSADDR + 4:
922         ret = (uint32_t)(s->admasysaddr >> 32);
923         break;
924     case SDHC_SLOT_INT_STATUS:
925         ret = (SD_HOST_SPECv2_VERS << 16) | sdhci_slotint(s);
926         break;
927     default:
928         ERRPRINT("bad %ub read: addr[0x%04x]\n", size, (int)offset);
929         break;
930     }
931 
932     ret >>= (offset & 0x3) * 8;
933     ret &= (1ULL << (size * 8)) - 1;
934     DPRINT_L2("read %ub: addr[0x%04x] -> %u(0x%x)\n", size, (int)offset, ret, ret);
935     return ret;
936 }
937 
938 static inline void sdhci_blkgap_write(SDHCIState *s, uint8_t value)
939 {
940     if ((value & SDHC_STOP_AT_GAP_REQ) && (s->blkgap & SDHC_STOP_AT_GAP_REQ)) {
941         return;
942     }
943     s->blkgap = value & SDHC_STOP_AT_GAP_REQ;
944 
945     if ((value & SDHC_CONTINUE_REQ) && s->stopped_state &&
946             (s->blkgap & SDHC_STOP_AT_GAP_REQ) == 0) {
947         if (s->stopped_state == sdhc_gap_read) {
948             s->prnsts |= SDHC_DAT_LINE_ACTIVE | SDHC_DOING_READ;
949             sdhci_read_block_from_card(s);
950         } else {
951             s->prnsts |= SDHC_DAT_LINE_ACTIVE | SDHC_DOING_WRITE;
952             sdhci_write_block_to_card(s);
953         }
954         s->stopped_state = sdhc_not_stopped;
955     } else if (!s->stopped_state && (value & SDHC_STOP_AT_GAP_REQ)) {
956         if (s->prnsts & SDHC_DOING_READ) {
957             s->stopped_state = sdhc_gap_read;
958         } else if (s->prnsts & SDHC_DOING_WRITE) {
959             s->stopped_state = sdhc_gap_write;
960         }
961     }
962 }
963 
964 static inline void sdhci_reset_write(SDHCIState *s, uint8_t value)
965 {
966     switch (value) {
967     case SDHC_RESET_ALL:
968         sdhci_reset(s);
969         break;
970     case SDHC_RESET_CMD:
971         s->prnsts &= ~SDHC_CMD_INHIBIT;
972         s->norintsts &= ~SDHC_NIS_CMDCMP;
973         break;
974     case SDHC_RESET_DATA:
975         s->data_count = 0;
976         s->prnsts &= ~(SDHC_SPACE_AVAILABLE | SDHC_DATA_AVAILABLE |
977                 SDHC_DOING_READ | SDHC_DOING_WRITE |
978                 SDHC_DATA_INHIBIT | SDHC_DAT_LINE_ACTIVE);
979         s->blkgap &= ~(SDHC_STOP_AT_GAP_REQ | SDHC_CONTINUE_REQ);
980         s->stopped_state = sdhc_not_stopped;
981         s->norintsts &= ~(SDHC_NIS_WBUFRDY | SDHC_NIS_RBUFRDY |
982                 SDHC_NIS_DMA | SDHC_NIS_TRSCMP | SDHC_NIS_BLKGAP);
983         break;
984     }
985 }
986 
987 static void
988 sdhci_write(void *opaque, hwaddr offset, uint64_t val, unsigned size)
989 {
990     SDHCIState *s = (SDHCIState *)opaque;
991     unsigned shift =  8 * (offset & 0x3);
992     uint32_t mask = ~(((1ULL << (size * 8)) - 1) << shift);
993     uint32_t value = val;
994     value <<= shift;
995 
996     switch (offset & ~0x3) {
997     case SDHC_SYSAD:
998         s->sdmasysad = (s->sdmasysad & mask) | value;
999         MASKED_WRITE(s->sdmasysad, mask, value);
1000         /* Writing to last byte of sdmasysad might trigger transfer */
1001         if (!(mask & 0xFF000000) && TRANSFERRING_DATA(s->prnsts) && s->blkcnt &&
1002                 s->blksize && SDHC_DMA_TYPE(s->hostctl) == SDHC_CTRL_SDMA) {
1003             sdhci_sdma_transfer_multi_blocks(s);
1004         }
1005         break;
1006     case SDHC_BLKSIZE:
1007         if (!TRANSFERRING_DATA(s->prnsts)) {
1008             MASKED_WRITE(s->blksize, mask, value);
1009             MASKED_WRITE(s->blkcnt, mask >> 16, value >> 16);
1010         }
1011 
1012         /* Limit block size to the maximum buffer size */
1013         if (extract32(s->blksize, 0, 12) > s->buf_maxsz) {
1014             qemu_log_mask(LOG_GUEST_ERROR, "%s: Size 0x%x is larger than " \
1015                           "the maximum buffer 0x%x", __func__, s->blksize,
1016                           s->buf_maxsz);
1017 
1018             s->blksize = deposit32(s->blksize, 0, 12, s->buf_maxsz);
1019         }
1020 
1021         break;
1022     case SDHC_ARGUMENT:
1023         MASKED_WRITE(s->argument, mask, value);
1024         break;
1025     case SDHC_TRNMOD:
1026         /* DMA can be enabled only if it is supported as indicated by
1027          * capabilities register */
1028         if (!(s->capareg & SDHC_CAN_DO_DMA)) {
1029             value &= ~SDHC_TRNS_DMA;
1030         }
1031         MASKED_WRITE(s->trnmod, mask, value);
1032         MASKED_WRITE(s->cmdreg, mask >> 16, value >> 16);
1033 
1034         /* Writing to the upper byte of CMDREG triggers SD command generation */
1035         if ((mask & 0xFF000000) || !sdhci_can_issue_command(s)) {
1036             break;
1037         }
1038 
1039         sdhci_send_command(s);
1040         break;
1041     case  SDHC_BDATA:
1042         if (sdhci_buff_access_is_sequential(s, offset - SDHC_BDATA)) {
1043             sdhci_write_dataport(s, value >> shift, size);
1044         }
1045         break;
1046     case SDHC_HOSTCTL:
1047         if (!(mask & 0xFF0000)) {
1048             sdhci_blkgap_write(s, value >> 16);
1049         }
1050         MASKED_WRITE(s->hostctl, mask, value);
1051         MASKED_WRITE(s->pwrcon, mask >> 8, value >> 8);
1052         MASKED_WRITE(s->wakcon, mask >> 24, value >> 24);
1053         if (!(s->prnsts & SDHC_CARD_PRESENT) || ((s->pwrcon >> 1) & 0x7) < 5 ||
1054                 !(s->capareg & (1 << (31 - ((s->pwrcon >> 1) & 0x7))))) {
1055             s->pwrcon &= ~SDHC_POWER_ON;
1056         }
1057         break;
1058     case SDHC_CLKCON:
1059         if (!(mask & 0xFF000000)) {
1060             sdhci_reset_write(s, value >> 24);
1061         }
1062         MASKED_WRITE(s->clkcon, mask, value);
1063         MASKED_WRITE(s->timeoutcon, mask >> 16, value >> 16);
1064         if (s->clkcon & SDHC_CLOCK_INT_EN) {
1065             s->clkcon |= SDHC_CLOCK_INT_STABLE;
1066         } else {
1067             s->clkcon &= ~SDHC_CLOCK_INT_STABLE;
1068         }
1069         break;
1070     case SDHC_NORINTSTS:
1071         if (s->norintstsen & SDHC_NISEN_CARDINT) {
1072             value &= ~SDHC_NIS_CARDINT;
1073         }
1074         s->norintsts &= mask | ~value;
1075         s->errintsts &= (mask >> 16) | ~(value >> 16);
1076         if (s->errintsts) {
1077             s->norintsts |= SDHC_NIS_ERR;
1078         } else {
1079             s->norintsts &= ~SDHC_NIS_ERR;
1080         }
1081         sdhci_update_irq(s);
1082         break;
1083     case SDHC_NORINTSTSEN:
1084         MASKED_WRITE(s->norintstsen, mask, value);
1085         MASKED_WRITE(s->errintstsen, mask >> 16, value >> 16);
1086         s->norintsts &= s->norintstsen;
1087         s->errintsts &= s->errintstsen;
1088         if (s->errintsts) {
1089             s->norintsts |= SDHC_NIS_ERR;
1090         } else {
1091             s->norintsts &= ~SDHC_NIS_ERR;
1092         }
1093         sdhci_update_irq(s);
1094         break;
1095     case SDHC_NORINTSIGEN:
1096         MASKED_WRITE(s->norintsigen, mask, value);
1097         MASKED_WRITE(s->errintsigen, mask >> 16, value >> 16);
1098         sdhci_update_irq(s);
1099         break;
1100     case SDHC_ADMAERR:
1101         MASKED_WRITE(s->admaerr, mask, value);
1102         break;
1103     case SDHC_ADMASYSADDR:
1104         s->admasysaddr = (s->admasysaddr & (0xFFFFFFFF00000000ULL |
1105                 (uint64_t)mask)) | (uint64_t)value;
1106         break;
1107     case SDHC_ADMASYSADDR + 4:
1108         s->admasysaddr = (s->admasysaddr & (0x00000000FFFFFFFFULL |
1109                 ((uint64_t)mask << 32))) | ((uint64_t)value << 32);
1110         break;
1111     case SDHC_FEAER:
1112         s->acmd12errsts |= value;
1113         s->errintsts |= (value >> 16) & s->errintstsen;
1114         if (s->acmd12errsts) {
1115             s->errintsts |= SDHC_EIS_CMD12ERR;
1116         }
1117         if (s->errintsts) {
1118             s->norintsts |= SDHC_NIS_ERR;
1119         }
1120         sdhci_update_irq(s);
1121         break;
1122     default:
1123         ERRPRINT("bad %ub write offset: addr[0x%04x] <- %u(0x%x)\n",
1124                  size, (int)offset, value >> shift, value >> shift);
1125         break;
1126     }
1127     DPRINT_L2("write %ub: addr[0x%04x] <- %u(0x%x)\n",
1128               size, (int)offset, value >> shift, value >> shift);
1129 }
1130 
1131 static const MemoryRegionOps sdhci_mmio_ops = {
1132     .read = sdhci_read,
1133     .write = sdhci_write,
1134     .valid = {
1135         .min_access_size = 1,
1136         .max_access_size = 4,
1137         .unaligned = false
1138     },
1139     .endianness = DEVICE_LITTLE_ENDIAN,
1140 };
1141 
1142 static inline unsigned int sdhci_get_fifolen(SDHCIState *s)
1143 {
1144     switch (SDHC_CAPAB_BLOCKSIZE(s->capareg)) {
1145     case 0:
1146         return 512;
1147     case 1:
1148         return 1024;
1149     case 2:
1150         return 2048;
1151     default:
1152         hw_error("SDHC: unsupported value for maximum block size\n");
1153         return 0;
1154     }
1155 }
1156 
1157 static void sdhci_initfn(SDHCIState *s, BlockBackend *blk)
1158 {
1159     s->card = sd_init(blk, false);
1160     if (s->card == NULL) {
1161         exit(1);
1162     }
1163     s->eject_cb = qemu_allocate_irq(sdhci_insert_eject_cb, s, 0);
1164     s->ro_cb = qemu_allocate_irq(sdhci_card_readonly_cb, s, 0);
1165     sd_set_cb(s->card, s->ro_cb, s->eject_cb);
1166 
1167     s->insert_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, sdhci_raise_insertion_irq, s);
1168     s->transfer_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, sdhci_data_transfer, s);
1169 }
1170 
1171 static void sdhci_uninitfn(SDHCIState *s)
1172 {
1173     timer_del(s->insert_timer);
1174     timer_free(s->insert_timer);
1175     timer_del(s->transfer_timer);
1176     timer_free(s->transfer_timer);
1177     qemu_free_irq(s->eject_cb);
1178     qemu_free_irq(s->ro_cb);
1179 
1180     g_free(s->fifo_buffer);
1181     s->fifo_buffer = NULL;
1182 }
1183 
1184 const VMStateDescription sdhci_vmstate = {
1185     .name = "sdhci",
1186     .version_id = 1,
1187     .minimum_version_id = 1,
1188     .fields = (VMStateField[]) {
1189         VMSTATE_UINT32(sdmasysad, SDHCIState),
1190         VMSTATE_UINT16(blksize, SDHCIState),
1191         VMSTATE_UINT16(blkcnt, SDHCIState),
1192         VMSTATE_UINT32(argument, SDHCIState),
1193         VMSTATE_UINT16(trnmod, SDHCIState),
1194         VMSTATE_UINT16(cmdreg, SDHCIState),
1195         VMSTATE_UINT32_ARRAY(rspreg, SDHCIState, 4),
1196         VMSTATE_UINT32(prnsts, SDHCIState),
1197         VMSTATE_UINT8(hostctl, SDHCIState),
1198         VMSTATE_UINT8(pwrcon, SDHCIState),
1199         VMSTATE_UINT8(blkgap, SDHCIState),
1200         VMSTATE_UINT8(wakcon, SDHCIState),
1201         VMSTATE_UINT16(clkcon, SDHCIState),
1202         VMSTATE_UINT8(timeoutcon, SDHCIState),
1203         VMSTATE_UINT8(admaerr, SDHCIState),
1204         VMSTATE_UINT16(norintsts, SDHCIState),
1205         VMSTATE_UINT16(errintsts, SDHCIState),
1206         VMSTATE_UINT16(norintstsen, SDHCIState),
1207         VMSTATE_UINT16(errintstsen, SDHCIState),
1208         VMSTATE_UINT16(norintsigen, SDHCIState),
1209         VMSTATE_UINT16(errintsigen, SDHCIState),
1210         VMSTATE_UINT16(acmd12errsts, SDHCIState),
1211         VMSTATE_UINT16(data_count, SDHCIState),
1212         VMSTATE_UINT64(admasysaddr, SDHCIState),
1213         VMSTATE_UINT8(stopped_state, SDHCIState),
1214         VMSTATE_VBUFFER_UINT32(fifo_buffer, SDHCIState, 1, NULL, 0, buf_maxsz),
1215         VMSTATE_TIMER_PTR(insert_timer, SDHCIState),
1216         VMSTATE_TIMER_PTR(transfer_timer, SDHCIState),
1217         VMSTATE_END_OF_LIST()
1218     }
1219 };
1220 
1221 /* Capabilities registers provide information on supported features of this
1222  * specific host controller implementation */
1223 static Property sdhci_pci_properties[] = {
1224     /*
1225      * We currently fuse controller and card into a single device
1226      * model, but we intend to separate them.  For that purpose, the
1227      * properties that belong to the card are marked as experimental.
1228      */
1229     DEFINE_PROP_DRIVE("x-drive", SDHCIState, blk),
1230     DEFINE_PROP_UINT32("capareg", SDHCIState, capareg,
1231             SDHC_CAPAB_REG_DEFAULT),
1232     DEFINE_PROP_UINT32("maxcurr", SDHCIState, maxcurr, 0),
1233     DEFINE_PROP_END_OF_LIST(),
1234 };
1235 
1236 static void sdhci_pci_realize(PCIDevice *dev, Error **errp)
1237 {
1238     SDHCIState *s = PCI_SDHCI(dev);
1239     dev->config[PCI_CLASS_PROG] = 0x01; /* Standard Host supported DMA */
1240     dev->config[PCI_INTERRUPT_PIN] = 0x01; /* interrupt pin A */
1241     sdhci_initfn(s, s->blk);
1242     s->buf_maxsz = sdhci_get_fifolen(s);
1243     s->fifo_buffer = g_malloc0(s->buf_maxsz);
1244     s->irq = pci_allocate_irq(dev);
1245     memory_region_init_io(&s->iomem, OBJECT(s), &sdhci_mmio_ops, s, "sdhci",
1246             SDHC_REGISTERS_MAP_SIZE);
1247     pci_register_bar(dev, 0, 0, &s->iomem);
1248 }
1249 
1250 static void sdhci_pci_exit(PCIDevice *dev)
1251 {
1252     SDHCIState *s = PCI_SDHCI(dev);
1253     sdhci_uninitfn(s);
1254 }
1255 
1256 static void sdhci_pci_class_init(ObjectClass *klass, void *data)
1257 {
1258     DeviceClass *dc = DEVICE_CLASS(klass);
1259     PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
1260 
1261     k->realize = sdhci_pci_realize;
1262     k->exit = sdhci_pci_exit;
1263     k->vendor_id = PCI_VENDOR_ID_REDHAT;
1264     k->device_id = PCI_DEVICE_ID_REDHAT_SDHCI;
1265     k->class_id = PCI_CLASS_SYSTEM_SDHCI;
1266     set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
1267     dc->vmsd = &sdhci_vmstate;
1268     dc->props = sdhci_pci_properties;
1269 }
1270 
1271 static const TypeInfo sdhci_pci_info = {
1272     .name = TYPE_PCI_SDHCI,
1273     .parent = TYPE_PCI_DEVICE,
1274     .instance_size = sizeof(SDHCIState),
1275     .class_init = sdhci_pci_class_init,
1276 };
1277 
1278 static Property sdhci_sysbus_properties[] = {
1279     DEFINE_PROP_UINT32("capareg", SDHCIState, capareg,
1280             SDHC_CAPAB_REG_DEFAULT),
1281     DEFINE_PROP_UINT32("maxcurr", SDHCIState, maxcurr, 0),
1282     DEFINE_PROP_END_OF_LIST(),
1283 };
1284 
1285 static void sdhci_sysbus_init(Object *obj)
1286 {
1287     SDHCIState *s = SYSBUS_SDHCI(obj);
1288     DriveInfo *di;
1289 
1290     /* FIXME use a qdev drive property instead of drive_get_next() */
1291     di = drive_get_next(IF_SD);
1292     sdhci_initfn(s, di ? blk_by_legacy_dinfo(di) : NULL);
1293 }
1294 
1295 static void sdhci_sysbus_finalize(Object *obj)
1296 {
1297     SDHCIState *s = SYSBUS_SDHCI(obj);
1298     sdhci_uninitfn(s);
1299 }
1300 
1301 static void sdhci_sysbus_realize(DeviceState *dev, Error ** errp)
1302 {
1303     SDHCIState *s = SYSBUS_SDHCI(dev);
1304     SysBusDevice *sbd = SYS_BUS_DEVICE(dev);
1305 
1306     s->buf_maxsz = sdhci_get_fifolen(s);
1307     s->fifo_buffer = g_malloc0(s->buf_maxsz);
1308     sysbus_init_irq(sbd, &s->irq);
1309     memory_region_init_io(&s->iomem, OBJECT(s), &sdhci_mmio_ops, s, "sdhci",
1310             SDHC_REGISTERS_MAP_SIZE);
1311     sysbus_init_mmio(sbd, &s->iomem);
1312 }
1313 
1314 static void sdhci_sysbus_class_init(ObjectClass *klass, void *data)
1315 {
1316     DeviceClass *dc = DEVICE_CLASS(klass);
1317 
1318     dc->vmsd = &sdhci_vmstate;
1319     dc->props = sdhci_sysbus_properties;
1320     dc->realize = sdhci_sysbus_realize;
1321     /* Reason: instance_init() method uses drive_get_next() */
1322     dc->cannot_instantiate_with_device_add_yet = true;
1323 }
1324 
1325 static const TypeInfo sdhci_sysbus_info = {
1326     .name = TYPE_SYSBUS_SDHCI,
1327     .parent = TYPE_SYS_BUS_DEVICE,
1328     .instance_size = sizeof(SDHCIState),
1329     .instance_init = sdhci_sysbus_init,
1330     .instance_finalize = sdhci_sysbus_finalize,
1331     .class_init = sdhci_sysbus_class_init,
1332 };
1333 
1334 static void sdhci_register_types(void)
1335 {
1336     type_register_static(&sdhci_pci_info);
1337     type_register_static(&sdhci_sysbus_info);
1338 }
1339 
1340 type_init(sdhci_register_types)
1341