Bug fix: race condition in I2C cr1 read-modify-write #662
Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
Buggy code:
The
modifymethod executes a read-modify-write operation on thecr1control register, as can be verified with the following disassembly code. Notably, thereadvariable is assigned a constanttruewithin the example, which results in the elimination of the if comparison due to compiler optimization.The issue arises when an IRQ occurs between the second read and write operations. Due to the CPU's faster execution speed compared to the peripheral, it is highly likely that the second read operation will still observe the
cr1register with thestartbit set. However, if an IRQ is serviced, the peripheral may have sufficient time to complete generating the start condition, resulting in the hardware clearing thestartbit in the peripheral'scr1register. Nonetheless, the copy of thecr1register stored inr0during the second read operation will still retain thestartbit set. Consequently, when the second write operation is executed oncr1, thestartbit is once again set. As a result, the peripheral attempts to generate a second start condition, leading to a situation where the I²C peripheral becomes unresponsive in my specific case.The solution is to swap the two method calls. Once the
ackbit is set, it will not be automatically cleared, thus we are safe even if being interrupted in between.Attached is the bug captured on a logic analyzer.
