[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[avr-libc-dev] "cli" and "sei" should clobber memory
From: |
Paulo Marques |
Subject: |
[avr-libc-dev] "cli" and "sei" should clobber memory |
Date: |
Mon, 12 Dec 2005 19:42:12 +0000 |
User-agent: |
Mozilla Thunderbird 1.0.6 (X11/20050716) |
Hi, all
I have a 32 bit variable that is updated on an interrupt. I don't want
to declare it volatile as it is _not_ volatile most of the time.
I want to explicitly state the places where I want to do an "atomic"
access to it.
So I wrote this simple function:
dword atomic_get_dword(dword *ptr)
{
dword ret;
cli();
ret = *ptr;
sei();
return ret;
}
Whenever I want an atomic access to var X, I just do
atomic_get_dword(&X) instead of accessing X directly.
The problem is that gcc reorders around the "sei" instruction, resulting
in this output:
cli();
22e: f8 94 cli
ret = *ptr;
sei();
230: 78 94 sei
232: 60 81 ld r22, Z
234: 71 81 ldd r23, Z+1 ; 0x01
236: 82 81 ldd r24, Z+2 ; 0x02
238: 93 81 ldd r25, Z+3 ; 0x03
23a: 08 95 ret
Changing the "sei" and "cli" definitions in avr/interrupt.h to:
# define sei() __asm__ __volatile__ ("sei" ::: "memory")
# define cli() __asm__ __volatile__ ("cli" ::: "memory")
fixes the problem. The output is then:
cli();
22e: f8 94 cli
ret = *ptr;
230: 60 81 ld r22, Z
232: 71 81 ldd r23, Z+1 ; 0x01
234: 82 81 ldd r24, Z+2 ; 0x02
236: 93 81 ldd r25, Z+3 ; 0x03
sei();
238: 78 94 sei
23a: 08 95 ret
Basically this forces gcc to not reorder memory accesses around cli or
sei calls.
This seems like the correct thing to do since we want to make sure that
accesses to variables between "cli" and "sei" are not affect by interrupts.
This particular case might be solved by using a volatile var but others
are not. For instance, if you want to take the value from one volatile
var and add it to another atomically, you really need a "cli"/"sei"
sequence.
Should I submit this as a patch? Where to?
--
Paulo Marques
Software Development Department - Grupo PIE, S.A.
Phone: +351 252 290600, Fax: +351 252 290601
Web: www.grupopie.com
Pointy-Haired Boss: I don't see anything that could stand in our way.
Dilbert: Sanity? Reality? The laws of physics?
- [avr-libc-dev] "cli" and "sei" should clobber memory,
Paulo Marques <=