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