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