From afa408e2c6fc6f2588e8cb1035dd051e47a53950 Mon Sep 17 00:00:00 2001
From: Stefan Rueger <stefan.rueger@urclocks.com>
Date: Wed, 9 Nov 2022 21:00:16 +0000
Subject: [PATCH] Make urclock.c iron out a bug in some bootloaders

---
 src/urclock.c | 7 +++++++
 1 file changed, 7 insertions(+)

diff --git a/src/urclock.c b/src/urclock.c
index d172f795..50b8f4f4 100644
--- a/src/urclock.c
+++ b/src/urclock.c
@@ -1397,6 +1397,7 @@ static int urclock_load_baddr(const PROGRAMMER *pgm, const AVRPART *p, char memc
   // For classic parts (think optiboot, avrisp) use word addr, otherwise byte addr (optiboot_x etc)
   int classic = !(p->prog_modes & (PM_UPDI | PM_PDI | PM_aWire));
   unsigned int addr = classic? baddr/2: baddr;
+  int effpgsiz = classic? ur.uP.pagesize/2: ur.uP.pagesize;
 
   // STK500 protocol: support flash > 64k words/bytes with the correct extended-address byte
   if(memchr == 'F' && ur.uP.flashsize > (classic? 128*1024: 64*1024)) {
@@ -1410,6 +1411,12 @@ static int urclock_load_baddr(const PROGRAMMER *pgm, const AVRPART *p, char memc
       urclock_cmd(pgm, buf, buf);
       ur.ext_addr_byte = ext_byte;
     }
+    /*
+     * Ensure next paged r/w will reload ext addr if page is just below a 64k boundary
+     * to iron out a bug in some bootloaders
+     */
+    if((addr & 0xffff0000) != ((addr+effpgsiz) & 0xffff0000))
+      ur.ext_addr_byte = 0xff;
   }
 
   buf[0] = Cmnd_STK_LOAD_ADDRESS;