xref: /openbmc/qemu/hw/sd/sdhci.c (revision 0dacec87)
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 "qemu/error-report.h"
27 #include "qapi/error.h"
28 #include "hw/hw.h"
29 #include "sysemu/block-backend.h"
30 #include "sysemu/blockdev.h"
31 #include "sysemu/dma.h"
32 #include "qemu/timer.h"
33 #include "qemu/bitops.h"
34 #include "hw/sd/sdhci.h"
35 #include "sdhci-internal.h"
36 #include "qemu/log.h"
37 #include "qemu/cutils.h"
38 #include "trace.h"
39 
40 #define TYPE_SDHCI_BUS "sdhci-bus"
41 #define SDHCI_BUS(obj) OBJECT_CHECK(SDBus, (obj), TYPE_SDHCI_BUS)
42 
43 #define MASKED_WRITE(reg, mask, val)  (reg = (reg & (mask)) | (val))
44 
45 /* Default SD/MMC host controller features information, which will be
46  * presented in CAPABILITIES register of generic SD host controller at reset.
47  *
48  * support:
49  * - 3.3v and 1.8v voltages
50  * - SDMA/ADMA1/ADMA2
51  * - high-speed
52  * max host controller R/W buffers size: 512B
53  * max clock frequency for SDclock: 52 MHz
54  * timeout clock frequency: 52 MHz
55  *
56  * does not support:
57  * - 3.0v voltage
58  * - 64-bit system bus
59  * - suspend/resume
60  */
61 #define SDHC_CAPAB_REG_DEFAULT 0x057834b4
62 
63 static inline unsigned int sdhci_get_fifolen(SDHCIState *s)
64 {
65     return 1 << (9 + FIELD_EX32(s->capareg, SDHC_CAPAB, MAXBLOCKLENGTH));
66 }
67 
68 /* return true on error */
69 static bool sdhci_check_capab_freq_range(SDHCIState *s, const char *desc,
70                                          uint8_t freq, Error **errp)
71 {
72     if (s->sd_spec_version >= 3) {
73         return false;
74     }
75     switch (freq) {
76     case 0:
77     case 10 ... 63:
78         break;
79     default:
80         error_setg(errp, "SD %s clock frequency can have value"
81                    "in range 0-63 only", desc);
82         return true;
83     }
84     return false;
85 }
86 
87 static void sdhci_check_capareg(SDHCIState *s, Error **errp)
88 {
89     uint64_t msk = s->capareg;
90     uint32_t val;
91     bool y;
92 
93     switch (s->sd_spec_version) {
94     case 4:
95         val = FIELD_EX64(s->capareg, SDHC_CAPAB, BUS64BIT_V4);
96         trace_sdhci_capareg("64-bit system bus (v4)", val);
97         msk = FIELD_DP64(msk, SDHC_CAPAB, BUS64BIT_V4, 0);
98 
99         val = FIELD_EX64(s->capareg, SDHC_CAPAB, UHS_II);
100         trace_sdhci_capareg("UHS-II", val);
101         msk = FIELD_DP64(msk, SDHC_CAPAB, UHS_II, 0);
102 
103         val = FIELD_EX64(s->capareg, SDHC_CAPAB, ADMA3);
104         trace_sdhci_capareg("ADMA3", val);
105         msk = FIELD_DP64(msk, SDHC_CAPAB, ADMA3, 0);
106 
107     /* fallthrough */
108     case 3:
109         val = FIELD_EX64(s->capareg, SDHC_CAPAB, ASYNC_INT);
110         trace_sdhci_capareg("async interrupt", val);
111         msk = FIELD_DP64(msk, SDHC_CAPAB, ASYNC_INT, 0);
112 
113         val = FIELD_EX64(s->capareg, SDHC_CAPAB, SLOT_TYPE);
114         if (val) {
115             error_setg(errp, "slot-type not supported");
116             return;
117         }
118         trace_sdhci_capareg("slot type", val);
119         msk = FIELD_DP64(msk, SDHC_CAPAB, SLOT_TYPE, 0);
120 
121         if (val != 2) {
122             val = FIELD_EX64(s->capareg, SDHC_CAPAB, EMBEDDED_8BIT);
123             trace_sdhci_capareg("8-bit bus", val);
124         }
125         msk = FIELD_DP64(msk, SDHC_CAPAB, EMBEDDED_8BIT, 0);
126 
127         val = FIELD_EX64(s->capareg, SDHC_CAPAB, BUS_SPEED);
128         trace_sdhci_capareg("bus speed mask", val);
129         msk = FIELD_DP64(msk, SDHC_CAPAB, BUS_SPEED, 0);
130 
131         val = FIELD_EX64(s->capareg, SDHC_CAPAB, DRIVER_STRENGTH);
132         trace_sdhci_capareg("driver strength mask", val);
133         msk = FIELD_DP64(msk, SDHC_CAPAB, DRIVER_STRENGTH, 0);
134 
135         val = FIELD_EX64(s->capareg, SDHC_CAPAB, TIMER_RETUNING);
136         trace_sdhci_capareg("timer re-tuning", val);
137         msk = FIELD_DP64(msk, SDHC_CAPAB, TIMER_RETUNING, 0);
138 
139         val = FIELD_EX64(s->capareg, SDHC_CAPAB, SDR50_TUNING);
140         trace_sdhci_capareg("use SDR50 tuning", val);
141         msk = FIELD_DP64(msk, SDHC_CAPAB, SDR50_TUNING, 0);
142 
143         val = FIELD_EX64(s->capareg, SDHC_CAPAB, RETUNING_MODE);
144         trace_sdhci_capareg("re-tuning mode", val);
145         msk = FIELD_DP64(msk, SDHC_CAPAB, RETUNING_MODE, 0);
146 
147         val = FIELD_EX64(s->capareg, SDHC_CAPAB, CLOCK_MULT);
148         trace_sdhci_capareg("clock multiplier", val);
149         msk = FIELD_DP64(msk, SDHC_CAPAB, CLOCK_MULT, 0);
150 
151     /* fallthrough */
152     case 2: /* default version */
153         val = FIELD_EX64(s->capareg, SDHC_CAPAB, ADMA2);
154         trace_sdhci_capareg("ADMA2", val);
155         msk = FIELD_DP64(msk, SDHC_CAPAB, ADMA2, 0);
156 
157         val = FIELD_EX64(s->capareg, SDHC_CAPAB, ADMA1);
158         trace_sdhci_capareg("ADMA1", val);
159         msk = FIELD_DP64(msk, SDHC_CAPAB, ADMA1, 0);
160 
161         val = FIELD_EX64(s->capareg, SDHC_CAPAB, BUS64BIT);
162         trace_sdhci_capareg("64-bit system bus (v3)", val);
163         msk = FIELD_DP64(msk, SDHC_CAPAB, BUS64BIT, 0);
164 
165     /* fallthrough */
166     case 1:
167         y = FIELD_EX64(s->capareg, SDHC_CAPAB, TOUNIT);
168         msk = FIELD_DP64(msk, SDHC_CAPAB, TOUNIT, 0);
169 
170         val = FIELD_EX64(s->capareg, SDHC_CAPAB, TOCLKFREQ);
171         trace_sdhci_capareg(y ? "timeout (MHz)" : "Timeout (KHz)", val);
172         if (sdhci_check_capab_freq_range(s, "timeout", val, errp)) {
173             return;
174         }
175         msk = FIELD_DP64(msk, SDHC_CAPAB, TOCLKFREQ, 0);
176 
177         val = FIELD_EX64(s->capareg, SDHC_CAPAB, BASECLKFREQ);
178         trace_sdhci_capareg(y ? "base (MHz)" : "Base (KHz)", val);
179         if (sdhci_check_capab_freq_range(s, "base", val, errp)) {
180             return;
181         }
182         msk = FIELD_DP64(msk, SDHC_CAPAB, BASECLKFREQ, 0);
183 
184         val = FIELD_EX64(s->capareg, SDHC_CAPAB, MAXBLOCKLENGTH);
185         if (val >= 3) {
186             error_setg(errp, "block size can be 512, 1024 or 2048 only");
187             return;
188         }
189         trace_sdhci_capareg("max block length", sdhci_get_fifolen(s));
190         msk = FIELD_DP64(msk, SDHC_CAPAB, MAXBLOCKLENGTH, 0);
191 
192         val = FIELD_EX64(s->capareg, SDHC_CAPAB, HIGHSPEED);
193         trace_sdhci_capareg("high speed", val);
194         msk = FIELD_DP64(msk, SDHC_CAPAB, HIGHSPEED, 0);
195 
196         val = FIELD_EX64(s->capareg, SDHC_CAPAB, SDMA);
197         trace_sdhci_capareg("SDMA", val);
198         msk = FIELD_DP64(msk, SDHC_CAPAB, SDMA, 0);
199 
200         val = FIELD_EX64(s->capareg, SDHC_CAPAB, SUSPRESUME);
201         trace_sdhci_capareg("suspend/resume", val);
202         msk = FIELD_DP64(msk, SDHC_CAPAB, SUSPRESUME, 0);
203 
204         val = FIELD_EX64(s->capareg, SDHC_CAPAB, V33);
205         trace_sdhci_capareg("3.3v", val);
206         msk = FIELD_DP64(msk, SDHC_CAPAB, V33, 0);
207 
208         val = FIELD_EX64(s->capareg, SDHC_CAPAB, V30);
209         trace_sdhci_capareg("3.0v", val);
210         msk = FIELD_DP64(msk, SDHC_CAPAB, V30, 0);
211 
212         val = FIELD_EX64(s->capareg, SDHC_CAPAB, V18);
213         trace_sdhci_capareg("1.8v", val);
214         msk = FIELD_DP64(msk, SDHC_CAPAB, V18, 0);
215         break;
216 
217     default:
218         error_setg(errp, "Unsupported spec version: %u", s->sd_spec_version);
219     }
220     if (msk) {
221         qemu_log_mask(LOG_UNIMP,
222                       "SDHCI: unknown CAPAB mask: 0x%016" PRIx64 "\n", msk);
223     }
224 }
225 
226 static uint8_t sdhci_slotint(SDHCIState *s)
227 {
228     return (s->norintsts & s->norintsigen) || (s->errintsts & s->errintsigen) ||
229          ((s->norintsts & SDHC_NIS_INSERT) && (s->wakcon & SDHC_WKUP_ON_INS)) ||
230          ((s->norintsts & SDHC_NIS_REMOVE) && (s->wakcon & SDHC_WKUP_ON_RMV));
231 }
232 
233 static inline void sdhci_update_irq(SDHCIState *s)
234 {
235     qemu_set_irq(s->irq, sdhci_slotint(s));
236 }
237 
238 static void sdhci_raise_insertion_irq(void *opaque)
239 {
240     SDHCIState *s = (SDHCIState *)opaque;
241 
242     if (s->norintsts & SDHC_NIS_REMOVE) {
243         timer_mod(s->insert_timer,
244                        qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + SDHC_INSERTION_DELAY);
245     } else {
246         s->prnsts = 0x1ff0000;
247         if (s->norintstsen & SDHC_NISEN_INSERT) {
248             s->norintsts |= SDHC_NIS_INSERT;
249         }
250         sdhci_update_irq(s);
251     }
252 }
253 
254 static void sdhci_set_inserted(DeviceState *dev, bool level)
255 {
256     SDHCIState *s = (SDHCIState *)dev;
257 
258     trace_sdhci_set_inserted(level ? "insert" : "eject");
259     if ((s->norintsts & SDHC_NIS_REMOVE) && level) {
260         /* Give target some time to notice card ejection */
261         timer_mod(s->insert_timer,
262                        qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + SDHC_INSERTION_DELAY);
263     } else {
264         if (level) {
265             s->prnsts = 0x1ff0000;
266             if (s->norintstsen & SDHC_NISEN_INSERT) {
267                 s->norintsts |= SDHC_NIS_INSERT;
268             }
269         } else {
270             s->prnsts = 0x1fa0000;
271             s->pwrcon &= ~SDHC_POWER_ON;
272             s->clkcon &= ~SDHC_CLOCK_SDCLK_EN;
273             if (s->norintstsen & SDHC_NISEN_REMOVE) {
274                 s->norintsts |= SDHC_NIS_REMOVE;
275             }
276         }
277         sdhci_update_irq(s);
278     }
279 }
280 
281 static void sdhci_set_readonly(DeviceState *dev, bool level)
282 {
283     SDHCIState *s = (SDHCIState *)dev;
284 
285     if (level) {
286         s->prnsts &= ~SDHC_WRITE_PROTECT;
287     } else {
288         /* Write enabled */
289         s->prnsts |= SDHC_WRITE_PROTECT;
290     }
291 }
292 
293 static void sdhci_reset(SDHCIState *s)
294 {
295     DeviceState *dev = DEVICE(s);
296 
297     timer_del(s->insert_timer);
298     timer_del(s->transfer_timer);
299 
300     /* Set all registers to 0. Capabilities/Version registers are not cleared
301      * and assumed to always preserve their value, given to them during
302      * initialization */
303     memset(&s->sdmasysad, 0, (uintptr_t)&s->capareg - (uintptr_t)&s->sdmasysad);
304 
305     /* Reset other state based on current card insertion/readonly status */
306     sdhci_set_inserted(dev, sdbus_get_inserted(&s->sdbus));
307     sdhci_set_readonly(dev, sdbus_get_readonly(&s->sdbus));
308 
309     s->data_count = 0;
310     s->stopped_state = sdhc_not_stopped;
311     s->pending_insert_state = false;
312 }
313 
314 static void sdhci_poweron_reset(DeviceState *dev)
315 {
316     /* QOM (ie power-on) reset. This is identical to reset
317      * commanded via device register apart from handling of the
318      * 'pending insert on powerup' quirk.
319      */
320     SDHCIState *s = (SDHCIState *)dev;
321 
322     sdhci_reset(s);
323 
324     if (s->pending_insert_quirk) {
325         s->pending_insert_state = true;
326     }
327 }
328 
329 static void sdhci_data_transfer(void *opaque);
330 
331 static void sdhci_send_command(SDHCIState *s)
332 {
333     SDRequest request;
334     uint8_t response[16];
335     int rlen;
336 
337     s->errintsts = 0;
338     s->acmd12errsts = 0;
339     request.cmd = s->cmdreg >> 8;
340     request.arg = s->argument;
341 
342     trace_sdhci_send_command(request.cmd, request.arg);
343     rlen = sdbus_do_command(&s->sdbus, &request, response);
344 
345     if (s->cmdreg & SDHC_CMD_RESPONSE) {
346         if (rlen == 4) {
347             s->rspreg[0] = (response[0] << 24) | (response[1] << 16) |
348                            (response[2] << 8)  |  response[3];
349             s->rspreg[1] = s->rspreg[2] = s->rspreg[3] = 0;
350             trace_sdhci_response4(s->rspreg[0]);
351         } else if (rlen == 16) {
352             s->rspreg[0] = (response[11] << 24) | (response[12] << 16) |
353                            (response[13] << 8) |  response[14];
354             s->rspreg[1] = (response[7] << 24) | (response[8] << 16) |
355                            (response[9] << 8)  |  response[10];
356             s->rspreg[2] = (response[3] << 24) | (response[4] << 16) |
357                            (response[5] << 8)  |  response[6];
358             s->rspreg[3] = (response[0] << 16) | (response[1] << 8) |
359                             response[2];
360             trace_sdhci_response16(s->rspreg[3], s->rspreg[2],
361                                    s->rspreg[1], s->rspreg[0]);
362         } else {
363             trace_sdhci_error("timeout waiting for command response");
364             if (s->errintstsen & SDHC_EISEN_CMDTIMEOUT) {
365                 s->errintsts |= SDHC_EIS_CMDTIMEOUT;
366                 s->norintsts |= SDHC_NIS_ERR;
367             }
368         }
369 
370         if (!(s->quirks & SDHCI_QUIRK_NO_BUSY_IRQ) &&
371             (s->norintstsen & SDHC_NISEN_TRSCMP) &&
372             (s->cmdreg & SDHC_CMD_RESPONSE) == SDHC_CMD_RSP_WITH_BUSY) {
373             s->norintsts |= SDHC_NIS_TRSCMP;
374         }
375     }
376 
377     if (s->norintstsen & SDHC_NISEN_CMDCMP) {
378         s->norintsts |= SDHC_NIS_CMDCMP;
379     }
380 
381     sdhci_update_irq(s);
382 
383     if (s->blksize && (s->cmdreg & SDHC_CMD_DATA_PRESENT)) {
384         s->data_count = 0;
385         sdhci_data_transfer(s);
386     }
387 }
388 
389 static void sdhci_end_transfer(SDHCIState *s)
390 {
391     /* Automatically send CMD12 to stop transfer if AutoCMD12 enabled */
392     if ((s->trnmod & SDHC_TRNS_ACMD12) != 0) {
393         SDRequest request;
394         uint8_t response[16];
395 
396         request.cmd = 0x0C;
397         request.arg = 0;
398         trace_sdhci_end_transfer(request.cmd, request.arg);
399         sdbus_do_command(&s->sdbus, &request, response);
400         /* Auto CMD12 response goes to the upper Response register */
401         s->rspreg[3] = (response[0] << 24) | (response[1] << 16) |
402                 (response[2] << 8) | response[3];
403     }
404 
405     s->prnsts &= ~(SDHC_DOING_READ | SDHC_DOING_WRITE |
406             SDHC_DAT_LINE_ACTIVE | SDHC_DATA_INHIBIT |
407             SDHC_SPACE_AVAILABLE | SDHC_DATA_AVAILABLE);
408 
409     if (s->norintstsen & SDHC_NISEN_TRSCMP) {
410         s->norintsts |= SDHC_NIS_TRSCMP;
411     }
412 
413     sdhci_update_irq(s);
414 }
415 
416 /*
417  * Programmed i/o data transfer
418  */
419 #define BLOCK_SIZE_MASK (4 * K_BYTE - 1)
420 
421 /* Fill host controller's read buffer with BLKSIZE bytes of data from card */
422 static void sdhci_read_block_from_card(SDHCIState *s)
423 {
424     int index = 0;
425     uint8_t data;
426     const uint16_t blk_size = s->blksize & BLOCK_SIZE_MASK;
427 
428     if ((s->trnmod & SDHC_TRNS_MULTI) &&
429             (s->trnmod & SDHC_TRNS_BLK_CNT_EN) && (s->blkcnt == 0)) {
430         return;
431     }
432 
433     for (index = 0; index < blk_size; index++) {
434         data = sdbus_read_data(&s->sdbus);
435         if (!FIELD_EX32(s->hostctl2, SDHC_HOSTCTL2, EXECUTE_TUNING)) {
436             /* Device is not in tuning */
437             s->fifo_buffer[index] = data;
438         }
439     }
440 
441     if (FIELD_EX32(s->hostctl2, SDHC_HOSTCTL2, EXECUTE_TUNING)) {
442         /* Device is in tuning */
443         s->hostctl2 &= ~R_SDHC_HOSTCTL2_EXECUTE_TUNING_MASK;
444         s->hostctl2 |= R_SDHC_HOSTCTL2_SAMPLING_CLKSEL_MASK;
445         s->prnsts &= ~(SDHC_DAT_LINE_ACTIVE | SDHC_DOING_READ |
446                        SDHC_DATA_INHIBIT);
447         goto read_done;
448     }
449 
450     /* New data now available for READ through Buffer Port Register */
451     s->prnsts |= SDHC_DATA_AVAILABLE;
452     if (s->norintstsen & SDHC_NISEN_RBUFRDY) {
453         s->norintsts |= SDHC_NIS_RBUFRDY;
454     }
455 
456     /* Clear DAT line active status if that was the last block */
457     if ((s->trnmod & SDHC_TRNS_MULTI) == 0 ||
458             ((s->trnmod & SDHC_TRNS_MULTI) && s->blkcnt == 1)) {
459         s->prnsts &= ~SDHC_DAT_LINE_ACTIVE;
460     }
461 
462     /* If stop at block gap request was set and it's not the last block of
463      * data - generate Block Event interrupt */
464     if (s->stopped_state == sdhc_gap_read && (s->trnmod & SDHC_TRNS_MULTI) &&
465             s->blkcnt != 1)    {
466         s->prnsts &= ~SDHC_DAT_LINE_ACTIVE;
467         if (s->norintstsen & SDHC_EISEN_BLKGAP) {
468             s->norintsts |= SDHC_EIS_BLKGAP;
469         }
470     }
471 
472 read_done:
473     sdhci_update_irq(s);
474 }
475 
476 /* Read @size byte of data from host controller @s BUFFER DATA PORT register */
477 static uint32_t sdhci_read_dataport(SDHCIState *s, unsigned size)
478 {
479     uint32_t value = 0;
480     int i;
481 
482     /* first check that a valid data exists in host controller input buffer */
483     if ((s->prnsts & SDHC_DATA_AVAILABLE) == 0) {
484         trace_sdhci_error("read from empty buffer");
485         return 0;
486     }
487 
488     for (i = 0; i < size; i++) {
489         value |= s->fifo_buffer[s->data_count] << i * 8;
490         s->data_count++;
491         /* check if we've read all valid data (blksize bytes) from buffer */
492         if ((s->data_count) >= (s->blksize & BLOCK_SIZE_MASK)) {
493             trace_sdhci_read_dataport(s->data_count);
494             s->prnsts &= ~SDHC_DATA_AVAILABLE; /* no more data in a buffer */
495             s->data_count = 0;  /* next buff read must start at position [0] */
496 
497             if (s->trnmod & SDHC_TRNS_BLK_CNT_EN) {
498                 s->blkcnt--;
499             }
500 
501             /* if that was the last block of data */
502             if ((s->trnmod & SDHC_TRNS_MULTI) == 0 ||
503                 ((s->trnmod & SDHC_TRNS_BLK_CNT_EN) && (s->blkcnt == 0)) ||
504                  /* stop at gap request */
505                 (s->stopped_state == sdhc_gap_read &&
506                  !(s->prnsts & SDHC_DAT_LINE_ACTIVE))) {
507                 sdhci_end_transfer(s);
508             } else { /* if there are more data, read next block from card */
509                 sdhci_read_block_from_card(s);
510             }
511             break;
512         }
513     }
514 
515     return value;
516 }
517 
518 /* Write data from host controller FIFO to card */
519 static void sdhci_write_block_to_card(SDHCIState *s)
520 {
521     int index = 0;
522 
523     if (s->prnsts & SDHC_SPACE_AVAILABLE) {
524         if (s->norintstsen & SDHC_NISEN_WBUFRDY) {
525             s->norintsts |= SDHC_NIS_WBUFRDY;
526         }
527         sdhci_update_irq(s);
528         return;
529     }
530 
531     if (s->trnmod & SDHC_TRNS_BLK_CNT_EN) {
532         if (s->blkcnt == 0) {
533             return;
534         } else {
535             s->blkcnt--;
536         }
537     }
538 
539     for (index = 0; index < (s->blksize & BLOCK_SIZE_MASK); index++) {
540         sdbus_write_data(&s->sdbus, s->fifo_buffer[index]);
541     }
542 
543     /* Next data can be written through BUFFER DATORT register */
544     s->prnsts |= SDHC_SPACE_AVAILABLE;
545 
546     /* Finish transfer if that was the last block of data */
547     if ((s->trnmod & SDHC_TRNS_MULTI) == 0 ||
548             ((s->trnmod & SDHC_TRNS_MULTI) &&
549             (s->trnmod & SDHC_TRNS_BLK_CNT_EN) && (s->blkcnt == 0))) {
550         sdhci_end_transfer(s);
551     } else if (s->norintstsen & SDHC_NISEN_WBUFRDY) {
552         s->norintsts |= SDHC_NIS_WBUFRDY;
553     }
554 
555     /* Generate Block Gap Event if requested and if not the last block */
556     if (s->stopped_state == sdhc_gap_write && (s->trnmod & SDHC_TRNS_MULTI) &&
557             s->blkcnt > 0) {
558         s->prnsts &= ~SDHC_DOING_WRITE;
559         if (s->norintstsen & SDHC_EISEN_BLKGAP) {
560             s->norintsts |= SDHC_EIS_BLKGAP;
561         }
562         sdhci_end_transfer(s);
563     }
564 
565     sdhci_update_irq(s);
566 }
567 
568 /* Write @size bytes of @value data to host controller @s Buffer Data Port
569  * register */
570 static void sdhci_write_dataport(SDHCIState *s, uint32_t value, unsigned size)
571 {
572     unsigned i;
573 
574     /* Check that there is free space left in a buffer */
575     if (!(s->prnsts & SDHC_SPACE_AVAILABLE)) {
576         trace_sdhci_error("Can't write to data buffer: buffer full");
577         return;
578     }
579 
580     for (i = 0; i < size; i++) {
581         s->fifo_buffer[s->data_count] = value & 0xFF;
582         s->data_count++;
583         value >>= 8;
584         if (s->data_count >= (s->blksize & BLOCK_SIZE_MASK)) {
585             trace_sdhci_write_dataport(s->data_count);
586             s->data_count = 0;
587             s->prnsts &= ~SDHC_SPACE_AVAILABLE;
588             if (s->prnsts & SDHC_DOING_WRITE) {
589                 sdhci_write_block_to_card(s);
590             }
591         }
592     }
593 }
594 
595 /*
596  * Single DMA data transfer
597  */
598 
599 /* Multi block SDMA transfer */
600 static void sdhci_sdma_transfer_multi_blocks(SDHCIState *s)
601 {
602     bool page_aligned = false;
603     unsigned int n, begin;
604     const uint16_t block_size = s->blksize & BLOCK_SIZE_MASK;
605     uint32_t boundary_chk = 1 << (((s->blksize & ~BLOCK_SIZE_MASK) >> 12) + 12);
606     uint32_t boundary_count = boundary_chk - (s->sdmasysad % boundary_chk);
607 
608     if (!(s->trnmod & SDHC_TRNS_BLK_CNT_EN) || !s->blkcnt) {
609         qemu_log_mask(LOG_UNIMP, "infinite transfer is not supported\n");
610         return;
611     }
612 
613     /* XXX: Some sd/mmc drivers (for example, u-boot-slp) do not account for
614      * possible stop at page boundary if initial address is not page aligned,
615      * allow them to work properly */
616     if ((s->sdmasysad % boundary_chk) == 0) {
617         page_aligned = true;
618     }
619 
620     if (s->trnmod & SDHC_TRNS_READ) {
621         s->prnsts |= SDHC_DOING_READ | SDHC_DATA_INHIBIT |
622                 SDHC_DAT_LINE_ACTIVE;
623         while (s->blkcnt) {
624             if (s->data_count == 0) {
625                 for (n = 0; n < block_size; n++) {
626                     s->fifo_buffer[n] = sdbus_read_data(&s->sdbus);
627                 }
628             }
629             begin = s->data_count;
630             if (((boundary_count + begin) < block_size) && page_aligned) {
631                 s->data_count = boundary_count + begin;
632                 boundary_count = 0;
633              } else {
634                 s->data_count = block_size;
635                 boundary_count -= block_size - begin;
636                 if (s->trnmod & SDHC_TRNS_BLK_CNT_EN) {
637                     s->blkcnt--;
638                 }
639             }
640             dma_memory_write(s->dma_as, s->sdmasysad,
641                              &s->fifo_buffer[begin], s->data_count - begin);
642             s->sdmasysad += s->data_count - begin;
643             if (s->data_count == block_size) {
644                 s->data_count = 0;
645             }
646             if (page_aligned && boundary_count == 0) {
647                 break;
648             }
649         }
650     } else {
651         s->prnsts |= SDHC_DOING_WRITE | SDHC_DATA_INHIBIT |
652                 SDHC_DAT_LINE_ACTIVE;
653         while (s->blkcnt) {
654             begin = s->data_count;
655             if (((boundary_count + begin) < block_size) && page_aligned) {
656                 s->data_count = boundary_count + begin;
657                 boundary_count = 0;
658              } else {
659                 s->data_count = block_size;
660                 boundary_count -= block_size - begin;
661             }
662             dma_memory_read(s->dma_as, s->sdmasysad,
663                             &s->fifo_buffer[begin], s->data_count - begin);
664             s->sdmasysad += s->data_count - begin;
665             if (s->data_count == block_size) {
666                 for (n = 0; n < block_size; n++) {
667                     sdbus_write_data(&s->sdbus, s->fifo_buffer[n]);
668                 }
669                 s->data_count = 0;
670                 if (s->trnmod & SDHC_TRNS_BLK_CNT_EN) {
671                     s->blkcnt--;
672                 }
673             }
674             if (page_aligned && boundary_count == 0) {
675                 break;
676             }
677         }
678     }
679 
680     if (s->blkcnt == 0) {
681         sdhci_end_transfer(s);
682     } else {
683         if (s->norintstsen & SDHC_NISEN_DMA) {
684             s->norintsts |= SDHC_NIS_DMA;
685         }
686         sdhci_update_irq(s);
687     }
688 }
689 
690 /* single block SDMA transfer */
691 static void sdhci_sdma_transfer_single_block(SDHCIState *s)
692 {
693     int n;
694     uint32_t datacnt = s->blksize & BLOCK_SIZE_MASK;
695 
696     if (s->trnmod & SDHC_TRNS_READ) {
697         for (n = 0; n < datacnt; n++) {
698             s->fifo_buffer[n] = sdbus_read_data(&s->sdbus);
699         }
700         dma_memory_write(s->dma_as, s->sdmasysad, s->fifo_buffer, datacnt);
701     } else {
702         dma_memory_read(s->dma_as, s->sdmasysad, s->fifo_buffer, datacnt);
703         for (n = 0; n < datacnt; n++) {
704             sdbus_write_data(&s->sdbus, s->fifo_buffer[n]);
705         }
706     }
707     s->blkcnt--;
708 
709     sdhci_end_transfer(s);
710 }
711 
712 typedef struct ADMADescr {
713     hwaddr addr;
714     uint16_t length;
715     uint8_t attr;
716     uint8_t incr;
717 } ADMADescr;
718 
719 static void get_adma_description(SDHCIState *s, ADMADescr *dscr)
720 {
721     uint32_t adma1 = 0;
722     uint64_t adma2 = 0;
723     hwaddr entry_addr = (hwaddr)s->admasysaddr;
724     switch (SDHC_DMA_TYPE(s->hostctl1)) {
725     case SDHC_CTRL_ADMA2_32:
726         dma_memory_read(s->dma_as, entry_addr, (uint8_t *)&adma2,
727                         sizeof(adma2));
728         adma2 = le64_to_cpu(adma2);
729         /* The spec does not specify endianness of descriptor table.
730          * We currently assume that it is LE.
731          */
732         dscr->addr = (hwaddr)extract64(adma2, 32, 32) & ~0x3ull;
733         dscr->length = (uint16_t)extract64(adma2, 16, 16);
734         dscr->attr = (uint8_t)extract64(adma2, 0, 7);
735         dscr->incr = 8;
736         break;
737     case SDHC_CTRL_ADMA1_32:
738         dma_memory_read(s->dma_as, entry_addr, (uint8_t *)&adma1,
739                         sizeof(adma1));
740         adma1 = le32_to_cpu(adma1);
741         dscr->addr = (hwaddr)(adma1 & 0xFFFFF000);
742         dscr->attr = (uint8_t)extract32(adma1, 0, 7);
743         dscr->incr = 4;
744         if ((dscr->attr & SDHC_ADMA_ATTR_ACT_MASK) == SDHC_ADMA_ATTR_SET_LEN) {
745             dscr->length = (uint16_t)extract32(adma1, 12, 16);
746         } else {
747             dscr->length = 4096;
748         }
749         break;
750     case SDHC_CTRL_ADMA2_64:
751         dma_memory_read(s->dma_as, entry_addr,
752                         (uint8_t *)(&dscr->attr), 1);
753         dma_memory_read(s->dma_as, entry_addr + 2,
754                         (uint8_t *)(&dscr->length), 2);
755         dscr->length = le16_to_cpu(dscr->length);
756         dma_memory_read(s->dma_as, entry_addr + 4,
757                         (uint8_t *)(&dscr->addr), 8);
758         dscr->addr = le64_to_cpu(dscr->addr);
759         dscr->attr &= (uint8_t) ~0xC0;
760         dscr->incr = 12;
761         break;
762     }
763 }
764 
765 /* Advanced DMA data transfer */
766 
767 static void sdhci_do_adma(SDHCIState *s)
768 {
769     unsigned int n, begin, length;
770     const uint16_t block_size = s->blksize & BLOCK_SIZE_MASK;
771     ADMADescr dscr = {};
772     int i;
773 
774     for (i = 0; i < SDHC_ADMA_DESCS_PER_DELAY; ++i) {
775         s->admaerr &= ~SDHC_ADMAERR_LENGTH_MISMATCH;
776 
777         get_adma_description(s, &dscr);
778         trace_sdhci_adma_loop(dscr.addr, dscr.length, dscr.attr);
779 
780         if ((dscr.attr & SDHC_ADMA_ATTR_VALID) == 0) {
781             /* Indicate that error occurred in ST_FDS state */
782             s->admaerr &= ~SDHC_ADMAERR_STATE_MASK;
783             s->admaerr |= SDHC_ADMAERR_STATE_ST_FDS;
784 
785             /* Generate ADMA error interrupt */
786             if (s->errintstsen & SDHC_EISEN_ADMAERR) {
787                 s->errintsts |= SDHC_EIS_ADMAERR;
788                 s->norintsts |= SDHC_NIS_ERR;
789             }
790 
791             sdhci_update_irq(s);
792             return;
793         }
794 
795         length = dscr.length ? dscr.length : 65536;
796 
797         switch (dscr.attr & SDHC_ADMA_ATTR_ACT_MASK) {
798         case SDHC_ADMA_ATTR_ACT_TRAN:  /* data transfer */
799 
800             if (s->trnmod & SDHC_TRNS_READ) {
801                 while (length) {
802                     if (s->data_count == 0) {
803                         for (n = 0; n < block_size; n++) {
804                             s->fifo_buffer[n] = sdbus_read_data(&s->sdbus);
805                         }
806                     }
807                     begin = s->data_count;
808                     if ((length + begin) < block_size) {
809                         s->data_count = length + begin;
810                         length = 0;
811                      } else {
812                         s->data_count = block_size;
813                         length -= block_size - begin;
814                     }
815                     dma_memory_write(s->dma_as, dscr.addr,
816                                      &s->fifo_buffer[begin],
817                                      s->data_count - begin);
818                     dscr.addr += s->data_count - begin;
819                     if (s->data_count == block_size) {
820                         s->data_count = 0;
821                         if (s->trnmod & SDHC_TRNS_BLK_CNT_EN) {
822                             s->blkcnt--;
823                             if (s->blkcnt == 0) {
824                                 break;
825                             }
826                         }
827                     }
828                 }
829             } else {
830                 while (length) {
831                     begin = s->data_count;
832                     if ((length + begin) < block_size) {
833                         s->data_count = length + begin;
834                         length = 0;
835                      } else {
836                         s->data_count = block_size;
837                         length -= block_size - begin;
838                     }
839                     dma_memory_read(s->dma_as, dscr.addr,
840                                     &s->fifo_buffer[begin],
841                                     s->data_count - begin);
842                     dscr.addr += s->data_count - begin;
843                     if (s->data_count == block_size) {
844                         for (n = 0; n < block_size; n++) {
845                             sdbus_write_data(&s->sdbus, s->fifo_buffer[n]);
846                         }
847                         s->data_count = 0;
848                         if (s->trnmod & SDHC_TRNS_BLK_CNT_EN) {
849                             s->blkcnt--;
850                             if (s->blkcnt == 0) {
851                                 break;
852                             }
853                         }
854                     }
855                 }
856             }
857             s->admasysaddr += dscr.incr;
858             break;
859         case SDHC_ADMA_ATTR_ACT_LINK:   /* link to next descriptor table */
860             s->admasysaddr = dscr.addr;
861             trace_sdhci_adma("link", s->admasysaddr);
862             break;
863         default:
864             s->admasysaddr += dscr.incr;
865             break;
866         }
867 
868         if (dscr.attr & SDHC_ADMA_ATTR_INT) {
869             trace_sdhci_adma("interrupt", s->admasysaddr);
870             if (s->norintstsen & SDHC_NISEN_DMA) {
871                 s->norintsts |= SDHC_NIS_DMA;
872             }
873 
874             sdhci_update_irq(s);
875         }
876 
877         /* ADMA transfer terminates if blkcnt == 0 or by END attribute */
878         if (((s->trnmod & SDHC_TRNS_BLK_CNT_EN) &&
879                     (s->blkcnt == 0)) || (dscr.attr & SDHC_ADMA_ATTR_END)) {
880             trace_sdhci_adma_transfer_completed();
881             if (length || ((dscr.attr & SDHC_ADMA_ATTR_END) &&
882                 (s->trnmod & SDHC_TRNS_BLK_CNT_EN) &&
883                 s->blkcnt != 0)) {
884                 trace_sdhci_error("SD/MMC host ADMA length mismatch");
885                 s->admaerr |= SDHC_ADMAERR_LENGTH_MISMATCH |
886                         SDHC_ADMAERR_STATE_ST_TFR;
887                 if (s->errintstsen & SDHC_EISEN_ADMAERR) {
888                     trace_sdhci_error("Set ADMA error flag");
889                     s->errintsts |= SDHC_EIS_ADMAERR;
890                     s->norintsts |= SDHC_NIS_ERR;
891                 }
892 
893                 sdhci_update_irq(s);
894             }
895             sdhci_end_transfer(s);
896             return;
897         }
898 
899     }
900 
901     /* we have unfinished business - reschedule to continue ADMA */
902     timer_mod(s->transfer_timer,
903                    qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + SDHC_TRANSFER_DELAY);
904 }
905 
906 /* Perform data transfer according to controller configuration */
907 
908 static void sdhci_data_transfer(void *opaque)
909 {
910     SDHCIState *s = (SDHCIState *)opaque;
911 
912     if (s->trnmod & SDHC_TRNS_DMA) {
913         switch (SDHC_DMA_TYPE(s->hostctl1)) {
914         case SDHC_CTRL_SDMA:
915             if ((s->blkcnt == 1) || !(s->trnmod & SDHC_TRNS_MULTI)) {
916                 sdhci_sdma_transfer_single_block(s);
917             } else {
918                 sdhci_sdma_transfer_multi_blocks(s);
919             }
920 
921             break;
922         case SDHC_CTRL_ADMA1_32:
923             if (!(s->capareg & R_SDHC_CAPAB_ADMA1_MASK)) {
924                 trace_sdhci_error("ADMA1 not supported");
925                 break;
926             }
927 
928             sdhci_do_adma(s);
929             break;
930         case SDHC_CTRL_ADMA2_32:
931             if (!(s->capareg & R_SDHC_CAPAB_ADMA2_MASK)) {
932                 trace_sdhci_error("ADMA2 not supported");
933                 break;
934             }
935 
936             sdhci_do_adma(s);
937             break;
938         case SDHC_CTRL_ADMA2_64:
939             if (!(s->capareg & R_SDHC_CAPAB_ADMA2_MASK) ||
940                     !(s->capareg & R_SDHC_CAPAB_BUS64BIT_MASK)) {
941                 trace_sdhci_error("64 bit ADMA not supported");
942                 break;
943             }
944 
945             sdhci_do_adma(s);
946             break;
947         default:
948             trace_sdhci_error("Unsupported DMA type");
949             break;
950         }
951     } else {
952         if ((s->trnmod & SDHC_TRNS_READ) && sdbus_data_ready(&s->sdbus)) {
953             s->prnsts |= SDHC_DOING_READ | SDHC_DATA_INHIBIT |
954                     SDHC_DAT_LINE_ACTIVE;
955             sdhci_read_block_from_card(s);
956         } else {
957             s->prnsts |= SDHC_DOING_WRITE | SDHC_DAT_LINE_ACTIVE |
958                     SDHC_SPACE_AVAILABLE | SDHC_DATA_INHIBIT;
959             sdhci_write_block_to_card(s);
960         }
961     }
962 }
963 
964 static bool sdhci_can_issue_command(SDHCIState *s)
965 {
966     if (!SDHC_CLOCK_IS_ON(s->clkcon) ||
967         (((s->prnsts & SDHC_DATA_INHIBIT) || s->stopped_state) &&
968         ((s->cmdreg & SDHC_CMD_DATA_PRESENT) ||
969         ((s->cmdreg & SDHC_CMD_RESPONSE) == SDHC_CMD_RSP_WITH_BUSY &&
970         !(SDHC_COMMAND_TYPE(s->cmdreg) == SDHC_CMD_ABORT))))) {
971         return false;
972     }
973 
974     return true;
975 }
976 
977 /* The Buffer Data Port register must be accessed in sequential and
978  * continuous manner */
979 static inline bool
980 sdhci_buff_access_is_sequential(SDHCIState *s, unsigned byte_num)
981 {
982     if ((s->data_count & 0x3) != byte_num) {
983         trace_sdhci_error("Non-sequential access to Buffer Data Port register"
984                           "is prohibited\n");
985         return false;
986     }
987     return true;
988 }
989 
990 static uint64_t sdhci_read(void *opaque, hwaddr offset, unsigned size)
991 {
992     SDHCIState *s = (SDHCIState *)opaque;
993     uint32_t ret = 0;
994 
995     switch (offset & ~0x3) {
996     case SDHC_SYSAD:
997         ret = s->sdmasysad;
998         break;
999     case SDHC_BLKSIZE:
1000         ret = s->blksize | (s->blkcnt << 16);
1001         break;
1002     case SDHC_ARGUMENT:
1003         ret = s->argument;
1004         break;
1005     case SDHC_TRNMOD:
1006         ret = s->trnmod | (s->cmdreg << 16);
1007         break;
1008     case SDHC_RSPREG0 ... SDHC_RSPREG3:
1009         ret = s->rspreg[((offset & ~0x3) - SDHC_RSPREG0) >> 2];
1010         break;
1011     case  SDHC_BDATA:
1012         if (sdhci_buff_access_is_sequential(s, offset - SDHC_BDATA)) {
1013             ret = sdhci_read_dataport(s, size);
1014             trace_sdhci_access("rd", size << 3, offset, "->", ret, ret);
1015             return ret;
1016         }
1017         break;
1018     case SDHC_PRNSTS:
1019         ret = s->prnsts;
1020         ret = FIELD_DP32(ret, SDHC_PRNSTS, DAT_LVL,
1021                          sdbus_get_dat_lines(&s->sdbus));
1022         ret = FIELD_DP32(ret, SDHC_PRNSTS, CMD_LVL,
1023                          sdbus_get_cmd_line(&s->sdbus));
1024         break;
1025     case SDHC_HOSTCTL:
1026         ret = s->hostctl1 | (s->pwrcon << 8) | (s->blkgap << 16) |
1027               (s->wakcon << 24);
1028         break;
1029     case SDHC_CLKCON:
1030         ret = s->clkcon | (s->timeoutcon << 16);
1031         break;
1032     case SDHC_NORINTSTS:
1033         ret = s->norintsts | (s->errintsts << 16);
1034         break;
1035     case SDHC_NORINTSTSEN:
1036         ret = s->norintstsen | (s->errintstsen << 16);
1037         break;
1038     case SDHC_NORINTSIGEN:
1039         ret = s->norintsigen | (s->errintsigen << 16);
1040         break;
1041     case SDHC_ACMD12ERRSTS:
1042         ret = s->acmd12errsts | (s->hostctl2 << 16);
1043         break;
1044     case SDHC_CAPAB:
1045         ret = (uint32_t)s->capareg;
1046         break;
1047     case SDHC_CAPAB + 4:
1048         ret = (uint32_t)(s->capareg >> 32);
1049         break;
1050     case SDHC_MAXCURR:
1051         ret = (uint32_t)s->maxcurr;
1052         break;
1053     case SDHC_MAXCURR + 4:
1054         ret = (uint32_t)(s->maxcurr >> 32);
1055         break;
1056     case SDHC_ADMAERR:
1057         ret =  s->admaerr;
1058         break;
1059     case SDHC_ADMASYSADDR:
1060         ret = (uint32_t)s->admasysaddr;
1061         break;
1062     case SDHC_ADMASYSADDR + 4:
1063         ret = (uint32_t)(s->admasysaddr >> 32);
1064         break;
1065     case SDHC_SLOT_INT_STATUS:
1066         ret = (s->version << 16) | sdhci_slotint(s);
1067         break;
1068     default:
1069         qemu_log_mask(LOG_UNIMP, "SDHC rd_%ub @0x%02" HWADDR_PRIx " "
1070                       "not implemented\n", size, offset);
1071         break;
1072     }
1073 
1074     ret >>= (offset & 0x3) * 8;
1075     ret &= (1ULL << (size * 8)) - 1;
1076     trace_sdhci_access("rd", size << 3, offset, "->", ret, ret);
1077     return ret;
1078 }
1079 
1080 static inline void sdhci_blkgap_write(SDHCIState *s, uint8_t value)
1081 {
1082     if ((value & SDHC_STOP_AT_GAP_REQ) && (s->blkgap & SDHC_STOP_AT_GAP_REQ)) {
1083         return;
1084     }
1085     s->blkgap = value & SDHC_STOP_AT_GAP_REQ;
1086 
1087     if ((value & SDHC_CONTINUE_REQ) && s->stopped_state &&
1088             (s->blkgap & SDHC_STOP_AT_GAP_REQ) == 0) {
1089         if (s->stopped_state == sdhc_gap_read) {
1090             s->prnsts |= SDHC_DAT_LINE_ACTIVE | SDHC_DOING_READ;
1091             sdhci_read_block_from_card(s);
1092         } else {
1093             s->prnsts |= SDHC_DAT_LINE_ACTIVE | SDHC_DOING_WRITE;
1094             sdhci_write_block_to_card(s);
1095         }
1096         s->stopped_state = sdhc_not_stopped;
1097     } else if (!s->stopped_state && (value & SDHC_STOP_AT_GAP_REQ)) {
1098         if (s->prnsts & SDHC_DOING_READ) {
1099             s->stopped_state = sdhc_gap_read;
1100         } else if (s->prnsts & SDHC_DOING_WRITE) {
1101             s->stopped_state = sdhc_gap_write;
1102         }
1103     }
1104 }
1105 
1106 static inline void sdhci_reset_write(SDHCIState *s, uint8_t value)
1107 {
1108     switch (value) {
1109     case SDHC_RESET_ALL:
1110         sdhci_reset(s);
1111         break;
1112     case SDHC_RESET_CMD:
1113         s->prnsts &= ~SDHC_CMD_INHIBIT;
1114         s->norintsts &= ~SDHC_NIS_CMDCMP;
1115         break;
1116     case SDHC_RESET_DATA:
1117         s->data_count = 0;
1118         s->prnsts &= ~(SDHC_SPACE_AVAILABLE | SDHC_DATA_AVAILABLE |
1119                 SDHC_DOING_READ | SDHC_DOING_WRITE |
1120                 SDHC_DATA_INHIBIT | SDHC_DAT_LINE_ACTIVE);
1121         s->blkgap &= ~(SDHC_STOP_AT_GAP_REQ | SDHC_CONTINUE_REQ);
1122         s->stopped_state = sdhc_not_stopped;
1123         s->norintsts &= ~(SDHC_NIS_WBUFRDY | SDHC_NIS_RBUFRDY |
1124                 SDHC_NIS_DMA | SDHC_NIS_TRSCMP | SDHC_NIS_BLKGAP);
1125         break;
1126     }
1127 }
1128 
1129 static void
1130 sdhci_write(void *opaque, hwaddr offset, uint64_t val, unsigned size)
1131 {
1132     SDHCIState *s = (SDHCIState *)opaque;
1133     unsigned shift =  8 * (offset & 0x3);
1134     uint32_t mask = ~(((1ULL << (size * 8)) - 1) << shift);
1135     uint32_t value = val;
1136     value <<= shift;
1137 
1138     switch (offset & ~0x3) {
1139     case SDHC_SYSAD:
1140         s->sdmasysad = (s->sdmasysad & mask) | value;
1141         MASKED_WRITE(s->sdmasysad, mask, value);
1142         /* Writing to last byte of sdmasysad might trigger transfer */
1143         if (!(mask & 0xFF000000) && TRANSFERRING_DATA(s->prnsts) && s->blkcnt &&
1144                 s->blksize && SDHC_DMA_TYPE(s->hostctl1) == SDHC_CTRL_SDMA) {
1145             if (s->trnmod & SDHC_TRNS_MULTI) {
1146                 sdhci_sdma_transfer_multi_blocks(s);
1147             } else {
1148                 sdhci_sdma_transfer_single_block(s);
1149             }
1150         }
1151         break;
1152     case SDHC_BLKSIZE:
1153         if (!TRANSFERRING_DATA(s->prnsts)) {
1154             MASKED_WRITE(s->blksize, mask, value);
1155             MASKED_WRITE(s->blkcnt, mask >> 16, value >> 16);
1156         }
1157 
1158         /* Limit block size to the maximum buffer size */
1159         if (extract32(s->blksize, 0, 12) > s->buf_maxsz) {
1160             qemu_log_mask(LOG_GUEST_ERROR, "%s: Size 0x%x is larger than " \
1161                           "the maximum buffer 0x%x", __func__, s->blksize,
1162                           s->buf_maxsz);
1163 
1164             s->blksize = deposit32(s->blksize, 0, 12, s->buf_maxsz);
1165         }
1166 
1167         break;
1168     case SDHC_ARGUMENT:
1169         MASKED_WRITE(s->argument, mask, value);
1170         break;
1171     case SDHC_TRNMOD:
1172         /* DMA can be enabled only if it is supported as indicated by
1173          * capabilities register */
1174         if (!(s->capareg & R_SDHC_CAPAB_SDMA_MASK)) {
1175             value &= ~SDHC_TRNS_DMA;
1176         }
1177         MASKED_WRITE(s->trnmod, mask, value & SDHC_TRNMOD_MASK);
1178         MASKED_WRITE(s->cmdreg, mask >> 16, value >> 16);
1179 
1180         /* Writing to the upper byte of CMDREG triggers SD command generation */
1181         if ((mask & 0xFF000000) || !sdhci_can_issue_command(s)) {
1182             break;
1183         }
1184 
1185         sdhci_send_command(s);
1186         break;
1187     case  SDHC_BDATA:
1188         if (sdhci_buff_access_is_sequential(s, offset - SDHC_BDATA)) {
1189             sdhci_write_dataport(s, value >> shift, size);
1190         }
1191         break;
1192     case SDHC_HOSTCTL:
1193         if (!(mask & 0xFF0000)) {
1194             sdhci_blkgap_write(s, value >> 16);
1195         }
1196         MASKED_WRITE(s->hostctl1, mask, value);
1197         MASKED_WRITE(s->pwrcon, mask >> 8, value >> 8);
1198         MASKED_WRITE(s->wakcon, mask >> 24, value >> 24);
1199         if (!(s->prnsts & SDHC_CARD_PRESENT) || ((s->pwrcon >> 1) & 0x7) < 5 ||
1200                 !(s->capareg & (1 << (31 - ((s->pwrcon >> 1) & 0x7))))) {
1201             s->pwrcon &= ~SDHC_POWER_ON;
1202         }
1203         break;
1204     case SDHC_CLKCON:
1205         if (!(mask & 0xFF000000)) {
1206             sdhci_reset_write(s, value >> 24);
1207         }
1208         MASKED_WRITE(s->clkcon, mask, value);
1209         MASKED_WRITE(s->timeoutcon, mask >> 16, value >> 16);
1210         if (s->clkcon & SDHC_CLOCK_INT_EN) {
1211             s->clkcon |= SDHC_CLOCK_INT_STABLE;
1212         } else {
1213             s->clkcon &= ~SDHC_CLOCK_INT_STABLE;
1214         }
1215         break;
1216     case SDHC_NORINTSTS:
1217         if (s->norintstsen & SDHC_NISEN_CARDINT) {
1218             value &= ~SDHC_NIS_CARDINT;
1219         }
1220         s->norintsts &= mask | ~value;
1221         s->errintsts &= (mask >> 16) | ~(value >> 16);
1222         if (s->errintsts) {
1223             s->norintsts |= SDHC_NIS_ERR;
1224         } else {
1225             s->norintsts &= ~SDHC_NIS_ERR;
1226         }
1227         sdhci_update_irq(s);
1228         break;
1229     case SDHC_NORINTSTSEN:
1230         MASKED_WRITE(s->norintstsen, mask, value);
1231         MASKED_WRITE(s->errintstsen, mask >> 16, value >> 16);
1232         s->norintsts &= s->norintstsen;
1233         s->errintsts &= s->errintstsen;
1234         if (s->errintsts) {
1235             s->norintsts |= SDHC_NIS_ERR;
1236         } else {
1237             s->norintsts &= ~SDHC_NIS_ERR;
1238         }
1239         /* Quirk for Raspberry Pi: pending card insert interrupt
1240          * appears when first enabled after power on */
1241         if ((s->norintstsen & SDHC_NISEN_INSERT) && s->pending_insert_state) {
1242             assert(s->pending_insert_quirk);
1243             s->norintsts |= SDHC_NIS_INSERT;
1244             s->pending_insert_state = false;
1245         }
1246         sdhci_update_irq(s);
1247         break;
1248     case SDHC_NORINTSIGEN:
1249         MASKED_WRITE(s->norintsigen, mask, value);
1250         MASKED_WRITE(s->errintsigen, mask >> 16, value >> 16);
1251         sdhci_update_irq(s);
1252         break;
1253     case SDHC_ADMAERR:
1254         MASKED_WRITE(s->admaerr, mask, value);
1255         break;
1256     case SDHC_ADMASYSADDR:
1257         s->admasysaddr = (s->admasysaddr & (0xFFFFFFFF00000000ULL |
1258                 (uint64_t)mask)) | (uint64_t)value;
1259         break;
1260     case SDHC_ADMASYSADDR + 4:
1261         s->admasysaddr = (s->admasysaddr & (0x00000000FFFFFFFFULL |
1262                 ((uint64_t)mask << 32))) | ((uint64_t)value << 32);
1263         break;
1264     case SDHC_FEAER:
1265         s->acmd12errsts |= value;
1266         s->errintsts |= (value >> 16) & s->errintstsen;
1267         if (s->acmd12errsts) {
1268             s->errintsts |= SDHC_EIS_CMD12ERR;
1269         }
1270         if (s->errintsts) {
1271             s->norintsts |= SDHC_NIS_ERR;
1272         }
1273         sdhci_update_irq(s);
1274         break;
1275     case SDHC_ACMD12ERRSTS:
1276         MASKED_WRITE(s->acmd12errsts, mask, value & UINT16_MAX);
1277         if (s->uhs_mode >= UHS_I) {
1278             MASKED_WRITE(s->hostctl2, mask >> 16, value >> 16);
1279 
1280             if (FIELD_EX32(s->hostctl2, SDHC_HOSTCTL2, V18_ENA)) {
1281                 sdbus_set_voltage(&s->sdbus, SD_VOLTAGE_1_8V);
1282             } else {
1283                 sdbus_set_voltage(&s->sdbus, SD_VOLTAGE_3_3V);
1284             }
1285         }
1286         break;
1287 
1288     case SDHC_CAPAB:
1289     case SDHC_CAPAB + 4:
1290     case SDHC_MAXCURR:
1291     case SDHC_MAXCURR + 4:
1292         qemu_log_mask(LOG_GUEST_ERROR, "SDHC wr_%ub @0x%02" HWADDR_PRIx
1293                       " <- 0x%08x read-only\n", size, offset, value >> shift);
1294         break;
1295 
1296     default:
1297         qemu_log_mask(LOG_UNIMP, "SDHC wr_%ub @0x%02" HWADDR_PRIx " <- 0x%08x "
1298                       "not implemented\n", size, offset, value >> shift);
1299         break;
1300     }
1301     trace_sdhci_access("wr", size << 3, offset, "<-",
1302                        value >> shift, value >> shift);
1303 }
1304 
1305 static const MemoryRegionOps sdhci_mmio_ops = {
1306     .read = sdhci_read,
1307     .write = sdhci_write,
1308     .valid = {
1309         .min_access_size = 1,
1310         .max_access_size = 4,
1311         .unaligned = false
1312     },
1313     .endianness = DEVICE_LITTLE_ENDIAN,
1314 };
1315 
1316 static void sdhci_init_readonly_registers(SDHCIState *s, Error **errp)
1317 {
1318     Error *local_err = NULL;
1319 
1320     switch (s->sd_spec_version) {
1321     case 2 ... 3:
1322         break;
1323     default:
1324         error_setg(errp, "Only Spec v2/v3 are supported");
1325         return;
1326     }
1327     s->version = (SDHC_HCVER_VENDOR << 8) | (s->sd_spec_version - 1);
1328 
1329     sdhci_check_capareg(s, &local_err);
1330     if (local_err) {
1331         error_propagate(errp, local_err);
1332         return;
1333     }
1334 }
1335 
1336 /* --- qdev common --- */
1337 
1338 #define DEFINE_SDHCI_COMMON_PROPERTIES(_state) \
1339     DEFINE_PROP_UINT8("sd-spec-version", _state, sd_spec_version, 2), \
1340     DEFINE_PROP_UINT8("uhs", _state, uhs_mode, UHS_NOT_SUPPORTED), \
1341     \
1342     /* Capabilities registers provide information on supported
1343      * features of this specific host controller implementation */ \
1344     DEFINE_PROP_UINT64("capareg", _state, capareg, SDHC_CAPAB_REG_DEFAULT), \
1345     DEFINE_PROP_UINT64("maxcurr", _state, maxcurr, 0)
1346 
1347 static void sdhci_initfn(SDHCIState *s)
1348 {
1349     qbus_create_inplace(&s->sdbus, sizeof(s->sdbus),
1350                         TYPE_SDHCI_BUS, DEVICE(s), "sd-bus");
1351 
1352     s->insert_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, sdhci_raise_insertion_irq, s);
1353     s->transfer_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, sdhci_data_transfer, s);
1354 
1355     s->io_ops = &sdhci_mmio_ops;
1356 }
1357 
1358 static void sdhci_uninitfn(SDHCIState *s)
1359 {
1360     timer_del(s->insert_timer);
1361     timer_free(s->insert_timer);
1362     timer_del(s->transfer_timer);
1363     timer_free(s->transfer_timer);
1364 
1365     g_free(s->fifo_buffer);
1366     s->fifo_buffer = NULL;
1367 }
1368 
1369 static void sdhci_common_realize(SDHCIState *s, Error **errp)
1370 {
1371     Error *local_err = NULL;
1372 
1373     sdhci_init_readonly_registers(s, &local_err);
1374     if (local_err) {
1375         error_propagate(errp, local_err);
1376         return;
1377     }
1378     s->buf_maxsz = sdhci_get_fifolen(s);
1379     s->fifo_buffer = g_malloc0(s->buf_maxsz);
1380 
1381     memory_region_init_io(&s->iomem, OBJECT(s), &sdhci_mmio_ops, s, "sdhci",
1382                           SDHC_REGISTERS_MAP_SIZE);
1383 }
1384 
1385 static void sdhci_common_unrealize(SDHCIState *s, Error **errp)
1386 {
1387     /* This function is expected to be called only once for each class:
1388      * - SysBus:    via DeviceClass->unrealize(),
1389      * - PCI:       via PCIDeviceClass->exit().
1390      * However to avoid double-free and/or use-after-free we still nullify
1391      * this variable (better safe than sorry!). */
1392     g_free(s->fifo_buffer);
1393     s->fifo_buffer = NULL;
1394 }
1395 
1396 static bool sdhci_pending_insert_vmstate_needed(void *opaque)
1397 {
1398     SDHCIState *s = opaque;
1399 
1400     return s->pending_insert_state;
1401 }
1402 
1403 static const VMStateDescription sdhci_pending_insert_vmstate = {
1404     .name = "sdhci/pending-insert",
1405     .version_id = 1,
1406     .minimum_version_id = 1,
1407     .needed = sdhci_pending_insert_vmstate_needed,
1408     .fields = (VMStateField[]) {
1409         VMSTATE_BOOL(pending_insert_state, SDHCIState),
1410         VMSTATE_END_OF_LIST()
1411     },
1412 };
1413 
1414 const VMStateDescription sdhci_vmstate = {
1415     .name = "sdhci",
1416     .version_id = 1,
1417     .minimum_version_id = 1,
1418     .fields = (VMStateField[]) {
1419         VMSTATE_UINT32(sdmasysad, SDHCIState),
1420         VMSTATE_UINT16(blksize, SDHCIState),
1421         VMSTATE_UINT16(blkcnt, SDHCIState),
1422         VMSTATE_UINT32(argument, SDHCIState),
1423         VMSTATE_UINT16(trnmod, SDHCIState),
1424         VMSTATE_UINT16(cmdreg, SDHCIState),
1425         VMSTATE_UINT32_ARRAY(rspreg, SDHCIState, 4),
1426         VMSTATE_UINT32(prnsts, SDHCIState),
1427         VMSTATE_UINT8(hostctl1, SDHCIState),
1428         VMSTATE_UINT8(pwrcon, SDHCIState),
1429         VMSTATE_UINT8(blkgap, SDHCIState),
1430         VMSTATE_UINT8(wakcon, SDHCIState),
1431         VMSTATE_UINT16(clkcon, SDHCIState),
1432         VMSTATE_UINT8(timeoutcon, SDHCIState),
1433         VMSTATE_UINT8(admaerr, SDHCIState),
1434         VMSTATE_UINT16(norintsts, SDHCIState),
1435         VMSTATE_UINT16(errintsts, SDHCIState),
1436         VMSTATE_UINT16(norintstsen, SDHCIState),
1437         VMSTATE_UINT16(errintstsen, SDHCIState),
1438         VMSTATE_UINT16(norintsigen, SDHCIState),
1439         VMSTATE_UINT16(errintsigen, SDHCIState),
1440         VMSTATE_UINT16(acmd12errsts, SDHCIState),
1441         VMSTATE_UINT16(data_count, SDHCIState),
1442         VMSTATE_UINT64(admasysaddr, SDHCIState),
1443         VMSTATE_UINT8(stopped_state, SDHCIState),
1444         VMSTATE_VBUFFER_UINT32(fifo_buffer, SDHCIState, 1, NULL, buf_maxsz),
1445         VMSTATE_TIMER_PTR(insert_timer, SDHCIState),
1446         VMSTATE_TIMER_PTR(transfer_timer, SDHCIState),
1447         VMSTATE_END_OF_LIST()
1448     },
1449     .subsections = (const VMStateDescription*[]) {
1450         &sdhci_pending_insert_vmstate,
1451         NULL
1452     },
1453 };
1454 
1455 static void sdhci_common_class_init(ObjectClass *klass, void *data)
1456 {
1457     DeviceClass *dc = DEVICE_CLASS(klass);
1458 
1459     set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
1460     dc->vmsd = &sdhci_vmstate;
1461     dc->reset = sdhci_poweron_reset;
1462 }
1463 
1464 /* --- qdev PCI --- */
1465 
1466 static Property sdhci_pci_properties[] = {
1467     DEFINE_SDHCI_COMMON_PROPERTIES(SDHCIState),
1468     DEFINE_PROP_END_OF_LIST(),
1469 };
1470 
1471 static void sdhci_pci_realize(PCIDevice *dev, Error **errp)
1472 {
1473     SDHCIState *s = PCI_SDHCI(dev);
1474     Error *local_err = NULL;
1475 
1476     sdhci_initfn(s);
1477     sdhci_common_realize(s, errp);
1478     if (local_err) {
1479         error_propagate(errp, local_err);
1480         return;
1481     }
1482 
1483     dev->config[PCI_CLASS_PROG] = 0x01; /* Standard Host supported DMA */
1484     dev->config[PCI_INTERRUPT_PIN] = 0x01; /* interrupt pin A */
1485     s->irq = pci_allocate_irq(dev);
1486     s->dma_as = pci_get_address_space(dev);
1487     pci_register_bar(dev, 0, PCI_BASE_ADDRESS_SPACE_MEMORY, &s->iomem);
1488 }
1489 
1490 static void sdhci_pci_exit(PCIDevice *dev)
1491 {
1492     SDHCIState *s = PCI_SDHCI(dev);
1493 
1494     sdhci_common_unrealize(s, &error_abort);
1495     sdhci_uninitfn(s);
1496 }
1497 
1498 static void sdhci_pci_class_init(ObjectClass *klass, void *data)
1499 {
1500     DeviceClass *dc = DEVICE_CLASS(klass);
1501     PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);
1502 
1503     k->realize = sdhci_pci_realize;
1504     k->exit = sdhci_pci_exit;
1505     k->vendor_id = PCI_VENDOR_ID_REDHAT;
1506     k->device_id = PCI_DEVICE_ID_REDHAT_SDHCI;
1507     k->class_id = PCI_CLASS_SYSTEM_SDHCI;
1508     dc->props = sdhci_pci_properties;
1509 
1510     sdhci_common_class_init(klass, data);
1511 }
1512 
1513 static const TypeInfo sdhci_pci_info = {
1514     .name = TYPE_PCI_SDHCI,
1515     .parent = TYPE_PCI_DEVICE,
1516     .instance_size = sizeof(SDHCIState),
1517     .class_init = sdhci_pci_class_init,
1518     .interfaces = (InterfaceInfo[]) {
1519         { INTERFACE_CONVENTIONAL_PCI_DEVICE },
1520         { },
1521     },
1522 };
1523 
1524 /* --- qdev SysBus --- */
1525 
1526 static Property sdhci_sysbus_properties[] = {
1527     DEFINE_SDHCI_COMMON_PROPERTIES(SDHCIState),
1528     DEFINE_PROP_BOOL("pending-insert-quirk", SDHCIState, pending_insert_quirk,
1529                      false),
1530     DEFINE_PROP_LINK("dma", SDHCIState,
1531                      dma_mr, TYPE_MEMORY_REGION, MemoryRegion *),
1532     DEFINE_PROP_END_OF_LIST(),
1533 };
1534 
1535 static void sdhci_sysbus_init(Object *obj)
1536 {
1537     SDHCIState *s = SYSBUS_SDHCI(obj);
1538 
1539     sdhci_initfn(s);
1540 }
1541 
1542 static void sdhci_sysbus_finalize(Object *obj)
1543 {
1544     SDHCIState *s = SYSBUS_SDHCI(obj);
1545 
1546     if (s->dma_mr) {
1547         object_unparent(OBJECT(s->dma_mr));
1548     }
1549 
1550     sdhci_uninitfn(s);
1551 }
1552 
1553 static void sdhci_sysbus_realize(DeviceState *dev, Error ** errp)
1554 {
1555     SDHCIState *s = SYSBUS_SDHCI(dev);
1556     SysBusDevice *sbd = SYS_BUS_DEVICE(dev);
1557     Error *local_err = NULL;
1558 
1559     sdhci_common_realize(s, errp);
1560     if (local_err) {
1561         error_propagate(errp, local_err);
1562         return;
1563     }
1564 
1565     if (s->dma_mr) {
1566         s->dma_as = &s->sysbus_dma_as;
1567         address_space_init(s->dma_as, s->dma_mr, "sdhci-dma");
1568     } else {
1569         /* use system_memory() if property "dma" not set */
1570         s->dma_as = &address_space_memory;
1571     }
1572 
1573     sysbus_init_irq(sbd, &s->irq);
1574 
1575     memory_region_init_io(&s->iomem, OBJECT(s), s->io_ops, s, "sdhci",
1576             SDHC_REGISTERS_MAP_SIZE);
1577 
1578     sysbus_init_mmio(sbd, &s->iomem);
1579 }
1580 
1581 static void sdhci_sysbus_unrealize(DeviceState *dev, Error **errp)
1582 {
1583     SDHCIState *s = SYSBUS_SDHCI(dev);
1584 
1585     sdhci_common_unrealize(s, &error_abort);
1586 
1587      if (s->dma_mr) {
1588         address_space_destroy(s->dma_as);
1589     }
1590 }
1591 
1592 static void sdhci_sysbus_class_init(ObjectClass *klass, void *data)
1593 {
1594     DeviceClass *dc = DEVICE_CLASS(klass);
1595 
1596     dc->props = sdhci_sysbus_properties;
1597     dc->realize = sdhci_sysbus_realize;
1598     dc->unrealize = sdhci_sysbus_unrealize;
1599 
1600     sdhci_common_class_init(klass, data);
1601 }
1602 
1603 static const TypeInfo sdhci_sysbus_info = {
1604     .name = TYPE_SYSBUS_SDHCI,
1605     .parent = TYPE_SYS_BUS_DEVICE,
1606     .instance_size = sizeof(SDHCIState),
1607     .instance_init = sdhci_sysbus_init,
1608     .instance_finalize = sdhci_sysbus_finalize,
1609     .class_init = sdhci_sysbus_class_init,
1610 };
1611 
1612 /* --- qdev bus master --- */
1613 
1614 static void sdhci_bus_class_init(ObjectClass *klass, void *data)
1615 {
1616     SDBusClass *sbc = SD_BUS_CLASS(klass);
1617 
1618     sbc->set_inserted = sdhci_set_inserted;
1619     sbc->set_readonly = sdhci_set_readonly;
1620 }
1621 
1622 static const TypeInfo sdhci_bus_info = {
1623     .name = TYPE_SDHCI_BUS,
1624     .parent = TYPE_SD_BUS,
1625     .instance_size = sizeof(SDBus),
1626     .class_init = sdhci_bus_class_init,
1627 };
1628 
1629 static uint64_t usdhc_read(void *opaque, hwaddr offset, unsigned size)
1630 {
1631     SDHCIState *s = SYSBUS_SDHCI(opaque);
1632     uint32_t ret;
1633     uint16_t hostctl1;
1634 
1635     switch (offset) {
1636     default:
1637         return sdhci_read(opaque, offset, size);
1638 
1639     case SDHC_HOSTCTL:
1640         /*
1641          * For a detailed explanation on the following bit
1642          * manipulation code see comments in a similar part of
1643          * usdhc_write()
1644          */
1645         hostctl1 = SDHC_DMA_TYPE(s->hostctl1) << (8 - 3);
1646 
1647         if (s->hostctl1 & SDHC_CTRL_8BITBUS) {
1648             hostctl1 |= ESDHC_CTRL_8BITBUS;
1649         }
1650 
1651         if (s->hostctl1 & SDHC_CTRL_4BITBUS) {
1652             hostctl1 |= ESDHC_CTRL_4BITBUS;
1653         }
1654 
1655         ret  = hostctl1;
1656         ret |= (uint32_t)s->blkgap << 16;
1657         ret |= (uint32_t)s->wakcon << 24;
1658 
1659         break;
1660 
1661     case ESDHC_DLL_CTRL:
1662     case ESDHC_TUNE_CTRL_STATUS:
1663     case ESDHC_UNDOCUMENTED_REG27:
1664     case ESDHC_TUNING_CTRL:
1665     case ESDHC_VENDOR_SPEC:
1666     case ESDHC_MIX_CTRL:
1667     case ESDHC_WTMK_LVL:
1668         ret = 0;
1669         break;
1670     }
1671 
1672     return ret;
1673 }
1674 
1675 static void
1676 usdhc_write(void *opaque, hwaddr offset, uint64_t val, unsigned size)
1677 {
1678     SDHCIState *s = SYSBUS_SDHCI(opaque);
1679     uint8_t hostctl1;
1680     uint32_t value = (uint32_t)val;
1681 
1682     switch (offset) {
1683     case ESDHC_DLL_CTRL:
1684     case ESDHC_TUNE_CTRL_STATUS:
1685     case ESDHC_UNDOCUMENTED_REG27:
1686     case ESDHC_TUNING_CTRL:
1687     case ESDHC_WTMK_LVL:
1688     case ESDHC_VENDOR_SPEC:
1689         break;
1690 
1691     case SDHC_HOSTCTL:
1692         /*
1693          * Here's What ESDHCI has at offset 0x28 (SDHC_HOSTCTL)
1694          *
1695          *       7         6     5      4      3      2        1      0
1696          * |-----------+--------+--------+-----------+----------+---------|
1697          * | Card      | Card   | Endian | DATA3     | Data     | Led     |
1698          * | Detect    | Detect | Mode   | as Card   | Transfer | Control |
1699          * | Signal    | Test   |        | Detection | Width    |         |
1700          * | Selection | Level  |        | Pin       |          |         |
1701          * |-----------+--------+--------+-----------+----------+---------|
1702          *
1703          * and 0x29
1704          *
1705          *  15      10 9    8
1706          * |----------+------|
1707          * | Reserved | DMA  |
1708          * |          | Sel. |
1709          * |          |      |
1710          * |----------+------|
1711          *
1712          * and here's what SDCHI spec expects those offsets to be:
1713          *
1714          * 0x28 (Host Control Register)
1715          *
1716          *     7        6         5       4  3      2         1        0
1717          * |--------+--------+----------+------+--------+----------+---------|
1718          * | Card   | Card   | Extended | DMA  | High   | Data     | LED     |
1719          * | Detect | Detect | Data     | Sel. | Speed  | Transfer | Control |
1720          * | Signal | Test   | Transfer |      | Enable | Width    |         |
1721          * | Sel.   | Level  | Width    |      |        |          |         |
1722          * |--------+--------+----------+------+--------+----------+---------|
1723          *
1724          * and 0x29 (Power Control Register)
1725          *
1726          * |----------------------------------|
1727          * | Power Control Register           |
1728          * |                                  |
1729          * | Description omitted,             |
1730          * | since it has no analog in ESDHCI |
1731          * |                                  |
1732          * |----------------------------------|
1733          *
1734          * Since offsets 0x2A and 0x2B should be compatible between
1735          * both IP specs we only need to reconcile least 16-bit of the
1736          * word we've been given.
1737          */
1738 
1739         /*
1740          * First, save bits 7 6 and 0 since they are identical
1741          */
1742         hostctl1 = value & (SDHC_CTRL_LED |
1743                             SDHC_CTRL_CDTEST_INS |
1744                             SDHC_CTRL_CDTEST_EN);
1745         /*
1746          * Second, split "Data Transfer Width" from bits 2 and 1 in to
1747          * bits 5 and 1
1748          */
1749         if (value & ESDHC_CTRL_8BITBUS) {
1750             hostctl1 |= SDHC_CTRL_8BITBUS;
1751         }
1752 
1753         if (value & ESDHC_CTRL_4BITBUS) {
1754             hostctl1 |= ESDHC_CTRL_4BITBUS;
1755         }
1756 
1757         /*
1758          * Third, move DMA select from bits 9 and 8 to bits 4 and 3
1759          */
1760         hostctl1 |= SDHC_DMA_TYPE(value >> (8 - 3));
1761 
1762         /*
1763          * Now place the corrected value into low 16-bit of the value
1764          * we are going to give standard SDHCI write function
1765          *
1766          * NOTE: This transformation should be the inverse of what can
1767          * be found in drivers/mmc/host/sdhci-esdhc-imx.c in Linux
1768          * kernel
1769          */
1770         value &= ~UINT16_MAX;
1771         value |= hostctl1;
1772         value |= (uint16_t)s->pwrcon << 8;
1773 
1774         sdhci_write(opaque, offset, value, size);
1775         break;
1776 
1777     case ESDHC_MIX_CTRL:
1778         /*
1779          * So, when SD/MMC stack in Linux tries to write to "Transfer
1780          * Mode Register", ESDHC i.MX quirk code will translate it
1781          * into a write to ESDHC_MIX_CTRL, so we do the opposite in
1782          * order to get where we started
1783          *
1784          * Note that Auto CMD23 Enable bit is located in a wrong place
1785          * on i.MX, but since it is not used by QEMU we do not care.
1786          *
1787          * We don't want to call sdhci_write(.., SDHC_TRNMOD, ...)
1788          * here becuase it will result in a call to
1789          * sdhci_send_command(s) which we don't want.
1790          *
1791          */
1792         s->trnmod = value & UINT16_MAX;
1793         break;
1794     case SDHC_TRNMOD:
1795         /*
1796          * Similar to above, but this time a write to "Command
1797          * Register" will be translated into a 4-byte write to
1798          * "Transfer Mode register" where lower 16-bit of value would
1799          * be set to zero. So what we do is fill those bits with
1800          * cached value from s->trnmod and let the SDHCI
1801          * infrastructure handle the rest
1802          */
1803         sdhci_write(opaque, offset, val | s->trnmod, size);
1804         break;
1805     case SDHC_BLKSIZE:
1806         /*
1807          * ESDHCI does not implement "Host SDMA Buffer Boundary", and
1808          * Linux driver will try to zero this field out which will
1809          * break the rest of SDHCI emulation.
1810          *
1811          * Linux defaults to maximum possible setting (512K boundary)
1812          * and it seems to be the only option that i.MX IP implements,
1813          * so we artificially set it to that value.
1814          */
1815         val |= 0x7 << 12;
1816         /* FALLTHROUGH */
1817     default:
1818         sdhci_write(opaque, offset, val, size);
1819         break;
1820     }
1821 }
1822 
1823 
1824 static const MemoryRegionOps usdhc_mmio_ops = {
1825     .read = usdhc_read,
1826     .write = usdhc_write,
1827     .valid = {
1828         .min_access_size = 1,
1829         .max_access_size = 4,
1830         .unaligned = false
1831     },
1832     .endianness = DEVICE_LITTLE_ENDIAN,
1833 };
1834 
1835 static void imx_usdhc_init(Object *obj)
1836 {
1837     SDHCIState *s = SYSBUS_SDHCI(obj);
1838 
1839     s->io_ops = &usdhc_mmio_ops;
1840     s->quirks = SDHCI_QUIRK_NO_BUSY_IRQ;
1841 }
1842 
1843 static const TypeInfo imx_usdhc_info = {
1844     .name = TYPE_IMX_USDHC,
1845     .parent = TYPE_SYSBUS_SDHCI,
1846     .instance_init = imx_usdhc_init,
1847 };
1848 
1849 static void sdhci_register_types(void)
1850 {
1851     type_register_static(&sdhci_pci_info);
1852     type_register_static(&sdhci_sysbus_info);
1853     type_register_static(&sdhci_bus_info);
1854     type_register_static(&imx_usdhc_info);
1855 }
1856 
1857 type_init(sdhci_register_types)
1858