xref: /openbmc/qemu/hw/ssi/aspeed_smc.c (revision 38472890)
1 /*
2  * ASPEED AST2400 SMC Controller (SPI Flash Only)
3  *
4  * Copyright (C) 2016 IBM Corp.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 
25 #include "qemu/osdep.h"
26 #include "hw/sysbus.h"
27 #include "migration/vmstate.h"
28 #include "qemu/log.h"
29 #include "qemu/module.h"
30 #include "qemu/error-report.h"
31 #include "qapi/error.h"
32 #include "exec/address-spaces.h"
33 #include "qemu/units.h"
34 #include "trace.h"
35 
36 #include "hw/irq.h"
37 #include "hw/qdev-properties.h"
38 #include "hw/ssi/aspeed_smc.h"
39 
40 /* CE Type Setting Register */
41 #define R_CONF            (0x00 / 4)
42 #define   CONF_LEGACY_DISABLE  (1 << 31)
43 #define   CONF_ENABLE_W4       20
44 #define   CONF_ENABLE_W3       19
45 #define   CONF_ENABLE_W2       18
46 #define   CONF_ENABLE_W1       17
47 #define   CONF_ENABLE_W0       16
48 #define   CONF_FLASH_TYPE4     8
49 #define   CONF_FLASH_TYPE3     6
50 #define   CONF_FLASH_TYPE2     4
51 #define   CONF_FLASH_TYPE1     2
52 #define   CONF_FLASH_TYPE0     0
53 #define      CONF_FLASH_TYPE_NOR   0x0
54 #define      CONF_FLASH_TYPE_NAND  0x1
55 #define      CONF_FLASH_TYPE_SPI   0x2 /* AST2600 is SPI only */
56 
57 /* CE Control Register */
58 #define R_CE_CTRL            (0x04 / 4)
59 #define   CTRL_EXTENDED4       4  /* 32 bit addressing for SPI */
60 #define   CTRL_EXTENDED3       3  /* 32 bit addressing for SPI */
61 #define   CTRL_EXTENDED2       2  /* 32 bit addressing for SPI */
62 #define   CTRL_EXTENDED1       1  /* 32 bit addressing for SPI */
63 #define   CTRL_EXTENDED0       0  /* 32 bit addressing for SPI */
64 
65 /* Interrupt Control and Status Register */
66 #define R_INTR_CTRL       (0x08 / 4)
67 #define   INTR_CTRL_DMA_STATUS            (1 << 11)
68 #define   INTR_CTRL_CMD_ABORT_STATUS      (1 << 10)
69 #define   INTR_CTRL_WRITE_PROTECT_STATUS  (1 << 9)
70 #define   INTR_CTRL_DMA_EN                (1 << 3)
71 #define   INTR_CTRL_CMD_ABORT_EN          (1 << 2)
72 #define   INTR_CTRL_WRITE_PROTECT_EN      (1 << 1)
73 
74 /* CEx Control Register */
75 #define R_CTRL0           (0x10 / 4)
76 #define   CTRL_IO_QPI              (1 << 31)
77 #define   CTRL_IO_QUAD_DATA        (1 << 30)
78 #define   CTRL_IO_DUAL_DATA        (1 << 29)
79 #define   CTRL_IO_DUAL_ADDR_DATA   (1 << 28) /* Includes dummies */
80 #define   CTRL_IO_QUAD_ADDR_DATA   (1 << 28) /* Includes dummies */
81 #define   CTRL_CMD_SHIFT           16
82 #define   CTRL_CMD_MASK            0xff
83 #define   CTRL_DUMMY_HIGH_SHIFT    14
84 #define   CTRL_AST2400_SPI_4BYTE   (1 << 13)
85 #define CE_CTRL_CLOCK_FREQ_SHIFT   8
86 #define CE_CTRL_CLOCK_FREQ_MASK    0xf
87 #define CE_CTRL_CLOCK_FREQ(div)                                         \
88     (((div) & CE_CTRL_CLOCK_FREQ_MASK) << CE_CTRL_CLOCK_FREQ_SHIFT)
89 #define   CTRL_DUMMY_LOW_SHIFT     6 /* 2 bits [7:6] */
90 #define   CTRL_CE_STOP_ACTIVE      (1 << 2)
91 #define   CTRL_CMD_MODE_MASK       0x3
92 #define     CTRL_READMODE          0x0
93 #define     CTRL_FREADMODE         0x1
94 #define     CTRL_WRITEMODE         0x2
95 #define     CTRL_USERMODE          0x3
96 #define R_CTRL1           (0x14 / 4)
97 #define R_CTRL2           (0x18 / 4)
98 #define R_CTRL3           (0x1C / 4)
99 #define R_CTRL4           (0x20 / 4)
100 
101 /* CEx Segment Address Register */
102 #define R_SEG_ADDR0       (0x30 / 4)
103 #define   SEG_END_SHIFT        24   /* 8MB units */
104 #define   SEG_END_MASK         0xff
105 #define   SEG_START_SHIFT      16   /* address bit [A29-A23] */
106 #define   SEG_START_MASK       0xff
107 #define R_SEG_ADDR1       (0x34 / 4)
108 #define R_SEG_ADDR2       (0x38 / 4)
109 #define R_SEG_ADDR3       (0x3C / 4)
110 #define R_SEG_ADDR4       (0x40 / 4)
111 
112 /* Misc Control Register #1 */
113 #define R_MISC_CTRL1      (0x50 / 4)
114 
115 /* SPI dummy cycle data */
116 #define R_DUMMY_DATA      (0x54 / 4)
117 
118 /* DMA Control/Status Register */
119 #define R_DMA_CTRL        (0x80 / 4)
120 #define   DMA_CTRL_DELAY_MASK   0xf
121 #define   DMA_CTRL_DELAY_SHIFT  8
122 #define   DMA_CTRL_FREQ_MASK    0xf
123 #define   DMA_CTRL_FREQ_SHIFT   4
124 #define   DMA_CTRL_CALIB        (1 << 3)
125 #define   DMA_CTRL_CKSUM        (1 << 2)
126 #define   DMA_CTRL_WRITE        (1 << 1)
127 #define   DMA_CTRL_ENABLE       (1 << 0)
128 
129 /* DMA Flash Side Address */
130 #define R_DMA_FLASH_ADDR  (0x84 / 4)
131 
132 /* DMA DRAM Side Address */
133 #define R_DMA_DRAM_ADDR   (0x88 / 4)
134 
135 /* DMA Length Register */
136 #define R_DMA_LEN         (0x8C / 4)
137 
138 /* Checksum Calculation Result */
139 #define R_DMA_CHECKSUM    (0x90 / 4)
140 
141 /* Read Timing Compensation Register */
142 #define R_TIMINGS         (0x94 / 4)
143 
144 /* SPI controller registers and bits (AST2400) */
145 #define R_SPI_CONF        (0x00 / 4)
146 #define   SPI_CONF_ENABLE_W0   0
147 #define R_SPI_CTRL0       (0x4 / 4)
148 #define R_SPI_MISC_CTRL   (0x10 / 4)
149 #define R_SPI_TIMINGS     (0x14 / 4)
150 
151 #define ASPEED_SMC_R_SPI_MAX (0x20 / 4)
152 #define ASPEED_SMC_R_SMC_MAX (0x20 / 4)
153 
154 #define ASPEED_SOC_SMC_FLASH_BASE   0x10000000
155 #define ASPEED_SOC_FMC_FLASH_BASE   0x20000000
156 #define ASPEED_SOC_SPI_FLASH_BASE   0x30000000
157 #define ASPEED_SOC_SPI2_FLASH_BASE  0x38000000
158 
159 /*
160  * DMA DRAM addresses should be 4 bytes aligned and the valid address
161  * range is 0x40000000 - 0x5FFFFFFF (AST2400)
162  *          0x80000000 - 0xBFFFFFFF (AST2500)
163  *
164  * DMA flash addresses should be 4 bytes aligned and the valid address
165  * range is 0x20000000 - 0x2FFFFFFF.
166  *
167  * DMA length is from 4 bytes to 32MB
168  *   0: 4 bytes
169  *   0x7FFFFF: 32M bytes
170  */
171 #define DMA_DRAM_ADDR(s, val)   ((s)->sdram_base | \
172                                  ((val) & (s)->ctrl->dma_dram_mask))
173 #define DMA_FLASH_ADDR(s, val)  ((s)->ctrl->flash_window_base | \
174                                 ((val) & (s)->ctrl->dma_flash_mask))
175 #define DMA_LENGTH(val)         ((val) & 0x01FFFFFC)
176 
177 /* Flash opcodes. */
178 #define SPI_OP_READ       0x03    /* Read data bytes (low frequency) */
179 
180 #define SNOOP_OFF         0xFF
181 #define SNOOP_START       0x0
182 
183 /*
184  * Default segments mapping addresses and size for each slave per
185  * controller. These can be changed when board is initialized with the
186  * Segment Address Registers.
187  */
188 static const AspeedSegments aspeed_segments_legacy[] = {
189     { 0x10000000, 32 * 1024 * 1024 },
190 };
191 
192 static const AspeedSegments aspeed_segments_fmc[] = {
193     { 0x20000000, 64 * 1024 * 1024 }, /* start address is readonly */
194     { 0x24000000, 32 * 1024 * 1024 },
195     { 0x26000000, 32 * 1024 * 1024 },
196     { 0x28000000, 32 * 1024 * 1024 },
197     { 0x2A000000, 32 * 1024 * 1024 }
198 };
199 
200 static const AspeedSegments aspeed_segments_spi[] = {
201     { 0x30000000, 64 * 1024 * 1024 },
202 };
203 
204 static const AspeedSegments aspeed_segments_ast2500_fmc[] = {
205     { 0x20000000, 128 * 1024 * 1024 }, /* start address is readonly */
206     { 0x28000000,  32 * 1024 * 1024 },
207     { 0x2A000000,  32 * 1024 * 1024 },
208 };
209 
210 static const AspeedSegments aspeed_segments_ast2500_spi1[] = {
211     { 0x30000000, 32 * 1024 * 1024 }, /* start address is readonly */
212     { 0x32000000, 96 * 1024 * 1024 }, /* end address is readonly */
213 };
214 
215 static const AspeedSegments aspeed_segments_ast2500_spi2[] = {
216     { 0x38000000, 32 * 1024 * 1024 }, /* start address is readonly */
217     { 0x3A000000, 96 * 1024 * 1024 }, /* end address is readonly */
218 };
219 static uint32_t aspeed_smc_segment_to_reg(const AspeedSMCState *s,
220                                           const AspeedSegments *seg);
221 static void aspeed_smc_reg_to_segment(const AspeedSMCState *s, uint32_t reg,
222                                       AspeedSegments *seg);
223 
224 /*
225  * AST2600 definitions
226  */
227 #define ASPEED26_SOC_FMC_FLASH_BASE   0x20000000
228 #define ASPEED26_SOC_SPI_FLASH_BASE   0x30000000
229 #define ASPEED26_SOC_SPI2_FLASH_BASE  0x50000000
230 
231 static const AspeedSegments aspeed_segments_ast2600_fmc[] = {
232     { 0x0, 128 * MiB }, /* start address is readonly */
233     { 0x0, 0 }, /* disabled */
234     { 0x0, 0 }, /* disabled */
235 };
236 
237 static const AspeedSegments aspeed_segments_ast2600_spi1[] = {
238     { 0x0, 128 * MiB }, /* start address is readonly */
239     { 0x0, 0 }, /* disabled */
240 };
241 
242 static const AspeedSegments aspeed_segments_ast2600_spi2[] = {
243     { 0x0, 128 * MiB }, /* start address is readonly */
244     { 0x0, 0 }, /* disabled */
245     { 0x0, 0 }, /* disabled */
246 };
247 
248 static uint32_t aspeed_2600_smc_segment_to_reg(const AspeedSMCState *s,
249                                                const AspeedSegments *seg);
250 static void aspeed_2600_smc_reg_to_segment(const AspeedSMCState *s,
251                                            uint32_t reg, AspeedSegments *seg);
252 
253 static const AspeedSMCController controllers[] = {
254     {
255         .name              = "aspeed.smc-ast2400",
256         .r_conf            = R_CONF,
257         .r_ce_ctrl         = R_CE_CTRL,
258         .r_ctrl0           = R_CTRL0,
259         .r_timings         = R_TIMINGS,
260         .nregs_timings     = 1,
261         .conf_enable_w0    = CONF_ENABLE_W0,
262         .max_slaves        = 5,
263         .segments          = aspeed_segments_legacy,
264         .flash_window_base = ASPEED_SOC_SMC_FLASH_BASE,
265         .flash_window_size = 0x6000000,
266         .has_dma           = false,
267         .nregs             = ASPEED_SMC_R_SMC_MAX,
268         .segment_to_reg    = aspeed_smc_segment_to_reg,
269         .reg_to_segment    = aspeed_smc_reg_to_segment,
270     }, {
271         .name              = "aspeed.fmc-ast2400",
272         .r_conf            = R_CONF,
273         .r_ce_ctrl         = R_CE_CTRL,
274         .r_ctrl0           = R_CTRL0,
275         .r_timings         = R_TIMINGS,
276         .nregs_timings     = 1,
277         .conf_enable_w0    = CONF_ENABLE_W0,
278         .max_slaves        = 5,
279         .segments          = aspeed_segments_fmc,
280         .flash_window_base = ASPEED_SOC_FMC_FLASH_BASE,
281         .flash_window_size = 0x10000000,
282         .has_dma           = true,
283         .dma_flash_mask    = 0x0FFFFFFC,
284         .dma_dram_mask     = 0x1FFFFFFC,
285         .nregs             = ASPEED_SMC_R_MAX,
286         .segment_to_reg    = aspeed_smc_segment_to_reg,
287         .reg_to_segment    = aspeed_smc_reg_to_segment,
288     }, {
289         .name              = "aspeed.spi1-ast2400",
290         .r_conf            = R_SPI_CONF,
291         .r_ce_ctrl         = 0xff,
292         .r_ctrl0           = R_SPI_CTRL0,
293         .r_timings         = R_SPI_TIMINGS,
294         .nregs_timings     = 1,
295         .conf_enable_w0    = SPI_CONF_ENABLE_W0,
296         .max_slaves        = 1,
297         .segments          = aspeed_segments_spi,
298         .flash_window_base = ASPEED_SOC_SPI_FLASH_BASE,
299         .flash_window_size = 0x10000000,
300         .has_dma           = false,
301         .nregs             = ASPEED_SMC_R_SPI_MAX,
302         .segment_to_reg    = aspeed_smc_segment_to_reg,
303         .reg_to_segment    = aspeed_smc_reg_to_segment,
304     }, {
305         .name              = "aspeed.fmc-ast2500",
306         .r_conf            = R_CONF,
307         .r_ce_ctrl         = R_CE_CTRL,
308         .r_ctrl0           = R_CTRL0,
309         .r_timings         = R_TIMINGS,
310         .nregs_timings     = 1,
311         .conf_enable_w0    = CONF_ENABLE_W0,
312         .max_slaves        = 3,
313         .segments          = aspeed_segments_ast2500_fmc,
314         .flash_window_base = ASPEED_SOC_FMC_FLASH_BASE,
315         .flash_window_size = 0x10000000,
316         .has_dma           = true,
317         .dma_flash_mask    = 0x0FFFFFFC,
318         .dma_dram_mask     = 0x3FFFFFFC,
319         .nregs             = ASPEED_SMC_R_MAX,
320         .segment_to_reg    = aspeed_smc_segment_to_reg,
321         .reg_to_segment    = aspeed_smc_reg_to_segment,
322     }, {
323         .name              = "aspeed.spi1-ast2500",
324         .r_conf            = R_CONF,
325         .r_ce_ctrl         = R_CE_CTRL,
326         .r_ctrl0           = R_CTRL0,
327         .r_timings         = R_TIMINGS,
328         .nregs_timings     = 1,
329         .conf_enable_w0    = CONF_ENABLE_W0,
330         .max_slaves        = 2,
331         .segments          = aspeed_segments_ast2500_spi1,
332         .flash_window_base = ASPEED_SOC_SPI_FLASH_BASE,
333         .flash_window_size = 0x8000000,
334         .has_dma           = false,
335         .nregs             = ASPEED_SMC_R_MAX,
336         .segment_to_reg    = aspeed_smc_segment_to_reg,
337         .reg_to_segment    = aspeed_smc_reg_to_segment,
338     }, {
339         .name              = "aspeed.spi2-ast2500",
340         .r_conf            = R_CONF,
341         .r_ce_ctrl         = R_CE_CTRL,
342         .r_ctrl0           = R_CTRL0,
343         .r_timings         = R_TIMINGS,
344         .nregs_timings     = 1,
345         .conf_enable_w0    = CONF_ENABLE_W0,
346         .max_slaves        = 2,
347         .segments          = aspeed_segments_ast2500_spi2,
348         .flash_window_base = ASPEED_SOC_SPI2_FLASH_BASE,
349         .flash_window_size = 0x8000000,
350         .has_dma           = false,
351         .nregs             = ASPEED_SMC_R_MAX,
352         .segment_to_reg    = aspeed_smc_segment_to_reg,
353         .reg_to_segment    = aspeed_smc_reg_to_segment,
354     }, {
355         .name              = "aspeed.fmc-ast2600",
356         .r_conf            = R_CONF,
357         .r_ce_ctrl         = R_CE_CTRL,
358         .r_ctrl0           = R_CTRL0,
359         .r_timings         = R_TIMINGS,
360         .nregs_timings     = 1,
361         .conf_enable_w0    = CONF_ENABLE_W0,
362         .max_slaves        = 3,
363         .segments          = aspeed_segments_ast2600_fmc,
364         .flash_window_base = ASPEED26_SOC_FMC_FLASH_BASE,
365         .flash_window_size = 0x10000000,
366         .has_dma           = true,
367         .dma_flash_mask    = 0x0FFFFFFC,
368         .dma_dram_mask     = 0x3FFFFFFC,
369         .nregs             = ASPEED_SMC_R_MAX,
370         .segment_to_reg    = aspeed_2600_smc_segment_to_reg,
371         .reg_to_segment    = aspeed_2600_smc_reg_to_segment,
372     }, {
373         .name              = "aspeed.spi1-ast2600",
374         .r_conf            = R_CONF,
375         .r_ce_ctrl         = R_CE_CTRL,
376         .r_ctrl0           = R_CTRL0,
377         .r_timings         = R_TIMINGS,
378         .nregs_timings     = 2,
379         .conf_enable_w0    = CONF_ENABLE_W0,
380         .max_slaves        = 2,
381         .segments          = aspeed_segments_ast2600_spi1,
382         .flash_window_base = ASPEED26_SOC_SPI_FLASH_BASE,
383         .flash_window_size = 0x10000000,
384         .has_dma           = true,
385         .dma_flash_mask    = 0x0FFFFFFC,
386         .dma_dram_mask     = 0x3FFFFFFC,
387         .nregs             = ASPEED_SMC_R_MAX,
388         .segment_to_reg    = aspeed_2600_smc_segment_to_reg,
389         .reg_to_segment    = aspeed_2600_smc_reg_to_segment,
390     }, {
391         .name              = "aspeed.spi2-ast2600",
392         .r_conf            = R_CONF,
393         .r_ce_ctrl         = R_CE_CTRL,
394         .r_ctrl0           = R_CTRL0,
395         .r_timings         = R_TIMINGS,
396         .nregs_timings     = 3,
397         .conf_enable_w0    = CONF_ENABLE_W0,
398         .max_slaves        = 3,
399         .segments          = aspeed_segments_ast2600_spi2,
400         .flash_window_base = ASPEED26_SOC_SPI2_FLASH_BASE,
401         .flash_window_size = 0x10000000,
402         .has_dma           = true,
403         .dma_flash_mask    = 0x0FFFFFFC,
404         .dma_dram_mask     = 0x3FFFFFFC,
405         .nregs             = ASPEED_SMC_R_MAX,
406         .segment_to_reg    = aspeed_2600_smc_segment_to_reg,
407         .reg_to_segment    = aspeed_2600_smc_reg_to_segment,
408     },
409 };
410 
411 /*
412  * The Segment Registers of the AST2400 and AST2500 have a 8MB
413  * unit. The address range of a flash SPI slave is encoded with
414  * absolute addresses which should be part of the overall controller
415  * window.
416  */
417 static uint32_t aspeed_smc_segment_to_reg(const AspeedSMCState *s,
418                                           const AspeedSegments *seg)
419 {
420     uint32_t reg = 0;
421     reg |= ((seg->addr >> 23) & SEG_START_MASK) << SEG_START_SHIFT;
422     reg |= (((seg->addr + seg->size) >> 23) & SEG_END_MASK) << SEG_END_SHIFT;
423     return reg;
424 }
425 
426 static void aspeed_smc_reg_to_segment(const AspeedSMCState *s,
427                                       uint32_t reg, AspeedSegments *seg)
428 {
429     seg->addr = ((reg >> SEG_START_SHIFT) & SEG_START_MASK) << 23;
430     seg->size = (((reg >> SEG_END_SHIFT) & SEG_END_MASK) << 23) - seg->addr;
431 }
432 
433 /*
434  * The Segment Registers of the AST2600 have a 1MB unit. The address
435  * range of a flash SPI slave is encoded with offsets in the overall
436  * controller window. The previous SoC AST2400 and AST2500 used
437  * absolute addresses. Only bits [27:20] are relevant and the end
438  * address is an upper bound limit.
439  */
440 #define AST2600_SEG_ADDR_MASK 0x0ff00000
441 
442 static uint32_t aspeed_2600_smc_segment_to_reg(const AspeedSMCState *s,
443                                                const AspeedSegments *seg)
444 {
445     uint32_t reg = 0;
446 
447     /* Disabled segments have a nil register */
448     if (!seg->size) {
449         return 0;
450     }
451 
452     reg |= (seg->addr & AST2600_SEG_ADDR_MASK) >> 16; /* start offset */
453     reg |= (seg->addr + seg->size - 1) & AST2600_SEG_ADDR_MASK; /* end offset */
454     return reg;
455 }
456 
457 static void aspeed_2600_smc_reg_to_segment(const AspeedSMCState *s,
458                                            uint32_t reg, AspeedSegments *seg)
459 {
460     uint32_t start_offset = (reg << 16) & AST2600_SEG_ADDR_MASK;
461     uint32_t end_offset = reg & AST2600_SEG_ADDR_MASK;
462 
463     if (reg) {
464         seg->addr = s->ctrl->flash_window_base + start_offset;
465         seg->size = end_offset + MiB - start_offset;
466     } else {
467         seg->addr = s->ctrl->flash_window_base;
468         seg->size = 0;
469     }
470 }
471 
472 static bool aspeed_smc_flash_overlap(const AspeedSMCState *s,
473                                      const AspeedSegments *new,
474                                      int cs)
475 {
476     AspeedSegments seg;
477     int i;
478 
479     for (i = 0; i < s->ctrl->max_slaves; i++) {
480         if (i == cs) {
481             continue;
482         }
483 
484         s->ctrl->reg_to_segment(s, s->regs[R_SEG_ADDR0 + i], &seg);
485 
486         if (new->addr + new->size > seg.addr &&
487             new->addr < seg.addr + seg.size) {
488             qemu_log_mask(LOG_GUEST_ERROR, "%s: new segment CS%d [ 0x%"
489                           HWADDR_PRIx" - 0x%"HWADDR_PRIx" ] overlaps with "
490                           "CS%d [ 0x%"HWADDR_PRIx" - 0x%"HWADDR_PRIx" ]\n",
491                           s->ctrl->name, cs, new->addr, new->addr + new->size,
492                           i, seg.addr, seg.addr + seg.size);
493             return true;
494         }
495     }
496     return false;
497 }
498 
499 static void aspeed_smc_flash_set_segment_region(AspeedSMCState *s, int cs,
500                                                 uint64_t regval)
501 {
502     AspeedSMCFlash *fl = &s->flashes[cs];
503     AspeedSegments seg;
504 
505     s->ctrl->reg_to_segment(s, regval, &seg);
506 
507     memory_region_transaction_begin();
508     memory_region_set_size(&fl->mmio, seg.size);
509     memory_region_set_address(&fl->mmio, seg.addr - s->ctrl->flash_window_base);
510     memory_region_set_enabled(&fl->mmio, !!seg.size);
511     memory_region_transaction_commit();
512 
513     s->regs[R_SEG_ADDR0 + cs] = regval;
514 }
515 
516 static void aspeed_smc_flash_set_segment(AspeedSMCState *s, int cs,
517                                          uint64_t new)
518 {
519     AspeedSegments seg;
520 
521     s->ctrl->reg_to_segment(s, new, &seg);
522 
523     trace_aspeed_smc_flash_set_segment(cs, new, seg.addr, seg.addr + seg.size);
524 
525     /* The start address of CS0 is read-only */
526     if (cs == 0 && seg.addr != s->ctrl->flash_window_base) {
527         qemu_log_mask(LOG_GUEST_ERROR,
528                       "%s: Tried to change CS0 start address to 0x%"
529                       HWADDR_PRIx "\n", s->ctrl->name, seg.addr);
530         seg.addr = s->ctrl->flash_window_base;
531         new = s->ctrl->segment_to_reg(s, &seg);
532     }
533 
534     /*
535      * The end address of the AST2500 spi controllers is also
536      * read-only.
537      */
538     if ((s->ctrl->segments == aspeed_segments_ast2500_spi1 ||
539          s->ctrl->segments == aspeed_segments_ast2500_spi2) &&
540         cs == s->ctrl->max_slaves &&
541         seg.addr + seg.size != s->ctrl->segments[cs].addr +
542         s->ctrl->segments[cs].size) {
543         qemu_log_mask(LOG_GUEST_ERROR,
544                       "%s: Tried to change CS%d end address to 0x%"
545                       HWADDR_PRIx "\n", s->ctrl->name, cs, seg.addr + seg.size);
546         seg.size = s->ctrl->segments[cs].addr + s->ctrl->segments[cs].size -
547             seg.addr;
548         new = s->ctrl->segment_to_reg(s, &seg);
549     }
550 
551     /* Keep the segment in the overall flash window */
552     if (seg.size &&
553         (seg.addr + seg.size <= s->ctrl->flash_window_base ||
554          seg.addr > s->ctrl->flash_window_base + s->ctrl->flash_window_size)) {
555         qemu_log_mask(LOG_GUEST_ERROR, "%s: new segment for CS%d is invalid : "
556                       "[ 0x%"HWADDR_PRIx" - 0x%"HWADDR_PRIx" ]\n",
557                       s->ctrl->name, cs, seg.addr, seg.addr + seg.size);
558         return;
559     }
560 
561     /* Check start address vs. alignment */
562     if (seg.size && !QEMU_IS_ALIGNED(seg.addr, seg.size)) {
563         qemu_log_mask(LOG_GUEST_ERROR, "%s: new segment for CS%d is not "
564                       "aligned : [ 0x%"HWADDR_PRIx" - 0x%"HWADDR_PRIx" ]\n",
565                       s->ctrl->name, cs, seg.addr, seg.addr + seg.size);
566     }
567 
568     /* And segments should not overlap (in the specs) */
569     aspeed_smc_flash_overlap(s, &seg, cs);
570 
571     /* All should be fine now to move the region */
572     aspeed_smc_flash_set_segment_region(s, cs, new);
573 }
574 
575 static uint64_t aspeed_smc_flash_default_read(void *opaque, hwaddr addr,
576                                               unsigned size)
577 {
578     qemu_log_mask(LOG_GUEST_ERROR, "%s: To 0x%" HWADDR_PRIx " of size %u"
579                   PRIx64 "\n", __func__, addr, size);
580     return 0;
581 }
582 
583 static void aspeed_smc_flash_default_write(void *opaque, hwaddr addr,
584                                            uint64_t data, unsigned size)
585 {
586     qemu_log_mask(LOG_GUEST_ERROR, "%s: To 0x%" HWADDR_PRIx " of size %u: 0x%"
587                   PRIx64 "\n", __func__, addr, size, data);
588 }
589 
590 static const MemoryRegionOps aspeed_smc_flash_default_ops = {
591     .read = aspeed_smc_flash_default_read,
592     .write = aspeed_smc_flash_default_write,
593     .endianness = DEVICE_LITTLE_ENDIAN,
594     .valid = {
595         .min_access_size = 1,
596         .max_access_size = 4,
597     },
598 };
599 
600 static inline int aspeed_smc_flash_mode(const AspeedSMCFlash *fl)
601 {
602     const AspeedSMCState *s = fl->controller;
603 
604     return s->regs[s->r_ctrl0 + fl->id] & CTRL_CMD_MODE_MASK;
605 }
606 
607 static inline bool aspeed_smc_is_writable(const AspeedSMCFlash *fl)
608 {
609     const AspeedSMCState *s = fl->controller;
610 
611     return s->regs[s->r_conf] & (1 << (s->conf_enable_w0 + fl->id));
612 }
613 
614 static inline int aspeed_smc_flash_cmd(const AspeedSMCFlash *fl)
615 {
616     const AspeedSMCState *s = fl->controller;
617     int cmd = (s->regs[s->r_ctrl0 + fl->id] >> CTRL_CMD_SHIFT) & CTRL_CMD_MASK;
618 
619     /*
620      * In read mode, the default SPI command is READ (0x3). In other
621      * modes, the command should necessarily be defined
622      *
623      * TODO: add support for READ4 (0x13) on AST2600
624      */
625     if (aspeed_smc_flash_mode(fl) == CTRL_READMODE) {
626         cmd = SPI_OP_READ;
627     }
628 
629     if (!cmd) {
630         qemu_log_mask(LOG_GUEST_ERROR, "%s: no command defined for mode %d\n",
631                       __func__, aspeed_smc_flash_mode(fl));
632     }
633 
634     return cmd;
635 }
636 
637 static inline int aspeed_smc_flash_is_4byte(const AspeedSMCFlash *fl)
638 {
639     const AspeedSMCState *s = fl->controller;
640 
641     if (s->ctrl->segments == aspeed_segments_spi) {
642         return s->regs[s->r_ctrl0] & CTRL_AST2400_SPI_4BYTE;
643     } else {
644         return s->regs[s->r_ce_ctrl] & (1 << (CTRL_EXTENDED0 + fl->id));
645     }
646 }
647 
648 static void aspeed_smc_flash_do_select(AspeedSMCFlash *fl, bool unselect)
649 {
650     AspeedSMCState *s = fl->controller;
651 
652     trace_aspeed_smc_flash_select(fl->id, unselect ? "un" : "");
653 
654     qemu_set_irq(s->cs_lines[fl->id], unselect);
655 }
656 
657 static void aspeed_smc_flash_select(AspeedSMCFlash *fl)
658 {
659     aspeed_smc_flash_do_select(fl, false);
660 }
661 
662 static void aspeed_smc_flash_unselect(AspeedSMCFlash *fl)
663 {
664     aspeed_smc_flash_do_select(fl, true);
665 }
666 
667 static uint32_t aspeed_smc_check_segment_addr(const AspeedSMCFlash *fl,
668                                               uint32_t addr)
669 {
670     const AspeedSMCState *s = fl->controller;
671     AspeedSegments seg;
672 
673     s->ctrl->reg_to_segment(s, s->regs[R_SEG_ADDR0 + fl->id], &seg);
674     if ((addr % seg.size) != addr) {
675         qemu_log_mask(LOG_GUEST_ERROR,
676                       "%s: invalid address 0x%08x for CS%d segment : "
677                       "[ 0x%"HWADDR_PRIx" - 0x%"HWADDR_PRIx" ]\n",
678                       s->ctrl->name, addr, fl->id, seg.addr,
679                       seg.addr + seg.size);
680         addr %= seg.size;
681     }
682 
683     return addr;
684 }
685 
686 static int aspeed_smc_flash_dummies(const AspeedSMCFlash *fl)
687 {
688     const AspeedSMCState *s = fl->controller;
689     uint32_t r_ctrl0 = s->regs[s->r_ctrl0 + fl->id];
690     uint32_t dummy_high = (r_ctrl0 >> CTRL_DUMMY_HIGH_SHIFT) & 0x1;
691     uint32_t dummy_low = (r_ctrl0 >> CTRL_DUMMY_LOW_SHIFT) & 0x3;
692     uint32_t dummies = ((dummy_high << 2) | dummy_low) * 8;
693 
694     if (r_ctrl0 & CTRL_IO_DUAL_ADDR_DATA) {
695         dummies /= 2;
696     }
697 
698     return dummies;
699 }
700 
701 static void aspeed_smc_flash_setup(AspeedSMCFlash *fl, uint32_t addr)
702 {
703     const AspeedSMCState *s = fl->controller;
704     uint8_t cmd = aspeed_smc_flash_cmd(fl);
705     int i;
706 
707     /* Flash access can not exceed CS segment */
708     addr = aspeed_smc_check_segment_addr(fl, addr);
709 
710     ssi_transfer(s->spi, cmd);
711 
712     if (aspeed_smc_flash_is_4byte(fl)) {
713         ssi_transfer(s->spi, (addr >> 24) & 0xff);
714     }
715     ssi_transfer(s->spi, (addr >> 16) & 0xff);
716     ssi_transfer(s->spi, (addr >> 8) & 0xff);
717     ssi_transfer(s->spi, (addr & 0xff));
718 
719     /*
720      * Use fake transfers to model dummy bytes. The value should
721      * be configured to some non-zero value in fast read mode and
722      * zero in read mode. But, as the HW allows inconsistent
723      * settings, let's check for fast read mode.
724      */
725     if (aspeed_smc_flash_mode(fl) == CTRL_FREADMODE) {
726         for (i = 0; i < aspeed_smc_flash_dummies(fl); i++) {
727             ssi_transfer(fl->controller->spi, s->regs[R_DUMMY_DATA] & 0xff);
728         }
729     }
730 }
731 
732 static uint64_t aspeed_smc_flash_read(void *opaque, hwaddr addr, unsigned size)
733 {
734     AspeedSMCFlash *fl = opaque;
735     AspeedSMCState *s = fl->controller;
736     uint64_t ret = 0;
737     int i;
738 
739     switch (aspeed_smc_flash_mode(fl)) {
740     case CTRL_USERMODE:
741         for (i = 0; i < size; i++) {
742             ret |= ssi_transfer(s->spi, 0x0) << (8 * i);
743         }
744         break;
745     case CTRL_READMODE:
746     case CTRL_FREADMODE:
747         aspeed_smc_flash_select(fl);
748         aspeed_smc_flash_setup(fl, addr);
749 
750         for (i = 0; i < size; i++) {
751             ret |= ssi_transfer(s->spi, 0x0) << (8 * i);
752         }
753 
754         aspeed_smc_flash_unselect(fl);
755         break;
756     default:
757         qemu_log_mask(LOG_GUEST_ERROR, "%s: invalid flash mode %d\n",
758                       __func__, aspeed_smc_flash_mode(fl));
759     }
760 
761     trace_aspeed_smc_flash_read(fl->id, addr, size, ret,
762                                 aspeed_smc_flash_mode(fl));
763     return ret;
764 }
765 
766 /*
767  * TODO (clg@kaod.org): stolen from xilinx_spips.c. Should move to a
768  * common include header.
769  */
770 typedef enum {
771     READ = 0x3,         READ_4 = 0x13,
772     FAST_READ = 0xb,    FAST_READ_4 = 0x0c,
773     DOR = 0x3b,         DOR_4 = 0x3c,
774     QOR = 0x6b,         QOR_4 = 0x6c,
775     DIOR = 0xbb,        DIOR_4 = 0xbc,
776     QIOR = 0xeb,        QIOR_4 = 0xec,
777 
778     PP = 0x2,           PP_4 = 0x12,
779     DPP = 0xa2,
780     QPP = 0x32,         QPP_4 = 0x34,
781 } FlashCMD;
782 
783 static int aspeed_smc_num_dummies(uint8_t command)
784 {
785     switch (command) { /* check for dummies */
786     case READ: /* no dummy bytes/cycles */
787     case PP:
788     case DPP:
789     case QPP:
790     case READ_4:
791     case PP_4:
792     case QPP_4:
793         return 0;
794     case FAST_READ:
795     case DOR:
796     case QOR:
797     case FAST_READ_4:
798     case DOR_4:
799     case QOR_4:
800         return 1;
801     case DIOR:
802     case DIOR_4:
803         return 2;
804     case QIOR:
805     case QIOR_4:
806         return 4;
807     default:
808         return -1;
809     }
810 }
811 
812 static bool aspeed_smc_do_snoop(AspeedSMCFlash *fl,  uint64_t data,
813                                 unsigned size)
814 {
815     AspeedSMCState *s = fl->controller;
816     uint8_t addr_width = aspeed_smc_flash_is_4byte(fl) ? 4 : 3;
817 
818     trace_aspeed_smc_do_snoop(fl->id, s->snoop_index, s->snoop_dummies,
819                               (uint8_t) data & 0xff);
820 
821     if (s->snoop_index == SNOOP_OFF) {
822         return false; /* Do nothing */
823 
824     } else if (s->snoop_index == SNOOP_START) {
825         uint8_t cmd = data & 0xff;
826         int ndummies = aspeed_smc_num_dummies(cmd);
827 
828         /*
829          * No dummy cycles are expected with the current command. Turn
830          * off snooping and let the transfer proceed normally.
831          */
832         if (ndummies <= 0) {
833             s->snoop_index = SNOOP_OFF;
834             return false;
835         }
836 
837         s->snoop_dummies = ndummies * 8;
838 
839     } else if (s->snoop_index >= addr_width + 1) {
840 
841         /* The SPI transfer has reached the dummy cycles sequence */
842         for (; s->snoop_dummies; s->snoop_dummies--) {
843             ssi_transfer(s->spi, s->regs[R_DUMMY_DATA] & 0xff);
844         }
845 
846         /* If no more dummy cycles are expected, turn off snooping */
847         if (!s->snoop_dummies) {
848             s->snoop_index = SNOOP_OFF;
849         } else {
850             s->snoop_index += size;
851         }
852 
853         /*
854          * Dummy cycles have been faked already. Ignore the current
855          * SPI transfer
856          */
857         return true;
858     }
859 
860     s->snoop_index += size;
861     return false;
862 }
863 
864 static void aspeed_smc_flash_write(void *opaque, hwaddr addr, uint64_t data,
865                                    unsigned size)
866 {
867     AspeedSMCFlash *fl = opaque;
868     AspeedSMCState *s = fl->controller;
869     int i;
870 
871     trace_aspeed_smc_flash_write(fl->id, addr, size, data,
872                                  aspeed_smc_flash_mode(fl));
873 
874     if (!aspeed_smc_is_writable(fl)) {
875         qemu_log_mask(LOG_GUEST_ERROR, "%s: flash is not writable at 0x%"
876                       HWADDR_PRIx "\n", __func__, addr);
877         return;
878     }
879 
880     switch (aspeed_smc_flash_mode(fl)) {
881     case CTRL_USERMODE:
882         if (aspeed_smc_do_snoop(fl, data, size)) {
883             break;
884         }
885 
886         for (i = 0; i < size; i++) {
887             ssi_transfer(s->spi, (data >> (8 * i)) & 0xff);
888         }
889         break;
890     case CTRL_WRITEMODE:
891         aspeed_smc_flash_select(fl);
892         aspeed_smc_flash_setup(fl, addr);
893 
894         for (i = 0; i < size; i++) {
895             ssi_transfer(s->spi, (data >> (8 * i)) & 0xff);
896         }
897 
898         aspeed_smc_flash_unselect(fl);
899         break;
900     default:
901         qemu_log_mask(LOG_GUEST_ERROR, "%s: invalid flash mode %d\n",
902                       __func__, aspeed_smc_flash_mode(fl));
903     }
904 }
905 
906 static const MemoryRegionOps aspeed_smc_flash_ops = {
907     .read = aspeed_smc_flash_read,
908     .write = aspeed_smc_flash_write,
909     .endianness = DEVICE_LITTLE_ENDIAN,
910     .valid = {
911         .min_access_size = 1,
912         .max_access_size = 4,
913     },
914 };
915 
916 static void aspeed_smc_flash_update_ctrl(AspeedSMCFlash *fl, uint32_t value)
917 {
918     AspeedSMCState *s = fl->controller;
919     bool unselect;
920 
921     /* User mode selects the CS, other modes unselect */
922     unselect = (value & CTRL_CMD_MODE_MASK) != CTRL_USERMODE;
923 
924     /* A change of CTRL_CE_STOP_ACTIVE from 0 to 1, unselects the CS */
925     if (!(s->regs[s->r_ctrl0 + fl->id] & CTRL_CE_STOP_ACTIVE) &&
926         value & CTRL_CE_STOP_ACTIVE) {
927         unselect = true;
928     }
929 
930     s->regs[s->r_ctrl0 + fl->id] = value;
931 
932     s->snoop_index = unselect ? SNOOP_OFF : SNOOP_START;
933 
934     aspeed_smc_flash_do_select(fl, unselect);
935 }
936 
937 static void aspeed_smc_reset(DeviceState *d)
938 {
939     AspeedSMCState *s = ASPEED_SMC(d);
940     int i;
941 
942     memset(s->regs, 0, sizeof s->regs);
943 
944     /* Unselect all slaves */
945     for (i = 0; i < s->num_cs; ++i) {
946         s->regs[s->r_ctrl0 + i] |= CTRL_CE_STOP_ACTIVE;
947         qemu_set_irq(s->cs_lines[i], true);
948     }
949 
950     /* setup the default segment register values and regions for all */
951     for (i = 0; i < s->ctrl->max_slaves; ++i) {
952         aspeed_smc_flash_set_segment_region(s, i,
953                     s->ctrl->segment_to_reg(s, &s->ctrl->segments[i]));
954     }
955 
956     /* HW strapping flash type for the AST2600 controllers  */
957     if (s->ctrl->segments == aspeed_segments_ast2600_fmc) {
958         /* flash type is fixed to SPI for all */
959         s->regs[s->r_conf] |= (CONF_FLASH_TYPE_SPI << CONF_FLASH_TYPE0);
960         s->regs[s->r_conf] |= (CONF_FLASH_TYPE_SPI << CONF_FLASH_TYPE1);
961         s->regs[s->r_conf] |= (CONF_FLASH_TYPE_SPI << CONF_FLASH_TYPE2);
962     }
963 
964     /* HW strapping flash type for FMC controllers  */
965     if (s->ctrl->segments == aspeed_segments_ast2500_fmc) {
966         /* flash type is fixed to SPI for CE0 and CE1 */
967         s->regs[s->r_conf] |= (CONF_FLASH_TYPE_SPI << CONF_FLASH_TYPE0);
968         s->regs[s->r_conf] |= (CONF_FLASH_TYPE_SPI << CONF_FLASH_TYPE1);
969     }
970 
971     /* HW strapping for AST2400 FMC controllers (SCU70). Let's use the
972      * configuration of the palmetto-bmc machine */
973     if (s->ctrl->segments == aspeed_segments_fmc) {
974         s->regs[s->r_conf] |= (CONF_FLASH_TYPE_SPI << CONF_FLASH_TYPE0);
975     }
976 
977     s->snoop_index = SNOOP_OFF;
978     s->snoop_dummies = 0;
979 }
980 
981 static uint64_t aspeed_smc_read(void *opaque, hwaddr addr, unsigned int size)
982 {
983     AspeedSMCState *s = ASPEED_SMC(opaque);
984 
985     addr >>= 2;
986 
987     if (addr == s->r_conf ||
988         (addr >= s->r_timings &&
989          addr < s->r_timings + s->ctrl->nregs_timings) ||
990         addr == s->r_ce_ctrl ||
991         addr == R_INTR_CTRL ||
992         addr == R_DUMMY_DATA ||
993         (s->ctrl->has_dma && addr == R_DMA_CTRL) ||
994         (s->ctrl->has_dma && addr == R_DMA_FLASH_ADDR) ||
995         (s->ctrl->has_dma && addr == R_DMA_DRAM_ADDR) ||
996         (s->ctrl->has_dma && addr == R_DMA_LEN) ||
997         (s->ctrl->has_dma && addr == R_DMA_CHECKSUM) ||
998         (addr >= R_SEG_ADDR0 && addr < R_SEG_ADDR0 + s->ctrl->max_slaves) ||
999         (addr >= s->r_ctrl0 && addr < s->r_ctrl0 + s->ctrl->max_slaves)) {
1000 
1001         trace_aspeed_smc_read(addr, size, s->regs[addr]);
1002 
1003         return s->regs[addr];
1004     } else {
1005         qemu_log_mask(LOG_UNIMP, "%s: not implemented: 0x%" HWADDR_PRIx "\n",
1006                       __func__, addr);
1007         return -1;
1008     }
1009 }
1010 
1011 static uint8_t aspeed_smc_hclk_divisor(uint8_t hclk_mask)
1012 {
1013     /* HCLK/1 .. HCLK/16 */
1014     const uint8_t hclk_divisors[] = {
1015         15, 7, 14, 6, 13, 5, 12, 4, 11, 3, 10, 2, 9, 1, 8, 0
1016     };
1017     int i;
1018 
1019     for (i = 0; i < ARRAY_SIZE(hclk_divisors); i++) {
1020         if (hclk_mask == hclk_divisors[i]) {
1021             return i + 1;
1022         }
1023     }
1024 
1025     qemu_log_mask(LOG_GUEST_ERROR, "invalid HCLK mask %x", hclk_mask);
1026     return 0;
1027 }
1028 
1029 /*
1030  * When doing calibration, the SPI clock rate in the CE0 Control
1031  * Register and the read delay cycles in the Read Timing Compensation
1032  * Register are set using bit[11:4] of the DMA Control Register.
1033  */
1034 static void aspeed_smc_dma_calibration(AspeedSMCState *s)
1035 {
1036     uint8_t delay =
1037         (s->regs[R_DMA_CTRL] >> DMA_CTRL_DELAY_SHIFT) & DMA_CTRL_DELAY_MASK;
1038     uint8_t hclk_mask =
1039         (s->regs[R_DMA_CTRL] >> DMA_CTRL_FREQ_SHIFT) & DMA_CTRL_FREQ_MASK;
1040     uint8_t hclk_div = aspeed_smc_hclk_divisor(hclk_mask);
1041     uint32_t hclk_shift = (hclk_div - 1) << 2;
1042     uint8_t cs;
1043 
1044     /*
1045      * The Read Timing Compensation Register values apply to all CS on
1046      * the SPI bus and only HCLK/1 - HCLK/5 can have tunable delays
1047      */
1048     if (hclk_div && hclk_div < 6) {
1049         s->regs[s->r_timings] &= ~(0xf << hclk_shift);
1050         s->regs[s->r_timings] |= delay << hclk_shift;
1051     }
1052 
1053     /*
1054      * TODO: compute the CS from the DMA address and the segment
1055      * registers. This is not really a problem for now because the
1056      * Timing Register values apply to all CS and software uses CS0 to
1057      * do calibration.
1058      */
1059     cs = 0;
1060     s->regs[s->r_ctrl0 + cs] &=
1061         ~(CE_CTRL_CLOCK_FREQ_MASK << CE_CTRL_CLOCK_FREQ_SHIFT);
1062     s->regs[s->r_ctrl0 + cs] |= CE_CTRL_CLOCK_FREQ(hclk_div);
1063 }
1064 
1065 /*
1066  * Emulate read errors in the DMA Checksum Register for high
1067  * frequencies and optimistic settings of the Read Timing Compensation
1068  * Register. This will help in tuning the SPI timing calibration
1069  * algorithm.
1070  */
1071 static bool aspeed_smc_inject_read_failure(AspeedSMCState *s)
1072 {
1073     uint8_t delay =
1074         (s->regs[R_DMA_CTRL] >> DMA_CTRL_DELAY_SHIFT) & DMA_CTRL_DELAY_MASK;
1075     uint8_t hclk_mask =
1076         (s->regs[R_DMA_CTRL] >> DMA_CTRL_FREQ_SHIFT) & DMA_CTRL_FREQ_MASK;
1077 
1078     /*
1079      * Typical values of a palmetto-bmc machine.
1080      */
1081     switch (aspeed_smc_hclk_divisor(hclk_mask)) {
1082     case 4 ... 16:
1083         return false;
1084     case 3: /* at least one HCLK cycle delay */
1085         return (delay & 0x7) < 1;
1086     case 2: /* at least two HCLK cycle delay */
1087         return (delay & 0x7) < 2;
1088     case 1: /* (> 100MHz) is above the max freq of the controller */
1089         return true;
1090     default:
1091         g_assert_not_reached();
1092     }
1093 }
1094 
1095 /*
1096  * Accumulate the result of the reads to provide a checksum that will
1097  * be used to validate the read timing settings.
1098  */
1099 static void aspeed_smc_dma_checksum(AspeedSMCState *s)
1100 {
1101     MemTxResult result;
1102     uint32_t data;
1103 
1104     if (s->regs[R_DMA_CTRL] & DMA_CTRL_WRITE) {
1105         qemu_log_mask(LOG_GUEST_ERROR,
1106                       "%s: invalid direction for DMA checksum\n",  __func__);
1107         return;
1108     }
1109 
1110     if (s->regs[R_DMA_CTRL] & DMA_CTRL_CALIB) {
1111         aspeed_smc_dma_calibration(s);
1112     }
1113 
1114     while (s->regs[R_DMA_LEN]) {
1115         data = address_space_ldl_le(&s->flash_as, s->regs[R_DMA_FLASH_ADDR],
1116                                     MEMTXATTRS_UNSPECIFIED, &result);
1117         if (result != MEMTX_OK) {
1118             qemu_log_mask(LOG_GUEST_ERROR, "%s: Flash read failed @%08x\n",
1119                           __func__, s->regs[R_DMA_FLASH_ADDR]);
1120             return;
1121         }
1122         trace_aspeed_smc_dma_checksum(s->regs[R_DMA_FLASH_ADDR], data);
1123 
1124         /*
1125          * When the DMA is on-going, the DMA registers are updated
1126          * with the current working addresses and length.
1127          */
1128         s->regs[R_DMA_CHECKSUM] += data;
1129         s->regs[R_DMA_FLASH_ADDR] += 4;
1130         s->regs[R_DMA_LEN] -= 4;
1131     }
1132 
1133     if (s->inject_failure && aspeed_smc_inject_read_failure(s)) {
1134         s->regs[R_DMA_CHECKSUM] = 0xbadc0de;
1135     }
1136 
1137 }
1138 
1139 static void aspeed_smc_dma_rw(AspeedSMCState *s)
1140 {
1141     MemTxResult result;
1142     uint32_t data;
1143 
1144     trace_aspeed_smc_dma_rw(s->regs[R_DMA_CTRL] & DMA_CTRL_WRITE ?
1145                             "write" : "read",
1146                             s->regs[R_DMA_FLASH_ADDR],
1147                             s->regs[R_DMA_DRAM_ADDR],
1148                             s->regs[R_DMA_LEN]);
1149     while (s->regs[R_DMA_LEN]) {
1150         if (s->regs[R_DMA_CTRL] & DMA_CTRL_WRITE) {
1151             data = address_space_ldl_le(&s->dram_as, s->regs[R_DMA_DRAM_ADDR],
1152                                         MEMTXATTRS_UNSPECIFIED, &result);
1153             if (result != MEMTX_OK) {
1154                 qemu_log_mask(LOG_GUEST_ERROR, "%s: DRAM read failed @%08x\n",
1155                               __func__, s->regs[R_DMA_DRAM_ADDR]);
1156                 return;
1157             }
1158 
1159             address_space_stl_le(&s->flash_as, s->regs[R_DMA_FLASH_ADDR],
1160                                  data, MEMTXATTRS_UNSPECIFIED, &result);
1161             if (result != MEMTX_OK) {
1162                 qemu_log_mask(LOG_GUEST_ERROR, "%s: Flash write failed @%08x\n",
1163                               __func__, s->regs[R_DMA_FLASH_ADDR]);
1164                 return;
1165             }
1166         } else {
1167             data = address_space_ldl_le(&s->flash_as, s->regs[R_DMA_FLASH_ADDR],
1168                                         MEMTXATTRS_UNSPECIFIED, &result);
1169             if (result != MEMTX_OK) {
1170                 qemu_log_mask(LOG_GUEST_ERROR, "%s: Flash read failed @%08x\n",
1171                               __func__, s->regs[R_DMA_FLASH_ADDR]);
1172                 return;
1173             }
1174 
1175             address_space_stl_le(&s->dram_as, s->regs[R_DMA_DRAM_ADDR],
1176                                  data, MEMTXATTRS_UNSPECIFIED, &result);
1177             if (result != MEMTX_OK) {
1178                 qemu_log_mask(LOG_GUEST_ERROR, "%s: DRAM write failed @%08x\n",
1179                               __func__, s->regs[R_DMA_DRAM_ADDR]);
1180                 return;
1181             }
1182         }
1183 
1184         /*
1185          * When the DMA is on-going, the DMA registers are updated
1186          * with the current working addresses and length.
1187          */
1188         s->regs[R_DMA_FLASH_ADDR] += 4;
1189         s->regs[R_DMA_DRAM_ADDR] += 4;
1190         s->regs[R_DMA_LEN] -= 4;
1191         s->regs[R_DMA_CHECKSUM] += data;
1192     }
1193 }
1194 
1195 static void aspeed_smc_dma_stop(AspeedSMCState *s)
1196 {
1197     /*
1198      * When the DMA is disabled, INTR_CTRL_DMA_STATUS=0 means the
1199      * engine is idle
1200      */
1201     s->regs[R_INTR_CTRL] &= ~INTR_CTRL_DMA_STATUS;
1202     s->regs[R_DMA_CHECKSUM] = 0;
1203 
1204     /*
1205      * Lower the DMA irq in any case. The IRQ control register could
1206      * have been cleared before disabling the DMA.
1207      */
1208     qemu_irq_lower(s->irq);
1209 }
1210 
1211 /*
1212  * When INTR_CTRL_DMA_STATUS=1, the DMA has completed and a new DMA
1213  * can start even if the result of the previous was not collected.
1214  */
1215 static bool aspeed_smc_dma_in_progress(AspeedSMCState *s)
1216 {
1217     return s->regs[R_DMA_CTRL] & DMA_CTRL_ENABLE &&
1218         !(s->regs[R_INTR_CTRL] & INTR_CTRL_DMA_STATUS);
1219 }
1220 
1221 static void aspeed_smc_dma_done(AspeedSMCState *s)
1222 {
1223     s->regs[R_INTR_CTRL] |= INTR_CTRL_DMA_STATUS;
1224     if (s->regs[R_INTR_CTRL] & INTR_CTRL_DMA_EN) {
1225         qemu_irq_raise(s->irq);
1226     }
1227 }
1228 
1229 static void aspeed_smc_dma_ctrl(AspeedSMCState *s, uint64_t dma_ctrl)
1230 {
1231     if (!(dma_ctrl & DMA_CTRL_ENABLE)) {
1232         s->regs[R_DMA_CTRL] = dma_ctrl;
1233 
1234         aspeed_smc_dma_stop(s);
1235         return;
1236     }
1237 
1238     if (aspeed_smc_dma_in_progress(s)) {
1239         qemu_log_mask(LOG_GUEST_ERROR, "%s: DMA in progress\n",  __func__);
1240         return;
1241     }
1242 
1243     s->regs[R_DMA_CTRL] = dma_ctrl;
1244 
1245     if (s->regs[R_DMA_CTRL] & DMA_CTRL_CKSUM) {
1246         aspeed_smc_dma_checksum(s);
1247     } else {
1248         aspeed_smc_dma_rw(s);
1249     }
1250 
1251     aspeed_smc_dma_done(s);
1252 }
1253 
1254 static void aspeed_smc_write(void *opaque, hwaddr addr, uint64_t data,
1255                              unsigned int size)
1256 {
1257     AspeedSMCState *s = ASPEED_SMC(opaque);
1258     uint32_t value = data;
1259 
1260     addr >>= 2;
1261 
1262     trace_aspeed_smc_write(addr, size, data);
1263 
1264     if (addr == s->r_conf ||
1265         (addr >= s->r_timings &&
1266          addr < s->r_timings + s->ctrl->nregs_timings) ||
1267         addr == s->r_ce_ctrl) {
1268         s->regs[addr] = value;
1269     } else if (addr >= s->r_ctrl0 && addr < s->r_ctrl0 + s->num_cs) {
1270         int cs = addr - s->r_ctrl0;
1271         aspeed_smc_flash_update_ctrl(&s->flashes[cs], value);
1272     } else if (addr >= R_SEG_ADDR0 &&
1273                addr < R_SEG_ADDR0 + s->ctrl->max_slaves) {
1274         int cs = addr - R_SEG_ADDR0;
1275 
1276         if (value != s->regs[R_SEG_ADDR0 + cs]) {
1277             aspeed_smc_flash_set_segment(s, cs, value);
1278         }
1279     } else if (addr == R_DUMMY_DATA) {
1280         s->regs[addr] = value & 0xff;
1281     } else if (addr == R_INTR_CTRL) {
1282         s->regs[addr] = value;
1283     } else if (s->ctrl->has_dma && addr == R_DMA_CTRL) {
1284         aspeed_smc_dma_ctrl(s, value);
1285     } else if (s->ctrl->has_dma && addr == R_DMA_DRAM_ADDR) {
1286         s->regs[addr] = DMA_DRAM_ADDR(s, value);
1287     } else if (s->ctrl->has_dma && addr == R_DMA_FLASH_ADDR) {
1288         s->regs[addr] = DMA_FLASH_ADDR(s, value);
1289     } else if (s->ctrl->has_dma && addr == R_DMA_LEN) {
1290         s->regs[addr] = DMA_LENGTH(value);
1291     } else {
1292         qemu_log_mask(LOG_UNIMP, "%s: not implemented: 0x%" HWADDR_PRIx "\n",
1293                       __func__, addr);
1294         return;
1295     }
1296 }
1297 
1298 static const MemoryRegionOps aspeed_smc_ops = {
1299     .read = aspeed_smc_read,
1300     .write = aspeed_smc_write,
1301     .endianness = DEVICE_LITTLE_ENDIAN,
1302     .valid.unaligned = true,
1303 };
1304 
1305 
1306 /*
1307  * Initialize the custom address spaces for DMAs
1308  */
1309 static void aspeed_smc_dma_setup(AspeedSMCState *s, Error **errp)
1310 {
1311     char *name;
1312 
1313     if (!s->dram_mr) {
1314         error_setg(errp, TYPE_ASPEED_SMC ": 'dram' link not set");
1315         return;
1316     }
1317 
1318     name = g_strdup_printf("%s-dma-flash", s->ctrl->name);
1319     address_space_init(&s->flash_as, &s->mmio_flash, name);
1320     g_free(name);
1321 
1322     name = g_strdup_printf("%s-dma-dram", s->ctrl->name);
1323     address_space_init(&s->dram_as, s->dram_mr, name);
1324     g_free(name);
1325 }
1326 
1327 static void aspeed_smc_realize(DeviceState *dev, Error **errp)
1328 {
1329     SysBusDevice *sbd = SYS_BUS_DEVICE(dev);
1330     AspeedSMCState *s = ASPEED_SMC(dev);
1331     AspeedSMCClass *mc = ASPEED_SMC_GET_CLASS(s);
1332     int i;
1333     char name[32];
1334     hwaddr offset = 0;
1335 
1336     s->ctrl = mc->ctrl;
1337 
1338     /* keep a copy under AspeedSMCState to speed up accesses */
1339     s->r_conf = s->ctrl->r_conf;
1340     s->r_ce_ctrl = s->ctrl->r_ce_ctrl;
1341     s->r_ctrl0 = s->ctrl->r_ctrl0;
1342     s->r_timings = s->ctrl->r_timings;
1343     s->conf_enable_w0 = s->ctrl->conf_enable_w0;
1344 
1345     /* Enforce some real HW limits */
1346     if (s->num_cs > s->ctrl->max_slaves) {
1347         qemu_log_mask(LOG_GUEST_ERROR, "%s: num_cs cannot exceed: %d\n",
1348                       __func__, s->ctrl->max_slaves);
1349         s->num_cs = s->ctrl->max_slaves;
1350     }
1351 
1352     /* DMA irq. Keep it first for the initialization in the SoC */
1353     sysbus_init_irq(sbd, &s->irq);
1354 
1355     s->spi = ssi_create_bus(dev, "spi");
1356 
1357     /* Setup cs_lines for slaves */
1358     s->cs_lines = g_new0(qemu_irq, s->num_cs);
1359     ssi_auto_connect_slaves(dev, s->cs_lines, s->spi);
1360 
1361     for (i = 0; i < s->num_cs; ++i) {
1362         sysbus_init_irq(sbd, &s->cs_lines[i]);
1363     }
1364 
1365     /* The memory region for the controller registers */
1366     memory_region_init_io(&s->mmio, OBJECT(s), &aspeed_smc_ops, s,
1367                           s->ctrl->name, s->ctrl->nregs * 4);
1368     sysbus_init_mmio(sbd, &s->mmio);
1369 
1370     /*
1371      * The container memory region representing the address space
1372      * window in which the flash modules are mapped. The size and
1373      * address depends on the SoC model and controller type.
1374      */
1375     snprintf(name, sizeof(name), "%s.flash", s->ctrl->name);
1376 
1377     memory_region_init_io(&s->mmio_flash, OBJECT(s),
1378                           &aspeed_smc_flash_default_ops, s, name,
1379                           s->ctrl->flash_window_size);
1380     sysbus_init_mmio(sbd, &s->mmio_flash);
1381 
1382     s->flashes = g_new0(AspeedSMCFlash, s->ctrl->max_slaves);
1383 
1384     /*
1385      * Let's create a sub memory region for each possible slave. All
1386      * have a configurable memory segment in the overall flash mapping
1387      * window of the controller but, there is not necessarily a flash
1388      * module behind to handle the memory accesses. This depends on
1389      * the board configuration.
1390      */
1391     for (i = 0; i < s->ctrl->max_slaves; ++i) {
1392         AspeedSMCFlash *fl = &s->flashes[i];
1393 
1394         snprintf(name, sizeof(name), "%s.%d", s->ctrl->name, i);
1395 
1396         fl->id = i;
1397         fl->controller = s;
1398         fl->size = s->ctrl->segments[i].size;
1399         memory_region_init_io(&fl->mmio, OBJECT(s), &aspeed_smc_flash_ops,
1400                               fl, name, fl->size);
1401         memory_region_add_subregion(&s->mmio_flash, offset, &fl->mmio);
1402         offset += fl->size;
1403     }
1404 
1405     /* DMA support */
1406     if (s->ctrl->has_dma) {
1407         aspeed_smc_dma_setup(s, errp);
1408     }
1409 }
1410 
1411 static const VMStateDescription vmstate_aspeed_smc = {
1412     .name = "aspeed.smc",
1413     .version_id = 2,
1414     .minimum_version_id = 2,
1415     .fields = (VMStateField[]) {
1416         VMSTATE_UINT32_ARRAY(regs, AspeedSMCState, ASPEED_SMC_R_MAX),
1417         VMSTATE_UINT8(snoop_index, AspeedSMCState),
1418         VMSTATE_UINT8(snoop_dummies, AspeedSMCState),
1419         VMSTATE_END_OF_LIST()
1420     }
1421 };
1422 
1423 static Property aspeed_smc_properties[] = {
1424     DEFINE_PROP_UINT32("num-cs", AspeedSMCState, num_cs, 1),
1425     DEFINE_PROP_BOOL("inject-failure", AspeedSMCState, inject_failure, false),
1426     DEFINE_PROP_UINT64("sdram-base", AspeedSMCState, sdram_base, 0),
1427     DEFINE_PROP_LINK("dram", AspeedSMCState, dram_mr,
1428                      TYPE_MEMORY_REGION, MemoryRegion *),
1429     DEFINE_PROP_END_OF_LIST(),
1430 };
1431 
1432 static void aspeed_smc_class_init(ObjectClass *klass, void *data)
1433 {
1434     DeviceClass *dc = DEVICE_CLASS(klass);
1435     AspeedSMCClass *mc = ASPEED_SMC_CLASS(klass);
1436 
1437     dc->realize = aspeed_smc_realize;
1438     dc->reset = aspeed_smc_reset;
1439     device_class_set_props(dc, aspeed_smc_properties);
1440     dc->vmsd = &vmstate_aspeed_smc;
1441     mc->ctrl = data;
1442 }
1443 
1444 static const TypeInfo aspeed_smc_info = {
1445     .name           = TYPE_ASPEED_SMC,
1446     .parent         = TYPE_SYS_BUS_DEVICE,
1447     .instance_size  = sizeof(AspeedSMCState),
1448     .class_size     = sizeof(AspeedSMCClass),
1449     .abstract       = true,
1450 };
1451 
1452 static void aspeed_smc_register_types(void)
1453 {
1454     int i;
1455 
1456     type_register_static(&aspeed_smc_info);
1457     for (i = 0; i < ARRAY_SIZE(controllers); ++i) {
1458         TypeInfo ti = {
1459             .name       = controllers[i].name,
1460             .parent     = TYPE_ASPEED_SMC,
1461             .class_init = aspeed_smc_class_init,
1462             .class_data = (void *)&controllers[i],
1463         };
1464         type_register(&ti);
1465     }
1466 }
1467 
1468 type_init(aspeed_smc_register_types)
1469