Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 0744b81

Browse files
committedMar 1, 2019
WIP: firmware: guard I2C transactions with timeouts.
If we don't add timeouts on I2C transactions, then the USB request that caused it (for reads) or the next USB control request (for writes) will silently hang forever until the device is power cycled. This is clearly undesirable. However, this does not happen at all during normal operation, and although it hardens the device, the FX2 firmware size comes at a premium, and blindly spraying these guard conditions adds a nontrivial increase. Therefore this code, although tested, is not currently used.
1 parent a8ac6ba commit 0744b81

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
 

‎firmware/main.c

+24
Original file line numberDiff line numberDiff line change
@@ -284,6 +284,26 @@ static bool reset_status_bit(uint8_t bit) {
284284
return false;
285285
}
286286

287+
volatile uint8_t i2c_timeout;
288+
289+
void isr_TF0() __interrupt(_INT_TF0) {
290+
i2c_timeout++;
291+
// About 256 ms at 48 MHz clock.
292+
if(i2c_timeout == 16) {
293+
led_err_set(1);
294+
i2c_cancel = true;
295+
}
296+
}
297+
298+
#define I2C_PROTECT(code) \
299+
do { \
300+
i2c_timeout = 0; \
301+
T0 = 0; \
302+
TR0 = true; \
303+
code \
304+
TR0 = false; \
305+
} while(0)
306+
287307
// We perform lengthy operations in the main loop to avoid hogging the interrupt.
288308
// This flag is used for synchronization between the main loop and the ISR;
289309
// to allow new SETUP requests to arrive while the previous one is still being
@@ -771,6 +791,10 @@ int main() {
771791
SYNCDELAY;
772792
EP1OUTCFG = 0;
773793

794+
// Use timer 0 in 16-bit timer mode for I2C timeout.
795+
TMOD = _M0_0;
796+
ET0 = true;
797+
774798
// Use timer 2 in 16-bit timer mode for ACT LED.
775799
T2CON = _CPRL2;
776800
ET2 = true;

0 commit comments

Comments
 (0)
Please sign in to comment.