xref: /aosp_15_r20/external/flashrom/serprog.c (revision 0d6140be3aa665ecc836e8907834fcd3e3b018fc)
1 /*
2  * This file is part of the flashrom project.
3  *
4  * Copyright (C) 2009, 2011 Urja Rannikko <[email protected]>
5  * Copyright (C) 2009 Carl-Daniel Hailfinger
6  * Copyright (C) 2024 Riku Viitanen <[email protected]>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  */
18 
19 #include <stdbool.h>
20 #include <stdio.h>
21 #if ! IS_WINDOWS /* stuff (presumably) needed for sockets only */
22 #include <stdlib.h>
23 #include <unistd.h>
24 #include <fcntl.h>
25 #include <sys/socket.h>
26 #include <arpa/inet.h>
27 #include <netinet/in.h>
28 #include <netinet/tcp.h>
29 #include <netdb.h>
30 #endif
31 #if IS_WINDOWS
32 #include <conio.h>
33 #else
34 #include <termios.h>
35 #endif
36 #include <string.h>
37 #include <errno.h>
38 #include "flash.h"
39 #include "programmer.h"
40 #include "chipdrivers.h"
41 
42 /* According to Serial Flasher Protocol Specification - version 1 */
43 #define S_ACK			0x06
44 #define S_NAK			0x15
45 #define S_CMD_NOP		0x00	/* No operation					*/
46 #define S_CMD_Q_IFACE		0x01	/* Query interface version			*/
47 #define S_CMD_Q_CMDMAP		0x02	/* Query supported commands bitmap		*/
48 #define S_CMD_Q_PGMNAME		0x03	/* Query programmer name			*/
49 #define S_CMD_Q_SERBUF		0x04	/* Query Serial Buffer Size			*/
50 #define S_CMD_Q_BUSTYPE		0x05	/* Query supported bustypes			*/
51 #define S_CMD_Q_CHIPSIZE	0x06	/* Query supported chipsize (2^n format)	*/
52 #define S_CMD_Q_OPBUF		0x07	/* Query operation buffer size			*/
53 #define S_CMD_Q_WRNMAXLEN	0x08	/* Query Write to opbuf: Write-N maximum length */
54 #define S_CMD_R_BYTE		0x09	/* Read a single byte				*/
55 #define S_CMD_R_NBYTES		0x0A	/* Read n bytes					*/
56 #define S_CMD_O_INIT		0x0B	/* Initialize operation buffer			*/
57 #define S_CMD_O_WRITEB		0x0C	/* Write opbuf: Write byte with address		*/
58 #define S_CMD_O_WRITEN		0x0D	/* Write to opbuf: Write-N			*/
59 #define S_CMD_O_DELAY		0x0E	/* Write opbuf: udelay				*/
60 #define S_CMD_O_EXEC		0x0F	/* Execute operation buffer			*/
61 #define S_CMD_SYNCNOP		0x10	/* Special no-operation that returns NAK+ACK	*/
62 #define S_CMD_Q_RDNMAXLEN	0x11	/* Query read-n maximum length			*/
63 #define S_CMD_S_BUSTYPE		0x12	/* Set used bustype(s).				*/
64 #define S_CMD_O_SPIOP		0x13	/* Perform SPI operation.			*/
65 #define S_CMD_S_SPI_FREQ	0x14	/* Set SPI clock frequency			*/
66 #define S_CMD_S_PIN_STATE	0x15	/* Enable/disable output drivers		*/
67 #define S_CMD_S_SPI_CS		0x16	/* Set SPI chip select to use			*/
68 
69 #define MSGHEADER "serprog: "
70 
71 static uint16_t sp_device_serbuf_size = 16;
72 static uint16_t sp_device_opbuf_size = 300;
73 /* Bitmap of supported commands */
74 static uint8_t sp_cmdmap[32];
75 
76 /* sp_prev_was_write used to detect writes with contiguous addresses
77 	and combine them to write-n's */
78 static int sp_prev_was_write = 0;
79 /* sp_write_n_addr used as the starting addr of the currently
80 	combined write-n operation */
81 static uint32_t sp_write_n_addr;
82 /* The maximum length of an write_n operation; 0 = write-n not supported */
83 static uint32_t sp_max_write_n = 0;
84 /* The maximum length of a read_n operation; 0 = 2^24 */
85 static uint32_t sp_max_read_n = 0;
86 
87 /* A malloc'd buffer for combining the operation's data
88 	and a counter that tells how much data is there. */
89 static uint8_t *sp_write_n_buf;
90 static uint32_t sp_write_n_bytes = 0;
91 
92 /* sp_streamed_* used for flow control checking */
93 static unsigned int sp_streamed_transmit_ops = 0;
94 static unsigned int sp_streamed_transmit_bytes = 0;
95 
96 /* sp_opbuf_usage used for counting the amount of
97 	on-device operation buffer used */
98 static int sp_opbuf_usage = 0;
99 /* if true causes sp_docommand to automatically check
100 	whether the command is supported before doing it */
101 static int sp_check_avail_automatic = 0;
102 
103 #if ! IS_WINDOWS
sp_opensocket(char * ip,unsigned int port)104 static int sp_opensocket(char *ip, unsigned int port)
105 {
106 	int flag = 1;
107 	struct hostent *hostPtr = NULL;
108 	union { struct sockaddr_in si; struct sockaddr s; } sp = {};
109 	int sock;
110 	msg_pdbg(MSGHEADER "IP %s port %d\n", ip, port);
111 	sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
112 	if (sock < 0) {
113 		msg_perr("Error: serprog cannot open socket: %s\n", strerror(errno));
114 		return -1;
115 	}
116 	hostPtr = gethostbyname(ip);
117 	if (NULL == hostPtr) {
118 		hostPtr = gethostbyaddr(ip, strlen(ip), AF_INET);
119 		if (NULL == hostPtr) {
120 			close(sock);
121 			msg_perr("Error: cannot resolve %s\n", ip);
122 			return -1;
123 		}
124 	}
125 	sp.si.sin_family = AF_INET;
126 	sp.si.sin_port = htons(port);
127 	(void)memcpy(&sp.si.sin_addr, hostPtr->h_addr_list[0], hostPtr->h_length);
128 	if (connect(sock, &sp.s, sizeof(sp.si)) < 0) {
129 		close(sock);
130 		msg_perr("Error: serprog cannot connect: %s\n", strerror(errno));
131 		return -1;
132 	}
133 	/* We are latency limited, and sometimes do write-write-read    *
134 	 * (write-n) - so enable TCP_NODELAY.				*/
135 	if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, &flag, sizeof(int))) {
136 		close(sock);
137 		msg_perr("Error: serprog cannot set socket options: %s\n", strerror(errno));
138 		return -1;
139 	}
140 	return sock;
141 }
142 #endif
143 
144 /* Synchronize: a bit tricky algorithm that tries to (and in my tests has *
145  * always succeeded in) bring the serial protocol to known waiting-for-   *
146  * command state - uses nonblocking I/O - rest of the driver uses         *
147  * blocking read - TODO: add an alarm() timer for the rest of the app on  *
148  * serial operations, though not such a big issue as the first thing to   *
149  * do is synchronize (eg. check that device is alive).			  */
sp_synchronize(void)150 static int sp_synchronize(void)
151 {
152 	int i;
153 	unsigned char buf[8];
154 	/* First sends 8 NOPs, then flushes the return data - should cause *
155 	 * the device serial parser to get to a sane state, unless if it   *
156 	 * is waiting for a real long write-n.                             */
157 	memset(buf, S_CMD_NOP, 8);
158 	if (serialport_write_nonblock(buf, 8, 1, NULL) != 0) {
159 		goto err_out;
160 	}
161 	/* A second should be enough to get all the answers to the buffer */
162 	default_delay(1000 * 1000);
163 	sp_flush_incoming();
164 
165 	/* Then try up to 8 times to send syncnop and get the correct special *
166 	 * return of NAK+ACK. Timing note: up to 10 characters, 10*50ms =     *
167 	 * up to 500ms per try, 8*0.5s = 4s; +1s (above) = up to 5s sync      *
168 	 * attempt, ~1s if immediate success.                                 */
169 	for (i = 0; i < 8; i++) {
170 		int n;
171 		unsigned char c = S_CMD_SYNCNOP;
172 		if (serialport_write_nonblock(&c, 1, 1, NULL) != 0) {
173 			goto err_out;
174 		}
175 		msg_pdbg(".");
176 		fflush(stdout);
177 		for (n = 0; n < 10; n++) {
178 			int ret = serialport_read_nonblock(&c, 1, 50, NULL);
179 			if (ret < 0)
180 				goto err_out;
181 			if (ret > 0 || c != S_NAK)
182 				continue;
183 			ret = serialport_read_nonblock(&c, 1, 20, NULL);
184 			if (ret < 0)
185 				goto err_out;
186 			if (ret > 0 || c != S_ACK)
187 				continue;
188 			c = S_CMD_SYNCNOP;
189 			if (serialport_write_nonblock(&c, 1, 1, NULL) != 0) {
190 				goto err_out;
191 			}
192 			ret = serialport_read_nonblock(&c, 1, 500, NULL);
193 			if (ret < 0)
194 				goto err_out;
195 			if (ret > 0 || c != S_NAK)
196 				break;	/* fail */
197 			ret = serialport_read_nonblock(&c, 1, 100, NULL);
198 			if (ret > 0 || ret < 0)
199 				goto err_out;
200 			if (c != S_ACK)
201 				break;	/* fail */
202 			msg_pdbg("\n");
203 			return 0;
204 		}
205 	}
206 err_out:
207 	msg_perr("Error: cannot synchronize protocol - check communications and reset device?\n");
208 	return 1;
209 }
210 
sp_check_commandavail(uint8_t command)211 static int sp_check_commandavail(uint8_t command)
212 {
213 	int byteoffs, bitoffs;
214 	byteoffs = command / 8;
215 	bitoffs = command % 8;
216 	return (sp_cmdmap[byteoffs] & (1 << bitoffs)) ? 1 : 0;
217 }
218 
sp_automatic_cmdcheck(uint8_t cmd)219 static int sp_automatic_cmdcheck(uint8_t cmd)
220 {
221 	if ((sp_check_avail_automatic) && (sp_check_commandavail(cmd) == 0)) {
222 		msg_pdbg("Warning: Automatic command availability check failed "
223 			 "for cmd 0x%02x - won't execute cmd\n", cmd);
224 		return 1;
225 		}
226 	return 0;
227 }
228 
sp_docommand(uint8_t command,uint32_t parmlen,uint8_t * params,uint32_t retlen,void * retparms)229 static int sp_docommand(uint8_t command, uint32_t parmlen,
230 			uint8_t *params, uint32_t retlen, void *retparms)
231 {
232 	unsigned char c;
233 	if (sp_automatic_cmdcheck(command))
234 		return 1;
235 	if (serialport_write(&command, 1) != 0) {
236 		msg_perr("Error: cannot write op code: %s\n", strerror(errno));
237 		return 1;
238 	}
239 	if (serialport_write(params, parmlen) != 0) {
240 		msg_perr("Error: cannot write parameters: %s\n", strerror(errno));
241 		return 1;
242 	}
243 	if (serialport_read(&c, 1) != 0) {
244 		msg_perr("Error: cannot read from device: %s\n", strerror(errno));
245 		return 1;
246 	}
247 	if (c == S_NAK)
248 		return 1;
249 	if (c != S_ACK) {
250 		msg_perr("Error: invalid response 0x%02X from device (to command 0x%02X)\n", c, command);
251 		return 1;
252 	}
253 	if (retlen) {
254 		if (serialport_read(retparms, retlen) != 0) {
255 			msg_perr("Error: cannot read return parameters: %s\n", strerror(errno));
256 			return 1;
257 		}
258 	}
259 	return 0;
260 }
261 
sp_flush_stream(void)262 static int sp_flush_stream(void)
263 {
264 	if (sp_streamed_transmit_ops)
265 		do {
266 			unsigned char c;
267 			if (serialport_read(&c, 1) != 0) {
268 				msg_perr("Error: cannot read from device (flushing stream)");
269 				return 1;
270 			}
271 			if (c == S_NAK) {
272 				msg_perr("Error: NAK to a stream buffer operation\n");
273 				return 1;
274 			}
275 			if (c != S_ACK) {
276 				msg_perr("Error: Invalid reply 0x%02X from device\n", c);
277 				return 1;
278 			}
279 		} while (--sp_streamed_transmit_ops);
280 	sp_streamed_transmit_ops = 0;
281 	sp_streamed_transmit_bytes = 0;
282 	return 0;
283 }
284 
sp_stream_buffer_op(uint8_t cmd,uint32_t parmlen,uint8_t * parms)285 static int sp_stream_buffer_op(uint8_t cmd, uint32_t parmlen, uint8_t *parms)
286 {
287 	uint8_t *sp;
288 	if (sp_automatic_cmdcheck(cmd))
289 		return 1;
290 
291 	sp = malloc(1 + parmlen);
292 	if (!sp) {
293 		msg_perr("Error: cannot malloc command buffer\n");
294 		return 1;
295 	}
296 	sp[0] = cmd;
297 	if (parms)
298 		memcpy(&(sp[1]), parms, parmlen);
299 
300 	if (sp_streamed_transmit_bytes >= (1 + parmlen + sp_device_serbuf_size)) {
301 		if (sp_flush_stream() != 0) {
302 			free(sp);
303 			return 1;
304 		}
305 	}
306 	if (serialport_write(sp, 1 + parmlen) != 0) {
307 		msg_perr("Error: cannot write command\n");
308 		free(sp);
309 		return 1;
310 	}
311 	sp_streamed_transmit_ops += 1;
312 	sp_streamed_transmit_bytes += 1 + parmlen;
313 
314 	free(sp);
315 	return 0;
316 }
317 
318 /* Move an in flashrom buffer existing write-n operation to the on-device operation buffer. */
sp_pass_writen(void)319 static int sp_pass_writen(void)
320 {
321 	unsigned char header[7];
322 	msg_pspew(MSGHEADER "Passing write-n bytes=%d addr=0x%x\n", sp_write_n_bytes, sp_write_n_addr);
323 	if (sp_streamed_transmit_bytes >= (7 + sp_write_n_bytes + sp_device_serbuf_size)) {
324 		if (sp_flush_stream() != 0) {
325 			return 1;
326 		}
327 	}
328 	/* In case it's just a single byte send it as a single write. */
329 	if (sp_write_n_bytes == 1) {
330 		sp_write_n_bytes = 0;
331 		header[0] = (sp_write_n_addr >> 0) & 0xFF;
332 		header[1] = (sp_write_n_addr >> 8) & 0xFF;
333 		header[2] = (sp_write_n_addr >> 16) & 0xFF;
334 		header[3] = sp_write_n_buf[0];
335 		if (sp_stream_buffer_op(S_CMD_O_WRITEB, 4, header) != 0)
336 			return 1;
337 		sp_opbuf_usage += 5;
338 		return 0;
339 	}
340 	header[0] = S_CMD_O_WRITEN;
341 	header[1] = (sp_write_n_bytes >> 0) & 0xFF;
342 	header[2] = (sp_write_n_bytes >> 8) & 0xFF;
343 	header[3] = (sp_write_n_bytes >> 16) & 0xFF;
344 	header[4] = (sp_write_n_addr >> 0) & 0xFF;
345 	header[5] = (sp_write_n_addr >> 8) & 0xFF;
346 	header[6] = (sp_write_n_addr >> 16) & 0xFF;
347 	if (serialport_write(header, 7) != 0) {
348 		msg_perr(MSGHEADER "Error: cannot write write-n command\n");
349 		return 1;
350 	}
351 	if (serialport_write(sp_write_n_buf, sp_write_n_bytes) != 0) {
352 		msg_perr(MSGHEADER "Error: cannot write write-n data");
353 		return 1;
354 	}
355 	sp_streamed_transmit_bytes += 7 + sp_write_n_bytes;
356 	sp_streamed_transmit_ops += 1;
357 	sp_opbuf_usage += 7 + sp_write_n_bytes;
358 	sp_write_n_bytes = 0;
359 	sp_prev_was_write = 0;
360 	return 0;
361 }
362 
sp_execute_opbuf_noflush(void)363 static int sp_execute_opbuf_noflush(void)
364 {
365 	if ((sp_max_write_n) && (sp_write_n_bytes)) {
366 		if (sp_pass_writen() != 0) {
367 			msg_perr("Error: could not transfer write buffer\n");
368 			return 1;
369 		}
370 	}
371 	if (sp_stream_buffer_op(S_CMD_O_EXEC, 0, NULL) != 0) {
372 		msg_perr("Error: could not execute command buffer\n");
373 		return 1;
374 	}
375 	msg_pspew(MSGHEADER "Executed operation buffer of %d bytes\n", sp_opbuf_usage);
376 	sp_opbuf_usage = 0;
377 	sp_prev_was_write = 0;
378 	return 0;
379 }
380 
sp_execute_opbuf(void)381 static int sp_execute_opbuf(void)
382 {
383 	if (sp_execute_opbuf_noflush() != 0)
384 		return 1;
385 	if (sp_flush_stream() != 0)
386 		return 1;
387 
388 	return 0;
389 }
390 
serprog_spi_send_command(const struct flashctx * flash,unsigned int writecnt,unsigned int readcnt,const unsigned char * writearr,unsigned char * readarr)391 static int serprog_spi_send_command(const struct flashctx *flash,
392 				    unsigned int writecnt, unsigned int readcnt,
393 				    const unsigned char *writearr,
394 				    unsigned char *readarr)
395 {
396 	unsigned char *parmbuf;
397 	int ret;
398 	msg_pspew("%s, writecnt=%i, readcnt=%i\n", __func__, writecnt, readcnt);
399 	if ((sp_opbuf_usage) || (sp_max_write_n && sp_write_n_bytes)) {
400 		if (sp_execute_opbuf() != 0) {
401 			msg_perr("Error: could not execute command buffer before sending SPI commands.\n");
402 			return 1;
403 		}
404 	}
405 
406 	parmbuf = malloc(writecnt + 6);
407 	if (!parmbuf) {
408 		msg_perr("Error: could not allocate SPI send param buffer.\n");
409 		return 1;
410 	}
411 	parmbuf[0] = (writecnt >> 0) & 0xFF;
412 	parmbuf[1] = (writecnt >> 8) & 0xFF;
413 	parmbuf[2] = (writecnt >> 16) & 0xFF;
414 	parmbuf[3] = (readcnt >> 0) & 0xFF;
415 	parmbuf[4] = (readcnt >> 8) & 0xFF;
416 	parmbuf[5] = (readcnt >> 16) & 0xFF;
417 	memcpy(parmbuf + 6, writearr, writecnt);
418 	ret = sp_docommand(S_CMD_O_SPIOP, writecnt + 6, parmbuf, readcnt,
419 			   readarr);
420 	free(parmbuf);
421 	return ret;
422 }
423 
serprog_shutdown(void * data)424 static int serprog_shutdown(void *data)
425 {
426 	if ((sp_opbuf_usage) || (sp_max_write_n && sp_write_n_bytes))
427 	if (sp_execute_opbuf() != 0)
428 		msg_pwarn("Could not flush command buffer.\n");
429 	if (sp_check_commandavail(S_CMD_S_PIN_STATE)) {
430 		uint8_t dis = 0;
431 		if (sp_docommand(S_CMD_S_PIN_STATE, 1, &dis, 0, NULL) == 0)
432 			msg_pdbg(MSGHEADER "Output drivers disabled\n");
433 		else
434 			msg_pwarn(MSGHEADER "%s: Warning: could not disable output buffers\n", __func__);
435 	}
436 	/* FIXME: fix sockets on windows(?), especially closing */
437 	serialport_shutdown(&sp_fd);
438 	if (sp_max_write_n)
439 		free(sp_write_n_buf);
440 	return 0;
441 }
442 
serprog_map(const char * descr,uintptr_t phys_addr,size_t len)443 static void *serprog_map(const char *descr, uintptr_t phys_addr, size_t len)
444 {
445 	/* Serprog transmits 24 bits only and assumes the underlying implementation handles any remaining bits
446 	 * correctly (usually setting them to one either in software (for FWH/LPC) or relying on the fact that
447 	 * the hardware observes a subset of the address bits only). Combined with the standard mapping of
448 	 * flashrom this creates a 16 MB-wide window just below the 4 GB boundary where serprog can operate (as
449 	 * needed for non-SPI chips). Below we make sure that the requested range is within this window. */
450 	if ((phys_addr & 0xFF000000) == 0xFF000000) {
451 		return (void*)phys_addr;
452 	}
453 	msg_pwarn(MSGHEADER "requested mapping %s is incompatible: 0x%zx bytes at 0x%0*" PRIxPTR ".\n",
454 		  descr, len, PRIxPTR_WIDTH, phys_addr);
455 	return NULL;
456 }
457 
458 static void serprog_delay(const struct flashctx *flash, unsigned int usecs);
459 
460 static struct spi_master spi_master_serprog = {
461 	.map_flash_region	= serprog_map,
462 	.features	= SPI_MASTER_4BA,
463 	.max_data_read	= MAX_DATA_READ_UNLIMITED,
464 	.max_data_write	= MAX_DATA_WRITE_UNLIMITED,
465 	.command	= serprog_spi_send_command,
466 	.read		= default_spi_read,
467 	.write_256	= default_spi_write_256,
468 	.delay		= serprog_delay,
469 };
470 
sp_check_opbuf_usage(int bytes_to_be_added)471 static int sp_check_opbuf_usage(int bytes_to_be_added)
472 {
473 	if (sp_device_opbuf_size <= (sp_opbuf_usage + bytes_to_be_added)) {
474 		/* If this happens in the middle of a page load the page load will probably fail. */
475 		msg_pwarn(MSGHEADER "Warning: executed operation buffer due to size reasons\n");
476 		if (sp_execute_opbuf() != 0)
477 			return 1;
478 	}
479 	return 0;
480 }
481 
serprog_chip_writeb(const struct flashctx * flash,uint8_t val,chipaddr addr)482 static void serprog_chip_writeb(const struct flashctx *flash, uint8_t val,
483 				chipaddr addr)
484 {
485 	msg_pspew("%s\n", __func__);
486 	if (sp_max_write_n) {
487 		if ((sp_prev_was_write)
488 		    && (addr == (sp_write_n_addr + sp_write_n_bytes))) {
489 			sp_write_n_buf[sp_write_n_bytes++] = val;
490 		} else {
491 			if ((sp_prev_was_write) && (sp_write_n_bytes))
492 				sp_pass_writen();
493 			sp_prev_was_write = 1;
494 			sp_write_n_addr = addr;
495 			sp_write_n_bytes = 1;
496 			sp_write_n_buf[0] = val;
497 		}
498 		sp_check_opbuf_usage(7 + sp_write_n_bytes);
499 		if (sp_write_n_bytes >= sp_max_write_n)
500 			sp_pass_writen();
501 	} else {
502 		/* We will have to do single writeb ops. */
503 		unsigned char writeb_parm[4];
504 		sp_check_opbuf_usage(6);
505 		writeb_parm[0] = (addr >> 0) & 0xFF;
506 		writeb_parm[1] = (addr >> 8) & 0xFF;
507 		writeb_parm[2] = (addr >> 16) & 0xFF;
508 		writeb_parm[3] = val;
509 		sp_stream_buffer_op(S_CMD_O_WRITEB, 4, writeb_parm); // FIXME: return error
510 		sp_opbuf_usage += 5;
511 	}
512 }
513 
serprog_chip_readb(const struct flashctx * flash,const chipaddr addr)514 static uint8_t serprog_chip_readb(const struct flashctx *flash,
515 				  const chipaddr addr)
516 {
517 	unsigned char c;
518 	unsigned char buf[3];
519 	/* Will stream the read operation - eg. add it to the stream buffer, *
520 	 * then flush the buffer, then read the read answer.		     */
521 	if ((sp_opbuf_usage) || (sp_max_write_n && sp_write_n_bytes))
522 		sp_execute_opbuf_noflush();
523 	buf[0] = ((addr >> 0) & 0xFF);
524 	buf[1] = ((addr >> 8) & 0xFF);
525 	buf[2] = ((addr >> 16) & 0xFF);
526 	sp_stream_buffer_op(S_CMD_R_BYTE, 3, buf); // FIXME: return error
527 	sp_flush_stream(); // FIXME: return error
528 	if (serialport_read(&c, 1) != 0)
529 		msg_perr(MSGHEADER "readb byteread");  // FIXME: return error
530 	msg_pspew("%s addr=0x%" PRIxPTR " returning 0x%02X\n", __func__, addr, c);
531 	return c;
532 }
533 
534 /* Local version that really does the job, doesn't care of max_read_n. */
sp_do_read_n(uint8_t * buf,const chipaddr addr,size_t len)535 static int sp_do_read_n(uint8_t * buf, const chipaddr addr, size_t len)
536 {
537 	unsigned char sbuf[6];
538 	msg_pspew("%s: addr=0x%" PRIxPTR " len=%zu\n", __func__, addr, len);
539 	/* Stream the read-n -- as above. */
540 	if ((sp_opbuf_usage) || (sp_max_write_n && sp_write_n_bytes))
541 		sp_execute_opbuf_noflush();
542 	sbuf[0] = ((addr >> 0) & 0xFF);
543 	sbuf[1] = ((addr >> 8) & 0xFF);
544 	sbuf[2] = ((addr >> 16) & 0xFF);
545 	sbuf[3] = ((len >> 0) & 0xFF);
546 	sbuf[4] = ((len >> 8) & 0xFF);
547 	sbuf[5] = ((len >> 16) & 0xFF);
548 	sp_stream_buffer_op(S_CMD_R_NBYTES, 6, sbuf);
549 	if (sp_flush_stream() != 0)
550 		return 1;
551 	if (serialport_read(buf, len) != 0) {
552 		msg_perr(MSGHEADER "Error: cannot read read-n data");
553 		return 1;
554 	}
555 	return 0;
556 }
557 
558 /* The externally called version that makes sure that max_read_n is obeyed. */
serprog_chip_readn(const struct flashctx * flash,uint8_t * buf,const chipaddr addr,size_t len)559 static void serprog_chip_readn(const struct flashctx *flash, uint8_t * buf,
560 			       const chipaddr addr, size_t len)
561 {
562 	size_t lenm = len;
563 	chipaddr addrm = addr;
564 	while ((sp_max_read_n != 0) && (lenm > sp_max_read_n)) {
565 		sp_do_read_n(&(buf[addrm-addr]), addrm, sp_max_read_n); // FIXME: return error
566 		addrm += sp_max_read_n;
567 		lenm -= sp_max_read_n;
568 	}
569 	if (lenm)
570 		sp_do_read_n(&(buf[addrm-addr]), addrm, lenm); // FIXME: return error
571 }
572 
serprog_delay(const struct flashctx * flash,unsigned int usecs)573 static void serprog_delay(const struct flashctx *flash, unsigned int usecs)
574 {
575 	unsigned char buf[4];
576 	msg_pspew("%s usecs=%d\n", __func__, usecs);
577 	if (!sp_check_commandavail(S_CMD_O_DELAY)) {
578 		msg_pdbg2("serprog_delay used, but programmer doesn't support delays natively - emulating\n");
579 		default_delay(usecs);
580 		return;
581 	}
582 	if ((sp_max_write_n) && (sp_write_n_bytes))
583 		sp_pass_writen();
584 	sp_check_opbuf_usage(5);
585 	buf[0] = ((usecs >> 0) & 0xFF);
586 	buf[1] = ((usecs >> 8) & 0xFF);
587 	buf[2] = ((usecs >> 16) & 0xFF);
588 	buf[3] = ((usecs >> 24) & 0xFF);
589 	sp_stream_buffer_op(S_CMD_O_DELAY, 4, buf);
590 	sp_opbuf_usage += 5;
591 	sp_prev_was_write = 0;
592 }
593 
594 static const struct par_master par_master_serprog = {
595 	.map_flash_region	= serprog_map,
596 	.chip_readb	= serprog_chip_readb,
597 	.chip_readn	= serprog_chip_readn,
598 	.chip_writeb	= serprog_chip_writeb,
599 	.delay		= serprog_delay,
600 };
601 
602 static enum chipbustype serprog_buses_supported = BUS_NONE;
603 
serprog_init(const struct programmer_cfg * cfg)604 static int serprog_init(const struct programmer_cfg *cfg)
605 {
606 	uint16_t iface;
607 	unsigned char pgmname[17];
608 	unsigned char rbuf[3];
609 	unsigned char c;
610 	char *device;
611 	bool have_device = false;
612 
613 	/* the parameter is either of format "dev=/dev/device[:baud]" or "ip=ip:port" */
614 	device = extract_programmer_param_str(cfg, "dev");
615 	if (device && strlen(device)) {
616 		char *baud_str = strstr(device, ":");
617 		if (baud_str != NULL) {
618 			/* Split device from baudrate. */
619 			*baud_str = '\0';
620 			baud_str++;
621 		}
622 		int baud;
623 		/* Convert baud string to value.
624 		 * baud_str is either NULL (if strstr can't find the colon), points to the \0 after the colon
625 		 * if no characters where given after the colon, or a string to convert... */
626 		if (baud_str == NULL || *baud_str == '\0') {
627 			baud = -1;
628 			msg_pdbg("No baudrate specified, using the hardware's defaults.\n");
629 		} else {
630 			baud = atoi(baud_str); // FIXME: replace atoi with strtoul
631 		}
632 		if (strlen(device) > 0) {
633 			sp_fd = sp_openserport(device, baud);
634 			if (sp_fd == SER_INV_FD) {
635 				free(device);
636 				return 1;
637 			}
638 			have_device = true;
639 		}
640 	}
641 
642 #if !IS_WINDOWS
643 	if (device && !strlen(device)) {
644 		msg_perr("Error: No device specified.\n"
645 			 "Use flashrom -p serprog:dev=/dev/device[:baud]\n");
646 		free(device);
647 		return 1;
648 	}
649 	free(device);
650 
651 	device = extract_programmer_param_str(cfg, "ip");
652 	if (have_device && device) {
653 		msg_perr("Error: Both host and device specified.\n"
654 			 "Please use either dev= or ip= but not both.\n");
655 		free(device);
656 		return 1;
657 	}
658 	if (device && strlen(device)) {
659 		char *port = strstr(device, ":");
660 		if (port != NULL) {
661 			/* Split host from port. */
662 			*port = '\0';
663 			port++;
664 		}
665 		if (!port || !strlen(port)) {
666 			msg_perr("Error: No port specified.\n"
667 				 "Use flashrom -p serprog:ip=ipaddr:port\n");
668 			free(device);
669 			return 1;
670 		}
671 		if (strlen(device)) {
672 			sp_fd = sp_opensocket(device, atoi(port)); // FIXME: replace atoi with strtoul
673 			if (sp_fd < 0) {
674 				free(device);
675 				return 1;
676 			}
677 			have_device = true;
678 		}
679 	}
680 	if (device && !strlen(device)) {
681 		msg_perr("Error: No host specified.\n"
682 			 "Use flashrom -p serprog:ip=ipaddr:port\n");
683 		free(device);
684 		return 1;
685 	}
686 #endif
687 	free(device);
688 
689 	if (!have_device) {
690 #if IS_WINDOWS
691 		msg_perr("Error: No device specified.\n"
692 			 "Use flashrom -p serprog:dev=comN[:baud]\n");
693 #else
694 		msg_perr("Error: Neither host nor device specified.\n"
695 			 "Use flashrom -p serprog:dev=/dev/device:baud or "
696 			 "flashrom -p serprog:ip=ipaddr:port\n");
697 #endif
698 		return 1;
699 	}
700 
701 	msg_pdbg(MSGHEADER "connected - attempting to synchronize\n");
702 
703 	sp_check_avail_automatic = 0;
704 
705 	if (sp_synchronize())
706 		goto init_err_cleanup_exit;
707 
708 	msg_pdbg(MSGHEADER "Synchronized\n");
709 
710 	if (sp_docommand(S_CMD_Q_IFACE, 0, NULL, 2, &iface)) {
711 		msg_perr("Error: NAK to query interface version\n");
712 		goto init_err_cleanup_exit;
713 	}
714 
715 	if (iface != 1) {
716 		msg_perr("Error: Unknown interface version: %d\n", iface);
717 		goto init_err_cleanup_exit;
718 	}
719 
720 	msg_pdbg(MSGHEADER "Interface version ok.\n");
721 
722 	if (sp_docommand(S_CMD_Q_CMDMAP, 0, NULL, 32, sp_cmdmap)) {
723 		msg_perr("Error: query command map not supported\n");
724 		goto init_err_cleanup_exit;
725 	}
726 
727 	sp_check_avail_automatic = 1;
728 
729 	/* FIXME: This assumes that serprog device bustypes are always
730 	 * identical with flashrom bustype enums and that they all fit
731 	 * in a single byte.
732 	 */
733 	if (sp_docommand(S_CMD_Q_BUSTYPE, 0, NULL, 1, &c)) {
734 		msg_pwarn("Warning: NAK to query supported buses\n");
735 		c = BUS_NONSPI;	/* A reasonable default for now. */
736 	}
737 	serprog_buses_supported = c;
738 
739 	msg_pdbg(MSGHEADER "Bus support: parallel=%s, LPC=%s, FWH=%s, SPI=%s\n",
740 		 (c & BUS_PARALLEL) ? "on" : "off",
741 		 (c & BUS_LPC) ? "on" : "off",
742 		 (c & BUS_FWH) ? "on" : "off",
743 		 (c & BUS_SPI) ? "on" : "off");
744 	/* Check for the minimum operational set of commands. */
745 	if (serprog_buses_supported & BUS_SPI) {
746 		uint8_t bt = BUS_SPI;
747 		char *spispeed, *cs;
748 		if (sp_check_commandavail(S_CMD_O_SPIOP) == 0) {
749 			msg_perr("Error: SPI operation not supported while the "
750 				 "bustype is SPI\n");
751 			goto init_err_cleanup_exit;
752 		}
753 		if (sp_docommand(S_CMD_S_BUSTYPE, 1, &bt, 0, NULL))
754 			goto init_err_cleanup_exit;
755 		/* Success of any of these commands is optional. We don't need
756 		   the programmer to tell us its limits, but if it doesn't, we
757 		   will assume stuff, so it's in the programmers best interest
758 		   to tell us. */
759 		if (!sp_docommand(S_CMD_Q_WRNMAXLEN, 0, NULL, 3, rbuf)) {
760 			uint32_t v;
761 			v = ((unsigned int)(rbuf[0]) << 0);
762 			v |= ((unsigned int)(rbuf[1]) << 8);
763 			v |= ((unsigned int)(rbuf[2]) << 16);
764 			if (v == 0)
765 				v = (1 << 24) - 1; /* SPI-op maximum. */
766 			spi_master_serprog.max_data_write = v;
767 			msg_pdbg(MSGHEADER "Maximum write-n length is %d\n", v);
768 		}
769 		if (!sp_docommand(S_CMD_Q_RDNMAXLEN, 0, NULL, 3, rbuf)) {
770 			uint32_t v;
771 			v = ((unsigned int)(rbuf[0]) << 0);
772 			v |= ((unsigned int)(rbuf[1]) << 8);
773 			v |= ((unsigned int)(rbuf[2]) << 16);
774 			if (v == 0)
775 				v = (1 << 24) - 1; /* SPI-op maximum. */
776 			spi_master_serprog.max_data_read = v;
777 			msg_pdbg(MSGHEADER "Maximum read-n length is %d\n", v);
778 		}
779 		spispeed = extract_programmer_param_str(cfg, "spispeed");
780 		if (spispeed && strlen(spispeed)) {
781 			uint32_t f_spi_req, f_spi;
782 			uint8_t buf[4];
783 			char *f_spi_suffix;
784 
785 			errno = 0;
786 			f_spi_req = strtol(spispeed, &f_spi_suffix, 0);
787 			if (errno != 0 || spispeed == f_spi_suffix) {
788 				msg_perr("Error: Could not convert 'spispeed'.\n");
789 				free(spispeed);
790 				goto init_err_cleanup_exit;
791 			}
792 			if (strlen(f_spi_suffix) == 1) {
793 				if (!strcasecmp(f_spi_suffix, "M")) {
794 					f_spi_req *= 1000000;
795 				} else if (!strcasecmp(f_spi_suffix, "k")) {
796 					f_spi_req *= 1000;
797 				} else {
798 					msg_perr("Error: Garbage following 'spispeed' value.\n");
799 					free(spispeed);
800 					goto init_err_cleanup_exit;
801 				}
802 			} else if (strlen(f_spi_suffix) > 1) {
803 				msg_perr("Error: Garbage following 'spispeed' value.\n");
804 				free(spispeed);
805 				goto init_err_cleanup_exit;
806 			}
807 
808 			buf[0] = (f_spi_req >> (0 * 8)) & 0xFF;
809 			buf[1] = (f_spi_req >> (1 * 8)) & 0xFF;
810 			buf[2] = (f_spi_req >> (2 * 8)) & 0xFF;
811 			buf[3] = (f_spi_req >> (3 * 8)) & 0xFF;
812 
813 			if (sp_check_commandavail(S_CMD_S_SPI_FREQ) == 0) {
814 				msg_pwarn(MSGHEADER "Warning: Setting the SPI clock rate is not supported!\n");
815 			} else if (sp_docommand(S_CMD_S_SPI_FREQ, 4, buf, 4, buf) == 0) {
816 				f_spi = buf[0];
817 				f_spi |= buf[1] << (1 * 8);
818 				f_spi |= buf[2] << (2 * 8);
819 				f_spi |= buf[3] << (3 * 8);
820 				msg_pdbg(MSGHEADER "Requested to set SPI clock frequency to %u Hz. "
821 					 "It was actually set to %u Hz\n", f_spi_req, f_spi);
822 			} else {
823 				msg_pwarn(MSGHEADER "Setting SPI clock rate to %u Hz failed!\n", f_spi_req);
824 			}
825 		}
826 		free(spispeed);
827 		cs = extract_programmer_param_str(cfg, "cs");
828 		if (cs && strlen(cs)) {
829 			char *endptr = NULL;
830 			errno = 0;
831 			unsigned long cs_num = strtoul(cs, &endptr, 0);
832 			if (errno || *endptr || cs_num > 255) {
833 				msg_perr("Error: Invalid chip select requested! "
834 				         "Only 0-255 are valid.\n");
835 				free(cs);
836 				goto init_err_cleanup_exit;
837 			}
838 			if (!sp_check_commandavail(S_CMD_S_SPI_CS)) {
839 				msg_perr("Error: Setting SPI chip select is not supported!\n");
840 				free(cs);
841 				goto init_err_cleanup_exit;
842 			}
843 			msg_pdbg(MSGHEADER "Requested to use chip select %lu.\n", cs_num);
844 			uint8_t cs_num8 = cs_num;
845 			if (sp_docommand(S_CMD_S_SPI_CS, 1, &cs_num8, 0, NULL)) {
846 				msg_perr("Error: Chip select %u not supported "
847 				         "by programmer!\n", cs_num8);
848 				free(cs);
849 				goto init_err_cleanup_exit;
850 			}
851 		}
852 		free(cs);
853 
854 		bt = serprog_buses_supported;
855 		if (sp_docommand(S_CMD_S_BUSTYPE, 1, &bt, 0, NULL))
856 			goto init_err_cleanup_exit;
857 	}
858 
859 	if (serprog_buses_supported & BUS_NONSPI) {
860 		if (sp_check_commandavail(S_CMD_O_INIT) == 0) {
861 			msg_perr("Error: Initialize operation buffer "
862 				 "not supported\n");
863 			goto init_err_cleanup_exit;
864 		}
865 
866 		if (sp_check_commandavail(S_CMD_O_DELAY) == 0) {
867 			msg_perr("Error: Write to opbuf: "
868 				 "delay not supported\n");
869 			goto init_err_cleanup_exit;
870 		}
871 
872 		/* S_CMD_O_EXEC availability checked later. */
873 
874 		if (sp_check_commandavail(S_CMD_R_BYTE) == 0) {
875 			msg_perr("Error: Single byte read not supported\n");
876 			goto init_err_cleanup_exit;
877 		}
878 		/* This could be translated to single byte reads (if missing),
879 		 * but now we don't support that. */
880 		if (sp_check_commandavail(S_CMD_R_NBYTES) == 0) {
881 			msg_perr("Error: Read n bytes not supported\n");
882 			goto init_err_cleanup_exit;
883 		}
884 		if (sp_check_commandavail(S_CMD_O_WRITEB) == 0) {
885 			msg_perr("Error: Write to opbuf: "
886 				 "write byte not supported\n");
887 			goto init_err_cleanup_exit;
888 		}
889 
890 		if (sp_docommand(S_CMD_Q_WRNMAXLEN, 0, NULL, 3, rbuf)) {
891 			msg_pdbg(MSGHEADER "Write-n not supported");
892 			sp_max_write_n = 0;
893 		} else {
894 			sp_max_write_n = ((unsigned int)(rbuf[0]) << 0);
895 			sp_max_write_n |= ((unsigned int)(rbuf[1]) << 8);
896 			sp_max_write_n |= ((unsigned int)(rbuf[2]) << 16);
897 			if (!sp_max_write_n) {
898 				sp_max_write_n = (1 << 24);
899 			}
900 			msg_pdbg(MSGHEADER "Maximum write-n length is %d\n",
901 				 sp_max_write_n);
902 			sp_write_n_buf = malloc(sp_max_write_n);
903 			if (!sp_write_n_buf) {
904 				msg_perr("Error: cannot allocate memory for "
905 					 "Write-n buffer\n");
906 				goto init_err_cleanup_exit;
907 			}
908 			sp_write_n_bytes = 0;
909 		}
910 
911 		if (sp_check_commandavail(S_CMD_Q_RDNMAXLEN) &&
912 		    (sp_docommand(S_CMD_Q_RDNMAXLEN, 0, NULL, 3, rbuf) == 0)) {
913 			sp_max_read_n = ((unsigned int)(rbuf[0]) << 0);
914 			sp_max_read_n |= ((unsigned int)(rbuf[1]) << 8);
915 			sp_max_read_n |= ((unsigned int)(rbuf[2]) << 16);
916 			msg_pdbg(MSGHEADER "Maximum read-n length is %d\n",
917 				 sp_max_read_n ? sp_max_read_n : (1 << 24));
918 		} else {
919 			msg_pdbg(MSGHEADER "Maximum read-n length "
920 				 "not reported\n");
921 			sp_max_read_n = 0;
922 		}
923 
924 	}
925 
926 	if (sp_docommand(S_CMD_Q_PGMNAME, 0, NULL, 16, pgmname)) {
927 		msg_pwarn("Warning: NAK to query programmer name\n");
928 		strcpy((char *)pgmname, "(unknown)");
929 	}
930 	pgmname[16] = 0;
931 	msg_pinfo(MSGHEADER "Programmer name is \"%s\"\n", pgmname);
932 
933 	if (sp_docommand(S_CMD_Q_SERBUF, 0, NULL, 2, &sp_device_serbuf_size)) {
934 		msg_pwarn("Warning: NAK to query serial buffer size\n");
935 	}
936 	msg_pdbg(MSGHEADER "Serial buffer size is %d\n",
937 		     sp_device_serbuf_size);
938 
939 	if (sp_check_commandavail(S_CMD_O_INIT)) {
940 		/* This would be inconsistent. */
941 		if (sp_check_commandavail(S_CMD_O_EXEC) == 0) {
942 			msg_perr("Error: Execute operation buffer not "
943 				 "supported\n");
944 			goto init_err_cleanup_exit;
945 		}
946 
947 		if (sp_docommand(S_CMD_O_INIT, 0, NULL, 0, NULL)) {
948 			msg_perr("Error: NAK to initialize operation buffer\n");
949 			goto init_err_cleanup_exit;
950 		}
951 
952 		if (sp_docommand(S_CMD_Q_OPBUF, 0, NULL, 2,
953 		    &sp_device_opbuf_size)) {
954 			msg_pwarn("Warning: NAK to query operation buffer size\n");
955 		}
956 		msg_pdbg(MSGHEADER "operation buffer size is %d\n",
957 			 sp_device_opbuf_size);
958 	}
959 
960 	if (sp_check_commandavail(S_CMD_S_PIN_STATE)) {
961 		uint8_t en = 1;
962 		if (sp_docommand(S_CMD_S_PIN_STATE, 1, &en, 0, NULL) != 0) {
963 			msg_perr("Error: could not enable output buffers\n");
964 			goto init_err_cleanup_exit;
965 		} else {
966 			msg_pdbg(MSGHEADER "Output drivers enabled\n");
967 		}
968 	} else {
969 		msg_pdbg(MSGHEADER "Warning: Programmer does not support toggling its output drivers\n");
970 	}
971 
972 	sp_prev_was_write = 0;
973 	sp_streamed_transmit_ops = 0;
974 	sp_streamed_transmit_bytes = 0;
975 	sp_opbuf_usage = 0;
976 
977 	if (register_shutdown(serprog_shutdown, NULL))
978 		goto init_err_cleanup_exit;
979 	if (serprog_buses_supported & BUS_SPI)
980 		register_spi_master(&spi_master_serprog, NULL);
981 	if (serprog_buses_supported & BUS_NONSPI)
982 		register_par_master(&par_master_serprog, serprog_buses_supported & BUS_NONSPI, NULL);
983 	return 0;
984 
985 init_err_cleanup_exit:
986 	serprog_shutdown(NULL);
987 	return 1;
988 }
989 
990 const struct programmer_entry programmer_serprog = {
991 	.name			= "serprog",
992 	.type			= OTHER,
993 				/* FIXME */
994 	.devs.note		= "All programmer devices speaking the serprog protocol\n",
995 	.init			= serprog_init,
996 };
997