Why is Read-Modify-Write necessary for registers on embedded systems?

后端 未结 5 1761
伪装坚强ぢ
伪装坚强ぢ 2021-02-07 20:17

I was reading http://embeddedgurus.com/embedded-bridge/2010/03/different-bit-types-in-different-registers/, which said:

With read/write bits, firmware se

5条回答
  •  囚心锁ツ
    2021-02-07 20:48

    The thing is if you don't want to modify the other bits in the register you have to know what they are before you write something it. Hence the read/modiy/write. Note that if you use a C statement like:

    *pRegister |= SOME_BIT;
    

    Event though that might look like a simple write operation at first glace, the compiler must perform a read first in order to preserve the other bits in the value (this is generally true, even if you're not talking about hardware registers, unless the compiler is able to use other knowledge about the value to optimize the read away).

    Note that memory-mapped hardware registers are generally marked volatile specifically so that these optimizations cannot take place (otherwise many hardware register routines wouldn't work properly).

    Finally, sometimes there is hardware support for registers that specifically set or clear bits in the hardware without requiring a read/modify/write sequence. Some Atmel ARM microcontrollers I've worked with have this with specific registers that clear or set bits in hardware only those bits that are set when you write to the register (leaving any unset bit alone). Also the Cortex M3 ARM CPU supports accessing a single bit (for read or write) in memory or in hardware registers this through accessing a specific address space with a technique they call 'bit-banding'. The bit-banding algorithm looks complex at first glance, but it's really just some simple arithmetic to map the offset of a bit in one address to another 'bit-specific' address.

    Anyway, the bottom line is that there are some processors where you can get away without a read/modify/write series, but that's by no means universally true.

提交回复
热议问题