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