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