4 Copyright 2008, 2009 Michel Pollet <buserror@gmail.com>
6 This file is part of simavr.
8 simavr is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
13 simavr is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with simavr. If not, see <http://www.gnu.org/licenses/>.
26 #include "sim_interrupts.h"
29 void avr_register_vector(avr_t *avr, avr_int_vector_t * vector)
32 avr->vector[vector->vector] = vector;
35 int avr_has_pending_interrupts(avr_t * avr)
37 return avr->pending[0] || avr->pending[1];
40 int avr_is_interrupt_pending(avr_t * avr, avr_int_vector_t * vector)
42 return avr->pending[vector->vector >> 5] & (1 << (vector->vector & 0x1f));
45 int avr_raise_interrupt(avr_t * avr, avr_int_vector_t * vector)
47 if (!vector || !vector->vector)
49 // printf("%s raising %d\n", __FUNCTION__, vector->vector);
50 // always mark the 'raised' flag to one, even if the interuot is disabled
51 // this allow "pooling" for the "raised" flag, like for non-interrupt
52 // driven UART and so so. These flags are often "write one to clear"
53 if (vector->raised.reg)
54 avr_regbit_set(avr, vector->raised);
55 if (vector->enable.reg) {
56 if (!avr_regbit_get(avr, vector->enable))
59 if (!avr_is_interrupt_pending(avr, vector)) {
60 if (!avr->pending_wait)
61 avr->pending_wait = 2; // latency on interrupts ??
62 avr->pending[vector->vector >> 5] |= (1 << (vector->vector & 0x1f));
64 if (avr->state != cpu_Running) {
65 // printf("Waking CPU due to interrupt\n");
66 avr->state = cpu_Running; // in case we were sleeping
69 // return 'raised' even if it was already pending
73 void avr_clear_interrupt(avr_t * avr, int v)
75 avr_int_vector_t * vector = avr->vector[v];
76 avr->pending[v >> 5] &= ~(1 << (v & 0x1f));
79 printf("%s cleared %d\n", __FUNCTION__, vector->vector);
80 if (vector->raised.reg)
81 avr_regbit_clear(avr, vector->raised);
85 * check wether interrupts are pending. I so, check if the interrupt "latency" is reached,
86 * and if so triggers the handlers and jump to the vector.
88 void avr_service_interrupts(avr_t * avr)
93 if (avr_has_pending_interrupts(avr)) {
94 if (avr->pending_wait) {
96 if (avr->pending_wait == 0) {
98 for (int bi = 0; bi < 2 && !done; bi++) if (avr->pending[bi]) {
99 for (int ii = 0; ii < 32 && !done; ii++)
100 if (avr->pending[bi] & (1 << ii)) {
102 int v = (bi * 32) + ii; // vector
104 // printf("%s calling %d\n", __FUNCTION__, v);
105 _avr_push16(avr, avr->pc >> 1);
107 avr->pc = v * avr->vector_size;
109 avr_clear_interrupt(avr, v);
117 avr->pending_wait = 2; // for next one...