xref: /openbmc/qemu/hw/sd/sdhci.c (revision 52f91c37)
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/blockdev.h"
27 #include "sysemu/dma.h"
28 #include "qemu/timer.h"
29 #include "qemu/bitops.h"
30 
31 #include "sdhci.h"
32 
33 /* host controller debug messages */
34 #ifndef SDHC_DEBUG
35 #define SDHC_DEBUG                        0
36 #endif
37 
38 #if SDHC_DEBUG == 0
39     #define DPRINT_L1(fmt, args...)       do { } while (0)
40     #define DPRINT_L2(fmt, args...)       do { } while (0)
41     #define ERRPRINT(fmt, args...)        do { } while (0)
42 #elif SDHC_DEBUG == 1
43     #define DPRINT_L1(fmt, args...)       \
44         do {fprintf(stderr, "QEMU SDHC: "fmt, ## args); } while (0)
45     #define DPRINT_L2(fmt, args...)       do { } while (0)
46     #define ERRPRINT(fmt, args...)        \
47         do {fprintf(stderr, "QEMU SDHC ERROR: "fmt, ## args); } while (0)
48 #else
49     #define DPRINT_L1(fmt, args...)       \
50         do {fprintf(stderr, "QEMU SDHC: "fmt, ## args); } while (0)
51     #define DPRINT_L2(fmt, args...)       \
52         do {fprintf(stderr, "QEMU SDHC: "fmt, ## args); } while (0)
53     #define ERRPRINT(fmt, args...)        \
54         do {fprintf(stderr, "QEMU SDHC ERROR: "fmt, ## args); } while (0)
55 #endif
56 
57 /* Default SD/MMC host controller features information, which will be
58  * presented in CAPABILITIES register of generic SD host controller at reset.
59  * If not stated otherwise:
60  * 0 - not supported, 1 - supported, other - prohibited.
61  */
62 #define SDHC_CAPAB_64BITBUS       0ul        /* 64-bit System Bus Support */
63 #define SDHC_CAPAB_18V            1ul        /* Voltage support 1.8v */
64 #define SDHC_CAPAB_30V            0ul        /* Voltage support 3.0v */
65 #define SDHC_CAPAB_33V            1ul        /* Voltage support 3.3v */
66 #define SDHC_CAPAB_SUSPRESUME     0ul        /* Suspend/resume support */
67 #define SDHC_CAPAB_SDMA           1ul        /* SDMA support */
68 #define SDHC_CAPAB_HIGHSPEED      1ul        /* High speed support */
69 #define SDHC_CAPAB_ADMA1          1ul        /* ADMA1 support */
70 #define SDHC_CAPAB_ADMA2          1ul        /* ADMA2 support */
71 /* Maximum host controller R/W buffers size
72  * Possible values: 512, 1024, 2048 bytes */
73 #define SDHC_CAPAB_MAXBLOCKLENGTH 512ul
74 /* Maximum clock frequency for SDclock in MHz
75  * value in range 10-63 MHz, 0 - not defined */
76 #define SDHC_CAPAB_BASECLKFREQ    0ul
77 #define SDHC_CAPAB_TOUNIT         1ul  /* Timeout clock unit 0 - kHz, 1 - MHz */
78 /* Timeout clock frequency 1-63, 0 - not defined */
79 #define SDHC_CAPAB_TOCLKFREQ      0ul
80 
81 /* Now check all parameters and calculate CAPABILITIES REGISTER value */
82 #if SDHC_CAPAB_64BITBUS > 1 || SDHC_CAPAB_18V > 1 || SDHC_CAPAB_30V > 1 ||     \
83     SDHC_CAPAB_33V > 1 || SDHC_CAPAB_SUSPRESUME > 1 || SDHC_CAPAB_SDMA > 1 ||  \
84     SDHC_CAPAB_HIGHSPEED > 1 || SDHC_CAPAB_ADMA2 > 1 || SDHC_CAPAB_ADMA1 > 1 ||\
85     SDHC_CAPAB_TOUNIT > 1
86 #error Capabilities features can have value 0 or 1 only!
87 #endif
88 
89 #if SDHC_CAPAB_MAXBLOCKLENGTH == 512
90 #define MAX_BLOCK_LENGTH 0ul
91 #elif SDHC_CAPAB_MAXBLOCKLENGTH == 1024
92 #define MAX_BLOCK_LENGTH 1ul
93 #elif SDHC_CAPAB_MAXBLOCKLENGTH == 2048
94 #define MAX_BLOCK_LENGTH 2ul
95 #else
96 #error Max host controller block size can have value 512, 1024 or 2048 only!
97 #endif
98 
99 #if (SDHC_CAPAB_BASECLKFREQ > 0 && SDHC_CAPAB_BASECLKFREQ < 10) || \
100     SDHC_CAPAB_BASECLKFREQ > 63
101 #error SDclock frequency can have value in range 0, 10-63 only!
102 #endif
103 
104 #if SDHC_CAPAB_TOCLKFREQ > 63
105 #error Timeout clock frequency can have value in range 0-63 only!
106 #endif
107 
108 #define SDHC_CAPAB_REG_DEFAULT                                 \
109    ((SDHC_CAPAB_64BITBUS << 28) | (SDHC_CAPAB_18V << 26) |     \
110     (SDHC_CAPAB_30V << 25) | (SDHC_CAPAB_33V << 24) |          \
111     (SDHC_CAPAB_SUSPRESUME << 23) | (SDHC_CAPAB_SDMA << 22) |  \
112     (SDHC_CAPAB_HIGHSPEED << 21) | (SDHC_CAPAB_ADMA1 << 20) |  \
113     (SDHC_CAPAB_ADMA2 << 19) | (MAX_BLOCK_LENGTH << 16) |      \
114     (SDHC_CAPAB_BASECLKFREQ << 8) | (SDHC_CAPAB_TOUNIT << 7) | \
115     (SDHC_CAPAB_TOCLKFREQ))
116 
117 #define MASKED_WRITE(reg, mask, val)  (reg = (reg & (mask)) | (val))
118 
119 static uint8_t sdhci_slotint(SDHCIState *s)
120 {
121     return (s->norintsts & s->norintsigen) || (s->errintsts & s->errintsigen) ||
122          ((s->norintsts & SDHC_NIS_INSERT) && (s->wakcon & SDHC_WKUP_ON_INS)) ||
123          ((s->norintsts & SDHC_NIS_REMOVE) && (s->wakcon & SDHC_WKUP_ON_RMV));
124 }
125 
126 static inline void sdhci_update_irq(SDHCIState *s)
127 {
128     qemu_set_irq(s->irq, sdhci_slotint(s));
129 }
130 
131 static void sdhci_raise_insertion_irq(void *opaque)
132 {
133     SDHCIState *s = (SDHCIState *)opaque;
134 
135     if (s->norintsts & SDHC_NIS_REMOVE) {
136         timer_mod(s->insert_timer,
137                        qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + SDHC_INSERTION_DELAY);
138     } else {
139         s->prnsts = 0x1ff0000;
140         if (s->norintstsen & SDHC_NISEN_INSERT) {
141             s->norintsts |= SDHC_NIS_INSERT;
142         }
143         sdhci_update_irq(s);
144     }
145 }
146 
147 static void sdhci_insert_eject_cb(void *opaque, int irq, int level)
148 {
149     SDHCIState *s = (SDHCIState *)opaque;
150     DPRINT_L1("Card state changed: %s!\n", level ? "insert" : "eject");
151 
152     if ((s->norintsts & SDHC_NIS_REMOVE) && level) {
153         /* Give target some time to notice card ejection */
154         timer_mod(s->insert_timer,
155                        qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + SDHC_INSERTION_DELAY);
156     } else {
157         if (level) {
158             s->prnsts = 0x1ff0000;
159             if (s->norintstsen & SDHC_NISEN_INSERT) {
160                 s->norintsts |= SDHC_NIS_INSERT;
161             }
162         } else {
163             s->prnsts = 0x1fa0000;
164             s->pwrcon &= ~SDHC_POWER_ON;
165             s->clkcon &= ~SDHC_CLOCK_SDCLK_EN;
166             if (s->norintstsen & SDHC_NISEN_REMOVE) {
167                 s->norintsts |= SDHC_NIS_REMOVE;
168             }
169         }
170         sdhci_update_irq(s);
171     }
172 }
173 
174 static void sdhci_card_readonly_cb(void *opaque, int irq, int level)
175 {
176     SDHCIState *s = (SDHCIState *)opaque;
177 
178     if (level) {
179         s->prnsts &= ~SDHC_WRITE_PROTECT;
180     } else {
181         /* Write enabled */
182         s->prnsts |= SDHC_WRITE_PROTECT;
183     }
184 }
185 
186 static void sdhci_reset(SDHCIState *s)
187 {
188     timer_del(s->insert_timer);
189     timer_del(s->transfer_timer);
190     /* Set all registers to 0. Capabilities registers are not cleared
191      * and assumed to always preserve their value, given to them during
192      * initialization */
193     memset(&s->sdmasysad, 0, (uintptr_t)&s->capareg - (uintptr_t)&s->sdmasysad);
194 
195     sd_set_cb(s->card, s->ro_cb, s->eject_cb);
196     s->data_count = 0;
197     s->stopped_state = sdhc_not_stopped;
198 }
199 
200 static void sdhci_do_data_transfer(void *opaque)
201 {
202     SDHCIState *s = (SDHCIState *)opaque;
203 
204     SDHCI_GET_CLASS(s)->data_transfer(s);
205 }
206 
207 static void sdhci_send_command(SDHCIState *s)
208 {
209     SDRequest request;
210     uint8_t response[16];
211     int rlen;
212 
213     s->errintsts = 0;
214     s->acmd12errsts = 0;
215     request.cmd = s->cmdreg >> 8;
216     request.arg = s->argument;
217     DPRINT_L1("sending CMD%u ARG[0x%08x]\n", request.cmd, request.arg);
218     rlen = sd_do_command(s->card, &request, response);
219 
220     if (s->cmdreg & SDHC_CMD_RESPONSE) {
221         if (rlen == 4) {
222             s->rspreg[0] = (response[0] << 24) | (response[1] << 16) |
223                            (response[2] << 8)  |  response[3];
224             s->rspreg[1] = s->rspreg[2] = s->rspreg[3] = 0;
225             DPRINT_L1("Response: RSPREG[31..0]=0x%08x\n", s->rspreg[0]);
226         } else if (rlen == 16) {
227             s->rspreg[0] = (response[11] << 24) | (response[12] << 16) |
228                            (response[13] << 8) |  response[14];
229             s->rspreg[1] = (response[7] << 24) | (response[8] << 16) |
230                            (response[9] << 8)  |  response[10];
231             s->rspreg[2] = (response[3] << 24) | (response[4] << 16) |
232                            (response[5] << 8)  |  response[6];
233             s->rspreg[3] = (response[0] << 16) | (response[1] << 8) |
234                             response[2];
235             DPRINT_L1("Response received:\n RSPREG[127..96]=0x%08x, RSPREG[95.."
236                   "64]=0x%08x,\n RSPREG[63..32]=0x%08x, RSPREG[31..0]=0x%08x\n",
237                   s->rspreg[3], s->rspreg[2], s->rspreg[1], s->rspreg[0]);
238         } else {
239             ERRPRINT("Timeout waiting for command response\n");
240             if (s->errintstsen & SDHC_EISEN_CMDTIMEOUT) {
241                 s->errintsts |= SDHC_EIS_CMDTIMEOUT;
242                 s->norintsts |= SDHC_NIS_ERR;
243             }
244         }
245 
246         if ((s->norintstsen & SDHC_NISEN_TRSCMP) &&
247             (s->cmdreg & SDHC_CMD_RESPONSE) == SDHC_CMD_RSP_WITH_BUSY) {
248             s->norintsts |= SDHC_NIS_TRSCMP;
249         }
250     } else if (rlen != 0 && (s->errintstsen & SDHC_EISEN_CMDIDX)) {
251         s->errintsts |= SDHC_EIS_CMDIDX;
252         s->norintsts |= SDHC_NIS_ERR;
253     }
254 
255     if (s->norintstsen & SDHC_NISEN_CMDCMP) {
256         s->norintsts |= SDHC_NIS_CMDCMP;
257     }
258 
259     sdhci_update_irq(s);
260 
261     if (s->blksize && (s->cmdreg & SDHC_CMD_DATA_PRESENT)) {
262         s->data_count = 0;
263         sdhci_do_data_transfer(s);
264     }
265 }
266 
267 static void sdhci_end_transfer(SDHCIState *s)
268 {
269     /* Automatically send CMD12 to stop transfer if AutoCMD12 enabled */
270     if ((s->trnmod & SDHC_TRNS_ACMD12) != 0) {
271         SDRequest request;
272         uint8_t response[16];
273 
274         request.cmd = 0x0C;
275         request.arg = 0;
276         DPRINT_L1("Automatically issue CMD%d %08x\n", request.cmd, request.arg);
277         sd_do_command(s->card, &request, response);
278         /* Auto CMD12 response goes to the upper Response register */
279         s->rspreg[3] = (response[0] << 24) | (response[1] << 16) |
280                 (response[2] << 8) | response[3];
281     }
282 
283     s->prnsts &= ~(SDHC_DOING_READ | SDHC_DOING_WRITE |
284             SDHC_DAT_LINE_ACTIVE | SDHC_DATA_INHIBIT |
285             SDHC_SPACE_AVAILABLE | SDHC_DATA_AVAILABLE);
286 
287     if (s->norintstsen & SDHC_NISEN_TRSCMP) {
288         s->norintsts |= SDHC_NIS_TRSCMP;
289     }
290 
291     sdhci_update_irq(s);
292 }
293 
294 /*
295  * Programmed i/o data transfer
296  */
297 
298 /* Fill host controller's read buffer with BLKSIZE bytes of data from card */
299 static void sdhci_read_block_from_card(SDHCIState *s)
300 {
301     int index = 0;
302 
303     if ((s->trnmod & SDHC_TRNS_MULTI) &&
304             (s->trnmod & SDHC_TRNS_BLK_CNT_EN) && (s->blkcnt == 0)) {
305         return;
306     }
307 
308     for (index = 0; index < (s->blksize & 0x0fff); index++) {
309         s->fifo_buffer[index] = sd_read_data(s->card);
310     }
311 
312     /* New data now available for READ through Buffer Port Register */
313     s->prnsts |= SDHC_DATA_AVAILABLE;
314     if (s->norintstsen & SDHC_NISEN_RBUFRDY) {
315         s->norintsts |= SDHC_NIS_RBUFRDY;
316     }
317 
318     /* Clear DAT line active status if that was the last block */
319     if ((s->trnmod & SDHC_TRNS_MULTI) == 0 ||
320             ((s->trnmod & SDHC_TRNS_MULTI) && s->blkcnt == 1)) {
321         s->prnsts &= ~SDHC_DAT_LINE_ACTIVE;
322     }
323 
324     /* If stop at block gap request was set and it's not the last block of
325      * data - generate Block Event interrupt */
326     if (s->stopped_state == sdhc_gap_read && (s->trnmod & SDHC_TRNS_MULTI) &&
327             s->blkcnt != 1)    {
328         s->prnsts &= ~SDHC_DAT_LINE_ACTIVE;
329         if (s->norintstsen & SDHC_EISEN_BLKGAP) {
330             s->norintsts |= SDHC_EIS_BLKGAP;
331         }
332     }
333 
334     sdhci_update_irq(s);
335 }
336 
337 /* Read @size byte of data from host controller @s BUFFER DATA PORT register */
338 static uint32_t sdhci_read_dataport(SDHCIState *s, unsigned size)
339 {
340     uint32_t value = 0;
341     int i;
342 
343     /* first check that a valid data exists in host controller input buffer */
344     if ((s->prnsts & SDHC_DATA_AVAILABLE) == 0) {
345         ERRPRINT("Trying to read from empty buffer\n");
346         return 0;
347     }
348 
349     for (i = 0; i < size; i++) {
350         value |= s->fifo_buffer[s->data_count] << i * 8;
351         s->data_count++;
352         /* check if we've read all valid data (blksize bytes) from buffer */
353         if ((s->data_count) >= (s->blksize & 0x0fff)) {
354             DPRINT_L2("All %u bytes of data have been read from input buffer\n",
355                     s->data_count);
356             s->prnsts &= ~SDHC_DATA_AVAILABLE; /* no more data in a buffer */
357             s->data_count = 0;  /* next buff read must start at position [0] */
358 
359             if (s->trnmod & SDHC_TRNS_BLK_CNT_EN) {
360                 s->blkcnt--;
361             }
362 
363             /* if that was the last block of data */
364             if ((s->trnmod & SDHC_TRNS_MULTI) == 0 ||
365                 ((s->trnmod & SDHC_TRNS_BLK_CNT_EN) && (s->blkcnt == 0)) ||
366                  /* stop at gap request */
367                 (s->stopped_state == sdhc_gap_read &&
368                  !(s->prnsts & SDHC_DAT_LINE_ACTIVE))) {
369                 SDHCI_GET_CLASS(s)->end_data_transfer(s);
370             } else { /* if there are more data, read next block from card */
371                 SDHCI_GET_CLASS(s)->read_block_from_card(s);
372             }
373             break;
374         }
375     }
376 
377     return value;
378 }
379 
380 /* Write data from host controller FIFO to card */
381 static void sdhci_write_block_to_card(SDHCIState *s)
382 {
383     int index = 0;
384 
385     if (s->prnsts & SDHC_SPACE_AVAILABLE) {
386         if (s->norintstsen & SDHC_NISEN_WBUFRDY) {
387             s->norintsts |= SDHC_NIS_WBUFRDY;
388         }
389         sdhci_update_irq(s);
390         return;
391     }
392 
393     if (s->trnmod & SDHC_TRNS_BLK_CNT_EN) {
394         if (s->blkcnt == 0) {
395             return;
396         } else {
397             s->blkcnt--;
398         }
399     }
400 
401     for (index = 0; index < (s->blksize & 0x0fff); index++) {
402         sd_write_data(s->card, s->fifo_buffer[index]);
403     }
404 
405     /* Next data can be written through BUFFER DATORT register */
406     s->prnsts |= SDHC_SPACE_AVAILABLE;
407 
408     /* Finish transfer if that was the last block of data */
409     if ((s->trnmod & SDHC_TRNS_MULTI) == 0 ||
410             ((s->trnmod & SDHC_TRNS_MULTI) &&
411             (s->trnmod & SDHC_TRNS_BLK_CNT_EN) && (s->blkcnt == 0))) {
412         SDHCI_GET_CLASS(s)->end_data_transfer(s);
413     } else if (s->norintstsen & SDHC_NISEN_WBUFRDY) {
414         s->norintsts |= SDHC_NIS_WBUFRDY;
415     }
416 
417     /* Generate Block Gap Event if requested and if not the last block */
418     if (s->stopped_state == sdhc_gap_write && (s->trnmod & SDHC_TRNS_MULTI) &&
419             s->blkcnt > 0) {
420         s->prnsts &= ~SDHC_DOING_WRITE;
421         if (s->norintstsen & SDHC_EISEN_BLKGAP) {
422             s->norintsts |= SDHC_EIS_BLKGAP;
423         }
424         SDHCI_GET_CLASS(s)->end_data_transfer(s);
425     }
426 
427     sdhci_update_irq(s);
428 }
429 
430 /* Write @size bytes of @value data to host controller @s Buffer Data Port
431  * register */
432 static void sdhci_write_dataport(SDHCIState *s, uint32_t value, unsigned size)
433 {
434     unsigned i;
435 
436     /* Check that there is free space left in a buffer */
437     if (!(s->prnsts & SDHC_SPACE_AVAILABLE)) {
438         ERRPRINT("Can't write to data buffer: buffer full\n");
439         return;
440     }
441 
442     for (i = 0; i < size; i++) {
443         s->fifo_buffer[s->data_count] = value & 0xFF;
444         s->data_count++;
445         value >>= 8;
446         if (s->data_count >= (s->blksize & 0x0fff)) {
447             DPRINT_L2("write buffer filled with %u bytes of data\n",
448                     s->data_count);
449             s->data_count = 0;
450             s->prnsts &= ~SDHC_SPACE_AVAILABLE;
451             if (s->prnsts & SDHC_DOING_WRITE) {
452                 SDHCI_GET_CLASS(s)->write_block_to_card(s);
453             }
454         }
455     }
456 }
457 
458 /*
459  * Single DMA data transfer
460  */
461 
462 /* Multi block SDMA transfer */
463 static void sdhci_sdma_transfer_multi_blocks(SDHCIState *s)
464 {
465     bool page_aligned = false;
466     unsigned int n, begin;
467     const uint16_t block_size = s->blksize & 0x0fff;
468     uint32_t boundary_chk = 1 << (((s->blksize & 0xf000) >> 12) + 12);
469     uint32_t boundary_count = boundary_chk - (s->sdmasysad % boundary_chk);
470 
471     /* XXX: Some sd/mmc drivers (for example, u-boot-slp) do not account for
472      * possible stop at page boundary if initial address is not page aligned,
473      * allow them to work properly */
474     if ((s->sdmasysad % boundary_chk) == 0) {
475         page_aligned = true;
476     }
477 
478     if (s->trnmod & SDHC_TRNS_READ) {
479         s->prnsts |= SDHC_DOING_READ | SDHC_DATA_INHIBIT |
480                 SDHC_DAT_LINE_ACTIVE;
481         while (s->blkcnt) {
482             if (s->data_count == 0) {
483                 for (n = 0; n < block_size; n++) {
484                     s->fifo_buffer[n] = sd_read_data(s->card);
485                 }
486             }
487             begin = s->data_count;
488             if (((boundary_count + begin) < block_size) && page_aligned) {
489                 s->data_count = boundary_count + begin;
490                 boundary_count = 0;
491              } else {
492                 s->data_count = block_size;
493                 boundary_count -= block_size - begin;
494                 if (s->trnmod & SDHC_TRNS_BLK_CNT_EN) {
495                     s->blkcnt--;
496                 }
497             }
498             dma_memory_write(&address_space_memory, s->sdmasysad,
499                              &s->fifo_buffer[begin], s->data_count - begin);
500             s->sdmasysad += s->data_count - begin;
501             if (s->data_count == block_size) {
502                 s->data_count = 0;
503             }
504             if (page_aligned && boundary_count == 0) {
505                 break;
506             }
507         }
508     } else {
509         s->prnsts |= SDHC_DOING_WRITE | SDHC_DATA_INHIBIT |
510                 SDHC_DAT_LINE_ACTIVE;
511         while (s->blkcnt) {
512             begin = s->data_count;
513             if (((boundary_count + begin) < block_size) && page_aligned) {
514                 s->data_count = boundary_count + begin;
515                 boundary_count = 0;
516              } else {
517                 s->data_count = block_size;
518                 boundary_count -= block_size - begin;
519             }
520             dma_memory_read(&address_space_memory, s->sdmasysad,
521                             &s->fifo_buffer[begin], s->data_count);
522             s->sdmasysad += s->data_count - begin;
523             if (s->data_count == block_size) {
524                 for (n = 0; n < block_size; n++) {
525                     sd_write_data(s->card, s->fifo_buffer[n]);
526                 }
527                 s->data_count = 0;
528                 if (s->trnmod & SDHC_TRNS_BLK_CNT_EN) {
529                     s->blkcnt--;
530                 }
531             }
532             if (page_aligned && boundary_count == 0) {
533                 break;
534             }
535         }
536     }
537 
538     if (s->blkcnt == 0) {
539         SDHCI_GET_CLASS(s)->end_data_transfer(s);
540     } else {
541         if (s->norintstsen & SDHC_NISEN_DMA) {
542             s->norintsts |= SDHC_NIS_DMA;
543         }
544         sdhci_update_irq(s);
545     }
546 }
547 
548 /* single block SDMA transfer */
549 
550 static void sdhci_sdma_transfer_single_block(SDHCIState *s)
551 {
552     int n;
553     uint32_t datacnt = s->blksize & 0x0fff;
554 
555     if (s->trnmod & SDHC_TRNS_READ) {
556         for (n = 0; n < datacnt; n++) {
557             s->fifo_buffer[n] = sd_read_data(s->card);
558         }
559         dma_memory_write(&address_space_memory, s->sdmasysad, s->fifo_buffer,
560                          datacnt);
561     } else {
562         dma_memory_read(&address_space_memory, s->sdmasysad, s->fifo_buffer,
563                         datacnt);
564         for (n = 0; n < datacnt; n++) {
565             sd_write_data(s->card, s->fifo_buffer[n]);
566         }
567     }
568 
569     if (s->trnmod & SDHC_TRNS_BLK_CNT_EN) {
570         s->blkcnt--;
571     }
572 
573     SDHCI_GET_CLASS(s)->end_data_transfer(s);
574 }
575 
576 typedef struct ADMADescr {
577     hwaddr addr;
578     uint16_t length;
579     uint8_t attr;
580     uint8_t incr;
581 } ADMADescr;
582 
583 static void get_adma_description(SDHCIState *s, ADMADescr *dscr)
584 {
585     uint32_t adma1 = 0;
586     uint64_t adma2 = 0;
587     hwaddr entry_addr = (hwaddr)s->admasysaddr;
588     switch (SDHC_DMA_TYPE(s->hostctl)) {
589     case SDHC_CTRL_ADMA2_32:
590         dma_memory_read(&address_space_memory, entry_addr, (uint8_t *)&adma2,
591                         sizeof(adma2));
592         adma2 = le64_to_cpu(adma2);
593         /* The spec does not specify endianness of descriptor table.
594          * We currently assume that it is LE.
595          */
596         dscr->addr = (hwaddr)extract64(adma2, 32, 32) & ~0x3ull;
597         dscr->length = (uint16_t)extract64(adma2, 16, 16);
598         dscr->attr = (uint8_t)extract64(adma2, 0, 7);
599         dscr->incr = 8;
600         break;
601     case SDHC_CTRL_ADMA1_32:
602         dma_memory_read(&address_space_memory, entry_addr, (uint8_t *)&adma1,
603                         sizeof(adma1));
604         adma1 = le32_to_cpu(adma1);
605         dscr->addr = (hwaddr)(adma1 & 0xFFFFF000);
606         dscr->attr = (uint8_t)extract32(adma1, 0, 7);
607         dscr->incr = 4;
608         if ((dscr->attr & SDHC_ADMA_ATTR_ACT_MASK) == SDHC_ADMA_ATTR_SET_LEN) {
609             dscr->length = (uint16_t)extract32(adma1, 12, 16);
610         } else {
611             dscr->length = 4096;
612         }
613         break;
614     case SDHC_CTRL_ADMA2_64:
615         dma_memory_read(&address_space_memory, entry_addr,
616                         (uint8_t *)(&dscr->attr), 1);
617         dma_memory_read(&address_space_memory, entry_addr + 2,
618                         (uint8_t *)(&dscr->length), 2);
619         dscr->length = le16_to_cpu(dscr->length);
620         dma_memory_read(&address_space_memory, entry_addr + 4,
621                         (uint8_t *)(&dscr->addr), 8);
622         dscr->attr = le64_to_cpu(dscr->attr);
623         dscr->attr &= 0xfffffff8;
624         dscr->incr = 12;
625         break;
626     }
627 }
628 
629 /* Advanced DMA data transfer */
630 
631 static void sdhci_do_adma(SDHCIState *s)
632 {
633     unsigned int n, begin, length;
634     const uint16_t block_size = s->blksize & 0x0fff;
635     ADMADescr dscr;
636     int i;
637 
638     for (i = 0; i < SDHC_ADMA_DESCS_PER_DELAY; ++i) {
639         s->admaerr &= ~SDHC_ADMAERR_LENGTH_MISMATCH;
640 
641         get_adma_description(s, &dscr);
642         DPRINT_L2("ADMA loop: addr=" TARGET_FMT_plx ", len=%d, attr=%x\n",
643                 dscr.addr, dscr.length, dscr.attr);
644 
645         if ((dscr.attr & SDHC_ADMA_ATTR_VALID) == 0) {
646             /* Indicate that error occurred in ST_FDS state */
647             s->admaerr &= ~SDHC_ADMAERR_STATE_MASK;
648             s->admaerr |= SDHC_ADMAERR_STATE_ST_FDS;
649 
650             /* Generate ADMA error interrupt */
651             if (s->errintstsen & SDHC_EISEN_ADMAERR) {
652                 s->errintsts |= SDHC_EIS_ADMAERR;
653                 s->norintsts |= SDHC_NIS_ERR;
654             }
655 
656             sdhci_update_irq(s);
657             return;
658         }
659 
660         length = dscr.length ? dscr.length : 65536;
661 
662         switch (dscr.attr & SDHC_ADMA_ATTR_ACT_MASK) {
663         case SDHC_ADMA_ATTR_ACT_TRAN:  /* data transfer */
664 
665             if (s->trnmod & SDHC_TRNS_READ) {
666                 while (length) {
667                     if (s->data_count == 0) {
668                         for (n = 0; n < block_size; n++) {
669                             s->fifo_buffer[n] = sd_read_data(s->card);
670                         }
671                     }
672                     begin = s->data_count;
673                     if ((length + begin) < block_size) {
674                         s->data_count = length + begin;
675                         length = 0;
676                      } else {
677                         s->data_count = block_size;
678                         length -= block_size - begin;
679                     }
680                     dma_memory_write(&address_space_memory, dscr.addr,
681                                      &s->fifo_buffer[begin],
682                                      s->data_count - begin);
683                     dscr.addr += s->data_count - begin;
684                     if (s->data_count == block_size) {
685                         s->data_count = 0;
686                         if (s->trnmod & SDHC_TRNS_BLK_CNT_EN) {
687                             s->blkcnt--;
688                             if (s->blkcnt == 0) {
689                                 break;
690                             }
691                         }
692                     }
693                 }
694             } else {
695                 while (length) {
696                     begin = s->data_count;
697                     if ((length + begin) < block_size) {
698                         s->data_count = length + begin;
699                         length = 0;
700                      } else {
701                         s->data_count = block_size;
702                         length -= block_size - begin;
703                     }
704                     dma_memory_read(&address_space_memory, dscr.addr,
705                                     &s->fifo_buffer[begin], s->data_count);
706                     dscr.addr += s->data_count - begin;
707                     if (s->data_count == block_size) {
708                         for (n = 0; n < block_size; n++) {
709                             sd_write_data(s->card, s->fifo_buffer[n]);
710                         }
711                         s->data_count = 0;
712                         if (s->trnmod & SDHC_TRNS_BLK_CNT_EN) {
713                             s->blkcnt--;
714                             if (s->blkcnt == 0) {
715                                 break;
716                             }
717                         }
718                     }
719                 }
720             }
721             s->admasysaddr += dscr.incr;
722             break;
723         case SDHC_ADMA_ATTR_ACT_LINK:   /* link to next descriptor table */
724             s->admasysaddr = dscr.addr;
725             DPRINT_L1("ADMA link: admasysaddr=0x%lx\n", s->admasysaddr);
726             break;
727         default:
728             s->admasysaddr += dscr.incr;
729             break;
730         }
731 
732         if (dscr.attr & SDHC_ADMA_ATTR_INT) {
733             DPRINT_L1("ADMA interrupt: admasysaddr=0x%lx\n", s->admasysaddr);
734             if (s->norintstsen & SDHC_NISEN_DMA) {
735                 s->norintsts |= SDHC_NIS_DMA;
736             }
737 
738             sdhci_update_irq(s);
739         }
740 
741         /* ADMA transfer terminates if blkcnt == 0 or by END attribute */
742         if (((s->trnmod & SDHC_TRNS_BLK_CNT_EN) &&
743                     (s->blkcnt == 0)) || (dscr.attr & SDHC_ADMA_ATTR_END)) {
744             DPRINT_L2("ADMA transfer completed\n");
745             if (length || ((dscr.attr & SDHC_ADMA_ATTR_END) &&
746                 (s->trnmod & SDHC_TRNS_BLK_CNT_EN) &&
747                 s->blkcnt != 0)) {
748                 ERRPRINT("SD/MMC host ADMA length mismatch\n");
749                 s->admaerr |= SDHC_ADMAERR_LENGTH_MISMATCH |
750                         SDHC_ADMAERR_STATE_ST_TFR;
751                 if (s->errintstsen & SDHC_EISEN_ADMAERR) {
752                     ERRPRINT("Set ADMA error flag\n");
753                     s->errintsts |= SDHC_EIS_ADMAERR;
754                     s->norintsts |= SDHC_NIS_ERR;
755                 }
756 
757                 sdhci_update_irq(s);
758             }
759             SDHCI_GET_CLASS(s)->end_data_transfer(s);
760             return;
761         }
762 
763     }
764 
765     /* we have unfinished business - reschedule to continue ADMA */
766     timer_mod(s->transfer_timer,
767                    qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + SDHC_TRANSFER_DELAY);
768 }
769 
770 /* Perform data transfer according to controller configuration */
771 
772 static void sdhci_data_transfer(SDHCIState *s)
773 {
774     SDHCIClass *k = SDHCI_GET_CLASS(s);
775 
776     if (s->trnmod & SDHC_TRNS_DMA) {
777         switch (SDHC_DMA_TYPE(s->hostctl)) {
778         case SDHC_CTRL_SDMA:
779             if ((s->trnmod & SDHC_TRNS_MULTI) &&
780                     (!(s->trnmod & SDHC_TRNS_BLK_CNT_EN) || s->blkcnt == 0)) {
781                 break;
782             }
783 
784             if ((s->blkcnt == 1) || !(s->trnmod & SDHC_TRNS_MULTI)) {
785                 k->do_sdma_single(s);
786             } else {
787                 k->do_sdma_multi(s);
788             }
789 
790             break;
791         case SDHC_CTRL_ADMA1_32:
792             if (!(s->capareg & SDHC_CAN_DO_ADMA1)) {
793                 ERRPRINT("ADMA1 not supported\n");
794                 break;
795             }
796 
797             k->do_adma(s);
798             break;
799         case SDHC_CTRL_ADMA2_32:
800             if (!(s->capareg & SDHC_CAN_DO_ADMA2)) {
801                 ERRPRINT("ADMA2 not supported\n");
802                 break;
803             }
804 
805             k->do_adma(s);
806             break;
807         case SDHC_CTRL_ADMA2_64:
808             if (!(s->capareg & SDHC_CAN_DO_ADMA2) ||
809                     !(s->capareg & SDHC_64_BIT_BUS_SUPPORT)) {
810                 ERRPRINT("64 bit ADMA not supported\n");
811                 break;
812             }
813 
814             k->do_adma(s);
815             break;
816         default:
817             ERRPRINT("Unsupported DMA type\n");
818             break;
819         }
820     } else {
821         if ((s->trnmod & SDHC_TRNS_READ) && sd_data_ready(s->card)) {
822             s->prnsts |= SDHC_DOING_READ | SDHC_DATA_INHIBIT |
823                     SDHC_DAT_LINE_ACTIVE;
824             SDHCI_GET_CLASS(s)->read_block_from_card(s);
825         } else {
826             s->prnsts |= SDHC_DOING_WRITE | SDHC_DAT_LINE_ACTIVE |
827                     SDHC_SPACE_AVAILABLE | SDHC_DATA_INHIBIT;
828             SDHCI_GET_CLASS(s)->write_block_to_card(s);
829         }
830     }
831 }
832 
833 static bool sdhci_can_issue_command(SDHCIState *s)
834 {
835     if (!SDHC_CLOCK_IS_ON(s->clkcon) || !(s->pwrcon & SDHC_POWER_ON) ||
836         (((s->prnsts & SDHC_DATA_INHIBIT) || s->stopped_state) &&
837         ((s->cmdreg & SDHC_CMD_DATA_PRESENT) ||
838         ((s->cmdreg & SDHC_CMD_RESPONSE) == SDHC_CMD_RSP_WITH_BUSY &&
839         !(SDHC_COMMAND_TYPE(s->cmdreg) == SDHC_CMD_ABORT))))) {
840         return false;
841     }
842 
843     return true;
844 }
845 
846 /* The Buffer Data Port register must be accessed in sequential and
847  * continuous manner */
848 static inline bool
849 sdhci_buff_access_is_sequential(SDHCIState *s, unsigned byte_num)
850 {
851     if ((s->data_count & 0x3) != byte_num) {
852         ERRPRINT("Non-sequential access to Buffer Data Port register"
853                 "is prohibited\n");
854         return false;
855     }
856     return true;
857 }
858 
859 static uint32_t sdhci_read(SDHCIState *s, unsigned int offset, unsigned size)
860 {
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_GET_CLASS(s)->bdata_read(s, size);
882             DPRINT_L2("read %ub: addr[0x%04x] -> %u(0x%x)\n", size, 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, 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, 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_GET_CLASS(s)->read_block_from_card(s);
950         } else {
951             s->prnsts |= SDHC_DAT_LINE_ACTIVE | SDHC_DOING_WRITE;
952             SDHCI_GET_CLASS(s)->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         DEVICE_GET_CLASS(s)->reset(DEVICE(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(SDHCIState *s, unsigned int offset, uint32_t value, unsigned size)
989 {
990     unsigned shift =  8 * (offset & 0x3);
991     uint32_t mask = ~(((1ULL << (size * 8)) - 1) << shift);
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_GET_CLASS(s)->do_sdma_multi(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_GET_CLASS(s)->can_issue_command(s)) {
1024             break;
1025         }
1026 
1027         SDHCI_GET_CLASS(s)->send_command(s);
1028         break;
1029     case  SDHC_BDATA:
1030         if (sdhci_buff_access_is_sequential(s, offset - SDHC_BDATA)) {
1031             SDHCI_GET_CLASS(s)->bdata_write(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, offset, value >> shift, value >> shift);
1113         break;
1114     }
1115     DPRINT_L2("write %ub: addr[0x%04x] <- %u(0x%x)\n",
1116             size, offset, value >> shift, value >> shift);
1117 }
1118 
1119 static uint64_t
1120 sdhci_readfn(void *opaque, hwaddr offset, unsigned size)
1121 {
1122     SDHCIState *s = (SDHCIState *)opaque;
1123 
1124     return SDHCI_GET_CLASS(s)->mem_read(s, offset, size);
1125 }
1126 
1127 static void
1128 sdhci_writefn(void *opaque, hwaddr off, uint64_t val, unsigned sz)
1129 {
1130     SDHCIState *s = (SDHCIState *)opaque;
1131 
1132     SDHCI_GET_CLASS(s)->mem_write(s, off, val, sz);
1133 }
1134 
1135 static const MemoryRegionOps sdhci_mmio_ops = {
1136     .read = sdhci_readfn,
1137     .write = sdhci_writefn,
1138     .valid = {
1139         .min_access_size = 1,
1140         .max_access_size = 4,
1141         .unaligned = false
1142     },
1143     .endianness = DEVICE_LITTLE_ENDIAN,
1144 };
1145 
1146 static inline unsigned int sdhci_get_fifolen(SDHCIState *s)
1147 {
1148     switch (SDHC_CAPAB_BLOCKSIZE(s->capareg)) {
1149     case 0:
1150         return 512;
1151     case 1:
1152         return 1024;
1153     case 2:
1154         return 2048;
1155     default:
1156         hw_error("SDHC: unsupported value for maximum block size\n");
1157         return 0;
1158     }
1159 }
1160 
1161 static void sdhci_initfn(Object *obj)
1162 {
1163     SDHCIState *s = SDHCI(obj);
1164     DriveInfo *di;
1165 
1166     di = drive_get_next(IF_SD);
1167     s->card = sd_init(di ? di->bdrv : NULL, false);
1168     if (s->card == NULL) {
1169         exit(1);
1170     }
1171     s->eject_cb = qemu_allocate_irqs(sdhci_insert_eject_cb, s, 1)[0];
1172     s->ro_cb = qemu_allocate_irqs(sdhci_card_readonly_cb, s, 1)[0];
1173     sd_set_cb(s->card, s->ro_cb, s->eject_cb);
1174 
1175     s->insert_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, sdhci_raise_insertion_irq, s);
1176     s->transfer_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, sdhci_do_data_transfer, s);
1177 }
1178 
1179 static void sdhci_uninitfn(Object *obj)
1180 {
1181     SDHCIState *s = SDHCI(obj);
1182 
1183     timer_del(s->insert_timer);
1184     timer_free(s->insert_timer);
1185     timer_del(s->transfer_timer);
1186     timer_free(s->transfer_timer);
1187     qemu_free_irqs(&s->eject_cb);
1188     qemu_free_irqs(&s->ro_cb);
1189 
1190     if (s->fifo_buffer) {
1191         g_free(s->fifo_buffer);
1192         s->fifo_buffer = NULL;
1193     }
1194 }
1195 
1196 const VMStateDescription sdhci_vmstate = {
1197     .name = "sdhci",
1198     .version_id = 1,
1199     .minimum_version_id = 1,
1200     .fields      = (VMStateField[]) {
1201         VMSTATE_UINT32(sdmasysad, SDHCIState),
1202         VMSTATE_UINT16(blksize, SDHCIState),
1203         VMSTATE_UINT16(blkcnt, SDHCIState),
1204         VMSTATE_UINT32(argument, SDHCIState),
1205         VMSTATE_UINT16(trnmod, SDHCIState),
1206         VMSTATE_UINT16(cmdreg, SDHCIState),
1207         VMSTATE_UINT32_ARRAY(rspreg, SDHCIState, 4),
1208         VMSTATE_UINT32(prnsts, SDHCIState),
1209         VMSTATE_UINT8(hostctl, SDHCIState),
1210         VMSTATE_UINT8(pwrcon, SDHCIState),
1211         VMSTATE_UINT8(blkgap, SDHCIState),
1212         VMSTATE_UINT8(wakcon, SDHCIState),
1213         VMSTATE_UINT16(clkcon, SDHCIState),
1214         VMSTATE_UINT8(timeoutcon, SDHCIState),
1215         VMSTATE_UINT8(admaerr, SDHCIState),
1216         VMSTATE_UINT16(norintsts, SDHCIState),
1217         VMSTATE_UINT16(errintsts, SDHCIState),
1218         VMSTATE_UINT16(norintstsen, SDHCIState),
1219         VMSTATE_UINT16(errintstsen, SDHCIState),
1220         VMSTATE_UINT16(norintsigen, SDHCIState),
1221         VMSTATE_UINT16(errintsigen, SDHCIState),
1222         VMSTATE_UINT16(acmd12errsts, SDHCIState),
1223         VMSTATE_UINT16(data_count, SDHCIState),
1224         VMSTATE_UINT64(admasysaddr, SDHCIState),
1225         VMSTATE_UINT8(stopped_state, SDHCIState),
1226         VMSTATE_VBUFFER_UINT32(fifo_buffer, SDHCIState, 1, NULL, 0, buf_maxsz),
1227         VMSTATE_TIMER(insert_timer, SDHCIState),
1228         VMSTATE_TIMER(transfer_timer, SDHCIState),
1229         VMSTATE_END_OF_LIST()
1230     }
1231 };
1232 
1233 /* Capabilities registers provide information on supported features of this
1234  * specific host controller implementation */
1235 static Property sdhci_properties[] = {
1236     DEFINE_PROP_UINT32("capareg", SDHCIState, capareg,
1237             SDHC_CAPAB_REG_DEFAULT),
1238     DEFINE_PROP_UINT32("maxcurr", SDHCIState, maxcurr, 0),
1239     DEFINE_PROP_END_OF_LIST(),
1240 };
1241 
1242 static void sdhci_realize(DeviceState *dev, Error ** errp)
1243 {
1244     SDHCIState *s = SDHCI(dev);
1245     SysBusDevice *sbd = SYS_BUS_DEVICE(dev);
1246 
1247     s->buf_maxsz = sdhci_get_fifolen(s);
1248     s->fifo_buffer = g_malloc0(s->buf_maxsz);
1249     sysbus_init_irq(sbd, &s->irq);
1250     memory_region_init_io(&s->iomem, OBJECT(s), &sdhci_mmio_ops, s, "sdhci",
1251             SDHC_REGISTERS_MAP_SIZE);
1252     sysbus_init_mmio(sbd, &s->iomem);
1253 }
1254 
1255 static void sdhci_generic_reset(DeviceState *ds)
1256 {
1257     SDHCIState *s = SDHCI(ds);
1258     SDHCI_GET_CLASS(s)->reset(s);
1259 }
1260 
1261 static void sdhci_class_init(ObjectClass *klass, void *data)
1262 {
1263     DeviceClass *dc = DEVICE_CLASS(klass);
1264     SDHCIClass *k = SDHCI_CLASS(klass);
1265 
1266     dc->vmsd = &sdhci_vmstate;
1267     dc->props = sdhci_properties;
1268     dc->reset = sdhci_generic_reset;
1269     dc->realize = sdhci_realize;
1270 
1271     k->reset = sdhci_reset;
1272     k->mem_read = sdhci_read;
1273     k->mem_write = sdhci_write;
1274     k->send_command = sdhci_send_command;
1275     k->can_issue_command = sdhci_can_issue_command;
1276     k->data_transfer = sdhci_data_transfer;
1277     k->end_data_transfer = sdhci_end_transfer;
1278     k->do_sdma_single = sdhci_sdma_transfer_single_block;
1279     k->do_sdma_multi = sdhci_sdma_transfer_multi_blocks;
1280     k->do_adma = sdhci_do_adma;
1281     k->read_block_from_card = sdhci_read_block_from_card;
1282     k->write_block_to_card = sdhci_write_block_to_card;
1283     k->bdata_read = sdhci_read_dataport;
1284     k->bdata_write = sdhci_write_dataport;
1285 }
1286 
1287 static const TypeInfo sdhci_type_info = {
1288     .name = TYPE_SDHCI,
1289     .parent = TYPE_SYS_BUS_DEVICE,
1290     .instance_size = sizeof(SDHCIState),
1291     .instance_init = sdhci_initfn,
1292     .instance_finalize = sdhci_uninitfn,
1293     .class_init = sdhci_class_init,
1294     .class_size = sizeof(SDHCIClass)
1295 };
1296 
1297 static void sdhci_register_types(void)
1298 {
1299     type_register_static(&sdhci_type_info);
1300 }
1301 
1302 type_init(sdhci_register_types)
1303