Patchwork serprog: flush stream in sp_docommand

login
register
about
Submitter Urja Rannikko
Date 2013-10-14 14:26:57
Message ID <20131014142652.GA23751@gmail.com>
Download mbox | patch
Permalink /patch/4082/
State New
Headers show

Comments

Urja Rannikko - 2013-10-14 14:26:57
This is to prevent bugs in the future - currently sp_docommand
is not called with operations in flight, but this makes it safe.

Signed-off-by: Urja Rannikko <urjaman@gmail.com>
-----
The patch also moves sp_flush_stream above sp_docommand...

---
 serprog.c | 51 ++++++++++++++++++++++++++++-----------------------
 1 file changed, 28 insertions(+), 23 deletions(-)

Patch

diff --git a/serprog.c b/serprog.c
index d7483cf..03963ec 100644
--- a/serprog.c
+++ b/serprog.c
@@ -204,12 +204,40 @@  static int sp_automatic_cmdcheck(uint8_t cmd)
 	return 0;
 }
 
+static int sp_flush_stream(void)
+{
+	if (sp_streamed_transmit_ops)
+		do {
+			unsigned char c;
+			if (serialport_read(&c, 1) != 0) {
+				msg_perr("Error: cannot read from device (flushing stream)");
+				return 1;
+			}
+			if (c == S_NAK) {
+				msg_perr("Error: NAK to a stream buffer operation\n");
+				return 1;
+			}
+			if (c != S_ACK) {
+				msg_perr("Error: Invalid reply 0x%02X from device\n", c);
+				return 1;
+			}
+		} while (--sp_streamed_transmit_ops);
+	sp_streamed_transmit_ops = 0;
+	sp_streamed_transmit_bytes = 0;
+	return 0;
+}
+
 static int sp_docommand(uint8_t command, uint32_t parmlen,
 			uint8_t *params, uint32_t retlen, void *retparms)
 {
 	unsigned char c;
 	if (sp_automatic_cmdcheck(command))
 		return 1;
+
+	if (sp_flush_stream() != 0) {
+		return 1;
+	}
+
 	if (serialport_write(&command, 1) != 0) {
 		msg_perr("Error: cannot write op code: %s\n", strerror(errno));
 		return 1;
@@ -237,29 +265,6 @@  static int sp_docommand(uint8_t command, uint32_t parmlen,
 	return 0;
 }
 
-static int sp_flush_stream(void)
-{
-	if (sp_streamed_transmit_ops)
-		do {
-			unsigned char c;
-			if (serialport_read(&c, 1) != 0) {
-				msg_perr("Error: cannot read from device (flushing stream)");
-				return 1;
-			}
-			if (c == S_NAK) {
-				msg_perr("Error: NAK to a stream buffer operation\n");
-				return 1;
-			}
-			if (c != S_ACK) {
-				msg_perr("Error: Invalid reply 0x%02X from device\n", c);
-				return 1;
-			}
-		} while (--sp_streamed_transmit_ops);
-	sp_streamed_transmit_ops = 0;
-	sp_streamed_transmit_bytes = 0;
-	return 0;
-}
-
 static int sp_stream_buffer_op(uint8_t cmd, uint32_t parmlen, uint8_t *parms)
 {
 	uint8_t *sp;