xref: /openbmc/qemu/hw/dma/pl330.c (revision 37677d7d)
1 /*
2  * ARM PrimeCell PL330 DMA Controller
3  *
4  * Copyright (c) 2009 Samsung Electronics.
5  * Contributed by Kirill Batuzov <batuzovk@ispras.ru>
6  * Copyright (c) 2012 Peter A.G. Crosthwaite (peter.crosthwaite@petalogix.com)
7  * Copyright (c) 2012 PetaLogix Pty Ltd.
8  *
9  * This program is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU General Public License
11  * as published by the Free Software Foundation; version 2 or later.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program; if not, see <http://www.gnu.org/licenses/>.
15  */
16 
17 #include "qemu/osdep.h"
18 #include "qemu-common.h"
19 #include "hw/sysbus.h"
20 #include "qapi/error.h"
21 #include "qemu/timer.h"
22 #include "sysemu/dma.h"
23 #include "qemu/log.h"
24 #include "qemu/module.h"
25 
26 #ifndef PL330_ERR_DEBUG
27 #define PL330_ERR_DEBUG 0
28 #endif
29 
30 #define DB_PRINT_L(lvl, fmt, args...) do {\
31     if (PL330_ERR_DEBUG >= lvl) {\
32         fprintf(stderr, "PL330: %s:" fmt, __func__, ## args);\
33     } \
34 } while (0)
35 
36 #define DB_PRINT(fmt, args...) DB_PRINT_L(1, fmt, ## args)
37 
38 #define PL330_PERIPH_NUM            32
39 #define PL330_MAX_BURST_LEN         128
40 #define PL330_INSN_MAXSIZE          6
41 
42 #define PL330_FIFO_OK               0
43 #define PL330_FIFO_STALL            1
44 #define PL330_FIFO_ERR              (-1)
45 
46 #define PL330_FAULT_UNDEF_INSTR             (1 <<  0)
47 #define PL330_FAULT_OPERAND_INVALID         (1 <<  1)
48 #define PL330_FAULT_DMAGO_ERR               (1 <<  4)
49 #define PL330_FAULT_EVENT_ERR               (1 <<  5)
50 #define PL330_FAULT_CH_PERIPH_ERR           (1 <<  6)
51 #define PL330_FAULT_CH_RDWR_ERR             (1 <<  7)
52 #define PL330_FAULT_ST_DATA_UNAVAILABLE     (1 << 12)
53 #define PL330_FAULT_FIFOEMPTY_ERR           (1 << 13)
54 #define PL330_FAULT_INSTR_FETCH_ERR         (1 << 16)
55 #define PL330_FAULT_DATA_WRITE_ERR          (1 << 17)
56 #define PL330_FAULT_DATA_READ_ERR           (1 << 18)
57 #define PL330_FAULT_DBG_INSTR               (1 << 30)
58 #define PL330_FAULT_LOCKUP_ERR              (1 << 31)
59 
60 #define PL330_UNTAGGED              0xff
61 
62 #define PL330_SINGLE                0x0
63 #define PL330_BURST                 0x1
64 
65 #define PL330_WATCHDOG_LIMIT        1024
66 
67 /* IOMEM mapped registers */
68 #define PL330_REG_DSR               0x000
69 #define PL330_REG_DPC               0x004
70 #define PL330_REG_INTEN             0x020
71 #define PL330_REG_INT_EVENT_RIS     0x024
72 #define PL330_REG_INTMIS            0x028
73 #define PL330_REG_INTCLR            0x02C
74 #define PL330_REG_FSRD              0x030
75 #define PL330_REG_FSRC              0x034
76 #define PL330_REG_FTRD              0x038
77 #define PL330_REG_FTR_BASE          0x040
78 #define PL330_REG_CSR_BASE          0x100
79 #define PL330_REG_CPC_BASE          0x104
80 #define PL330_REG_CHANCTRL          0x400
81 #define PL330_REG_DBGSTATUS         0xD00
82 #define PL330_REG_DBGCMD            0xD04
83 #define PL330_REG_DBGINST0          0xD08
84 #define PL330_REG_DBGINST1          0xD0C
85 #define PL330_REG_CR0_BASE          0xE00
86 #define PL330_REG_PERIPH_ID         0xFE0
87 
88 #define PL330_IOMEM_SIZE    0x1000
89 
90 #define CFG_BOOT_ADDR 2
91 #define CFG_INS 3
92 #define CFG_PNS 4
93 #define CFG_CRD 5
94 
95 static const uint32_t pl330_id[] = {
96     0x30, 0x13, 0x24, 0x00, 0x0D, 0xF0, 0x05, 0xB1
97 };
98 
99 /* DMA channel states as they are described in PL330 Technical Reference Manual
100  * Most of them will not be used in emulation.
101  */
102 typedef enum  {
103     pl330_chan_stopped = 0,
104     pl330_chan_executing = 1,
105     pl330_chan_cache_miss = 2,
106     pl330_chan_updating_pc = 3,
107     pl330_chan_waiting_event = 4,
108     pl330_chan_at_barrier = 5,
109     pl330_chan_queue_busy = 6,
110     pl330_chan_waiting_periph = 7,
111     pl330_chan_killing = 8,
112     pl330_chan_completing = 9,
113     pl330_chan_fault_completing = 14,
114     pl330_chan_fault = 15,
115 } PL330ChanState;
116 
117 typedef struct PL330State PL330State;
118 
119 typedef struct PL330Chan {
120     uint32_t src;
121     uint32_t dst;
122     uint32_t pc;
123     uint32_t control;
124     uint32_t status;
125     uint32_t lc[2];
126     uint32_t fault_type;
127     uint32_t watchdog_timer;
128 
129     bool ns;
130     uint8_t request_flag;
131     uint8_t wakeup;
132     uint8_t wfp_sbp;
133 
134     uint8_t state;
135     uint8_t stall;
136 
137     bool is_manager;
138     PL330State *parent;
139     uint8_t tag;
140 } PL330Chan;
141 
142 static const VMStateDescription vmstate_pl330_chan = {
143     .name = "pl330_chan",
144     .version_id = 1,
145     .minimum_version_id = 1,
146     .fields = (VMStateField[]) {
147         VMSTATE_UINT32(src, PL330Chan),
148         VMSTATE_UINT32(dst, PL330Chan),
149         VMSTATE_UINT32(pc, PL330Chan),
150         VMSTATE_UINT32(control, PL330Chan),
151         VMSTATE_UINT32(status, PL330Chan),
152         VMSTATE_UINT32_ARRAY(lc, PL330Chan, 2),
153         VMSTATE_UINT32(fault_type, PL330Chan),
154         VMSTATE_UINT32(watchdog_timer, PL330Chan),
155         VMSTATE_BOOL(ns, PL330Chan),
156         VMSTATE_UINT8(request_flag, PL330Chan),
157         VMSTATE_UINT8(wakeup, PL330Chan),
158         VMSTATE_UINT8(wfp_sbp, PL330Chan),
159         VMSTATE_UINT8(state, PL330Chan),
160         VMSTATE_UINT8(stall, PL330Chan),
161         VMSTATE_END_OF_LIST()
162     }
163 };
164 
165 typedef struct PL330Fifo {
166     uint8_t *buf;
167     uint8_t *tag;
168     uint32_t head;
169     uint32_t num;
170     uint32_t buf_size;
171 } PL330Fifo;
172 
173 static const VMStateDescription vmstate_pl330_fifo = {
174     .name = "pl330_chan",
175     .version_id = 1,
176     .minimum_version_id = 1,
177     .fields = (VMStateField[]) {
178         VMSTATE_VBUFFER_UINT32(buf, PL330Fifo, 1, NULL, buf_size),
179         VMSTATE_VBUFFER_UINT32(tag, PL330Fifo, 1, NULL, buf_size),
180         VMSTATE_UINT32(head, PL330Fifo),
181         VMSTATE_UINT32(num, PL330Fifo),
182         VMSTATE_UINT32(buf_size, PL330Fifo),
183         VMSTATE_END_OF_LIST()
184     }
185 };
186 
187 typedef struct PL330QueueEntry {
188     uint32_t addr;
189     uint32_t len;
190     uint8_t n;
191     bool inc;
192     bool z;
193     uint8_t tag;
194     uint8_t seqn;
195 } PL330QueueEntry;
196 
197 static const VMStateDescription vmstate_pl330_queue_entry = {
198     .name = "pl330_queue_entry",
199     .version_id = 1,
200     .minimum_version_id = 1,
201     .fields = (VMStateField[]) {
202         VMSTATE_UINT32(addr, PL330QueueEntry),
203         VMSTATE_UINT32(len, PL330QueueEntry),
204         VMSTATE_UINT8(n, PL330QueueEntry),
205         VMSTATE_BOOL(inc, PL330QueueEntry),
206         VMSTATE_BOOL(z, PL330QueueEntry),
207         VMSTATE_UINT8(tag, PL330QueueEntry),
208         VMSTATE_UINT8(seqn, PL330QueueEntry),
209         VMSTATE_END_OF_LIST()
210     }
211 };
212 
213 typedef struct PL330Queue {
214     PL330State *parent;
215     PL330QueueEntry *queue;
216     uint32_t queue_size;
217 } PL330Queue;
218 
219 static const VMStateDescription vmstate_pl330_queue = {
220     .name = "pl330_queue",
221     .version_id = 1,
222     .minimum_version_id = 1,
223     .fields = (VMStateField[]) {
224         VMSTATE_STRUCT_VARRAY_UINT32(queue, PL330Queue, queue_size, 1,
225                                  vmstate_pl330_queue_entry, PL330QueueEntry),
226         VMSTATE_END_OF_LIST()
227     }
228 };
229 
230 struct PL330State {
231     SysBusDevice parent_obj;
232 
233     MemoryRegion iomem;
234     qemu_irq irq_abort;
235     qemu_irq *irq;
236 
237     /* Config registers. cfg[5] = CfgDn. */
238     uint32_t cfg[6];
239 #define EVENT_SEC_STATE 3
240 #define PERIPH_SEC_STATE 4
241     /* cfg 0 bits and pieces */
242     uint32_t num_chnls;
243     uint8_t num_periph_req;
244     uint8_t num_events;
245     uint8_t mgr_ns_at_rst;
246     /* cfg 1 bits and pieces */
247     uint8_t i_cache_len;
248     uint8_t num_i_cache_lines;
249     /* CRD bits and pieces */
250     uint8_t data_width;
251     uint8_t wr_cap;
252     uint8_t wr_q_dep;
253     uint8_t rd_cap;
254     uint8_t rd_q_dep;
255     uint16_t data_buffer_dep;
256 
257     PL330Chan manager;
258     PL330Chan *chan;
259     PL330Fifo fifo;
260     PL330Queue read_queue;
261     PL330Queue write_queue;
262     uint8_t *lo_seqn;
263     uint8_t *hi_seqn;
264     QEMUTimer *timer; /* is used for restore dma. */
265 
266     uint32_t inten;
267     uint32_t int_status;
268     uint32_t ev_status;
269     uint32_t dbg[2];
270     uint8_t debug_status;
271     uint8_t num_faulting;
272     uint8_t periph_busy[PL330_PERIPH_NUM];
273 
274 };
275 
276 #define TYPE_PL330 "pl330"
277 #define PL330(obj) OBJECT_CHECK(PL330State, (obj), TYPE_PL330)
278 
279 static const VMStateDescription vmstate_pl330 = {
280     .name = "pl330",
281     .version_id = 1,
282     .minimum_version_id = 1,
283     .fields = (VMStateField[]) {
284         VMSTATE_STRUCT(manager, PL330State, 0, vmstate_pl330_chan, PL330Chan),
285         VMSTATE_STRUCT_VARRAY_UINT32(chan, PL330State, num_chnls, 0,
286                                      vmstate_pl330_chan, PL330Chan),
287         VMSTATE_VBUFFER_UINT32(lo_seqn, PL330State, 1, NULL, num_chnls),
288         VMSTATE_VBUFFER_UINT32(hi_seqn, PL330State, 1, NULL, num_chnls),
289         VMSTATE_STRUCT(fifo, PL330State, 0, vmstate_pl330_fifo, PL330Fifo),
290         VMSTATE_STRUCT(read_queue, PL330State, 0, vmstate_pl330_queue,
291                        PL330Queue),
292         VMSTATE_STRUCT(write_queue, PL330State, 0, vmstate_pl330_queue,
293                        PL330Queue),
294         VMSTATE_TIMER_PTR(timer, PL330State),
295         VMSTATE_UINT32(inten, PL330State),
296         VMSTATE_UINT32(int_status, PL330State),
297         VMSTATE_UINT32(ev_status, PL330State),
298         VMSTATE_UINT32_ARRAY(dbg, PL330State, 2),
299         VMSTATE_UINT8(debug_status, PL330State),
300         VMSTATE_UINT8(num_faulting, PL330State),
301         VMSTATE_UINT8_ARRAY(periph_busy, PL330State, PL330_PERIPH_NUM),
302         VMSTATE_END_OF_LIST()
303     }
304 };
305 
306 typedef struct PL330InsnDesc {
307     /* OPCODE of the instruction */
308     uint8_t opcode;
309     /* Mask so we can select several sibling instructions, such as
310        DMALD, DMALDS and DMALDB */
311     uint8_t opmask;
312     /* Size of instruction in bytes */
313     uint8_t size;
314     /* Interpreter */
315     void (*exec)(PL330Chan *, uint8_t opcode, uint8_t *args, int len);
316 } PL330InsnDesc;
317 
318 
319 /* MFIFO Implementation
320  *
321  * MFIFO is implemented as a cyclic buffer of BUF_SIZE size. Tagged bytes are
322  * stored in this buffer. Data is stored in BUF field, tags - in the
323  * corresponding array elements of TAG field.
324  */
325 
326 /* Initialize queue. */
327 
328 static void pl330_fifo_init(PL330Fifo *s, uint32_t size)
329 {
330     s->buf = g_malloc0(size);
331     s->tag = g_malloc0(size);
332     s->buf_size = size;
333 }
334 
335 /* Cyclic increment */
336 
337 static inline int pl330_fifo_inc(PL330Fifo *s, int x)
338 {
339     return (x + 1) % s->buf_size;
340 }
341 
342 /* Number of empty bytes in MFIFO */
343 
344 static inline int pl330_fifo_num_free(PL330Fifo *s)
345 {
346     return s->buf_size - s->num;
347 }
348 
349 /* Push LEN bytes of data stored in BUF to MFIFO and tag it with TAG.
350  * Zero returned on success, PL330_FIFO_STALL if there is no enough free
351  * space in MFIFO to store requested amount of data. If push was unsuccessful
352  * no data is stored to MFIFO.
353  */
354 
355 static int pl330_fifo_push(PL330Fifo *s, uint8_t *buf, int len, uint8_t tag)
356 {
357     int i;
358 
359     if (s->buf_size - s->num < len) {
360         return PL330_FIFO_STALL;
361     }
362     for (i = 0; i < len; i++) {
363         int push_idx = (s->head + s->num + i) % s->buf_size;
364         s->buf[push_idx] = buf[i];
365         s->tag[push_idx] = tag;
366     }
367     s->num += len;
368     return PL330_FIFO_OK;
369 }
370 
371 /* Get LEN bytes of data from MFIFO and store it to BUF. Tag value of each
372  * byte is verified. Zero returned on success, PL330_FIFO_ERR on tag mismatch
373  * and PL330_FIFO_STALL if there is no enough data in MFIFO. If get was
374  * unsuccessful no data is removed from MFIFO.
375  */
376 
377 static int pl330_fifo_get(PL330Fifo *s, uint8_t *buf, int len, uint8_t tag)
378 {
379     int i;
380 
381     if (s->num < len) {
382         return PL330_FIFO_STALL;
383     }
384     for (i = 0; i < len; i++) {
385         if (s->tag[s->head] == tag) {
386             int get_idx = (s->head + i) % s->buf_size;
387             buf[i] = s->buf[get_idx];
388         } else { /* Tag mismatch - Rollback transaction */
389             return PL330_FIFO_ERR;
390         }
391     }
392     s->head = (s->head + len) % s->buf_size;
393     s->num -= len;
394     return PL330_FIFO_OK;
395 }
396 
397 /* Reset MFIFO. This completely erases all data in it. */
398 
399 static inline void pl330_fifo_reset(PL330Fifo *s)
400 {
401     s->head = 0;
402     s->num = 0;
403 }
404 
405 /* Return tag of the first byte stored in MFIFO. If MFIFO is empty
406  * PL330_UNTAGGED is returned.
407  */
408 
409 static inline uint8_t pl330_fifo_tag(PL330Fifo *s)
410 {
411     return (!s->num) ? PL330_UNTAGGED : s->tag[s->head];
412 }
413 
414 /* Returns non-zero if tag TAG is present in fifo or zero otherwise */
415 
416 static int pl330_fifo_has_tag(PL330Fifo *s, uint8_t tag)
417 {
418     int i, n;
419 
420     i = s->head;
421     for (n = 0; n < s->num; n++) {
422         if (s->tag[i] == tag) {
423             return 1;
424         }
425         i = pl330_fifo_inc(s, i);
426     }
427     return 0;
428 }
429 
430 /* Remove all entry tagged with TAG from MFIFO */
431 
432 static void pl330_fifo_tagged_remove(PL330Fifo *s, uint8_t tag)
433 {
434     int i, t, n;
435 
436     t = i = s->head;
437     for (n = 0; n < s->num; n++) {
438         if (s->tag[i] != tag) {
439             s->buf[t] = s->buf[i];
440             s->tag[t] = s->tag[i];
441             t = pl330_fifo_inc(s, t);
442         } else {
443             s->num = s->num - 1;
444         }
445         i = pl330_fifo_inc(s, i);
446     }
447 }
448 
449 /* Read-Write Queue implementation
450  *
451  * A Read-Write Queue stores up to QUEUE_SIZE instructions (loads or stores).
452  * Each instruction is described by source (for loads) or destination (for
453  * stores) address ADDR, width of data to be loaded/stored LEN, number of
454  * stores/loads to be performed N, INC bit, Z bit and TAG to identify channel
455  * this instruction belongs to. Queue does not store any information about
456  * nature of the instruction: is it load or store. PL330 has different queues
457  * for loads and stores so this is already known at the top level where it
458  * matters.
459  *
460  * Queue works as FIFO for instructions with equivalent tags, but can issue
461  * instructions with different tags in arbitrary order. SEQN field attached to
462  * each instruction helps to achieve this. For each TAG queue contains
463  * instructions with consecutive SEQN values ranging from LO_SEQN[TAG] to
464  * HI_SEQN[TAG]-1 inclusive. SEQN is 8-bit unsigned integer, so SEQN=255 is
465  * followed by SEQN=0.
466  *
467  * Z bit indicates that zeroes should be stored. No MFIFO fetches are performed
468  * in this case.
469  */
470 
471 static void pl330_queue_reset(PL330Queue *s)
472 {
473     int i;
474 
475     for (i = 0; i < s->queue_size; i++) {
476         s->queue[i].tag = PL330_UNTAGGED;
477     }
478 }
479 
480 /* Initialize queue */
481 static void pl330_queue_init(PL330Queue *s, int size, PL330State *parent)
482 {
483     s->parent = parent;
484     s->queue = g_new0(PL330QueueEntry, size);
485     s->queue_size = size;
486 }
487 
488 /* Returns pointer to an empty slot or NULL if queue is full */
489 static PL330QueueEntry *pl330_queue_find_empty(PL330Queue *s)
490 {
491     int i;
492 
493     for (i = 0; i < s->queue_size; i++) {
494         if (s->queue[i].tag == PL330_UNTAGGED) {
495             return &s->queue[i];
496         }
497     }
498     return NULL;
499 }
500 
501 /* Put instruction in queue.
502  * Return value:
503  * - zero - OK
504  * - non-zero - queue is full
505  */
506 
507 static int pl330_queue_put_insn(PL330Queue *s, uint32_t addr,
508                                 int len, int n, bool inc, bool z, uint8_t tag)
509 {
510     PL330QueueEntry *entry = pl330_queue_find_empty(s);
511 
512     if (!entry) {
513         return 1;
514     }
515     entry->tag = tag;
516     entry->addr = addr;
517     entry->len = len;
518     entry->n = n;
519     entry->z = z;
520     entry->inc = inc;
521     entry->seqn = s->parent->hi_seqn[tag];
522     s->parent->hi_seqn[tag]++;
523     return 0;
524 }
525 
526 /* Returns a pointer to queue slot containing instruction which satisfies
527  *  following conditions:
528  *   - it has valid tag value (not PL330_UNTAGGED)
529  *   - if enforce_seq is set it has to be issuable without violating queue
530  *     logic (see above)
531  *   - if TAG argument is not PL330_UNTAGGED this instruction has tag value
532  *     equivalent to the argument TAG value.
533  *  If such instruction cannot be found NULL is returned.
534  */
535 
536 static PL330QueueEntry *pl330_queue_find_insn(PL330Queue *s, uint8_t tag,
537                                               bool enforce_seq)
538 {
539     int i;
540 
541     for (i = 0; i < s->queue_size; i++) {
542         if (s->queue[i].tag != PL330_UNTAGGED) {
543             if ((!enforce_seq ||
544                     s->queue[i].seqn == s->parent->lo_seqn[s->queue[i].tag]) &&
545                     (s->queue[i].tag == tag || tag == PL330_UNTAGGED ||
546                     s->queue[i].z)) {
547                 return &s->queue[i];
548             }
549         }
550     }
551     return NULL;
552 }
553 
554 /* Removes instruction from queue. */
555 
556 static inline void pl330_queue_remove_insn(PL330Queue *s, PL330QueueEntry *e)
557 {
558     s->parent->lo_seqn[e->tag]++;
559     e->tag = PL330_UNTAGGED;
560 }
561 
562 /* Removes all instructions tagged with TAG from queue. */
563 
564 static inline void pl330_queue_remove_tagged(PL330Queue *s, uint8_t tag)
565 {
566     int i;
567 
568     for (i = 0; i < s->queue_size; i++) {
569         if (s->queue[i].tag == tag) {
570             s->queue[i].tag = PL330_UNTAGGED;
571         }
572     }
573 }
574 
575 /* DMA instruction execution engine */
576 
577 /* Moves DMA channel to the FAULT state and updates it's status. */
578 
579 static inline void pl330_fault(PL330Chan *ch, uint32_t flags)
580 {
581     DB_PRINT("ch: %p, flags: %" PRIx32 "\n", ch, flags);
582     ch->fault_type |= flags;
583     if (ch->state == pl330_chan_fault) {
584         return;
585     }
586     ch->state = pl330_chan_fault;
587     ch->parent->num_faulting++;
588     if (ch->parent->num_faulting == 1) {
589         DB_PRINT("abort interrupt raised\n");
590         qemu_irq_raise(ch->parent->irq_abort);
591     }
592 }
593 
594 /*
595  * For information about instructions see PL330 Technical Reference Manual.
596  *
597  * Arguments:
598  *   CH - channel executing the instruction
599  *   OPCODE - opcode
600  *   ARGS - array of 8-bit arguments
601  *   LEN - number of elements in ARGS array
602  */
603 
604 static void pl330_dmaadxh(PL330Chan *ch, uint8_t *args, bool ra, bool neg)
605 {
606     uint32_t im = (args[1] << 8) | args[0];
607     if (neg) {
608         im |= 0xffffu << 16;
609     }
610 
611     if (ch->is_manager) {
612         pl330_fault(ch, PL330_FAULT_UNDEF_INSTR);
613         return;
614     }
615     if (ra) {
616         ch->dst += im;
617     } else {
618         ch->src += im;
619     }
620 }
621 
622 static void pl330_dmaaddh(PL330Chan *ch, uint8_t opcode, uint8_t *args, int len)
623 {
624     pl330_dmaadxh(ch, args, extract32(opcode, 1, 1), false);
625 }
626 
627 static void pl330_dmaadnh(PL330Chan *ch, uint8_t opcode, uint8_t *args, int len)
628 {
629     pl330_dmaadxh(ch, args, extract32(opcode, 1, 1), true);
630 }
631 
632 static void pl330_dmaend(PL330Chan *ch, uint8_t opcode,
633                          uint8_t *args, int len)
634 {
635     PL330State *s = ch->parent;
636 
637     if (ch->state == pl330_chan_executing && !ch->is_manager) {
638         /* Wait for all transfers to complete */
639         if (pl330_fifo_has_tag(&s->fifo, ch->tag) ||
640             pl330_queue_find_insn(&s->read_queue, ch->tag, false) != NULL ||
641             pl330_queue_find_insn(&s->write_queue, ch->tag, false) != NULL) {
642 
643             ch->stall = 1;
644             return;
645         }
646     }
647     DB_PRINT("DMA ending!\n");
648     pl330_fifo_tagged_remove(&s->fifo, ch->tag);
649     pl330_queue_remove_tagged(&s->read_queue, ch->tag);
650     pl330_queue_remove_tagged(&s->write_queue, ch->tag);
651     ch->state = pl330_chan_stopped;
652 }
653 
654 static void pl330_dmaflushp(PL330Chan *ch, uint8_t opcode,
655                                             uint8_t *args, int len)
656 {
657     uint8_t periph_id;
658 
659     if (args[0] & 7) {
660         pl330_fault(ch, PL330_FAULT_OPERAND_INVALID);
661         return;
662     }
663     periph_id = (args[0] >> 3) & 0x1f;
664     if (periph_id >= ch->parent->num_periph_req) {
665         pl330_fault(ch, PL330_FAULT_OPERAND_INVALID);
666         return;
667     }
668     if (ch->ns && !(ch->parent->cfg[CFG_PNS] & (1 << periph_id))) {
669         pl330_fault(ch, PL330_FAULT_CH_PERIPH_ERR);
670         return;
671     }
672     /* Do nothing */
673 }
674 
675 static void pl330_dmago(PL330Chan *ch, uint8_t opcode, uint8_t *args, int len)
676 {
677     uint8_t chan_id;
678     uint8_t ns;
679     uint32_t pc;
680     PL330Chan *s;
681 
682     DB_PRINT("\n");
683 
684     if (!ch->is_manager) {
685         pl330_fault(ch, PL330_FAULT_UNDEF_INSTR);
686         return;
687     }
688     ns = !!(opcode & 2);
689     chan_id = args[0] & 7;
690     if ((args[0] >> 3)) {
691         pl330_fault(ch, PL330_FAULT_OPERAND_INVALID);
692         return;
693     }
694     if (chan_id >= ch->parent->num_chnls) {
695         pl330_fault(ch, PL330_FAULT_OPERAND_INVALID);
696         return;
697     }
698     pc = (((uint32_t)args[4]) << 24) | (((uint32_t)args[3]) << 16) |
699          (((uint32_t)args[2]) << 8)  | (((uint32_t)args[1]));
700     if (ch->parent->chan[chan_id].state != pl330_chan_stopped) {
701         pl330_fault(ch, PL330_FAULT_OPERAND_INVALID);
702         return;
703     }
704     if (ch->ns && !ns) {
705         pl330_fault(ch, PL330_FAULT_DMAGO_ERR);
706         return;
707     }
708     s = &ch->parent->chan[chan_id];
709     s->ns = ns;
710     s->pc = pc;
711     s->state = pl330_chan_executing;
712 }
713 
714 static void pl330_dmald(PL330Chan *ch, uint8_t opcode, uint8_t *args, int len)
715 {
716     uint8_t bs = opcode & 3;
717     uint32_t size, num;
718     bool inc;
719 
720     if (bs == 2) {
721         pl330_fault(ch, PL330_FAULT_OPERAND_INVALID);
722         return;
723     }
724     if ((bs == 1 && ch->request_flag == PL330_BURST) ||
725         (bs == 3 && ch->request_flag == PL330_SINGLE)) {
726         /* Perform NOP */
727         return;
728     }
729     if (bs == 1 && ch->request_flag == PL330_SINGLE) {
730         num = 1;
731     } else {
732         num = ((ch->control >> 4) & 0xf) + 1;
733     }
734     size = (uint32_t)1 << ((ch->control >> 1) & 0x7);
735     inc = !!(ch->control & 1);
736     ch->stall = pl330_queue_put_insn(&ch->parent->read_queue, ch->src,
737                                     size, num, inc, 0, ch->tag);
738     if (!ch->stall) {
739         DB_PRINT("channel:%" PRId8 " address:%08" PRIx32 " size:%" PRIx32
740                  " num:%" PRId32 " %c\n",
741                  ch->tag, ch->src, size, num, inc ? 'Y' : 'N');
742         ch->src += inc ? size * num - (ch->src & (size - 1)) : 0;
743     }
744 }
745 
746 static void pl330_dmaldp(PL330Chan *ch, uint8_t opcode, uint8_t *args, int len)
747 {
748     uint8_t periph_id;
749 
750     if (args[0] & 7) {
751         pl330_fault(ch, PL330_FAULT_OPERAND_INVALID);
752         return;
753     }
754     periph_id = (args[0] >> 3) & 0x1f;
755     if (periph_id >= ch->parent->num_periph_req) {
756         pl330_fault(ch, PL330_FAULT_OPERAND_INVALID);
757         return;
758     }
759     if (ch->ns && !(ch->parent->cfg[CFG_PNS] & (1 << periph_id))) {
760         pl330_fault(ch, PL330_FAULT_CH_PERIPH_ERR);
761         return;
762     }
763     pl330_dmald(ch, opcode, args, len);
764 }
765 
766 static void pl330_dmalp(PL330Chan *ch, uint8_t opcode, uint8_t *args, int len)
767 {
768     uint8_t lc = (opcode & 2) >> 1;
769 
770     ch->lc[lc] = args[0];
771 }
772 
773 static void pl330_dmakill(PL330Chan *ch, uint8_t opcode, uint8_t *args, int len)
774 {
775     if (ch->state == pl330_chan_fault ||
776         ch->state == pl330_chan_fault_completing) {
777         /* This is the only way for a channel to leave the faulting state */
778         ch->fault_type = 0;
779         ch->parent->num_faulting--;
780         if (ch->parent->num_faulting == 0) {
781             DB_PRINT("abort interrupt lowered\n");
782             qemu_irq_lower(ch->parent->irq_abort);
783         }
784     }
785     ch->state = pl330_chan_killing;
786     pl330_fifo_tagged_remove(&ch->parent->fifo, ch->tag);
787     pl330_queue_remove_tagged(&ch->parent->read_queue, ch->tag);
788     pl330_queue_remove_tagged(&ch->parent->write_queue, ch->tag);
789     ch->state = pl330_chan_stopped;
790 }
791 
792 static void pl330_dmalpend(PL330Chan *ch, uint8_t opcode,
793                                     uint8_t *args, int len)
794 {
795     uint8_t nf = (opcode & 0x10) >> 4;
796     uint8_t bs = opcode & 3;
797     uint8_t lc = (opcode & 4) >> 2;
798 
799     if (bs == 2) {
800         pl330_fault(ch, PL330_FAULT_OPERAND_INVALID);
801         return;
802     }
803     if ((bs == 1 && ch->request_flag == PL330_BURST) ||
804         (bs == 3 && ch->request_flag == PL330_SINGLE)) {
805         /* Perform NOP */
806         return;
807     }
808     if (!nf || ch->lc[lc]) {
809         if (nf) {
810             ch->lc[lc]--;
811         }
812         DB_PRINT("loop reiteration\n");
813         ch->pc -= args[0];
814         ch->pc -= len + 1;
815         /* "ch->pc -= args[0] + len + 1" is incorrect when args[0] == 256 */
816     } else {
817         DB_PRINT("loop fallthrough\n");
818     }
819 }
820 
821 
822 static void pl330_dmamov(PL330Chan *ch, uint8_t opcode, uint8_t *args, int len)
823 {
824     uint8_t rd = args[0] & 7;
825     uint32_t im;
826 
827     if ((args[0] >> 3)) {
828         pl330_fault(ch, PL330_FAULT_OPERAND_INVALID);
829         return;
830     }
831     im = (((uint32_t)args[4]) << 24) | (((uint32_t)args[3]) << 16) |
832          (((uint32_t)args[2]) << 8)  | (((uint32_t)args[1]));
833     switch (rd) {
834     case 0:
835         ch->src = im;
836         break;
837     case 1:
838         ch->control = im;
839         break;
840     case 2:
841         ch->dst = im;
842         break;
843     default:
844         pl330_fault(ch, PL330_FAULT_OPERAND_INVALID);
845         return;
846     }
847 }
848 
849 static void pl330_dmanop(PL330Chan *ch, uint8_t opcode,
850                          uint8_t *args, int len)
851 {
852     /* NOP is NOP. */
853 }
854 
855 static void pl330_dmarmb(PL330Chan *ch, uint8_t opcode, uint8_t *args, int len)
856 {
857    if (pl330_queue_find_insn(&ch->parent->read_queue, ch->tag, false)) {
858         ch->state = pl330_chan_at_barrier;
859         ch->stall = 1;
860         return;
861     } else {
862         ch->state = pl330_chan_executing;
863     }
864 }
865 
866 static void pl330_dmasev(PL330Chan *ch, uint8_t opcode, uint8_t *args, int len)
867 {
868     uint8_t ev_id;
869 
870     if (args[0] & 7) {
871         pl330_fault(ch, PL330_FAULT_OPERAND_INVALID);
872         return;
873     }
874     ev_id = (args[0] >> 3) & 0x1f;
875     if (ev_id >= ch->parent->num_events) {
876         pl330_fault(ch, PL330_FAULT_OPERAND_INVALID);
877         return;
878     }
879     if (ch->ns && !(ch->parent->cfg[CFG_INS] & (1 << ev_id))) {
880         pl330_fault(ch, PL330_FAULT_EVENT_ERR);
881         return;
882     }
883     if (ch->parent->inten & (1 << ev_id)) {
884         ch->parent->int_status |= (1 << ev_id);
885         DB_PRINT("event interrupt raised %" PRId8 "\n", ev_id);
886         qemu_irq_raise(ch->parent->irq[ev_id]);
887     }
888     DB_PRINT("event raised %" PRId8 "\n", ev_id);
889     ch->parent->ev_status |= (1 << ev_id);
890 }
891 
892 static void pl330_dmast(PL330Chan *ch, uint8_t opcode, uint8_t *args, int len)
893 {
894     uint8_t bs = opcode & 3;
895     uint32_t size, num;
896     bool inc;
897 
898     if (bs == 2) {
899         pl330_fault(ch, PL330_FAULT_OPERAND_INVALID);
900         return;
901     }
902     if ((bs == 1 && ch->request_flag == PL330_BURST) ||
903         (bs == 3 && ch->request_flag == PL330_SINGLE)) {
904         /* Perform NOP */
905         return;
906     }
907     num = ((ch->control >> 18) & 0xf) + 1;
908     size = (uint32_t)1 << ((ch->control >> 15) & 0x7);
909     inc = !!((ch->control >> 14) & 1);
910     ch->stall = pl330_queue_put_insn(&ch->parent->write_queue, ch->dst,
911                                     size, num, inc, 0, ch->tag);
912     if (!ch->stall) {
913         DB_PRINT("channel:%" PRId8 " address:%08" PRIx32 " size:%" PRIx32
914                  " num:%" PRId32 " %c\n",
915                  ch->tag, ch->dst, size, num, inc ? 'Y' : 'N');
916         ch->dst += inc ? size * num - (ch->dst & (size - 1)) : 0;
917     }
918 }
919 
920 static void pl330_dmastp(PL330Chan *ch, uint8_t opcode,
921                          uint8_t *args, int len)
922 {
923     uint8_t periph_id;
924 
925     if (args[0] & 7) {
926         pl330_fault(ch, PL330_FAULT_OPERAND_INVALID);
927         return;
928     }
929     periph_id = (args[0] >> 3) & 0x1f;
930     if (periph_id >= ch->parent->num_periph_req) {
931         pl330_fault(ch, PL330_FAULT_OPERAND_INVALID);
932         return;
933     }
934     if (ch->ns && !(ch->parent->cfg[CFG_PNS] & (1 << periph_id))) {
935         pl330_fault(ch, PL330_FAULT_CH_PERIPH_ERR);
936         return;
937     }
938     pl330_dmast(ch, opcode, args, len);
939 }
940 
941 static void pl330_dmastz(PL330Chan *ch, uint8_t opcode,
942                          uint8_t *args, int len)
943 {
944     uint32_t size, num;
945     bool inc;
946 
947     num = ((ch->control >> 18) & 0xf) + 1;
948     size = (uint32_t)1 << ((ch->control >> 15) & 0x7);
949     inc = !!((ch->control >> 14) & 1);
950     ch->stall = pl330_queue_put_insn(&ch->parent->write_queue, ch->dst,
951                                     size, num, inc, 1, ch->tag);
952     if (inc) {
953         ch->dst += size * num;
954     }
955 }
956 
957 static void pl330_dmawfe(PL330Chan *ch, uint8_t opcode,
958                          uint8_t *args, int len)
959 {
960     uint8_t ev_id;
961     int i;
962 
963     if (args[0] & 5) {
964         pl330_fault(ch, PL330_FAULT_OPERAND_INVALID);
965         return;
966     }
967     ev_id = (args[0] >> 3) & 0x1f;
968     if (ev_id >= ch->parent->num_events) {
969         pl330_fault(ch, PL330_FAULT_OPERAND_INVALID);
970         return;
971     }
972     if (ch->ns && !(ch->parent->cfg[CFG_INS] & (1 << ev_id))) {
973         pl330_fault(ch, PL330_FAULT_EVENT_ERR);
974         return;
975     }
976     ch->wakeup = ev_id;
977     ch->state = pl330_chan_waiting_event;
978     if (~ch->parent->inten & ch->parent->ev_status & 1 << ev_id) {
979         ch->state = pl330_chan_executing;
980         /* If anyone else is currently waiting on the same event, let them
981          * clear the ev_status so they pick up event as well
982          */
983         for (i = 0; i < ch->parent->num_chnls; ++i) {
984             PL330Chan *peer = &ch->parent->chan[i];
985             if (peer->state == pl330_chan_waiting_event &&
986                     peer->wakeup == ev_id) {
987                 return;
988             }
989         }
990         ch->parent->ev_status &= ~(1 << ev_id);
991         DB_PRINT("event lowered %" PRIx8 "\n", ev_id);
992     } else {
993         ch->stall = 1;
994     }
995 }
996 
997 static void pl330_dmawfp(PL330Chan *ch, uint8_t opcode,
998                          uint8_t *args, int len)
999 {
1000     uint8_t bs = opcode & 3;
1001     uint8_t periph_id;
1002 
1003     if (args[0] & 7) {
1004         pl330_fault(ch, PL330_FAULT_OPERAND_INVALID);
1005         return;
1006     }
1007     periph_id = (args[0] >> 3) & 0x1f;
1008     if (periph_id >= ch->parent->num_periph_req) {
1009         pl330_fault(ch, PL330_FAULT_OPERAND_INVALID);
1010         return;
1011     }
1012     if (ch->ns && !(ch->parent->cfg[CFG_PNS] & (1 << periph_id))) {
1013         pl330_fault(ch, PL330_FAULT_CH_PERIPH_ERR);
1014         return;
1015     }
1016     switch (bs) {
1017     case 0: /* S */
1018         ch->request_flag = PL330_SINGLE;
1019         ch->wfp_sbp = 0;
1020         break;
1021     case 1: /* P */
1022         ch->request_flag = PL330_BURST;
1023         ch->wfp_sbp = 2;
1024         break;
1025     case 2: /* B */
1026         ch->request_flag = PL330_BURST;
1027         ch->wfp_sbp = 1;
1028         break;
1029     default:
1030         pl330_fault(ch, PL330_FAULT_OPERAND_INVALID);
1031         return;
1032     }
1033 
1034     if (ch->parent->periph_busy[periph_id]) {
1035         ch->state = pl330_chan_waiting_periph;
1036         ch->stall = 1;
1037     } else if (ch->state == pl330_chan_waiting_periph) {
1038         ch->state = pl330_chan_executing;
1039     }
1040 }
1041 
1042 static void pl330_dmawmb(PL330Chan *ch, uint8_t opcode,
1043                          uint8_t *args, int len)
1044 {
1045     if (pl330_queue_find_insn(&ch->parent->write_queue, ch->tag, false)) {
1046         ch->state = pl330_chan_at_barrier;
1047         ch->stall = 1;
1048         return;
1049     } else {
1050         ch->state = pl330_chan_executing;
1051     }
1052 }
1053 
1054 /* NULL terminated array of the instruction descriptions. */
1055 static const PL330InsnDesc insn_desc[] = {
1056     { .opcode = 0x54, .opmask = 0xFD, .size = 3, .exec = pl330_dmaaddh, },
1057     { .opcode = 0x5c, .opmask = 0xFD, .size = 3, .exec = pl330_dmaadnh, },
1058     { .opcode = 0x00, .opmask = 0xFF, .size = 1, .exec = pl330_dmaend, },
1059     { .opcode = 0x35, .opmask = 0xFF, .size = 2, .exec = pl330_dmaflushp, },
1060     { .opcode = 0xA0, .opmask = 0xFD, .size = 6, .exec = pl330_dmago, },
1061     { .opcode = 0x04, .opmask = 0xFC, .size = 1, .exec = pl330_dmald, },
1062     { .opcode = 0x25, .opmask = 0xFD, .size = 2, .exec = pl330_dmaldp, },
1063     { .opcode = 0x20, .opmask = 0xFD, .size = 2, .exec = pl330_dmalp, },
1064     /* dmastp  must be before dmalpend in this list, because their maps
1065      * are overlapping
1066      */
1067     { .opcode = 0x29, .opmask = 0xFD, .size = 2, .exec = pl330_dmastp, },
1068     { .opcode = 0x28, .opmask = 0xE8, .size = 2, .exec = pl330_dmalpend, },
1069     { .opcode = 0x01, .opmask = 0xFF, .size = 1, .exec = pl330_dmakill, },
1070     { .opcode = 0xBC, .opmask = 0xFF, .size = 6, .exec = pl330_dmamov, },
1071     { .opcode = 0x18, .opmask = 0xFF, .size = 1, .exec = pl330_dmanop, },
1072     { .opcode = 0x12, .opmask = 0xFF, .size = 1, .exec = pl330_dmarmb, },
1073     { .opcode = 0x34, .opmask = 0xFF, .size = 2, .exec = pl330_dmasev, },
1074     { .opcode = 0x08, .opmask = 0xFC, .size = 1, .exec = pl330_dmast, },
1075     { .opcode = 0x0C, .opmask = 0xFF, .size = 1, .exec = pl330_dmastz, },
1076     { .opcode = 0x36, .opmask = 0xFF, .size = 2, .exec = pl330_dmawfe, },
1077     { .opcode = 0x30, .opmask = 0xFC, .size = 2, .exec = pl330_dmawfp, },
1078     { .opcode = 0x13, .opmask = 0xFF, .size = 1, .exec = pl330_dmawmb, },
1079     { .opcode = 0x00, .opmask = 0x00, .size = 0, .exec = NULL, }
1080 };
1081 
1082 /* Instructions which can be issued via debug registers. */
1083 static const PL330InsnDesc debug_insn_desc[] = {
1084     { .opcode = 0xA0, .opmask = 0xFD, .size = 6, .exec = pl330_dmago, },
1085     { .opcode = 0x01, .opmask = 0xFF, .size = 1, .exec = pl330_dmakill, },
1086     { .opcode = 0x34, .opmask = 0xFF, .size = 2, .exec = pl330_dmasev, },
1087     { .opcode = 0x00, .opmask = 0x00, .size = 0, .exec = NULL, }
1088 };
1089 
1090 static inline const PL330InsnDesc *pl330_fetch_insn(PL330Chan *ch)
1091 {
1092     uint8_t opcode;
1093     int i;
1094 
1095     dma_memory_read(&address_space_memory, ch->pc, &opcode, 1);
1096     for (i = 0; insn_desc[i].size; i++) {
1097         if ((opcode & insn_desc[i].opmask) == insn_desc[i].opcode) {
1098             return &insn_desc[i];
1099         }
1100     }
1101     return NULL;
1102 }
1103 
1104 static inline void pl330_exec_insn(PL330Chan *ch, const PL330InsnDesc *insn)
1105 {
1106     uint8_t buf[PL330_INSN_MAXSIZE];
1107 
1108     assert(insn->size <= PL330_INSN_MAXSIZE);
1109     dma_memory_read(&address_space_memory, ch->pc, buf, insn->size);
1110     insn->exec(ch, buf[0], &buf[1], insn->size - 1);
1111 }
1112 
1113 static inline void pl330_update_pc(PL330Chan *ch,
1114                                    const PL330InsnDesc *insn)
1115 {
1116     ch->pc += insn->size;
1117 }
1118 
1119 /* Try to execute current instruction in channel CH. Number of executed
1120    instructions is returned (0 or 1). */
1121 static int pl330_chan_exec(PL330Chan *ch)
1122 {
1123     const PL330InsnDesc *insn;
1124 
1125     if (ch->state != pl330_chan_executing &&
1126             ch->state != pl330_chan_waiting_periph &&
1127             ch->state != pl330_chan_at_barrier &&
1128             ch->state != pl330_chan_waiting_event) {
1129         return 0;
1130     }
1131     ch->stall = 0;
1132     insn = pl330_fetch_insn(ch);
1133     if (!insn) {
1134         DB_PRINT("pl330 undefined instruction\n");
1135         pl330_fault(ch, PL330_FAULT_UNDEF_INSTR);
1136         return 0;
1137     }
1138     pl330_exec_insn(ch, insn);
1139     if (!ch->stall) {
1140         pl330_update_pc(ch, insn);
1141         ch->watchdog_timer = 0;
1142         return 1;
1143     /* WDT only active in exec state */
1144     } else if (ch->state == pl330_chan_executing) {
1145         ch->watchdog_timer++;
1146         if (ch->watchdog_timer >= PL330_WATCHDOG_LIMIT) {
1147             pl330_fault(ch, PL330_FAULT_LOCKUP_ERR);
1148         }
1149     }
1150     return 0;
1151 }
1152 
1153 /* Try to execute 1 instruction in each channel, one instruction from read
1154    queue and one instruction from write queue. Number of successfully executed
1155    instructions is returned. */
1156 static int pl330_exec_cycle(PL330Chan *channel)
1157 {
1158     PL330State *s = channel->parent;
1159     PL330QueueEntry *q;
1160     int i;
1161     int num_exec = 0;
1162     int fifo_res = 0;
1163     uint8_t buf[PL330_MAX_BURST_LEN];
1164 
1165     /* Execute one instruction in each channel */
1166     num_exec += pl330_chan_exec(channel);
1167 
1168     /* Execute one instruction from read queue */
1169     q = pl330_queue_find_insn(&s->read_queue, PL330_UNTAGGED, true);
1170     if (q != NULL && q->len <= pl330_fifo_num_free(&s->fifo)) {
1171         int len = q->len - (q->addr & (q->len - 1));
1172 
1173         dma_memory_read(&address_space_memory, q->addr, buf, len);
1174         if (PL330_ERR_DEBUG > 1) {
1175             DB_PRINT("PL330 read from memory @%08" PRIx32 " (size = %08x):\n",
1176                       q->addr, len);
1177             qemu_hexdump((char *)buf, stderr, "", len);
1178         }
1179         fifo_res = pl330_fifo_push(&s->fifo, buf, len, q->tag);
1180         if (fifo_res == PL330_FIFO_OK) {
1181             if (q->inc) {
1182                 q->addr += len;
1183             }
1184             q->n--;
1185             if (!q->n) {
1186                 pl330_queue_remove_insn(&s->read_queue, q);
1187             }
1188             num_exec++;
1189         }
1190     }
1191 
1192     /* Execute one instruction from write queue. */
1193     q = pl330_queue_find_insn(&s->write_queue, pl330_fifo_tag(&s->fifo), true);
1194     if (q != NULL) {
1195         int len = q->len - (q->addr & (q->len - 1));
1196 
1197         if (q->z) {
1198             for (i = 0; i < len; i++) {
1199                 buf[i] = 0;
1200             }
1201         } else {
1202             fifo_res = pl330_fifo_get(&s->fifo, buf, len, q->tag);
1203         }
1204         if (fifo_res == PL330_FIFO_OK || q->z) {
1205             dma_memory_write(&address_space_memory, q->addr, buf, len);
1206             if (PL330_ERR_DEBUG > 1) {
1207                 DB_PRINT("PL330 read from memory @%08" PRIx32
1208                          " (size = %08x):\n", q->addr, len);
1209                 qemu_hexdump((char *)buf, stderr, "", len);
1210             }
1211             if (q->inc) {
1212                 q->addr += len;
1213             }
1214             num_exec++;
1215         } else if (fifo_res == PL330_FIFO_STALL) {
1216             pl330_fault(&channel->parent->chan[q->tag],
1217                                 PL330_FAULT_FIFOEMPTY_ERR);
1218         }
1219         q->n--;
1220         if (!q->n) {
1221             pl330_queue_remove_insn(&s->write_queue, q);
1222         }
1223     }
1224 
1225     return num_exec;
1226 }
1227 
1228 static int pl330_exec_channel(PL330Chan *channel)
1229 {
1230     int insr_exec = 0;
1231 
1232     /* TODO: Is it all right to execute everything or should we do per-cycle
1233        simulation? */
1234     while (pl330_exec_cycle(channel)) {
1235         insr_exec++;
1236     }
1237 
1238     /* Detect deadlock */
1239     if (channel->state == pl330_chan_executing) {
1240         pl330_fault(channel, PL330_FAULT_LOCKUP_ERR);
1241     }
1242     /* Situation when one of the queues has deadlocked but all channels
1243      * have finished their programs should be impossible.
1244      */
1245 
1246     return insr_exec;
1247 }
1248 
1249 static inline void pl330_exec(PL330State *s)
1250 {
1251     DB_PRINT("\n");
1252     int i, insr_exec;
1253     do {
1254         insr_exec = pl330_exec_channel(&s->manager);
1255 
1256         for (i = 0; i < s->num_chnls; i++) {
1257             insr_exec += pl330_exec_channel(&s->chan[i]);
1258         }
1259     } while (insr_exec);
1260 }
1261 
1262 static void pl330_exec_cycle_timer(void *opaque)
1263 {
1264     PL330State *s = (PL330State *)opaque;
1265     pl330_exec(s);
1266 }
1267 
1268 /* Stop or restore dma operations */
1269 
1270 static void pl330_dma_stop_irq(void *opaque, int irq, int level)
1271 {
1272     PL330State *s = (PL330State *)opaque;
1273 
1274     if (s->periph_busy[irq] != level) {
1275         s->periph_busy[irq] = level;
1276         timer_mod(s->timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL));
1277     }
1278 }
1279 
1280 static void pl330_debug_exec(PL330State *s)
1281 {
1282     uint8_t args[5];
1283     uint8_t opcode;
1284     uint8_t chan_id;
1285     int i;
1286     PL330Chan *ch;
1287     const PL330InsnDesc *insn;
1288 
1289     s->debug_status = 1;
1290     chan_id = (s->dbg[0] >>  8) & 0x07;
1291     opcode  = (s->dbg[0] >> 16) & 0xff;
1292     args[0] = (s->dbg[0] >> 24) & 0xff;
1293     args[1] = (s->dbg[1] >>  0) & 0xff;
1294     args[2] = (s->dbg[1] >>  8) & 0xff;
1295     args[3] = (s->dbg[1] >> 16) & 0xff;
1296     args[4] = (s->dbg[1] >> 24) & 0xff;
1297     DB_PRINT("chan id: %" PRIx8 "\n", chan_id);
1298     if (s->dbg[0] & 1) {
1299         ch = &s->chan[chan_id];
1300     } else {
1301         ch = &s->manager;
1302     }
1303     insn = NULL;
1304     for (i = 0; debug_insn_desc[i].size; i++) {
1305         if ((opcode & debug_insn_desc[i].opmask) == debug_insn_desc[i].opcode) {
1306             insn = &debug_insn_desc[i];
1307         }
1308     }
1309     if (!insn) {
1310         pl330_fault(ch, PL330_FAULT_UNDEF_INSTR | PL330_FAULT_DBG_INSTR);
1311         return ;
1312     }
1313     ch->stall = 0;
1314     insn->exec(ch, opcode, args, insn->size - 1);
1315     if (ch->fault_type) {
1316         ch->fault_type |= PL330_FAULT_DBG_INSTR;
1317     }
1318     if (ch->stall) {
1319         qemu_log_mask(LOG_UNIMP, "pl330: stall of debug instruction not "
1320                       "implemented\n");
1321     }
1322     s->debug_status = 0;
1323 }
1324 
1325 /* IOMEM mapped registers */
1326 
1327 static void pl330_iomem_write(void *opaque, hwaddr offset,
1328                               uint64_t value, unsigned size)
1329 {
1330     PL330State *s = (PL330State *) opaque;
1331     int i;
1332 
1333     DB_PRINT("addr: %08x data: %08x\n", (unsigned)offset, (unsigned)value);
1334 
1335     switch (offset) {
1336     case PL330_REG_INTEN:
1337         s->inten = value;
1338         break;
1339     case PL330_REG_INTCLR:
1340         for (i = 0; i < s->num_events; i++) {
1341             if (s->int_status & s->inten & value & (1 << i)) {
1342                 DB_PRINT("event interrupt lowered %d\n", i);
1343                 qemu_irq_lower(s->irq[i]);
1344             }
1345         }
1346         s->ev_status &= ~(value & s->inten);
1347         s->int_status &= ~(value & s->inten);
1348         break;
1349     case PL330_REG_DBGCMD:
1350         if ((value & 3) == 0) {
1351             pl330_debug_exec(s);
1352             pl330_exec(s);
1353         } else {
1354             qemu_log_mask(LOG_GUEST_ERROR, "pl330: write of illegal value %u "
1355                           "for offset " TARGET_FMT_plx "\n", (unsigned)value,
1356                           offset);
1357         }
1358         break;
1359     case PL330_REG_DBGINST0:
1360         DB_PRINT("s->dbg[0] = %08x\n", (unsigned)value);
1361         s->dbg[0] = value;
1362         break;
1363     case PL330_REG_DBGINST1:
1364         DB_PRINT("s->dbg[1] = %08x\n", (unsigned)value);
1365         s->dbg[1] = value;
1366         break;
1367     default:
1368         qemu_log_mask(LOG_GUEST_ERROR, "pl330: bad write offset " TARGET_FMT_plx
1369                       "\n", offset);
1370         break;
1371     }
1372 }
1373 
1374 static inline uint32_t pl330_iomem_read_imp(void *opaque,
1375         hwaddr offset)
1376 {
1377     PL330State *s = (PL330State *)opaque;
1378     int chan_id;
1379     int i;
1380     uint32_t res;
1381 
1382     if (offset >= PL330_REG_PERIPH_ID && offset < PL330_REG_PERIPH_ID + 32) {
1383         return pl330_id[(offset - PL330_REG_PERIPH_ID) >> 2];
1384     }
1385     if (offset >= PL330_REG_CR0_BASE && offset < PL330_REG_CR0_BASE + 24) {
1386         return s->cfg[(offset - PL330_REG_CR0_BASE) >> 2];
1387     }
1388     if (offset >= PL330_REG_CHANCTRL && offset < PL330_REG_DBGSTATUS) {
1389         offset -= PL330_REG_CHANCTRL;
1390         chan_id = offset >> 5;
1391         if (chan_id >= s->num_chnls) {
1392             qemu_log_mask(LOG_GUEST_ERROR, "pl330: bad read offset "
1393                           TARGET_FMT_plx "\n", offset);
1394             return 0;
1395         }
1396         switch (offset & 0x1f) {
1397         case 0x00:
1398             return s->chan[chan_id].src;
1399         case 0x04:
1400             return s->chan[chan_id].dst;
1401         case 0x08:
1402             return s->chan[chan_id].control;
1403         case 0x0C:
1404             return s->chan[chan_id].lc[0];
1405         case 0x10:
1406             return s->chan[chan_id].lc[1];
1407         default:
1408             qemu_log_mask(LOG_GUEST_ERROR, "pl330: bad read offset "
1409                           TARGET_FMT_plx "\n", offset);
1410             return 0;
1411         }
1412     }
1413     if (offset >= PL330_REG_CSR_BASE && offset < 0x400) {
1414         offset -= PL330_REG_CSR_BASE;
1415         chan_id = offset >> 3;
1416         if (chan_id >= s->num_chnls) {
1417             qemu_log_mask(LOG_GUEST_ERROR, "pl330: bad read offset "
1418                           TARGET_FMT_plx "\n", offset);
1419             return 0;
1420         }
1421         switch ((offset >> 2) & 1) {
1422         case 0x0:
1423             res = (s->chan[chan_id].ns << 21) |
1424                     (s->chan[chan_id].wakeup << 4) |
1425                     (s->chan[chan_id].state) |
1426                     (s->chan[chan_id].wfp_sbp << 14);
1427             return res;
1428         case 0x1:
1429             return s->chan[chan_id].pc;
1430         default:
1431             qemu_log_mask(LOG_GUEST_ERROR, "pl330: read error\n");
1432             return 0;
1433         }
1434     }
1435     if (offset >= PL330_REG_FTR_BASE && offset < 0x100) {
1436         offset -= PL330_REG_FTR_BASE;
1437         chan_id = offset >> 2;
1438         if (chan_id >= s->num_chnls) {
1439             qemu_log_mask(LOG_GUEST_ERROR, "pl330: bad read offset "
1440                           TARGET_FMT_plx "\n", offset);
1441             return 0;
1442         }
1443         return s->chan[chan_id].fault_type;
1444     }
1445     switch (offset) {
1446     case PL330_REG_DSR:
1447         return (s->manager.ns << 9) | (s->manager.wakeup << 4) |
1448             (s->manager.state & 0xf);
1449     case PL330_REG_DPC:
1450         return s->manager.pc;
1451     case PL330_REG_INTEN:
1452         return s->inten;
1453     case PL330_REG_INT_EVENT_RIS:
1454         return s->ev_status;
1455     case PL330_REG_INTMIS:
1456         return s->int_status;
1457     case PL330_REG_INTCLR:
1458         /* Documentation says that we can't read this register
1459          * but linux kernel does it
1460          */
1461         return 0;
1462     case PL330_REG_FSRD:
1463         return s->manager.state ? 1 : 0;
1464     case PL330_REG_FSRC:
1465         res = 0;
1466         for (i = 0; i < s->num_chnls; i++) {
1467             if (s->chan[i].state == pl330_chan_fault ||
1468                 s->chan[i].state == pl330_chan_fault_completing) {
1469                 res |= 1 << i;
1470             }
1471         }
1472         return res;
1473     case PL330_REG_FTRD:
1474         return s->manager.fault_type;
1475     case PL330_REG_DBGSTATUS:
1476         return s->debug_status;
1477     default:
1478         qemu_log_mask(LOG_GUEST_ERROR, "pl330: bad read offset "
1479                       TARGET_FMT_plx "\n", offset);
1480     }
1481     return 0;
1482 }
1483 
1484 static uint64_t pl330_iomem_read(void *opaque, hwaddr offset,
1485         unsigned size)
1486 {
1487     uint32_t ret = pl330_iomem_read_imp(opaque, offset);
1488     DB_PRINT("addr: %08" HWADDR_PRIx " data: %08" PRIx32 "\n", offset, ret);
1489     return ret;
1490 }
1491 
1492 static const MemoryRegionOps pl330_ops = {
1493     .read = pl330_iomem_read,
1494     .write = pl330_iomem_write,
1495     .endianness = DEVICE_NATIVE_ENDIAN,
1496     .impl = {
1497         .min_access_size = 4,
1498         .max_access_size = 4,
1499     }
1500 };
1501 
1502 /* Controller logic and initialization */
1503 
1504 static void pl330_chan_reset(PL330Chan *ch)
1505 {
1506     ch->src = 0;
1507     ch->dst = 0;
1508     ch->pc = 0;
1509     ch->state = pl330_chan_stopped;
1510     ch->watchdog_timer = 0;
1511     ch->stall = 0;
1512     ch->control = 0;
1513     ch->status = 0;
1514     ch->fault_type = 0;
1515 }
1516 
1517 static void pl330_reset(DeviceState *d)
1518 {
1519     int i;
1520     PL330State *s = PL330(d);
1521 
1522     s->inten = 0;
1523     s->int_status = 0;
1524     s->ev_status = 0;
1525     s->debug_status = 0;
1526     s->num_faulting = 0;
1527     s->manager.ns = s->mgr_ns_at_rst;
1528     pl330_fifo_reset(&s->fifo);
1529     pl330_queue_reset(&s->read_queue);
1530     pl330_queue_reset(&s->write_queue);
1531 
1532     for (i = 0; i < s->num_chnls; i++) {
1533         pl330_chan_reset(&s->chan[i]);
1534     }
1535     for (i = 0; i < s->num_periph_req; i++) {
1536         s->periph_busy[i] = 0;
1537     }
1538 
1539     timer_del(s->timer);
1540 }
1541 
1542 static void pl330_realize(DeviceState *dev, Error **errp)
1543 {
1544     int i;
1545     PL330State *s = PL330(dev);
1546 
1547     sysbus_init_irq(SYS_BUS_DEVICE(dev), &s->irq_abort);
1548     memory_region_init_io(&s->iomem, OBJECT(s), &pl330_ops, s,
1549                           "dma", PL330_IOMEM_SIZE);
1550     sysbus_init_mmio(SYS_BUS_DEVICE(dev), &s->iomem);
1551 
1552     s->timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, pl330_exec_cycle_timer, s);
1553 
1554     s->cfg[0] = (s->mgr_ns_at_rst ? 0x4 : 0) |
1555                 (s->num_periph_req > 0 ? 1 : 0) |
1556                 ((s->num_chnls - 1) & 0x7) << 4 |
1557                 ((s->num_periph_req - 1) & 0x1f) << 12 |
1558                 ((s->num_events - 1) & 0x1f) << 17;
1559 
1560     switch (s->i_cache_len) {
1561     case (4):
1562         s->cfg[1] |= 2;
1563         break;
1564     case (8):
1565         s->cfg[1] |= 3;
1566         break;
1567     case (16):
1568         s->cfg[1] |= 4;
1569         break;
1570     case (32):
1571         s->cfg[1] |= 5;
1572         break;
1573     default:
1574         error_setg(errp, "Bad value for i-cache_len property: %" PRIx8,
1575                    s->i_cache_len);
1576         return;
1577     }
1578     s->cfg[1] |= ((s->num_i_cache_lines - 1) & 0xf) << 4;
1579 
1580     s->chan = g_new0(PL330Chan, s->num_chnls);
1581     s->hi_seqn = g_new0(uint8_t, s->num_chnls);
1582     s->lo_seqn = g_new0(uint8_t, s->num_chnls);
1583     for (i = 0; i < s->num_chnls; i++) {
1584         s->chan[i].parent = s;
1585         s->chan[i].tag = (uint8_t)i;
1586     }
1587     s->manager.parent = s;
1588     s->manager.tag = s->num_chnls;
1589     s->manager.is_manager = true;
1590 
1591     s->irq = g_new0(qemu_irq, s->num_events);
1592     for (i = 0; i < s->num_events; i++) {
1593         sysbus_init_irq(SYS_BUS_DEVICE(dev), &s->irq[i]);
1594     }
1595 
1596     qdev_init_gpio_in(dev, pl330_dma_stop_irq, PL330_PERIPH_NUM);
1597 
1598     switch (s->data_width) {
1599     case (32):
1600         s->cfg[CFG_CRD] |= 0x2;
1601         break;
1602     case (64):
1603         s->cfg[CFG_CRD] |= 0x3;
1604         break;
1605     case (128):
1606         s->cfg[CFG_CRD] |= 0x4;
1607         break;
1608     default:
1609         error_setg(errp, "Bad value for data_width property: %" PRIx8,
1610                    s->data_width);
1611         return;
1612     }
1613 
1614     s->cfg[CFG_CRD] |= ((s->wr_cap - 1) & 0x7) << 4 |
1615                     ((s->wr_q_dep - 1) & 0xf) << 8 |
1616                     ((s->rd_cap - 1) & 0x7) << 12 |
1617                     ((s->rd_q_dep - 1) & 0xf) << 16 |
1618                     ((s->data_buffer_dep - 1) & 0x1ff) << 20;
1619 
1620     pl330_queue_init(&s->read_queue, s->rd_q_dep, s);
1621     pl330_queue_init(&s->write_queue, s->wr_q_dep, s);
1622     pl330_fifo_init(&s->fifo, s->data_width / 4 * s->data_buffer_dep);
1623 }
1624 
1625 static Property pl330_properties[] = {
1626     /* CR0 */
1627     DEFINE_PROP_UINT32("num_chnls", PL330State, num_chnls, 8),
1628     DEFINE_PROP_UINT8("num_periph_req", PL330State, num_periph_req, 4),
1629     DEFINE_PROP_UINT8("num_events", PL330State, num_events, 16),
1630     DEFINE_PROP_UINT8("mgr_ns_at_rst", PL330State, mgr_ns_at_rst, 0),
1631     /* CR1 */
1632     DEFINE_PROP_UINT8("i-cache_len", PL330State, i_cache_len, 4),
1633     DEFINE_PROP_UINT8("num_i-cache_lines", PL330State, num_i_cache_lines, 8),
1634     /* CR2-4 */
1635     DEFINE_PROP_UINT32("boot_addr", PL330State, cfg[CFG_BOOT_ADDR], 0),
1636     DEFINE_PROP_UINT32("INS", PL330State, cfg[CFG_INS], 0),
1637     DEFINE_PROP_UINT32("PNS", PL330State, cfg[CFG_PNS], 0),
1638     /* CRD */
1639     DEFINE_PROP_UINT8("data_width", PL330State, data_width, 64),
1640     DEFINE_PROP_UINT8("wr_cap", PL330State, wr_cap, 8),
1641     DEFINE_PROP_UINT8("wr_q_dep", PL330State, wr_q_dep, 16),
1642     DEFINE_PROP_UINT8("rd_cap", PL330State, rd_cap, 8),
1643     DEFINE_PROP_UINT8("rd_q_dep", PL330State, rd_q_dep, 16),
1644     DEFINE_PROP_UINT16("data_buffer_dep", PL330State, data_buffer_dep, 256),
1645 
1646     DEFINE_PROP_END_OF_LIST(),
1647 };
1648 
1649 static void pl330_class_init(ObjectClass *klass, void *data)
1650 {
1651     DeviceClass *dc = DEVICE_CLASS(klass);
1652 
1653     dc->realize = pl330_realize;
1654     dc->reset = pl330_reset;
1655     dc->props = pl330_properties;
1656     dc->vmsd = &vmstate_pl330;
1657 }
1658 
1659 static const TypeInfo pl330_type_info = {
1660     .name           = TYPE_PL330,
1661     .parent         = TYPE_SYS_BUS_DEVICE,
1662     .instance_size  = sizeof(PL330State),
1663     .class_init      = pl330_class_init,
1664 };
1665 
1666 static void pl330_register_types(void)
1667 {
1668     type_register_static(&pl330_type_info);
1669 }
1670 
1671 type_init(pl330_register_types)
1672