xref: /openbmc/qemu/hw/sd/sdhci.c (revision 2822c1b6)
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 "hw/hw.h"
26 #include "sysemu/block-backend.h"
27 #include "sysemu/blockdev.h"
28 #include "sysemu/dma.h"
29 #include "qemu/timer.h"
30 #include "qemu/bitops.h"
31 
32 #include "sdhci.h"
33 
34 /* host controller debug messages */
35 #ifndef SDHC_DEBUG
36 #define SDHC_DEBUG                        0
37 #endif
38 
39 #if SDHC_DEBUG == 0
40     #define DPRINT_L1(fmt, args...)       do { } while (0)
41     #define DPRINT_L2(fmt, args...)       do { } while (0)
42     #define ERRPRINT(fmt, args...)        do { } while (0)
43 #elif SDHC_DEBUG == 1
44     #define DPRINT_L1(fmt, args...)       \
45         do {fprintf(stderr, "QEMU SDHC: "fmt, ## args); } while (0)
46     #define DPRINT_L2(fmt, args...)       do { } while (0)
47     #define ERRPRINT(fmt, args...)        \
48         do {fprintf(stderr, "QEMU SDHC ERROR: "fmt, ## args); } while (0)
49 #else
50     #define DPRINT_L1(fmt, args...)       \
51         do {fprintf(stderr, "QEMU SDHC: "fmt, ## args); } while (0)
52     #define DPRINT_L2(fmt, args...)       \
53         do {fprintf(stderr, "QEMU SDHC: "fmt, ## args); } while (0)
54     #define ERRPRINT(fmt, args...)        \
55         do {fprintf(stderr, "QEMU SDHC ERROR: "fmt, ## args); } while (0)
56 #endif
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%lx\n", s->admasysaddr);
723             break;
724         default:
725             s->admasysaddr += dscr.incr;
726             break;
727         }
728 
729         if (dscr.attr & SDHC_ADMA_ATTR_INT) {
730             DPRINT_L1("ADMA interrupt: admasysaddr=0x%lx\n", s->admasysaddr);
731             if (s->norintstsen & SDHC_NISEN_DMA) {
732                 s->norintsts |= SDHC_NIS_DMA;
733             }
734 
735             sdhci_update_irq(s);
736         }
737 
738         /* ADMA transfer terminates if blkcnt == 0 or by END attribute */
739         if (((s->trnmod & SDHC_TRNS_BLK_CNT_EN) &&
740                     (s->blkcnt == 0)) || (dscr.attr & SDHC_ADMA_ATTR_END)) {
741             DPRINT_L2("ADMA transfer completed\n");
742             if (length || ((dscr.attr & SDHC_ADMA_ATTR_END) &&
743                 (s->trnmod & SDHC_TRNS_BLK_CNT_EN) &&
744                 s->blkcnt != 0)) {
745                 ERRPRINT("SD/MMC host ADMA length mismatch\n");
746                 s->admaerr |= SDHC_ADMAERR_LENGTH_MISMATCH |
747                         SDHC_ADMAERR_STATE_ST_TFR;
748                 if (s->errintstsen & SDHC_EISEN_ADMAERR) {
749                     ERRPRINT("Set ADMA error flag\n");
750                     s->errintsts |= SDHC_EIS_ADMAERR;
751                     s->norintsts |= SDHC_NIS_ERR;
752                 }
753 
754                 sdhci_update_irq(s);
755             }
756             sdhci_end_transfer(s);
757             return;
758         }
759 
760     }
761 
762     /* we have unfinished business - reschedule to continue ADMA */
763     timer_mod(s->transfer_timer,
764                    qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + SDHC_TRANSFER_DELAY);
765 }
766 
767 /* Perform data transfer according to controller configuration */
768 
769 static void sdhci_data_transfer(void *opaque)
770 {
771     SDHCIState *s = (SDHCIState *)opaque;
772 
773     if (s->trnmod & SDHC_TRNS_DMA) {
774         switch (SDHC_DMA_TYPE(s->hostctl)) {
775         case SDHC_CTRL_SDMA:
776             if ((s->trnmod & SDHC_TRNS_MULTI) &&
777                     (!(s->trnmod & SDHC_TRNS_BLK_CNT_EN) || s->blkcnt == 0)) {
778                 break;
779             }
780 
781             if ((s->blkcnt == 1) || !(s->trnmod & SDHC_TRNS_MULTI)) {
782                 sdhci_sdma_transfer_single_block(s);
783             } else {
784                 sdhci_sdma_transfer_multi_blocks(s);
785             }
786 
787             break;
788         case SDHC_CTRL_ADMA1_32:
789             if (!(s->capareg & SDHC_CAN_DO_ADMA1)) {
790                 ERRPRINT("ADMA1 not supported\n");
791                 break;
792             }
793 
794             sdhci_do_adma(s);
795             break;
796         case SDHC_CTRL_ADMA2_32:
797             if (!(s->capareg & SDHC_CAN_DO_ADMA2)) {
798                 ERRPRINT("ADMA2 not supported\n");
799                 break;
800             }
801 
802             sdhci_do_adma(s);
803             break;
804         case SDHC_CTRL_ADMA2_64:
805             if (!(s->capareg & SDHC_CAN_DO_ADMA2) ||
806                     !(s->capareg & SDHC_64_BIT_BUS_SUPPORT)) {
807                 ERRPRINT("64 bit ADMA not supported\n");
808                 break;
809             }
810 
811             sdhci_do_adma(s);
812             break;
813         default:
814             ERRPRINT("Unsupported DMA type\n");
815             break;
816         }
817     } else {
818         if ((s->trnmod & SDHC_TRNS_READ) && sd_data_ready(s->card)) {
819             s->prnsts |= SDHC_DOING_READ | SDHC_DATA_INHIBIT |
820                     SDHC_DAT_LINE_ACTIVE;
821             sdhci_read_block_from_card(s);
822         } else {
823             s->prnsts |= SDHC_DOING_WRITE | SDHC_DAT_LINE_ACTIVE |
824                     SDHC_SPACE_AVAILABLE | SDHC_DATA_INHIBIT;
825             sdhci_write_block_to_card(s);
826         }
827     }
828 }
829 
830 static bool sdhci_can_issue_command(SDHCIState *s)
831 {
832     if (!SDHC_CLOCK_IS_ON(s->clkcon) || !(s->pwrcon & SDHC_POWER_ON) ||
833         (((s->prnsts & SDHC_DATA_INHIBIT) || s->stopped_state) &&
834         ((s->cmdreg & SDHC_CMD_DATA_PRESENT) ||
835         ((s->cmdreg & SDHC_CMD_RESPONSE) == SDHC_CMD_RSP_WITH_BUSY &&
836         !(SDHC_COMMAND_TYPE(s->cmdreg) == SDHC_CMD_ABORT))))) {
837         return false;
838     }
839 
840     return true;
841 }
842 
843 /* The Buffer Data Port register must be accessed in sequential and
844  * continuous manner */
845 static inline bool
846 sdhci_buff_access_is_sequential(SDHCIState *s, unsigned byte_num)
847 {
848     if ((s->data_count & 0x3) != byte_num) {
849         ERRPRINT("Non-sequential access to Buffer Data Port register"
850                 "is prohibited\n");
851         return false;
852     }
853     return true;
854 }
855 
856 static uint64_t sdhci_read(void *opaque, hwaddr offset, unsigned size)
857 {
858     SDHCIState *s = (SDHCIState *)opaque;
859     uint32_t ret = 0;
860 
861     switch (offset & ~0x3) {
862     case SDHC_SYSAD:
863         ret = s->sdmasysad;
864         break;
865     case SDHC_BLKSIZE:
866         ret = s->blksize | (s->blkcnt << 16);
867         break;
868     case SDHC_ARGUMENT:
869         ret = s->argument;
870         break;
871     case SDHC_TRNMOD:
872         ret = s->trnmod | (s->cmdreg << 16);
873         break;
874     case SDHC_RSPREG0 ... SDHC_RSPREG3:
875         ret = s->rspreg[((offset & ~0x3) - SDHC_RSPREG0) >> 2];
876         break;
877     case  SDHC_BDATA:
878         if (sdhci_buff_access_is_sequential(s, offset - SDHC_BDATA)) {
879             ret = sdhci_read_dataport(s, size);
880             DPRINT_L2("read %ub: addr[0x%04x] -> %u(0x%x)\n", size, (int)offset,
881                       ret, ret);
882             return ret;
883         }
884         break;
885     case SDHC_PRNSTS:
886         ret = s->prnsts;
887         break;
888     case SDHC_HOSTCTL:
889         ret = s->hostctl | (s->pwrcon << 8) | (s->blkgap << 16) |
890               (s->wakcon << 24);
891         break;
892     case SDHC_CLKCON:
893         ret = s->clkcon | (s->timeoutcon << 16);
894         break;
895     case SDHC_NORINTSTS:
896         ret = s->norintsts | (s->errintsts << 16);
897         break;
898     case SDHC_NORINTSTSEN:
899         ret = s->norintstsen | (s->errintstsen << 16);
900         break;
901     case SDHC_NORINTSIGEN:
902         ret = s->norintsigen | (s->errintsigen << 16);
903         break;
904     case SDHC_ACMD12ERRSTS:
905         ret = s->acmd12errsts;
906         break;
907     case SDHC_CAPAREG:
908         ret = s->capareg;
909         break;
910     case SDHC_MAXCURR:
911         ret = s->maxcurr;
912         break;
913     case SDHC_ADMAERR:
914         ret =  s->admaerr;
915         break;
916     case SDHC_ADMASYSADDR:
917         ret = (uint32_t)s->admasysaddr;
918         break;
919     case SDHC_ADMASYSADDR + 4:
920         ret = (uint32_t)(s->admasysaddr >> 32);
921         break;
922     case SDHC_SLOT_INT_STATUS:
923         ret = (SD_HOST_SPECv2_VERS << 16) | sdhci_slotint(s);
924         break;
925     default:
926         ERRPRINT("bad %ub read: addr[0x%04x]\n", size, (int)offset);
927         break;
928     }
929 
930     ret >>= (offset & 0x3) * 8;
931     ret &= (1ULL << (size * 8)) - 1;
932     DPRINT_L2("read %ub: addr[0x%04x] -> %u(0x%x)\n", size, (int)offset, ret, ret);
933     return ret;
934 }
935 
936 static inline void sdhci_blkgap_write(SDHCIState *s, uint8_t value)
937 {
938     if ((value & SDHC_STOP_AT_GAP_REQ) && (s->blkgap & SDHC_STOP_AT_GAP_REQ)) {
939         return;
940     }
941     s->blkgap = value & SDHC_STOP_AT_GAP_REQ;
942 
943     if ((value & SDHC_CONTINUE_REQ) && s->stopped_state &&
944             (s->blkgap & SDHC_STOP_AT_GAP_REQ) == 0) {
945         if (s->stopped_state == sdhc_gap_read) {
946             s->prnsts |= SDHC_DAT_LINE_ACTIVE | SDHC_DOING_READ;
947             sdhci_read_block_from_card(s);
948         } else {
949             s->prnsts |= SDHC_DAT_LINE_ACTIVE | SDHC_DOING_WRITE;
950             sdhci_write_block_to_card(s);
951         }
952         s->stopped_state = sdhc_not_stopped;
953     } else if (!s->stopped_state && (value & SDHC_STOP_AT_GAP_REQ)) {
954         if (s->prnsts & SDHC_DOING_READ) {
955             s->stopped_state = sdhc_gap_read;
956         } else if (s->prnsts & SDHC_DOING_WRITE) {
957             s->stopped_state = sdhc_gap_write;
958         }
959     }
960 }
961 
962 static inline void sdhci_reset_write(SDHCIState *s, uint8_t value)
963 {
964     switch (value) {
965     case SDHC_RESET_ALL:
966         sdhci_reset(s);
967         break;
968     case SDHC_RESET_CMD:
969         s->prnsts &= ~SDHC_CMD_INHIBIT;
970         s->norintsts &= ~SDHC_NIS_CMDCMP;
971         break;
972     case SDHC_RESET_DATA:
973         s->data_count = 0;
974         s->prnsts &= ~(SDHC_SPACE_AVAILABLE | SDHC_DATA_AVAILABLE |
975                 SDHC_DOING_READ | SDHC_DOING_WRITE |
976                 SDHC_DATA_INHIBIT | SDHC_DAT_LINE_ACTIVE);
977         s->blkgap &= ~(SDHC_STOP_AT_GAP_REQ | SDHC_CONTINUE_REQ);
978         s->stopped_state = sdhc_not_stopped;
979         s->norintsts &= ~(SDHC_NIS_WBUFRDY | SDHC_NIS_RBUFRDY |
980                 SDHC_NIS_DMA | SDHC_NIS_TRSCMP | SDHC_NIS_BLKGAP);
981         break;
982     }
983 }
984 
985 static void
986 sdhci_write(void *opaque, hwaddr offset, uint64_t val, unsigned size)
987 {
988     SDHCIState *s = (SDHCIState *)opaque;
989     unsigned shift =  8 * (offset & 0x3);
990     uint32_t mask = ~(((1ULL << (size * 8)) - 1) << shift);
991     uint32_t value = val;
992     value <<= shift;
993 
994     switch (offset & ~0x3) {
995     case SDHC_SYSAD:
996         s->sdmasysad = (s->sdmasysad & mask) | value;
997         MASKED_WRITE(s->sdmasysad, mask, value);
998         /* Writing to last byte of sdmasysad might trigger transfer */
999         if (!(mask & 0xFF000000) && TRANSFERRING_DATA(s->prnsts) && s->blkcnt &&
1000                 s->blksize && SDHC_DMA_TYPE(s->hostctl) == SDHC_CTRL_SDMA) {
1001             sdhci_sdma_transfer_multi_blocks(s);
1002         }
1003         break;
1004     case SDHC_BLKSIZE:
1005         if (!TRANSFERRING_DATA(s->prnsts)) {
1006             MASKED_WRITE(s->blksize, mask, value);
1007             MASKED_WRITE(s->blkcnt, mask >> 16, value >> 16);
1008         }
1009         break;
1010     case SDHC_ARGUMENT:
1011         MASKED_WRITE(s->argument, mask, value);
1012         break;
1013     case SDHC_TRNMOD:
1014         /* DMA can be enabled only if it is supported as indicated by
1015          * capabilities register */
1016         if (!(s->capareg & SDHC_CAN_DO_DMA)) {
1017             value &= ~SDHC_TRNS_DMA;
1018         }
1019         MASKED_WRITE(s->trnmod, mask, value);
1020         MASKED_WRITE(s->cmdreg, mask >> 16, value >> 16);
1021 
1022         /* Writing to the upper byte of CMDREG triggers SD command generation */
1023         if ((mask & 0xFF000000) || !sdhci_can_issue_command(s)) {
1024             break;
1025         }
1026 
1027         sdhci_send_command(s);
1028         break;
1029     case  SDHC_BDATA:
1030         if (sdhci_buff_access_is_sequential(s, offset - SDHC_BDATA)) {
1031             sdhci_write_dataport(s, value >> shift, size);
1032         }
1033         break;
1034     case SDHC_HOSTCTL:
1035         if (!(mask & 0xFF0000)) {
1036             sdhci_blkgap_write(s, value >> 16);
1037         }
1038         MASKED_WRITE(s->hostctl, mask, value);
1039         MASKED_WRITE(s->pwrcon, mask >> 8, value >> 8);
1040         MASKED_WRITE(s->wakcon, mask >> 24, value >> 24);
1041         if (!(s->prnsts & SDHC_CARD_PRESENT) || ((s->pwrcon >> 1) & 0x7) < 5 ||
1042                 !(s->capareg & (1 << (31 - ((s->pwrcon >> 1) & 0x7))))) {
1043             s->pwrcon &= ~SDHC_POWER_ON;
1044         }
1045         break;
1046     case SDHC_CLKCON:
1047         if (!(mask & 0xFF000000)) {
1048             sdhci_reset_write(s, value >> 24);
1049         }
1050         MASKED_WRITE(s->clkcon, mask, value);
1051         MASKED_WRITE(s->timeoutcon, mask >> 16, value >> 16);
1052         if (s->clkcon & SDHC_CLOCK_INT_EN) {
1053             s->clkcon |= SDHC_CLOCK_INT_STABLE;
1054         } else {
1055             s->clkcon &= ~SDHC_CLOCK_INT_STABLE;
1056         }
1057         break;
1058     case SDHC_NORINTSTS:
1059         if (s->norintstsen & SDHC_NISEN_CARDINT) {
1060             value &= ~SDHC_NIS_CARDINT;
1061         }
1062         s->norintsts &= mask | ~value;
1063         s->errintsts &= (mask >> 16) | ~(value >> 16);
1064         if (s->errintsts) {
1065             s->norintsts |= SDHC_NIS_ERR;
1066         } else {
1067             s->norintsts &= ~SDHC_NIS_ERR;
1068         }
1069         sdhci_update_irq(s);
1070         break;
1071     case SDHC_NORINTSTSEN:
1072         MASKED_WRITE(s->norintstsen, mask, value);
1073         MASKED_WRITE(s->errintstsen, mask >> 16, value >> 16);
1074         s->norintsts &= s->norintstsen;
1075         s->errintsts &= s->errintstsen;
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_NORINTSIGEN:
1084         MASKED_WRITE(s->norintsigen, mask, value);
1085         MASKED_WRITE(s->errintsigen, mask >> 16, value >> 16);
1086         sdhci_update_irq(s);
1087         break;
1088     case SDHC_ADMAERR:
1089         MASKED_WRITE(s->admaerr, mask, value);
1090         break;
1091     case SDHC_ADMASYSADDR:
1092         s->admasysaddr = (s->admasysaddr & (0xFFFFFFFF00000000ULL |
1093                 (uint64_t)mask)) | (uint64_t)value;
1094         break;
1095     case SDHC_ADMASYSADDR + 4:
1096         s->admasysaddr = (s->admasysaddr & (0x00000000FFFFFFFFULL |
1097                 ((uint64_t)mask << 32))) | ((uint64_t)value << 32);
1098         break;
1099     case SDHC_FEAER:
1100         s->acmd12errsts |= value;
1101         s->errintsts |= (value >> 16) & s->errintstsen;
1102         if (s->acmd12errsts) {
1103             s->errintsts |= SDHC_EIS_CMD12ERR;
1104         }
1105         if (s->errintsts) {
1106             s->norintsts |= SDHC_NIS_ERR;
1107         }
1108         sdhci_update_irq(s);
1109         break;
1110     default:
1111         ERRPRINT("bad %ub write offset: addr[0x%04x] <- %u(0x%x)\n",
1112                  size, (int)offset, value >> shift, value >> shift);
1113         break;
1114     }
1115     DPRINT_L2("write %ub: addr[0x%04x] <- %u(0x%x)\n",
1116               size, (int)offset, value >> shift, value >> shift);
1117 }
1118 
1119 static const MemoryRegionOps sdhci_mmio_ops = {
1120     .read = sdhci_read,
1121     .write = sdhci_write,
1122     .valid = {
1123         .min_access_size = 1,
1124         .max_access_size = 4,
1125         .unaligned = false
1126     },
1127     .endianness = DEVICE_LITTLE_ENDIAN,
1128 };
1129 
1130 static inline unsigned int sdhci_get_fifolen(SDHCIState *s)
1131 {
1132     switch (SDHC_CAPAB_BLOCKSIZE(s->capareg)) {
1133     case 0:
1134         return 512;
1135     case 1:
1136         return 1024;
1137     case 2:
1138         return 2048;
1139     default:
1140         hw_error("SDHC: unsupported value for maximum block size\n");
1141         return 0;
1142     }
1143 }
1144 
1145 static void sdhci_initfn(SDHCIState *s)
1146 {
1147     DriveInfo *di;
1148 
1149     di = drive_get_next(IF_SD);
1150     s->card = sd_init(di ? blk_by_legacy_dinfo(di) : NULL, false);
1151     if (s->card == NULL) {
1152         exit(1);
1153     }
1154     s->eject_cb = qemu_allocate_irq(sdhci_insert_eject_cb, s, 0);
1155     s->ro_cb = qemu_allocate_irq(sdhci_card_readonly_cb, s, 0);
1156     sd_set_cb(s->card, s->ro_cb, s->eject_cb);
1157 
1158     s->insert_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, sdhci_raise_insertion_irq, s);
1159     s->transfer_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, sdhci_data_transfer, s);
1160 }
1161 
1162 static void sdhci_uninitfn(SDHCIState *s)
1163 {
1164     timer_del(s->insert_timer);
1165     timer_free(s->insert_timer);
1166     timer_del(s->transfer_timer);
1167     timer_free(s->transfer_timer);
1168     qemu_free_irq(s->eject_cb);
1169     qemu_free_irq(s->ro_cb);
1170 
1171     if (s->fifo_buffer) {
1172         g_free(s->fifo_buffer);
1173         s->fifo_buffer = NULL;
1174     }
1175 }
1176 
1177 const VMStateDescription sdhci_vmstate = {
1178     .name = "sdhci",
1179     .version_id = 1,
1180     .minimum_version_id = 1,
1181     .fields = (VMStateField[]) {
1182         VMSTATE_UINT32(sdmasysad, SDHCIState),
1183         VMSTATE_UINT16(blksize, SDHCIState),
1184         VMSTATE_UINT16(blkcnt, SDHCIState),
1185         VMSTATE_UINT32(argument, SDHCIState),
1186         VMSTATE_UINT16(trnmod, SDHCIState),
1187         VMSTATE_UINT16(cmdreg, SDHCIState),
1188         VMSTATE_UINT32_ARRAY(rspreg, SDHCIState, 4),
1189         VMSTATE_UINT32(prnsts, SDHCIState),
1190         VMSTATE_UINT8(hostctl, SDHCIState),
1191         VMSTATE_UINT8(pwrcon, SDHCIState),
1192         VMSTATE_UINT8(blkgap, SDHCIState),
1193         VMSTATE_UINT8(wakcon, SDHCIState),
1194         VMSTATE_UINT16(clkcon, SDHCIState),
1195         VMSTATE_UINT8(timeoutcon, SDHCIState),
1196         VMSTATE_UINT8(admaerr, SDHCIState),
1197         VMSTATE_UINT16(norintsts, SDHCIState),
1198         VMSTATE_UINT16(errintsts, SDHCIState),
1199         VMSTATE_UINT16(norintstsen, SDHCIState),
1200         VMSTATE_UINT16(errintstsen, SDHCIState),
1201         VMSTATE_UINT16(norintsigen, SDHCIState),
1202         VMSTATE_UINT16(errintsigen, SDHCIState),
1203         VMSTATE_UINT16(acmd12errsts, SDHCIState),
1204         VMSTATE_UINT16(data_count, SDHCIState),
1205         VMSTATE_UINT64(admasysaddr, SDHCIState),
1206         VMSTATE_UINT8(stopped_state, SDHCIState),
1207         VMSTATE_VBUFFER_UINT32(fifo_buffer, SDHCIState, 1, NULL, 0, buf_maxsz),
1208         VMSTATE_TIMER_PTR(insert_timer, SDHCIState),
1209         VMSTATE_TIMER_PTR(transfer_timer, SDHCIState),
1210         VMSTATE_END_OF_LIST()
1211     }
1212 };
1213 
1214 /* Capabilities registers provide information on supported features of this
1215  * specific host controller implementation */
1216 static Property sdhci_properties[] = {
1217     DEFINE_PROP_UINT32("capareg", SDHCIState, capareg,
1218             SDHC_CAPAB_REG_DEFAULT),
1219     DEFINE_PROP_UINT32("maxcurr", SDHCIState, maxcurr, 0),
1220     DEFINE_PROP_END_OF_LIST(),
1221 };
1222 
1223 static int sdhci_pci_init(PCIDevice *dev)
1224 {
1225     SDHCIState *s = PCI_SDHCI(dev);
1226     dev->config[PCI_CLASS_PROG] = 0x01; /* Standard Host supported DMA */
1227     dev->config[PCI_INTERRUPT_PIN] = 0x01; /* interrupt pin A */
1228     sdhci_initfn(s);
1229     s->buf_maxsz = sdhci_get_fifolen(s);
1230     s->fifo_buffer = g_malloc0(s->buf_maxsz);
1231     s->irq = pci_allocate_irq(dev);
1232     memory_region_init_io(&s->iomem, OBJECT(s), &sdhci_mmio_ops, s, "sdhci",
1233             SDHC_REGISTERS_MAP_SIZE);
1234     pci_register_bar(dev, 0, 0, &s->iomem);
1235     return 0;
1236 }
1237 
1238 static void sdhci_pci_exit(PCIDevice *dev)
1239 {
1240     SDHCIState *s = PCI_SDHCI(dev);
1241     sdhci_uninitfn(s);
1242 }
1243 
1244 static void sdhci_pci_class_init(ObjectClass *klass, void *data)
1245 {
1246     DeviceClass *dc = DEVICE_CLASS(klass);
1247     PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
1248 
1249     k->init = sdhci_pci_init;
1250     k->exit = sdhci_pci_exit;
1251     k->vendor_id = PCI_VENDOR_ID_REDHAT;
1252     k->device_id = PCI_DEVICE_ID_REDHAT_SDHCI;
1253     k->class_id = PCI_CLASS_SYSTEM_SDHCI;
1254     set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
1255     dc->vmsd = &sdhci_vmstate;
1256     dc->props = sdhci_properties;
1257 }
1258 
1259 static const TypeInfo sdhci_pci_info = {
1260     .name = TYPE_PCI_SDHCI,
1261     .parent = TYPE_PCI_DEVICE,
1262     .instance_size = sizeof(SDHCIState),
1263     .class_init = sdhci_pci_class_init,
1264 };
1265 
1266 static void sdhci_sysbus_init(Object *obj)
1267 {
1268     SDHCIState *s = SYSBUS_SDHCI(obj);
1269     sdhci_initfn(s);
1270 }
1271 
1272 static void sdhci_sysbus_finalize(Object *obj)
1273 {
1274     SDHCIState *s = SYSBUS_SDHCI(obj);
1275     sdhci_uninitfn(s);
1276 }
1277 
1278 static void sdhci_sysbus_realize(DeviceState *dev, Error ** errp)
1279 {
1280     SDHCIState *s = SYSBUS_SDHCI(dev);
1281     SysBusDevice *sbd = SYS_BUS_DEVICE(dev);
1282 
1283     s->buf_maxsz = sdhci_get_fifolen(s);
1284     s->fifo_buffer = g_malloc0(s->buf_maxsz);
1285     sysbus_init_irq(sbd, &s->irq);
1286     memory_region_init_io(&s->iomem, OBJECT(s), &sdhci_mmio_ops, s, "sdhci",
1287             SDHC_REGISTERS_MAP_SIZE);
1288     sysbus_init_mmio(sbd, &s->iomem);
1289 }
1290 
1291 static void sdhci_sysbus_class_init(ObjectClass *klass, void *data)
1292 {
1293     DeviceClass *dc = DEVICE_CLASS(klass);
1294 
1295     dc->vmsd = &sdhci_vmstate;
1296     dc->props = sdhci_properties;
1297     dc->realize = sdhci_sysbus_realize;
1298 }
1299 
1300 static const TypeInfo sdhci_sysbus_info = {
1301     .name = TYPE_SYSBUS_SDHCI,
1302     .parent = TYPE_SYS_BUS_DEVICE,
1303     .instance_size = sizeof(SDHCIState),
1304     .instance_init = sdhci_sysbus_init,
1305     .instance_finalize = sdhci_sysbus_finalize,
1306     .class_init = sdhci_sysbus_class_init,
1307 };
1308 
1309 static void sdhci_register_types(void)
1310 {
1311     type_register_static(&sdhci_pci_info);
1312     type_register_static(&sdhci_sysbus_info);
1313 }
1314 
1315 type_init(sdhci_register_types)
1316