xref: /openbmc/qemu/hw/sd/sdhci.c (revision 971febb8)
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         trace_sdhci_error("Non-sequential access to Buffer Data Port register"
987                           "is prohibited\n");
988         return false;
989     }
990     return true;
991 }
992 
993 static void sdhci_resume_pending_transfer(SDHCIState *s)
994 {
995     timer_del(s->transfer_timer);
996     sdhci_data_transfer(s);
997 }
998 
999 static uint64_t sdhci_read(void *opaque, hwaddr offset, unsigned size)
1000 {
1001     SDHCIState *s = (SDHCIState *)opaque;
1002     uint32_t ret = 0;
1003 
1004     if (timer_pending(s->transfer_timer)) {
1005         sdhci_resume_pending_transfer(s);
1006     }
1007 
1008     switch (offset & ~0x3) {
1009     case SDHC_SYSAD:
1010         ret = s->sdmasysad;
1011         break;
1012     case SDHC_BLKSIZE:
1013         ret = s->blksize | (s->blkcnt << 16);
1014         break;
1015     case SDHC_ARGUMENT:
1016         ret = s->argument;
1017         break;
1018     case SDHC_TRNMOD:
1019         ret = s->trnmod | (s->cmdreg << 16);
1020         break;
1021     case SDHC_RSPREG0 ... SDHC_RSPREG3:
1022         ret = s->rspreg[((offset & ~0x3) - SDHC_RSPREG0) >> 2];
1023         break;
1024     case  SDHC_BDATA:
1025         if (sdhci_buff_access_is_sequential(s, offset - SDHC_BDATA)) {
1026             ret = sdhci_read_dataport(s, size);
1027             trace_sdhci_access("rd", size << 3, offset, "->", ret, ret);
1028             return ret;
1029         }
1030         break;
1031     case SDHC_PRNSTS:
1032         ret = s->prnsts;
1033         ret = FIELD_DP32(ret, SDHC_PRNSTS, DAT_LVL,
1034                          sdbus_get_dat_lines(&s->sdbus));
1035         ret = FIELD_DP32(ret, SDHC_PRNSTS, CMD_LVL,
1036                          sdbus_get_cmd_line(&s->sdbus));
1037         break;
1038     case SDHC_HOSTCTL:
1039         ret = s->hostctl1 | (s->pwrcon << 8) | (s->blkgap << 16) |
1040               (s->wakcon << 24);
1041         break;
1042     case SDHC_CLKCON:
1043         ret = s->clkcon | (s->timeoutcon << 16);
1044         break;
1045     case SDHC_NORINTSTS:
1046         ret = s->norintsts | (s->errintsts << 16);
1047         break;
1048     case SDHC_NORINTSTSEN:
1049         ret = s->norintstsen | (s->errintstsen << 16);
1050         break;
1051     case SDHC_NORINTSIGEN:
1052         ret = s->norintsigen | (s->errintsigen << 16);
1053         break;
1054     case SDHC_ACMD12ERRSTS:
1055         ret = s->acmd12errsts | (s->hostctl2 << 16);
1056         break;
1057     case SDHC_CAPAB:
1058         ret = (uint32_t)s->capareg;
1059         break;
1060     case SDHC_CAPAB + 4:
1061         ret = (uint32_t)(s->capareg >> 32);
1062         break;
1063     case SDHC_MAXCURR:
1064         ret = (uint32_t)s->maxcurr;
1065         break;
1066     case SDHC_MAXCURR + 4:
1067         ret = (uint32_t)(s->maxcurr >> 32);
1068         break;
1069     case SDHC_ADMAERR:
1070         ret =  s->admaerr;
1071         break;
1072     case SDHC_ADMASYSADDR:
1073         ret = (uint32_t)s->admasysaddr;
1074         break;
1075     case SDHC_ADMASYSADDR + 4:
1076         ret = (uint32_t)(s->admasysaddr >> 32);
1077         break;
1078     case SDHC_SLOT_INT_STATUS:
1079         ret = (s->version << 16) | sdhci_slotint(s);
1080         break;
1081     default:
1082         qemu_log_mask(LOG_UNIMP, "SDHC rd_%ub @0x%02" HWADDR_PRIx " "
1083                       "not implemented\n", size, offset);
1084         break;
1085     }
1086 
1087     ret >>= (offset & 0x3) * 8;
1088     ret &= (1ULL << (size * 8)) - 1;
1089     trace_sdhci_access("rd", size << 3, offset, "->", ret, ret);
1090     return ret;
1091 }
1092 
1093 static inline void sdhci_blkgap_write(SDHCIState *s, uint8_t value)
1094 {
1095     if ((value & SDHC_STOP_AT_GAP_REQ) && (s->blkgap & SDHC_STOP_AT_GAP_REQ)) {
1096         return;
1097     }
1098     s->blkgap = value & SDHC_STOP_AT_GAP_REQ;
1099 
1100     if ((value & SDHC_CONTINUE_REQ) && s->stopped_state &&
1101             (s->blkgap & SDHC_STOP_AT_GAP_REQ) == 0) {
1102         if (s->stopped_state == sdhc_gap_read) {
1103             s->prnsts |= SDHC_DAT_LINE_ACTIVE | SDHC_DOING_READ;
1104             sdhci_read_block_from_card(s);
1105         } else {
1106             s->prnsts |= SDHC_DAT_LINE_ACTIVE | SDHC_DOING_WRITE;
1107             sdhci_write_block_to_card(s);
1108         }
1109         s->stopped_state = sdhc_not_stopped;
1110     } else if (!s->stopped_state && (value & SDHC_STOP_AT_GAP_REQ)) {
1111         if (s->prnsts & SDHC_DOING_READ) {
1112             s->stopped_state = sdhc_gap_read;
1113         } else if (s->prnsts & SDHC_DOING_WRITE) {
1114             s->stopped_state = sdhc_gap_write;
1115         }
1116     }
1117 }
1118 
1119 static inline void sdhci_reset_write(SDHCIState *s, uint8_t value)
1120 {
1121     switch (value) {
1122     case SDHC_RESET_ALL:
1123         sdhci_reset(s);
1124         break;
1125     case SDHC_RESET_CMD:
1126         s->prnsts &= ~SDHC_CMD_INHIBIT;
1127         s->norintsts &= ~SDHC_NIS_CMDCMP;
1128         break;
1129     case SDHC_RESET_DATA:
1130         s->data_count = 0;
1131         s->prnsts &= ~(SDHC_SPACE_AVAILABLE | SDHC_DATA_AVAILABLE |
1132                 SDHC_DOING_READ | SDHC_DOING_WRITE |
1133                 SDHC_DATA_INHIBIT | SDHC_DAT_LINE_ACTIVE);
1134         s->blkgap &= ~(SDHC_STOP_AT_GAP_REQ | SDHC_CONTINUE_REQ);
1135         s->stopped_state = sdhc_not_stopped;
1136         s->norintsts &= ~(SDHC_NIS_WBUFRDY | SDHC_NIS_RBUFRDY |
1137                 SDHC_NIS_DMA | SDHC_NIS_TRSCMP | SDHC_NIS_BLKGAP);
1138         break;
1139     }
1140 }
1141 
1142 static void
1143 sdhci_write(void *opaque, hwaddr offset, uint64_t val, unsigned size)
1144 {
1145     SDHCIState *s = (SDHCIState *)opaque;
1146     unsigned shift =  8 * (offset & 0x3);
1147     uint32_t mask = ~(((1ULL << (size * 8)) - 1) << shift);
1148     uint32_t value = val;
1149     value <<= shift;
1150 
1151     if (timer_pending(s->transfer_timer)) {
1152         sdhci_resume_pending_transfer(s);
1153     }
1154 
1155     switch (offset & ~0x3) {
1156     case SDHC_SYSAD:
1157         if (!TRANSFERRING_DATA(s->prnsts)) {
1158             s->sdmasysad = (s->sdmasysad & mask) | value;
1159             MASKED_WRITE(s->sdmasysad, mask, value);
1160             /* Writing to last byte of sdmasysad might trigger transfer */
1161             if (!(mask & 0xFF000000) && s->blkcnt &&
1162                 (s->blksize & BLOCK_SIZE_MASK) &&
1163                 SDHC_DMA_TYPE(s->hostctl1) == SDHC_CTRL_SDMA) {
1164                 if (s->trnmod & SDHC_TRNS_MULTI) {
1165                     sdhci_sdma_transfer_multi_blocks(s);
1166                 } else {
1167                     sdhci_sdma_transfer_single_block(s);
1168                 }
1169             }
1170         }
1171         break;
1172     case SDHC_BLKSIZE:
1173         if (!TRANSFERRING_DATA(s->prnsts)) {
1174             uint16_t blksize = s->blksize;
1175 
1176             /*
1177              * [14:12] SDMA Buffer Boundary
1178              * [11:00] Transfer Block Size
1179              */
1180             MASKED_WRITE(s->blksize, mask, extract32(value, 0, 15));
1181             MASKED_WRITE(s->blkcnt, mask >> 16, value >> 16);
1182 
1183             /* Limit block size to the maximum buffer size */
1184             if (extract32(s->blksize, 0, 12) > s->buf_maxsz) {
1185                 qemu_log_mask(LOG_GUEST_ERROR, "%s: Size 0x%x is larger than "
1186                               "the maximum buffer 0x%x\n", __func__, s->blksize,
1187                               s->buf_maxsz);
1188 
1189                 s->blksize = deposit32(s->blksize, 0, 12, s->buf_maxsz);
1190             }
1191 
1192             /*
1193              * If the block size is programmed to a different value from
1194              * the previous one, reset the data pointer of s->fifo_buffer[]
1195              * so that s->fifo_buffer[] can be filled in using the new block
1196              * size in the next transfer.
1197              */
1198             if (blksize != s->blksize) {
1199                 s->data_count = 0;
1200             }
1201         }
1202 
1203         break;
1204     case SDHC_ARGUMENT:
1205         MASKED_WRITE(s->argument, mask, value);
1206         break;
1207     case SDHC_TRNMOD:
1208         /* DMA can be enabled only if it is supported as indicated by
1209          * capabilities register */
1210         if (!(s->capareg & R_SDHC_CAPAB_SDMA_MASK)) {
1211             value &= ~SDHC_TRNS_DMA;
1212         }
1213 
1214         /* TRNMOD writes are inhibited while Command Inhibit (DAT) is true */
1215         if (s->prnsts & SDHC_DATA_INHIBIT) {
1216             mask |= 0xffff;
1217         }
1218 
1219         MASKED_WRITE(s->trnmod, mask, value & SDHC_TRNMOD_MASK);
1220         MASKED_WRITE(s->cmdreg, mask >> 16, value >> 16);
1221 
1222         /* Writing to the upper byte of CMDREG triggers SD command generation */
1223         if ((mask & 0xFF000000) || !sdhci_can_issue_command(s)) {
1224             break;
1225         }
1226 
1227         sdhci_send_command(s);
1228         break;
1229     case  SDHC_BDATA:
1230         if (sdhci_buff_access_is_sequential(s, offset - SDHC_BDATA)) {
1231             sdhci_write_dataport(s, value >> shift, size);
1232         }
1233         break;
1234     case SDHC_HOSTCTL:
1235         if (!(mask & 0xFF0000)) {
1236             sdhci_blkgap_write(s, value >> 16);
1237         }
1238         MASKED_WRITE(s->hostctl1, mask, value);
1239         MASKED_WRITE(s->pwrcon, mask >> 8, value >> 8);
1240         MASKED_WRITE(s->wakcon, mask >> 24, value >> 24);
1241         if (!(s->prnsts & SDHC_CARD_PRESENT) || ((s->pwrcon >> 1) & 0x7) < 5 ||
1242                 !(s->capareg & (1 << (31 - ((s->pwrcon >> 1) & 0x7))))) {
1243             s->pwrcon &= ~SDHC_POWER_ON;
1244         }
1245         break;
1246     case SDHC_CLKCON:
1247         if (!(mask & 0xFF000000)) {
1248             sdhci_reset_write(s, value >> 24);
1249         }
1250         MASKED_WRITE(s->clkcon, mask, value);
1251         MASKED_WRITE(s->timeoutcon, mask >> 16, value >> 16);
1252         if (s->clkcon & SDHC_CLOCK_INT_EN) {
1253             s->clkcon |= SDHC_CLOCK_INT_STABLE;
1254         } else {
1255             s->clkcon &= ~SDHC_CLOCK_INT_STABLE;
1256         }
1257         break;
1258     case SDHC_NORINTSTS:
1259         if (s->norintstsen & SDHC_NISEN_CARDINT) {
1260             value &= ~SDHC_NIS_CARDINT;
1261         }
1262         s->norintsts &= mask | ~value;
1263         s->errintsts &= (mask >> 16) | ~(value >> 16);
1264         if (s->errintsts) {
1265             s->norintsts |= SDHC_NIS_ERR;
1266         } else {
1267             s->norintsts &= ~SDHC_NIS_ERR;
1268         }
1269         sdhci_update_irq(s);
1270         break;
1271     case SDHC_NORINTSTSEN:
1272         MASKED_WRITE(s->norintstsen, mask, value);
1273         MASKED_WRITE(s->errintstsen, mask >> 16, value >> 16);
1274         s->norintsts &= s->norintstsen;
1275         s->errintsts &= s->errintstsen;
1276         if (s->errintsts) {
1277             s->norintsts |= SDHC_NIS_ERR;
1278         } else {
1279             s->norintsts &= ~SDHC_NIS_ERR;
1280         }
1281         /* Quirk for Raspberry Pi: pending card insert interrupt
1282          * appears when first enabled after power on */
1283         if ((s->norintstsen & SDHC_NISEN_INSERT) && s->pending_insert_state) {
1284             assert(s->pending_insert_quirk);
1285             s->norintsts |= SDHC_NIS_INSERT;
1286             s->pending_insert_state = false;
1287         }
1288         sdhci_update_irq(s);
1289         break;
1290     case SDHC_NORINTSIGEN:
1291         MASKED_WRITE(s->norintsigen, mask, value);
1292         MASKED_WRITE(s->errintsigen, mask >> 16, value >> 16);
1293         sdhci_update_irq(s);
1294         break;
1295     case SDHC_ADMAERR:
1296         MASKED_WRITE(s->admaerr, mask, value);
1297         break;
1298     case SDHC_ADMASYSADDR:
1299         s->admasysaddr = (s->admasysaddr & (0xFFFFFFFF00000000ULL |
1300                 (uint64_t)mask)) | (uint64_t)value;
1301         break;
1302     case SDHC_ADMASYSADDR + 4:
1303         s->admasysaddr = (s->admasysaddr & (0x00000000FFFFFFFFULL |
1304                 ((uint64_t)mask << 32))) | ((uint64_t)value << 32);
1305         break;
1306     case SDHC_FEAER:
1307         s->acmd12errsts |= value;
1308         s->errintsts |= (value >> 16) & s->errintstsen;
1309         if (s->acmd12errsts) {
1310             s->errintsts |= SDHC_EIS_CMD12ERR;
1311         }
1312         if (s->errintsts) {
1313             s->norintsts |= SDHC_NIS_ERR;
1314         }
1315         sdhci_update_irq(s);
1316         break;
1317     case SDHC_ACMD12ERRSTS:
1318         MASKED_WRITE(s->acmd12errsts, mask, value & UINT16_MAX);
1319         if (s->uhs_mode >= UHS_I) {
1320             MASKED_WRITE(s->hostctl2, mask >> 16, value >> 16);
1321 
1322             if (FIELD_EX32(s->hostctl2, SDHC_HOSTCTL2, V18_ENA)) {
1323                 sdbus_set_voltage(&s->sdbus, SD_VOLTAGE_1_8V);
1324             } else {
1325                 sdbus_set_voltage(&s->sdbus, SD_VOLTAGE_3_3V);
1326             }
1327         }
1328         break;
1329 
1330     case SDHC_CAPAB:
1331     case SDHC_CAPAB + 4:
1332     case SDHC_MAXCURR:
1333     case SDHC_MAXCURR + 4:
1334         qemu_log_mask(LOG_GUEST_ERROR, "SDHC wr_%ub @0x%02" HWADDR_PRIx
1335                       " <- 0x%08x read-only\n", size, offset, value >> shift);
1336         break;
1337 
1338     default:
1339         qemu_log_mask(LOG_UNIMP, "SDHC wr_%ub @0x%02" HWADDR_PRIx " <- 0x%08x "
1340                       "not implemented\n", size, offset, value >> shift);
1341         break;
1342     }
1343     trace_sdhci_access("wr", size << 3, offset, "<-",
1344                        value >> shift, value >> shift);
1345 }
1346 
1347 static const MemoryRegionOps sdhci_mmio_le_ops = {
1348     .read = sdhci_read,
1349     .write = sdhci_write,
1350     .valid = {
1351         .min_access_size = 1,
1352         .max_access_size = 4,
1353         .unaligned = false
1354     },
1355     .endianness = DEVICE_LITTLE_ENDIAN,
1356 };
1357 
1358 static const MemoryRegionOps sdhci_mmio_be_ops = {
1359     .read = sdhci_read,
1360     .write = sdhci_write,
1361     .impl = {
1362         .min_access_size = 4,
1363         .max_access_size = 4,
1364     },
1365     .valid = {
1366         .min_access_size = 1,
1367         .max_access_size = 4,
1368         .unaligned = false
1369     },
1370     .endianness = DEVICE_BIG_ENDIAN,
1371 };
1372 
1373 static void sdhci_init_readonly_registers(SDHCIState *s, Error **errp)
1374 {
1375     ERRP_GUARD();
1376 
1377     switch (s->sd_spec_version) {
1378     case 2 ... 3:
1379         break;
1380     default:
1381         error_setg(errp, "Only Spec v2/v3 are supported");
1382         return;
1383     }
1384     s->version = (SDHC_HCVER_VENDOR << 8) | (s->sd_spec_version - 1);
1385 
1386     sdhci_check_capareg(s, errp);
1387     if (*errp) {
1388         return;
1389     }
1390 }
1391 
1392 /* --- qdev common --- */
1393 
1394 void sdhci_initfn(SDHCIState *s)
1395 {
1396     qbus_init(&s->sdbus, sizeof(s->sdbus), TYPE_SDHCI_BUS, DEVICE(s), "sd-bus");
1397 
1398     s->insert_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, sdhci_raise_insertion_irq, s);
1399     s->transfer_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, sdhci_data_transfer, s);
1400 
1401     s->io_ops = &sdhci_mmio_le_ops;
1402 }
1403 
1404 void sdhci_uninitfn(SDHCIState *s)
1405 {
1406     timer_free(s->insert_timer);
1407     timer_free(s->transfer_timer);
1408 
1409     g_free(s->fifo_buffer);
1410     s->fifo_buffer = NULL;
1411 }
1412 
1413 void sdhci_common_realize(SDHCIState *s, Error **errp)
1414 {
1415     ERRP_GUARD();
1416 
1417     switch (s->endianness) {
1418     case DEVICE_LITTLE_ENDIAN:
1419         /* s->io_ops is little endian by default */
1420         break;
1421     case DEVICE_BIG_ENDIAN:
1422         if (s->io_ops != &sdhci_mmio_le_ops) {
1423             error_setg(errp, "SD controller doesn't support big endianness");
1424             return;
1425         }
1426         s->io_ops = &sdhci_mmio_be_ops;
1427         break;
1428     default:
1429         error_setg(errp, "Incorrect endianness");
1430         return;
1431     }
1432 
1433     sdhci_init_readonly_registers(s, errp);
1434     if (*errp) {
1435         return;
1436     }
1437 
1438     s->buf_maxsz = sdhci_get_fifolen(s);
1439     s->fifo_buffer = g_malloc0(s->buf_maxsz);
1440 
1441     memory_region_init_io(&s->iomem, OBJECT(s), s->io_ops, s, "sdhci",
1442                           SDHC_REGISTERS_MAP_SIZE);
1443 }
1444 
1445 void sdhci_common_unrealize(SDHCIState *s)
1446 {
1447     /* This function is expected to be called only once for each class:
1448      * - SysBus:    via DeviceClass->unrealize(),
1449      * - PCI:       via PCIDeviceClass->exit().
1450      * However to avoid double-free and/or use-after-free we still nullify
1451      * this variable (better safe than sorry!). */
1452     g_free(s->fifo_buffer);
1453     s->fifo_buffer = NULL;
1454 }
1455 
1456 static bool sdhci_pending_insert_vmstate_needed(void *opaque)
1457 {
1458     SDHCIState *s = opaque;
1459 
1460     return s->pending_insert_state;
1461 }
1462 
1463 static const VMStateDescription sdhci_pending_insert_vmstate = {
1464     .name = "sdhci/pending-insert",
1465     .version_id = 1,
1466     .minimum_version_id = 1,
1467     .needed = sdhci_pending_insert_vmstate_needed,
1468     .fields = (const VMStateField[]) {
1469         VMSTATE_BOOL(pending_insert_state, SDHCIState),
1470         VMSTATE_END_OF_LIST()
1471     },
1472 };
1473 
1474 const VMStateDescription sdhci_vmstate = {
1475     .name = "sdhci",
1476     .version_id = 1,
1477     .minimum_version_id = 1,
1478     .fields = (const VMStateField[]) {
1479         VMSTATE_UINT32(sdmasysad, SDHCIState),
1480         VMSTATE_UINT16(blksize, SDHCIState),
1481         VMSTATE_UINT16(blkcnt, SDHCIState),
1482         VMSTATE_UINT32(argument, SDHCIState),
1483         VMSTATE_UINT16(trnmod, SDHCIState),
1484         VMSTATE_UINT16(cmdreg, SDHCIState),
1485         VMSTATE_UINT32_ARRAY(rspreg, SDHCIState, 4),
1486         VMSTATE_UINT32(prnsts, SDHCIState),
1487         VMSTATE_UINT8(hostctl1, SDHCIState),
1488         VMSTATE_UINT8(pwrcon, SDHCIState),
1489         VMSTATE_UINT8(blkgap, SDHCIState),
1490         VMSTATE_UINT8(wakcon, SDHCIState),
1491         VMSTATE_UINT16(clkcon, SDHCIState),
1492         VMSTATE_UINT8(timeoutcon, SDHCIState),
1493         VMSTATE_UINT8(admaerr, SDHCIState),
1494         VMSTATE_UINT16(norintsts, SDHCIState),
1495         VMSTATE_UINT16(errintsts, SDHCIState),
1496         VMSTATE_UINT16(norintstsen, SDHCIState),
1497         VMSTATE_UINT16(errintstsen, SDHCIState),
1498         VMSTATE_UINT16(norintsigen, SDHCIState),
1499         VMSTATE_UINT16(errintsigen, SDHCIState),
1500         VMSTATE_UINT16(acmd12errsts, SDHCIState),
1501         VMSTATE_UINT16(data_count, SDHCIState),
1502         VMSTATE_UINT64(admasysaddr, SDHCIState),
1503         VMSTATE_UINT8(stopped_state, SDHCIState),
1504         VMSTATE_VBUFFER_UINT32(fifo_buffer, SDHCIState, 1, NULL, buf_maxsz),
1505         VMSTATE_TIMER_PTR(insert_timer, SDHCIState),
1506         VMSTATE_TIMER_PTR(transfer_timer, SDHCIState),
1507         VMSTATE_END_OF_LIST()
1508     },
1509     .subsections = (const VMStateDescription * const []) {
1510         &sdhci_pending_insert_vmstate,
1511         NULL
1512     },
1513 };
1514 
1515 void sdhci_common_class_init(ObjectClass *klass, void *data)
1516 {
1517     DeviceClass *dc = DEVICE_CLASS(klass);
1518 
1519     set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
1520     dc->vmsd = &sdhci_vmstate;
1521     dc->reset = sdhci_poweron_reset;
1522 }
1523 
1524 /* --- qdev SysBus --- */
1525 
1526 static Property sdhci_sysbus_properties[] = {
1527     DEFINE_SDHCI_COMMON_PROPERTIES(SDHCIState),
1528     DEFINE_PROP_BOOL("pending-insert-quirk", SDHCIState, pending_insert_quirk,
1529                      false),
1530     DEFINE_PROP_LINK("dma", SDHCIState,
1531                      dma_mr, TYPE_MEMORY_REGION, MemoryRegion *),
1532     DEFINE_PROP_END_OF_LIST(),
1533 };
1534 
1535 static void sdhci_sysbus_init(Object *obj)
1536 {
1537     SDHCIState *s = SYSBUS_SDHCI(obj);
1538 
1539     sdhci_initfn(s);
1540 }
1541 
1542 static void sdhci_sysbus_finalize(Object *obj)
1543 {
1544     SDHCIState *s = SYSBUS_SDHCI(obj);
1545 
1546     if (s->dma_mr) {
1547         object_unparent(OBJECT(s->dma_mr));
1548     }
1549 
1550     sdhci_uninitfn(s);
1551 }
1552 
1553 static void sdhci_sysbus_realize(DeviceState *dev, Error **errp)
1554 {
1555     ERRP_GUARD();
1556     SDHCIState *s = SYSBUS_SDHCI(dev);
1557     SysBusDevice *sbd = SYS_BUS_DEVICE(dev);
1558 
1559     sdhci_common_realize(s, errp);
1560     if (*errp) {
1561         return;
1562     }
1563 
1564     if (s->dma_mr) {
1565         s->dma_as = &s->sysbus_dma_as;
1566         address_space_init(s->dma_as, s->dma_mr, "sdhci-dma");
1567     } else {
1568         /* use system_memory() if property "dma" not set */
1569         s->dma_as = &address_space_memory;
1570     }
1571 
1572     sysbus_init_irq(sbd, &s->irq);
1573 
1574     sysbus_init_mmio(sbd, &s->iomem);
1575 }
1576 
1577 static void sdhci_sysbus_unrealize(DeviceState *dev)
1578 {
1579     SDHCIState *s = SYSBUS_SDHCI(dev);
1580 
1581     sdhci_common_unrealize(s);
1582 
1583      if (s->dma_mr) {
1584         address_space_destroy(s->dma_as);
1585     }
1586 }
1587 
1588 static void sdhci_sysbus_class_init(ObjectClass *klass, void *data)
1589 {
1590     DeviceClass *dc = DEVICE_CLASS(klass);
1591 
1592     device_class_set_props(dc, sdhci_sysbus_properties);
1593     dc->realize = sdhci_sysbus_realize;
1594     dc->unrealize = sdhci_sysbus_unrealize;
1595 
1596     sdhci_common_class_init(klass, data);
1597 }
1598 
1599 static const TypeInfo sdhci_sysbus_info = {
1600     .name = TYPE_SYSBUS_SDHCI,
1601     .parent = TYPE_SYS_BUS_DEVICE,
1602     .instance_size = sizeof(SDHCIState),
1603     .instance_init = sdhci_sysbus_init,
1604     .instance_finalize = sdhci_sysbus_finalize,
1605     .class_init = sdhci_sysbus_class_init,
1606 };
1607 
1608 /* --- qdev bus master --- */
1609 
1610 static void sdhci_bus_class_init(ObjectClass *klass, void *data)
1611 {
1612     SDBusClass *sbc = SD_BUS_CLASS(klass);
1613 
1614     sbc->set_inserted = sdhci_set_inserted;
1615     sbc->set_readonly = sdhci_set_readonly;
1616 }
1617 
1618 static const TypeInfo sdhci_bus_info = {
1619     .name = TYPE_SDHCI_BUS,
1620     .parent = TYPE_SD_BUS,
1621     .instance_size = sizeof(SDBus),
1622     .class_init = sdhci_bus_class_init,
1623 };
1624 
1625 /* --- qdev i.MX eSDHC --- */
1626 
1627 #define USDHC_MIX_CTRL                  0x48
1628 
1629 #define USDHC_VENDOR_SPEC               0xc0
1630 #define USDHC_IMX_FRC_SDCLK_ON          (1 << 8)
1631 
1632 #define USDHC_DLL_CTRL                  0x60
1633 
1634 #define USDHC_TUNING_CTRL               0xcc
1635 #define USDHC_TUNE_CTRL_STATUS          0x68
1636 #define USDHC_WTMK_LVL                  0x44
1637 
1638 /* Undocumented register used by guests working around erratum ERR004536 */
1639 #define USDHC_UNDOCUMENTED_REG27        0x6c
1640 
1641 #define USDHC_CTRL_4BITBUS              (0x1 << 1)
1642 #define USDHC_CTRL_8BITBUS              (0x2 << 1)
1643 
1644 #define USDHC_PRNSTS_SDSTB              (1 << 3)
1645 
1646 static uint64_t usdhc_read(void *opaque, hwaddr offset, unsigned size)
1647 {
1648     SDHCIState *s = SYSBUS_SDHCI(opaque);
1649     uint32_t ret;
1650     uint16_t hostctl1;
1651 
1652     switch (offset) {
1653     default:
1654         return sdhci_read(opaque, offset, size);
1655 
1656     case SDHC_HOSTCTL:
1657         /*
1658          * For a detailed explanation on the following bit
1659          * manipulation code see comments in a similar part of
1660          * usdhc_write()
1661          */
1662         hostctl1 = SDHC_DMA_TYPE(s->hostctl1) << (8 - 3);
1663 
1664         if (s->hostctl1 & SDHC_CTRL_8BITBUS) {
1665             hostctl1 |= USDHC_CTRL_8BITBUS;
1666         }
1667 
1668         if (s->hostctl1 & SDHC_CTRL_4BITBUS) {
1669             hostctl1 |= USDHC_CTRL_4BITBUS;
1670         }
1671 
1672         ret  = hostctl1;
1673         ret |= (uint32_t)s->blkgap << 16;
1674         ret |= (uint32_t)s->wakcon << 24;
1675 
1676         break;
1677 
1678     case SDHC_PRNSTS:
1679         /* Add SDSTB (SD Clock Stable) bit to PRNSTS */
1680         ret = sdhci_read(opaque, offset, size) & ~USDHC_PRNSTS_SDSTB;
1681         if (s->clkcon & SDHC_CLOCK_INT_STABLE) {
1682             ret |= USDHC_PRNSTS_SDSTB;
1683         }
1684         break;
1685 
1686     case USDHC_VENDOR_SPEC:
1687         ret = s->vendor_spec;
1688         break;
1689     case USDHC_DLL_CTRL:
1690     case USDHC_TUNE_CTRL_STATUS:
1691     case USDHC_UNDOCUMENTED_REG27:
1692     case USDHC_TUNING_CTRL:
1693     case USDHC_MIX_CTRL:
1694     case USDHC_WTMK_LVL:
1695         ret = 0;
1696         break;
1697     }
1698 
1699     return ret;
1700 }
1701 
1702 static void
1703 usdhc_write(void *opaque, hwaddr offset, uint64_t val, unsigned size)
1704 {
1705     SDHCIState *s = SYSBUS_SDHCI(opaque);
1706     uint8_t hostctl1;
1707     uint32_t value = (uint32_t)val;
1708 
1709     switch (offset) {
1710     case USDHC_DLL_CTRL:
1711     case USDHC_TUNE_CTRL_STATUS:
1712     case USDHC_UNDOCUMENTED_REG27:
1713     case USDHC_TUNING_CTRL:
1714     case USDHC_WTMK_LVL:
1715         break;
1716 
1717     case USDHC_VENDOR_SPEC:
1718         s->vendor_spec = value;
1719         switch (s->vendor) {
1720         case SDHCI_VENDOR_IMX:
1721             if (value & USDHC_IMX_FRC_SDCLK_ON) {
1722                 s->prnsts &= ~SDHC_IMX_CLOCK_GATE_OFF;
1723             } else {
1724                 s->prnsts |= SDHC_IMX_CLOCK_GATE_OFF;
1725             }
1726             break;
1727         default:
1728             break;
1729         }
1730         break;
1731 
1732     case SDHC_HOSTCTL:
1733         /*
1734          * Here's What ESDHCI has at offset 0x28 (SDHC_HOSTCTL)
1735          *
1736          *       7         6     5      4      3      2        1      0
1737          * |-----------+--------+--------+-----------+----------+---------|
1738          * | Card      | Card   | Endian | DATA3     | Data     | Led     |
1739          * | Detect    | Detect | Mode   | as Card   | Transfer | Control |
1740          * | Signal    | Test   |        | Detection | Width    |         |
1741          * | Selection | Level  |        | Pin       |          |         |
1742          * |-----------+--------+--------+-----------+----------+---------|
1743          *
1744          * and 0x29
1745          *
1746          *  15      10 9    8
1747          * |----------+------|
1748          * | Reserved | DMA  |
1749          * |          | Sel. |
1750          * |          |      |
1751          * |----------+------|
1752          *
1753          * and here's what SDCHI spec expects those offsets to be:
1754          *
1755          * 0x28 (Host Control Register)
1756          *
1757          *     7        6         5       4  3      2         1        0
1758          * |--------+--------+----------+------+--------+----------+---------|
1759          * | Card   | Card   | Extended | DMA  | High   | Data     | LED     |
1760          * | Detect | Detect | Data     | Sel. | Speed  | Transfer | Control |
1761          * | Signal | Test   | Transfer |      | Enable | Width    |         |
1762          * | Sel.   | Level  | Width    |      |        |          |         |
1763          * |--------+--------+----------+------+--------+----------+---------|
1764          *
1765          * and 0x29 (Power Control Register)
1766          *
1767          * |----------------------------------|
1768          * | Power Control Register           |
1769          * |                                  |
1770          * | Description omitted,             |
1771          * | since it has no analog in ESDHCI |
1772          * |                                  |
1773          * |----------------------------------|
1774          *
1775          * Since offsets 0x2A and 0x2B should be compatible between
1776          * both IP specs we only need to reconcile least 16-bit of the
1777          * word we've been given.
1778          */
1779 
1780         /*
1781          * First, save bits 7 6 and 0 since they are identical
1782          */
1783         hostctl1 = value & (SDHC_CTRL_LED |
1784                             SDHC_CTRL_CDTEST_INS |
1785                             SDHC_CTRL_CDTEST_EN);
1786         /*
1787          * Second, split "Data Transfer Width" from bits 2 and 1 in to
1788          * bits 5 and 1
1789          */
1790         if (value & USDHC_CTRL_8BITBUS) {
1791             hostctl1 |= SDHC_CTRL_8BITBUS;
1792         }
1793 
1794         if (value & USDHC_CTRL_4BITBUS) {
1795             hostctl1 |= USDHC_CTRL_4BITBUS;
1796         }
1797 
1798         /*
1799          * Third, move DMA select from bits 9 and 8 to bits 4 and 3
1800          */
1801         hostctl1 |= SDHC_DMA_TYPE(value >> (8 - 3));
1802 
1803         /*
1804          * Now place the corrected value into low 16-bit of the value
1805          * we are going to give standard SDHCI write function
1806          *
1807          * NOTE: This transformation should be the inverse of what can
1808          * be found in drivers/mmc/host/sdhci-esdhc-imx.c in Linux
1809          * kernel
1810          */
1811         value &= ~UINT16_MAX;
1812         value |= hostctl1;
1813         value |= (uint16_t)s->pwrcon << 8;
1814 
1815         sdhci_write(opaque, offset, value, size);
1816         break;
1817 
1818     case USDHC_MIX_CTRL:
1819         /*
1820          * So, when SD/MMC stack in Linux tries to write to "Transfer
1821          * Mode Register", ESDHC i.MX quirk code will translate it
1822          * into a write to ESDHC_MIX_CTRL, so we do the opposite in
1823          * order to get where we started
1824          *
1825          * Note that Auto CMD23 Enable bit is located in a wrong place
1826          * on i.MX, but since it is not used by QEMU we do not care.
1827          *
1828          * We don't want to call sdhci_write(.., SDHC_TRNMOD, ...)
1829          * here because it will result in a call to
1830          * sdhci_send_command(s) which we don't want.
1831          *
1832          */
1833         s->trnmod = value & UINT16_MAX;
1834         break;
1835     case SDHC_TRNMOD:
1836         /*
1837          * Similar to above, but this time a write to "Command
1838          * Register" will be translated into a 4-byte write to
1839          * "Transfer Mode register" where lower 16-bit of value would
1840          * be set to zero. So what we do is fill those bits with
1841          * cached value from s->trnmod and let the SDHCI
1842          * infrastructure handle the rest
1843          */
1844         sdhci_write(opaque, offset, val | s->trnmod, size);
1845         break;
1846     case SDHC_BLKSIZE:
1847         /*
1848          * ESDHCI does not implement "Host SDMA Buffer Boundary", and
1849          * Linux driver will try to zero this field out which will
1850          * break the rest of SDHCI emulation.
1851          *
1852          * Linux defaults to maximum possible setting (512K boundary)
1853          * and it seems to be the only option that i.MX IP implements,
1854          * so we artificially set it to that value.
1855          */
1856         val |= 0x7 << 12;
1857         /* FALLTHROUGH */
1858     default:
1859         sdhci_write(opaque, offset, val, size);
1860         break;
1861     }
1862 }
1863 
1864 static const MemoryRegionOps usdhc_mmio_ops = {
1865     .read = usdhc_read,
1866     .write = usdhc_write,
1867     .valid = {
1868         .min_access_size = 1,
1869         .max_access_size = 4,
1870         .unaligned = false
1871     },
1872     .endianness = DEVICE_LITTLE_ENDIAN,
1873 };
1874 
1875 static void imx_usdhc_init(Object *obj)
1876 {
1877     SDHCIState *s = SYSBUS_SDHCI(obj);
1878 
1879     s->io_ops = &usdhc_mmio_ops;
1880     s->quirks = SDHCI_QUIRK_NO_BUSY_IRQ;
1881 }
1882 
1883 static const TypeInfo imx_usdhc_info = {
1884     .name = TYPE_IMX_USDHC,
1885     .parent = TYPE_SYSBUS_SDHCI,
1886     .instance_init = imx_usdhc_init,
1887 };
1888 
1889 /* --- qdev Samsung s3c --- */
1890 
1891 #define S3C_SDHCI_CONTROL2      0x80
1892 #define S3C_SDHCI_CONTROL3      0x84
1893 #define S3C_SDHCI_CONTROL4      0x8c
1894 
1895 static uint64_t sdhci_s3c_read(void *opaque, hwaddr offset, unsigned size)
1896 {
1897     uint64_t ret;
1898 
1899     switch (offset) {
1900     case S3C_SDHCI_CONTROL2:
1901     case S3C_SDHCI_CONTROL3:
1902     case S3C_SDHCI_CONTROL4:
1903         /* ignore */
1904         ret = 0;
1905         break;
1906     default:
1907         ret = sdhci_read(opaque, offset, size);
1908         break;
1909     }
1910 
1911     return ret;
1912 }
1913 
1914 static void sdhci_s3c_write(void *opaque, hwaddr offset, uint64_t val,
1915                             unsigned size)
1916 {
1917     switch (offset) {
1918     case S3C_SDHCI_CONTROL2:
1919     case S3C_SDHCI_CONTROL3:
1920     case S3C_SDHCI_CONTROL4:
1921         /* ignore */
1922         break;
1923     default:
1924         sdhci_write(opaque, offset, val, size);
1925         break;
1926     }
1927 }
1928 
1929 static const MemoryRegionOps sdhci_s3c_mmio_ops = {
1930     .read = sdhci_s3c_read,
1931     .write = sdhci_s3c_write,
1932     .valid = {
1933         .min_access_size = 1,
1934         .max_access_size = 4,
1935         .unaligned = false
1936     },
1937     .endianness = DEVICE_LITTLE_ENDIAN,
1938 };
1939 
1940 static void sdhci_s3c_init(Object *obj)
1941 {
1942     SDHCIState *s = SYSBUS_SDHCI(obj);
1943 
1944     s->io_ops = &sdhci_s3c_mmio_ops;
1945 }
1946 
1947 static const TypeInfo sdhci_s3c_info = {
1948     .name = TYPE_S3C_SDHCI  ,
1949     .parent = TYPE_SYSBUS_SDHCI,
1950     .instance_init = sdhci_s3c_init,
1951 };
1952 
1953 static void sdhci_register_types(void)
1954 {
1955     type_register_static(&sdhci_sysbus_info);
1956     type_register_static(&sdhci_bus_info);
1957     type_register_static(&imx_usdhc_info);
1958     type_register_static(&sdhci_s3c_info);
1959 }
1960 
1961 type_init(sdhci_register_types)
1962