From 97381ac86e1e1d60000ef7208b3816ca9e6242a6 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Jan=20Hamal=20Dvo=C5=99=C3=A1k?= <mordae@anilinux.org>
Date: Sat, 15 Jun 2024 17:57:27 +0200
Subject: [PATCH] Fix circular buffer reading

---
 src/main.c | 23 ++++++++++++++++-------
 1 file changed, 16 insertions(+), 7 deletions(-)

diff --git a/src/main.c b/src/main.c
index 48ed291..8a2bd0f 100644
--- a/src/main.c
+++ b/src/main.c
@@ -457,9 +457,13 @@ static void rf_rx_stop(void)
 	dma_t_samp = -1;
 }
 
+#define TO_RX_BLOCK(addr) (const uint32_t *)(((uint32_t)(addr) & ~(4 * RX_STRIDE - 1)))
+
 static void rf_rx(void)
 {
-	uint32_t *prev_addr = rx_cos;
+	const uint32_t *prev1_block = TO_RX_BLOCK(rx_cos + RX_WORDS - RX_STRIDE);
+	const uint32_t *prev2_block = TO_RX_BLOCK(rx_cos);
+
 	unsigned pos = 0;
 
 	int64_t dcI = 0, dcQ = 0;
@@ -472,16 +476,21 @@ static void rf_rx(void)
 			return;
 		}
 
-		uint32_t *this_addr = (uint32_t *)dma_hw->ch[dma_ch_in_cos].write_addr;
+		const uint32_t *this_block = TO_RX_BLOCK(dma_hw->ch[dma_ch_in_cos].write_addr);
 
-		while (prev_addr <= this_addr && this_addr <= prev_addr + RX_STRIDE) {
-			this_addr = (uint32_t *)dma_hw->ch[dma_ch_in_cos].write_addr;
+		while (this_block == prev2_block) {
+			this_block = TO_RX_BLOCK(dma_hw->ch[dma_ch_in_cos].write_addr);
 			sleep_us(1);
 		}
 
-		prev_addr += RX_STRIDE;
-		if (prev_addr >= rx_cos + RX_WORDS)
-			prev_addr = rx_cos;
+		prev2_block = prev1_block;
+
+		while (this_block == prev1_block) {
+			this_block = TO_RX_BLOCK(dma_hw->ch[dma_ch_in_cos].write_addr);
+			sleep_us(1);
+		}
+
+		prev1_block = this_block;
 
 		uint32_t *cos_ptr = rx_cos + pos;
 		uint32_t *sin_ptr = rx_sin + pos;