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