timer: Reconfigure the timer in fast pwm mode
[simavr] / simavr / sim / avr_timer.c
1 /*
2         avr_timer.c
3
4         Handles the 8 bits and 16 bits AVR timer.
5         Handles
6         + CDC
7         + Fast PWM
8
9         Copyright 2008-2012 Michel Pollet <buserror@gmail.com>
10
11         This file is part of simavr.
12
13         simavr is free software: you can redistribute it and/or modify
14         it under the terms of the GNU General Public License as published by
15         the Free Software Foundation, either version 3 of the License, or
16         (at your option) any later version.
17
18         simavr is distributed in the hope that it will be useful,
19         but WITHOUT ANY WARRANTY; without even the implied warranty of
20         MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21         GNU General Public License for more details.
22
23         You should have received a copy of the GNU General Public License
24         along with simavr.  If not, see <http://www.gnu.org/licenses/>.
25  */
26
27 #include <stdio.h>
28 #include "avr_timer.h"
29 #include "avr_ioport.h"
30
31 /*
32  * The timers are /always/ 16 bits here, if the higher byte register
33  * is specified it's just added.
34  */
35 static uint16_t _timer_get_ocr(avr_timer_t * p, int compi)
36 {
37         return p->io.avr->data[p->comp[compi].r_ocr] |
38                       (p->comp[compi].r_ocrh ? (p->io.avr->data[p->comp[compi].r_ocrh] << 8) : 0);
39 }
40 static uint16_t _timer_get_tcnt(avr_timer_t * p)
41 {
42         return p->io.avr->data[p->r_tcnt] |
43                                 (p->r_tcnth ? (p->io.avr->data[p->r_tcnth] << 8) : 0);
44 }
45 static uint16_t _timer_get_icr(avr_timer_t * p)
46 {
47         return p->io.avr->data[p->r_icr] |
48                                 (p->r_tcnth ? (p->io.avr->data[p->r_icrh] << 8) : 0);
49 }
50 static avr_cycle_count_t avr_timer_comp(avr_timer_t *p, avr_cycle_count_t when, uint8_t comp)
51 {
52         avr_t * avr = p->io.avr;
53         avr_raise_interrupt(avr, &p->comp[comp].interrupt);
54
55         // check output compare mode and set/clear pins
56         uint8_t mode = avr_regbit_get(avr, p->comp[comp].com);
57         avr_irq_t * irq = &p->io.irq[TIMER_IRQ_OUT_COMP + comp];
58
59         switch (mode) {
60                 case avr_timer_com_normal: // Normal mode OCnA disconnected
61                         break;
62                 case avr_timer_com_toggle: // Toggle OCnA on compare match
63                         if (p->comp[comp].com_pin.reg)  // we got a physical pin
64                                 avr_raise_irq(irq,
65                                                 AVR_IOPORT_OUTPUT | (avr_regbit_get(avr, p->comp[comp].com_pin) ? 0 : 1));
66                         else // no pin, toggle the IRQ anyway
67                                 avr_raise_irq(irq,
68                                                 p->io.irq[TIMER_IRQ_OUT_COMP + comp].value ? 0 : 1);
69                         break;
70                 case avr_timer_com_clear:
71                         avr_raise_irq(irq, 0);
72                         break;
73                 case avr_timer_com_set:
74                         avr_raise_irq(irq, 1);
75                         break;
76         }
77
78         return p->tov_cycles ? 0 :
79                                 p->comp[comp].comp_cycles ?
80                                                 when + p->comp[comp].comp_cycles : 0;
81 }
82
83 static avr_cycle_count_t avr_timer_compa(struct avr_t * avr, avr_cycle_count_t when, void * param)
84 {
85         return avr_timer_comp((avr_timer_t*)param, when, AVR_TIMER_COMPA);
86 }
87
88 static avr_cycle_count_t avr_timer_compb(struct avr_t * avr, avr_cycle_count_t when, void * param)
89 {
90         return avr_timer_comp((avr_timer_t*)param, when, AVR_TIMER_COMPB);
91 }
92
93 static avr_cycle_count_t avr_timer_compc(struct avr_t * avr, avr_cycle_count_t when, void * param)
94 {
95         return avr_timer_comp((avr_timer_t*)param, when, AVR_TIMER_COMPC);
96 }
97
98 // timer overflow
99 static avr_cycle_count_t avr_timer_tov(struct avr_t * avr, avr_cycle_count_t when, void * param)
100 {
101         avr_timer_t * p = (avr_timer_t *)param;
102         int start = p->tov_base == 0;
103
104         if (!start)
105                 avr_raise_interrupt(avr, &p->overflow);
106         p->tov_base = when;
107
108         static const avr_cycle_timer_t dispatch[AVR_TIMER_COMP_COUNT] =
109                 { avr_timer_compa, avr_timer_compb, avr_timer_compc };
110
111         for (int compi = 0; compi < AVR_TIMER_COMP_COUNT; compi++) {
112                 if (p->comp[compi].comp_cycles) {
113                         if (p->comp[compi].comp_cycles < p->tov_cycles)
114                                 avr_cycle_timer_register(avr,
115                                         p->comp[compi].comp_cycles,
116                                         dispatch[compi], p);
117                         else if (p->tov_cycles == p->comp[compi].comp_cycles && !start)
118                                 dispatch[compi](avr, when, param);
119                 }
120         }
121
122         return when + p->tov_cycles;
123 }
124
125 static uint16_t _avr_timer_get_current_tcnt(avr_timer_t * p)
126 {
127         avr_t * avr = p->io.avr;
128         if (p->tov_cycles) {
129                 uint64_t when = avr->cycle - p->tov_base;
130
131                 return (when * (((uint32_t)p->tov_top)+1)) / p->tov_cycles;
132         }
133         return 0;
134 }
135
136 static uint8_t avr_timer_tcnt_read(struct avr_t * avr, avr_io_addr_t addr, void * param)
137 {
138         avr_timer_t * p = (avr_timer_t *)param;
139         // made to trigger potential watchpoints
140
141         uint16_t tcnt = _avr_timer_get_current_tcnt(p);
142
143         avr->data[p->r_tcnt] = tcnt;
144         if (p->r_tcnth)
145                 avr->data[p->r_tcnth] = tcnt >> 8;
146         
147         return avr_core_watch_read(avr, addr);
148 }
149
150 static void avr_timer_tcnt_write(struct avr_t * avr, avr_io_addr_t addr, uint8_t v, void * param)
151 {
152         avr_timer_t * p = (avr_timer_t *)param;
153         avr_core_watch_write(avr, addr, v);
154         uint16_t tcnt = _timer_get_tcnt(p);
155
156         if (!p->tov_top)
157                 return;
158                 
159         if (tcnt >= p->tov_top)
160                 tcnt = 0;
161         
162         // this involves some magicking
163         // cancel the current timers, recalculate the "base" we should be at, reset the
164         // timer base as it should, and re-shedule the timers using that base.
165         
166         avr_cycle_timer_cancel(avr, avr_timer_tov, p);
167         avr_cycle_timer_cancel(avr, avr_timer_compa, p);
168         avr_cycle_timer_cancel(avr, avr_timer_compb, p);
169         avr_cycle_timer_cancel(avr, avr_timer_compc, p);
170
171         uint64_t cycles = (tcnt * p->tov_cycles) / p->tov_top;
172
173 //      printf("%s-%c %d/%d -- cycles %d/%d\n", __FUNCTION__, p->name, tcnt, p->tov_top, (uint32_t)cycles, (uint32_t)p->tov_cycles);
174
175         // this reset the timers bases to the new base
176         p->tov_base = 0;
177         avr_cycle_timer_register(avr, p->tov_cycles - cycles, avr_timer_tov, p);
178         avr_timer_tov(avr, avr->cycle - cycles, p);
179
180 //      tcnt = ((avr->cycle - p->tov_base) * p->tov_top) / p->tov_cycles;
181 //      printf("%s-%c new tnt derive to %d\n", __FUNCTION__, p->name, tcnt);    
182 }
183
184 static void avr_timer_configure(avr_timer_t * p, uint32_t clock, uint32_t top)
185 {
186         float t = clock / (float)(top+1);
187         float frequency = p->io.avr->frequency;
188
189         p->tov_cycles = 0;
190         p->tov_top = top;
191
192         p->tov_cycles = frequency / t; // avr_hz_to_cycles(frequency, t);
193
194         if (p->trace_flags)
195                 printf("%s-%c TOP %.2fHz = %d cycles\n", __FUNCTION__, p->name, t, (int)p->tov_cycles);
196
197         for (int compi = 0; compi < AVR_TIMER_COMP_COUNT; compi++) {
198                 if (!p->comp[compi].r_ocr)
199                         continue;
200                 uint32_t ocr = _timer_get_ocr(p, compi);
201                 float fc = clock / (float)(ocr+1);
202
203                 p->comp[compi].comp_cycles = 0;
204         //      printf("%s-%c clock %d top %d OCR%c %d\n", __FUNCTION__, p->name, clock, top, 'A'+compi, ocr);
205
206                 if (ocr && ocr <= top) {
207                         p->comp[compi].comp_cycles = frequency / fc; // avr_hz_to_cycles(p->io.avr, fa);
208                         if (p->trace_flags /*& (1 << compi)*/)
209                                 printf("%s-%c %c %.2fHz = %d cycles\n", __FUNCTION__, p->name,
210                                         'A'+compi, fc, (int)p->comp[compi].comp_cycles);
211                 }
212         }
213
214         if (p->tov_cycles > 1) {
215                 avr_cycle_timer_register(p->io.avr, p->tov_cycles, avr_timer_tov, p);
216                 // calling it once, with when == 0 tells it to arm the A/B/C timers if needed
217                 p->tov_base = 0;
218                 avr_timer_tov(p->io.avr, p->io.avr->cycle, p);
219         }
220 }
221
222 static void avr_timer_reconfigure(avr_timer_t * p)
223 {
224         avr_t * avr = p->io.avr;
225
226         avr_timer_wgm_t zero={0};
227         p->mode = zero;
228         // cancel everything
229         p->comp[AVR_TIMER_COMPA].comp_cycles = 0;
230         p->comp[AVR_TIMER_COMPB].comp_cycles = 0;
231         p->comp[AVR_TIMER_COMPC].comp_cycles = 0;
232         p->tov_cycles = 0;
233         
234         avr_cycle_timer_cancel(avr, avr_timer_tov, p);
235         avr_cycle_timer_cancel(avr, avr_timer_compa, p);
236         avr_cycle_timer_cancel(avr, avr_timer_compb, p);
237         avr_cycle_timer_cancel(avr, avr_timer_compc, p);
238
239         long clock = avr->frequency;
240
241         // only can exists on "asynchronous" 8 bits timers
242         if (avr_regbit_get(avr, p->as2))
243                 clock = 32768;
244
245         uint8_t cs = avr_regbit_get_array(avr, p->cs, ARRAY_SIZE(p->cs));
246         if (cs == 0) {
247                 printf("%s-%c clock turned off\n", __FUNCTION__, p->name);              
248                 return;
249         }
250
251         uint8_t mode = avr_regbit_get_array(avr, p->wgm, ARRAY_SIZE(p->wgm));
252         uint8_t cs_div = p->cs_div[cs];
253         uint32_t f = clock >> cs_div;
254
255         p->mode = p->wgm_op[mode];
256         //printf("%s-%c clock %d, div %d(/%d) = %d ; mode %d\n", __FUNCTION__, p->name, clock, cs, 1 << cs_div, f, mode);
257         switch (p->mode.kind) {
258                 case avr_timer_wgm_normal:
259                         avr_timer_configure(p, f, (1 << p->mode.size) - 1);
260                         break;
261                 case avr_timer_wgm_fc_pwm:
262                         avr_timer_configure(p, f, (1 << p->mode.size) - 1);
263                         break;
264                 case avr_timer_wgm_ctc: {
265                         avr_timer_configure(p, f, _timer_get_ocr(p, AVR_TIMER_COMPA));
266                 }       break;
267                 case avr_timer_wgm_pwm: {
268                         uint16_t top = p->mode.top == avr_timer_wgm_reg_ocra ? _timer_get_ocr(p, AVR_TIMER_COMPA) : _timer_get_icr(p);
269                         avr_timer_configure(p, f, top);
270                 }       break;
271                 case avr_timer_wgm_fast_pwm:
272                         avr_timer_configure(p, f, (1 << p->mode.size) - 1);
273                         break;
274                 default:
275                         printf("%s-%c unsupported timer mode wgm=%d (%d)\n", __FUNCTION__, p->name,
276                                         mode, p->mode.kind);
277         }       
278 }
279
280 static void avr_timer_write_ocr(struct avr_t * avr, avr_io_addr_t addr, uint8_t v, void * param)
281 {
282         avr_timer_t * p = (avr_timer_t *)param;
283         uint16_t oldv[AVR_TIMER_COMP_COUNT];
284         int target = -1;
285
286         /* vheck to see if the OCR values actualy changed */
287         for (int oi = 0; oi < AVR_TIMER_COMP_COUNT; oi++)
288                 oldv[oi] = _timer_get_ocr(p, oi);
289         avr_core_watch_write(avr, addr, v);
290         for (int oi = 0; oi < AVR_TIMER_COMP_COUNT; oi++)
291                 if (oldv[oi] != _timer_get_ocr(p, oi)) {
292                         target = oi;
293                         break;
294                 }
295         uint16_t otrace = p->trace_flags;
296
297         if (target != -1) {
298                 p->trace_flags = 1 << target;
299         } else {
300                 p->trace_flags = 0;
301         }
302         switch (p->mode.kind) {
303                 case avr_timer_wgm_normal:
304                         avr_timer_reconfigure(p);
305                         break;
306                 case avr_timer_wgm_fc_pwm:      // OCR is not used here
307                         avr_timer_reconfigure(p);
308                         break;
309                 case avr_timer_wgm_ctc:
310                         avr_timer_reconfigure(p);
311                         break;
312                 case avr_timer_wgm_pwm:
313                         if (p->mode.top != avr_timer_wgm_reg_ocra) {
314                                 avr_raise_irq(p->io.irq + TIMER_IRQ_OUT_PWM0, _timer_get_ocr(p, AVR_TIMER_COMPA));
315                                 avr_raise_irq(p->io.irq + TIMER_IRQ_OUT_PWM1, _timer_get_ocr(p, AVR_TIMER_COMPB));
316                         }
317                         break;
318                 case avr_timer_wgm_fast_pwm:
319                         if (target != -1)
320                                 avr_timer_reconfigure(p);
321                         avr_raise_irq(p->io.irq + TIMER_IRQ_OUT_PWM0, _timer_get_ocr(p, AVR_TIMER_COMPA));
322                         avr_raise_irq(p->io.irq + TIMER_IRQ_OUT_PWM1, _timer_get_ocr(p, AVR_TIMER_COMPB));
323                         break;
324                 default:
325                         printf("%s-%c mode %d UNSUPPORTED\n", __FUNCTION__, p->name, p->mode.kind);
326                         avr_timer_reconfigure(p);
327                         break;
328         }
329         p->trace_flags = otrace;
330 }
331
332 static void avr_timer_write(struct avr_t * avr, avr_io_addr_t addr, uint8_t v, void * param)
333 {
334         avr_timer_t * p = (avr_timer_t *)param;
335
336         uint8_t as2 = avr_regbit_get(avr, p->as2);
337         uint8_t cs = avr_regbit_get_array(avr, p->cs, ARRAY_SIZE(p->cs));
338         uint8_t mode = avr_regbit_get_array(avr, p->wgm, ARRAY_SIZE(p->wgm));
339
340         avr_core_watch_write(avr, addr, v);
341
342         // only reconfigure the timer if "relevant" bits have changed
343         // this prevent the timer reset when changing the edge detector
344         // or other minor bits
345         if (avr_regbit_get_array(avr, p->cs, ARRAY_SIZE(p->cs)) != cs ||
346                         avr_regbit_get_array(avr, p->wgm, ARRAY_SIZE(p->wgm)) != mode ||
347                                         avr_regbit_get(avr, p->as2) != as2) {
348                 avr_timer_reconfigure(p);
349         }
350 }
351
352 /*
353  * write to the TIFR register. Watch for code that writes "1" to clear
354  * pending interrupts.
355  */
356 static void avr_timer_write_pending(struct avr_t * avr, avr_io_addr_t addr, uint8_t v, void * param)
357 {
358         avr_timer_t * p = (avr_timer_t *)param;
359         // save old bits values
360         uint8_t ov = avr_regbit_get(avr, p->overflow.raised);
361         uint8_t ic = avr_regbit_get(avr, p->icr.raised);
362         uint8_t cp[AVR_TIMER_COMP_COUNT];
363
364         for (int compi = 0; compi < AVR_TIMER_COMP_COUNT; compi++)
365                 cp[compi] = avr_regbit_get(avr, p->comp[compi].interrupt.raised);
366
367         // write the value
368         avr_core_watch_write(avr, addr, v);
369
370         // clear any interrupts & flags
371         avr_clear_interrupt_if(avr, &p->overflow, ov);
372         avr_clear_interrupt_if(avr, &p->icr, ic);
373
374         for (int compi = 0; compi < AVR_TIMER_COMP_COUNT; compi++)
375                 avr_clear_interrupt_if(avr, &p->comp[compi].interrupt, cp[compi]);
376 }
377
378 static void avr_timer_irq_icp(struct avr_irq_t * irq, uint32_t value, void * param)
379 {
380         avr_timer_t * p = (avr_timer_t *)param;
381         avr_t * avr = p->io.avr;
382
383         // input capture disabled when ICR is used as top
384         if (p->mode.top == avr_timer_wgm_reg_icr)
385                 return;
386         int bing = 0;
387         if (avr_regbit_get(avr, p->ices)) { // rising edge
388                 if (!irq->value && value)
389                         bing++;
390         } else {        // default, falling edge
391                 if (irq->value && !value)
392                         bing++;
393         }
394         if (!bing)
395                 return;
396         // get current TCNT, copy it to ICR, and raise interrupt
397         uint16_t tcnt = _avr_timer_get_current_tcnt(p);
398         avr->data[p->r_icr] = tcnt;
399         if (p->r_icrh)
400                 avr->data[p->r_icrh] = tcnt >> 8;
401         avr_raise_interrupt(avr, &p->icr);
402 }
403
404 static void avr_timer_reset(avr_io_t * port)
405 {
406         avr_timer_t * p = (avr_timer_t *)port;
407         avr_cycle_timer_cancel(p->io.avr, avr_timer_tov, p);
408         avr_cycle_timer_cancel(p->io.avr, avr_timer_compa, p);
409         avr_cycle_timer_cancel(p->io.avr, avr_timer_compb, p);
410         avr_cycle_timer_cancel(p->io.avr, avr_timer_compc, p);
411
412         // check to see if the comparators have a pin output. If they do,
413         // (try) to get the ioport corresponding IRQ and connect them
414         // they will automagically be triggered when the comparator raises
415         // it's own IRQ
416         for (int compi = 0; compi < AVR_TIMER_COMP_COUNT; compi++) {
417                 p->comp[compi].comp_cycles = 0;
418
419                 avr_ioport_getirq_t req = {
420                         .bit = p->comp[compi].com_pin
421                 };
422                 if (avr_ioctl(port->avr, AVR_IOCTL_IOPORT_GETIRQ_REGBIT, &req) > 0) {
423                         // cool, got an IRQ
424 //                      printf("%s-%c COMP%c Connecting PIN IRQ %d\n", __FUNCTION__, p->name, 'A'+compi, req.irq[0]->irq);
425                         avr_connect_irq(&port->irq[TIMER_IRQ_OUT_COMP + compi], req.irq[0]);
426                 }
427         }
428         avr_ioport_getirq_t req = {
429                 .bit = p->icp
430         };
431         if (avr_ioctl(port->avr, AVR_IOCTL_IOPORT_GETIRQ_REGBIT, &req) > 0) {
432                 // cool, got an IRQ for the input capture pin
433 //              printf("%s-%c ICP Connecting PIN IRQ %d\n", __FUNCTION__, p->name, req.irq[0]->irq);
434                 avr_irq_register_notify(req.irq[0], avr_timer_irq_icp, p);
435         }
436
437 }
438
439 static const char * irq_names[TIMER_IRQ_COUNT] = {
440         [TIMER_IRQ_OUT_PWM0] = "8>pwm0",
441         [TIMER_IRQ_OUT_PWM1] = "8>pwm1",
442         [TIMER_IRQ_OUT_COMP + 0] = ">compa",
443         [TIMER_IRQ_OUT_COMP + 1] = ">compb",
444         [TIMER_IRQ_OUT_COMP + 2] = ">compc",
445 };
446
447 static  avr_io_t        _io = {
448         .kind = "timer",
449         .reset = avr_timer_reset,
450         .irq_names = irq_names,
451 };
452
453 void avr_timer_init(avr_t * avr, avr_timer_t * p)
454 {
455         p->io = _io;
456
457         avr_register_io(avr, &p->io);
458         avr_register_vector(avr, &p->overflow);
459         avr_register_vector(avr, &p->icr);
460
461         // allocate this module's IRQ
462         avr_io_setirqs(&p->io, AVR_IOCTL_TIMER_GETIRQ(p->name), TIMER_IRQ_COUNT, NULL);
463
464         // marking IRQs as "filtered" means they don't propagate if the
465         // new value raised is the same as the last one.. in the case of the
466         // pwm value it makes sense not to bother.
467         p->io.irq[TIMER_IRQ_OUT_PWM0].flags |= IRQ_FLAG_FILTERED;
468         p->io.irq[TIMER_IRQ_OUT_PWM1].flags |= IRQ_FLAG_FILTERED;
469
470         if (p->wgm[0].reg) // these are not present on older AVRs
471                 avr_register_io_write(avr, p->wgm[0].reg, avr_timer_write, p);
472         avr_register_io_write(avr, p->cs[0].reg, avr_timer_write, p);
473
474         // this assumes all the "pending" interrupt bits are in the same
475         // register. Might not be true on all devices ?
476         avr_register_io_write(avr, p->overflow.raised.reg, avr_timer_write_pending, p);
477
478         /*
479          * Even if the timer is 16 bits, we don't care to have watches on the
480          * high bytes because the datasheet says that the low address is always
481          * the trigger.
482          */
483         for (int compi = 0; compi < AVR_TIMER_COMP_COUNT; compi++) {
484                 avr_register_vector(avr, &p->comp[compi].interrupt);
485
486                 if (p->comp[compi].r_ocr) // not all timers have all comparators
487                         avr_register_io_write(avr, p->comp[compi].r_ocr, avr_timer_write_ocr, p);
488         }
489         avr_register_io_write(avr, p->r_tcnt, avr_timer_tcnt_write, p);
490         avr_register_io_read(avr, p->r_tcnt, avr_timer_tcnt_read, p);
491         p->trace_flags = 0xf;
492 }