From 8150930958bc62b28a0a8268d3a2954f10ccd01f Mon Sep 17 00:00:00 2001
From: Stefan Rueger <stefan.rueger@urclocks.com>
Date: Mon, 9 Jan 2023 14:14:40 +0000
Subject: [PATCH] Only send write flash cmd to STK500v2 programmers if page not
 empty

... except if it's for a bootloader: they might need to know about
0xff pages if they use an SPM page erase command and therefore
memory does not look like NOR-memory.

This is a slight optimisation for all parts (as writing 0xff pages
on NOR-memory flash is a NOP), but more importantly, prevents a
firmware error to surface for those parts that need to carry out
value polling to determine when writing the page has finished on
the device.
---
 src/stk500v2.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/src/stk500v2.c b/src/stk500v2.c
index 49a331f3..c2d38053 100644
--- a/src/stk500v2.c
+++ b/src/stk500v2.c
@@ -2279,7 +2279,11 @@ static int stk500v2_paged_write(const PROGRAMMER *pgm, const AVRPART *p, const A
 
     memcpy(buf+10,m->buf+addr, block_size);
 
-    result = stk500v2_command(pgm,buf,block_size+10, sizeof(buf));
+    // Do not send request to write empty flash pages except for bootloaders (fixes Issue #425)
+    unsigned char *p = m->buf+addr;
+    result = (pgm->prog_modes & PM_SPM) || !addrshift || *p != 0xff || memcmp(p, p+1, block_size-1)?
+      stk500v2_command(pgm, buf, block_size+10, sizeof buf): 0;
+
     if (result < 0) {
       pmsg_error("write command failed\n");
       return -1;