b2d935acdf50f355a4efaff33c50ff4e97ba1d30
[simavr] / simavr / sim / sim_avr.h
1 /*
2         sim_avr.h
3
4         Copyright 2008-2012 Michel Pollet <buserror@gmail.com>
5
6         This file is part of simavr.
7
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.
12
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.
17
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/>.
20  */
21
22 #ifndef __SIM_AVR_H__
23 #define __SIM_AVR_H__
24
25 #ifdef __cplusplus
26 extern "C" {
27 #endif
28
29 #include "sim_irq.h"
30 #include "sim_interrupts.h"
31 #include "sim_cycle_timers.h"
32
33 typedef uint32_t avr_flashaddr_t;
34
35 struct avr_t;
36 typedef uint8_t (*avr_io_read_t)(
37                 struct avr_t * avr,
38                 avr_io_addr_t addr,
39                 void * param);
40 typedef void (*avr_io_write_t)(
41                 struct avr_t * avr,
42                 avr_io_addr_t addr,
43                 uint8_t v,
44                 void * param);
45
46 enum {
47         // SREG bit indexes
48         S_C = 0,S_Z,S_N,S_V,S_S,S_H,S_T,S_I,
49
50         // 16 bits register pairs
51         R_XL    = 0x1a, R_XH,R_YL,R_YH,R_ZL,R_ZH,
52         // stack pointer
53         R_SPL   = 32+0x3d, R_SPH,
54         // real SREG
55         R_SREG  = 32+0x3f,
56
57         // maximum number of IO registers, on normal AVRs
58         MAX_IOs = 279,  // Bigger AVRs need more than 256-32 (mega1280)
59 };
60
61 #define AVR_DATA_TO_IO(v) ((v) - 32)
62 #define AVR_IO_TO_DATA(v) ((v) + 32)
63
64 /**
65  * Logging macros and associated log levels.
66  * The current log level is kept in avr->log.
67  */
68 enum {
69         LOG_ERROR = 1,
70         LOG_WARNING,
71         LOG_TRACE,
72 };
73 typedef void (*logger_t)(const int level, const char * format, ... );
74 extern logger_t global_logger;
75 #ifndef AVR_LOG
76 #define AVR_LOG(avr, level, ...) \
77         do { \
78                 if (!avr || avr->log >= level) \
79                         global_logger( level, __VA_ARGS__); \
80         } while(0)
81 #endif
82
83 /*
84  * Core states.
85  */
86 enum {
87         cpu_Limbo = 0,  // before initialization is finished
88         cpu_Stopped,    // all is stopped, timers included
89
90         cpu_Running,    // we're free running
91
92         cpu_Sleeping,   // we're now sleeping until an interrupt
93
94         cpu_Step,               // run ONE instruction, then...
95         cpu_StepDone,   // tell gdb it's all OK, and give it registers
96         cpu_Done,       // avr software stopped gracefully
97         cpu_Crashed,    // avr software crashed (watchdog fired)
98 };
99
100 // this is only ever used if CONFIG_SIMAVR_TRACE is defined
101 struct avr_trace_data_t {
102         struct avr_symbol_t ** codeline;
103
104         /* DEBUG ONLY
105          * this keeps track of "jumps" ie, call,jmp,ret,reti and so on
106          * allows dumping of a meaningful data even if the stack is
107          * munched and so on
108          */
109         #define OLD_PC_SIZE     32
110         struct {
111                 uint32_t pc;
112                 uint16_t sp;
113         } old[OLD_PC_SIZE]; // catches reset..
114         int                     old_pci;
115
116 #if AVR_STACK_WATCH
117         #define STACK_FRAME_SIZE        32
118         // this records the call/ret pairs, to try to catch
119         // code that munches the stack -under- their own frame
120         struct {
121                 uint32_t        pc;
122                 uint16_t        sp;             
123         } stack_frame[STACK_FRAME_SIZE];
124         int                     stack_frame_index;
125 #endif
126
127         // DEBUG ONLY
128         // keeps track of which registers gets touched by instructions
129         // reset before each new instructions. Allows meaningful traces
130         uint32_t        touched[256 / 32];      // debug
131 };
132
133 /*
134  * Main AVR instance. Some of these fields are set by the AVR "Core" definition files
135  * the rest is runtime data (as little as possible)
136  */
137 typedef struct avr_t {
138         const char * mmcu;      // name of the AVR
139         // these are filled by sim_core_declare from constants in /usr/lib/avr/include/avr/io*.h
140         uint16_t        ramend;         
141         uint32_t        flashend;
142         uint32_t        e2end;
143         uint8_t         vector_size;
144         uint8_t         signature[3];
145         uint8_t         fuse[4];
146         avr_io_addr_t   rampz;  // optional, only for ELPM/SPM on >64Kb cores
147         avr_io_addr_t   eind;   // optional, only for EIJMP/EICALL on >64Kb cores
148
149         // filled by the ELF data, this allow tracking of invalid jumps
150         uint32_t                        codeend;
151
152         int                                     state;          // stopped, running, sleeping
153         uint32_t                        frequency;      // frequency we are running at
154         // mostly used by the ADC for now
155         uint32_t                        vcc,avcc,aref; // (optional) voltages in millivolts
156
157         // cycles gets incremented when sleeping and when running; it corresponds
158         // not only to "cycles that runs" but also "cycles that might have run"
159         // like, sleeping.
160         avr_cycle_count_t       cycle;          // current cycle
161
162         /**
163          * Sleep requests are accumulated in sleep_usec until the minimum sleep value
164          * is reached, at which point sleep_usec is cleared and the sleep request
165          * is passed on to the operating system.
166          */
167         uint32_t sleep_usec;
168         
169         // called at init time
170         void (*init)(struct avr_t * avr);
171         // called at init time (for special purposes like using a memory mapped file as flash see: simduino)
172         void (*special_init)(struct avr_t * avr);
173         // called at termination time ( to clean special initializations)
174         void (*special_deinit)(struct avr_t * avr);
175         // called at reset time
176         void (*reset)(struct avr_t * avr);
177
178         /*!
179          * Default AVR core run function.
180          * Two modes are available, a "raw" run that goes as fast as
181          * it can, and a "gdb" mode that also watchouts for gdb events
182          * and is a little bit slower.
183          */
184         void (*run)(struct avr_t * avr);
185
186         /*!
187          * Sleep default behaviour.
188          * In "raw" mode, it calls usleep, in gdb mode, it waits
189          * for howLong for gdb command on it's sockets.
190          */
191         void (*sleep)(struct avr_t * avr, avr_cycle_count_t howLong);
192
193         /*!
194          * Every IRQs will be stored in this pool. It is not
195          * mandatory (yet) but will allow listing IRQs and their connections
196          */
197         avr_irq_pool_t  irq_pool;
198
199         // Mirror of the SREG register, to facilitate the access to bits
200         // in the opcode decoder.
201         // This array is re-synthesized back/forth when SREG changes
202         uint8_t         sreg[8];
203         uint8_t         i_shadow;       // used to detect edges on I flag
204
205         /* 
206          * ** current PC **
207          * Note that the PC is representing /bytes/ while the AVR value is
208          * assumed to be "words". This is in line with what GDB does...
209          * this is why you will see >>1 and <<1 in the decoder to handle jumps.
210          * It CAN be a little confusing, so concentrate, young grasshopper.
211          */
212         avr_flashaddr_t pc;
213
214         /*
215          * callback when specific IO registers are read/written.
216          * There is one drawback here, there is in way of knowing what is the
217          * "beginning of useful sram" on a core, so there is no way to deduce
218          * what is the maximum IO register for a core, and thus, we can't
219          * allocate this table dynamically.
220          * If you wanted to emulate the BIG AVRs, and XMegas, this would need
221          * work.
222          */
223         struct {
224                 struct avr_irq_t * irq; // optional, used only if asked for with avr_iomem_getirq()
225                 struct {
226                         void * param;
227                         avr_io_read_t c;
228                 } r;
229                 struct {
230                         void * param;
231                         avr_io_write_t c;
232                 } w;
233         } io[MAX_IOs];
234
235         /*
236          * This block allows sharing of the IO write/read on addresses between
237          * multiple callbacks. In 99% of case it's not needed, however on the tiny*
238          * (tiny85 at last) some registers have bits that are used by different
239          * IO modules.
240          * If this case is detected, a special "dispatch" callback is installed that
241          * will handle this particular case, without impacting the performance of the
242          * other, normal cases...
243          */
244         int     io_shared_io_count;
245         struct {
246                 int used;
247                 struct {
248                         void * param;
249                         void * c;
250                 } io[4];
251         } io_shared_io[4];
252
253         // flash memory (initialized to 0xff, and code loaded into it)
254         uint8_t *       flash;
255         // this is the general purpose registers, IO registers, and SRAM
256         uint8_t *       data;
257
258         // queue of io modules
259         struct avr_io_t *io_port;
260
261         // cycle timers tracking & delivery
262         avr_cycle_timer_pool_t  cycle_timers;
263         // interrupt vectors and delivery fifo
264         avr_int_table_t interrupts;
265
266         // DEBUG ONLY -- value ignored if CONFIG_SIMAVR_TRACE = 0
267         uint8_t trace : 1,
268                         log : 2; // log level, default to 1
269
270         // Only used if CONFIG_SIMAVR_TRACE is defined
271         struct avr_trace_data_t *trace_data;
272
273         // VALUE CHANGE DUMP file (waveforms)
274         // this is the VCD file that gets allocated if the 
275         // firmware that is loaded explicitly asks for a trace
276         // to be generated, and allocates it's own symbols
277         // using AVR_MMCU_TAG_VCD_TRACE (see avr_mcu_section.h)
278         struct avr_vcd_t * vcd;
279         
280         // gdb hooking structure. Only present when gdb server is active
281         struct avr_gdb_t * gdb;
282
283         // if non-zero, the gdb server will be started when the core
284         // crashed even if not activated at startup
285         // if zero, the simulator will just exit() in case of a crash
286         int             gdb_port;
287 } avr_t;
288
289
290 // this is a static constructor for each of the AVR devices
291 typedef struct avr_kind_t {
292         const char * names[4];  // name aliases
293         avr_t * (*make)();
294 } avr_kind_t;
295
296 // a symbol loaded from the .elf file
297 typedef struct avr_symbol_t {
298         const char * symbol;
299         uint32_t        addr;
300 } avr_symbol_t;
301
302 // locate the maker for mcu "name" and allocates a new avr instance
303 avr_t *
304 avr_make_mcu_by_name(
305                 const char *name);
306 // initializes a new AVR instance. Will call the IO registers init(), and then reset()
307 int
308 avr_init(
309                 avr_t * avr);
310 // Used by the cores, allocated a mutable avr_t from the const global
311 avr_t *
312 avr_core_allocate(
313                 const avr_t * core,
314                 uint32_t coreLen);
315
316 // resets the AVR, and the IO modules
317 void
318 avr_reset(
319                 avr_t * avr);
320 // run one cycle of the AVR, sleep if necessary
321 int
322 avr_run(
323                 avr_t * avr);
324 // finish any pending operations 
325 void
326 avr_terminate(
327                 avr_t * avr);
328
329 // set an IO register to receive commands from the AVR firmware
330 // it's optional, and uses the ELF tags
331 void
332 avr_set_command_register(
333                 avr_t * avr,
334                 avr_io_addr_t addr);
335
336 // specify the "console register" -- output sent to this register
337 // is printed on the simulator console, without using a UART
338 void
339 avr_set_console_register(
340                 avr_t * avr,
341                 avr_io_addr_t addr);
342
343 // load code in the "flash"
344 void
345 avr_loadcode(
346                 avr_t * avr,
347                 uint8_t * code,
348                 uint32_t size,
349                 avr_flashaddr_t address);
350
351 /*
352  * These are accessors for avr->data but allows watchpoints to be set for gdb
353  * IO modules use that to set values to registers, and the AVR core decoder uses
354  * that to register "public" read by instructions.
355  */
356 void
357 avr_core_watch_write(
358                 avr_t *avr,
359                 uint16_t addr,
360                 uint8_t v);
361 uint8_t
362 avr_core_watch_read(
363                 avr_t *avr,
364                 uint16_t addr);
365
366 // called when the core has detected a crash somehow.
367 // this might activate gdb server
368 void
369 avr_sadly_crashed(
370                 avr_t *avr,
371                 uint8_t signal);
372
373
374 /*
375  * These are callbacks for the two 'main' behaviour in simavr
376  */
377 void avr_callback_sleep_gdb(avr_t * avr, avr_cycle_count_t howLong);
378 void avr_callback_run_gdb(avr_t * avr);
379 void avr_callback_sleep_raw(avr_t * avr, avr_cycle_count_t howLong);
380 void avr_callback_run_raw(avr_t * avr);
381
382 #ifdef __cplusplus
383 };
384 #endif
385
386 #include "sim_io.h"
387 #include "sim_regbit.h"
388
389 #endif /*__SIM_AVR_H__*/
390