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