packaging: minor amendments
[profile/ivi/flashrom.git] / serprog.c
1 /*
2  * This file is part of the flashrom project.
3  *
4  * Copyright (C) 2009, 2011 Urja Rannikko <urjaman@gmail.com>
5  * Copyright (C) 2009 Carl-Daniel Hailfinger
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
20  */
21
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <unistd.h>
25 #include <string.h>
26 #include <ctype.h>
27 #include <fcntl.h>
28 #include <sys/socket.h>
29 #include <arpa/inet.h>
30 #include <netinet/in.h>
31 #include <netinet/tcp.h>
32 #include <netdb.h>
33 #include <sys/stat.h>
34 #include <errno.h>
35 #include <inttypes.h>
36 #include <termios.h>
37 #include "flash.h"
38 #include "programmer.h"
39 #include "chipdrivers.h"
40
41 #define MSGHEADER "serprog: "
42
43 /*
44  * FIXME: This prototype was added to help reduce diffs for the shutdown
45  * registration patch, which shifted many lines of code to place
46  * serprog_shutdown() before serprog_init(). It should be removed soon.
47  */
48 static int serprog_shutdown(void *data);
49
50 #define S_ACK 0x06
51 #define S_NAK 0x15
52 #define S_CMD_NOP               0x00    /* No operation                                 */
53 #define S_CMD_Q_IFACE           0x01    /* Query interface version                      */
54 #define S_CMD_Q_CMDMAP          0x02    /* Query supported commands bitmap              */
55 #define S_CMD_Q_PGMNAME         0x03    /* Query programmer name                        */
56 #define S_CMD_Q_SERBUF          0x04    /* Query Serial Buffer Size                     */
57 #define S_CMD_Q_BUSTYPE         0x05    /* Query supported bustypes                     */
58 #define S_CMD_Q_CHIPSIZE        0x06    /* Query supported chipsize (2^n format)        */
59 #define S_CMD_Q_OPBUF           0x07    /* Query operation buffer size                  */
60 #define S_CMD_Q_WRNMAXLEN       0x08    /* Query opbuf-write-N maximum length           */
61 #define S_CMD_R_BYTE            0x09    /* Read a single byte                           */
62 #define S_CMD_R_NBYTES          0x0A    /* Read n bytes                                 */
63 #define S_CMD_O_INIT            0x0B    /* Initialize operation buffer                  */
64 #define S_CMD_O_WRITEB          0x0C    /* Write opbuf: Write byte with address         */
65 #define S_CMD_O_WRITEN          0x0D    /* Write to opbuf: Write-N                      */
66 #define S_CMD_O_DELAY           0x0E    /* Write opbuf: udelay                          */
67 #define S_CMD_O_EXEC            0x0F    /* Execute operation buffer                     */
68 #define S_CMD_SYNCNOP           0x10    /* Special no-operation that returns NAK+ACK    */
69 #define S_CMD_Q_RDNMAXLEN       0x11    /* Query read-n maximum length                  */
70 #define S_CMD_S_BUSTYPE         0x12    /* Set used bustype(s).                         */
71 #define S_CMD_O_SPIOP           0x13    /* Perform SPI operation.                       */
72
73 static uint16_t sp_device_serbuf_size = 16;
74 static uint16_t sp_device_opbuf_size = 300;
75 /* Bitmap of supported commands */
76 static uint8_t sp_cmdmap[32];
77
78 /* sp_prev_was_write used to detect writes with contiguous addresses
79         and combine them to write-n's */
80 static int sp_prev_was_write = 0;
81 /* sp_write_n_addr used as the starting addr of the currently
82         combined write-n operation */
83 static uint32_t sp_write_n_addr;
84 /* The maximum length of an write_n operation; 0 = write-n not supported */
85 static uint32_t sp_max_write_n = 0;
86 /* The maximum length of a read_n operation; 0 = 2^24 */
87 static uint32_t sp_max_read_n = 0;
88
89 /* A malloc'd buffer for combining the operation's data
90         and a counter that tells how much data is there. */
91 static uint8_t *sp_write_n_buf;
92 static uint32_t sp_write_n_bytes = 0;
93
94 /* sp_streamed_* used for flow control checking */
95 static int sp_streamed_transmit_ops = 0;
96 static int sp_streamed_transmit_bytes = 0;
97
98 /* sp_opbuf_usage used for counting the amount of
99         on-device operation buffer used */
100 static int sp_opbuf_usage = 0;
101 /* if true causes sp_docommand to automatically check
102         whether the command is supported before doing it */
103 static int sp_check_avail_automatic = 0;
104
105 static int sp_opensocket(char *ip, unsigned int port)
106 {
107         int flag = 1;
108         struct hostent *hostPtr = NULL;
109         union { struct sockaddr_in si; struct sockaddr s; } sp = {};
110         int sock;
111         msg_pdbg(MSGHEADER "IP %s port %d\n", ip, port);
112         sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
113         if (sock < 0) {
114                 msg_perr("Error: serprog cannot open socket: %s\n", strerror(errno));
115                 return -1;
116         }
117         hostPtr = gethostbyname(ip);
118         if (NULL == hostPtr) {
119                 hostPtr = gethostbyaddr(ip, strlen(ip), AF_INET);
120                 if (NULL == hostPtr) {
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, 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         setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, &flag, sizeof(int));
136         return sock;
137 }
138
139 static int sp_sync_read_timeout(int loops)
140 {
141         int i;
142         unsigned char c;
143         for (i = 0; i < loops; i++) {
144                 ssize_t rv;
145                 rv = read(sp_fd, &c, 1);
146                 if (rv == 1)
147                         return c;
148                 if ((rv == -1) && (errno != EAGAIN))
149                         sp_die("read");
150                 usleep(10 * 1000);      /* 10ms units */
151         }
152         return -1;
153 }
154
155 /* Synchronize: a bit tricky algorithm that tries to (and in my tests has *
156  * always succeeded in) bring the serial protocol to known waiting-for-   *
157  * command state - uses nonblocking read - rest of the driver uses        *
158  * blocking read - TODO: add an alarm() timer for the rest of the app on  *
159  * serial operations, though not such a big issue as the first thing to   *
160  * do is synchronize (eg. check that device is alive).                    */
161 static void sp_synchronize(void)
162 {
163         int i;
164         int flags = fcntl(sp_fd, F_GETFL);
165         unsigned char buf[8];
166         flags |= O_NONBLOCK;
167         fcntl(sp_fd, F_SETFL, flags);
168         /* First sends 8 NOPs, then flushes the return data - should cause *
169          * the device serial parser to get to a sane state, unless if it   *
170          * is waiting for a real long write-n.                             */
171         memset(buf, S_CMD_NOP, 8);
172         if (write(sp_fd, buf, 8) != 8)
173                 sp_die("flush write");
174         /* A second should be enough to get all the answers to the buffer */
175         usleep(1000 * 1000);
176         sp_flush_incoming();
177
178         /* Then try up to 8 times to send syncnop and get the correct special *
179          * return of NAK+ACK. Timing note: up to 10 characters, 10*50ms =     *
180          * up to 500ms per try, 8*0.5s = 4s; +1s (above) = up to 5s sync      *
181          * attempt, ~1s if immediate success.                                 */
182         for (i = 0; i < 8; i++) {
183                 int n;
184                 unsigned char c = S_CMD_SYNCNOP;
185                 if (write(sp_fd, &c, 1) != 1)
186                         sp_die("sync write");
187                 msg_pdbg(".");
188                 fflush(stdout);
189                 for (n = 0; n < 10; n++) {
190                         c = sp_sync_read_timeout(5);    /* wait up to 50ms */
191                         if (c != S_NAK)
192                                 continue;
193                         c = sp_sync_read_timeout(2);
194                         if (c != S_ACK)
195                                 continue;
196                         c = S_CMD_SYNCNOP;
197                         if (write(sp_fd, &c, 1) != 1)
198                                 sp_die("sync write");
199                         c = sp_sync_read_timeout(50);
200                         if (c != S_NAK)
201                                 break;  /* fail */
202                         c = sp_sync_read_timeout(10);
203                         if (c != S_ACK)
204                                 break;  /* fail */
205                         /* Ok, synchronized; back to blocking reads and return. */
206                         flags &= ~O_NONBLOCK;
207                         fcntl(sp_fd, F_SETFL, flags);
208                         msg_pdbg("\n");
209                         return;
210                 }
211         }
212         msg_perr("Error: cannot synchronize protocol "
213                 "- check communications and reset device?\n");
214         exit(1);
215 }
216
217 static int sp_check_commandavail(uint8_t command)
218 {
219         int byteoffs, bitoffs;
220         byteoffs = command / 8;
221         bitoffs = command % 8;
222         return (sp_cmdmap[byteoffs] & (1 << bitoffs)) ? 1 : 0;
223 }
224
225 static int sp_automatic_cmdcheck(uint8_t cmd)
226 {
227         if ((sp_check_avail_automatic) && (sp_check_commandavail(cmd) == 0)) {
228                 msg_pdbg("Warning: Automatic command availability check failed "
229                          "for cmd 0x%x - won't execute cmd\n", cmd);
230                 return 1;
231                 }
232         return 0;
233 }
234
235 static int sp_docommand(uint8_t command, uint32_t parmlen,
236                         uint8_t *params, uint32_t retlen, void *retparms)
237 {
238         unsigned char c;
239         if (sp_automatic_cmdcheck(command))
240                 return 1;
241         if (write(sp_fd, &command, 1) != 1) {
242                 msg_perr("Error: cannot write op code: %s\n", strerror(errno));
243                 return 1;
244         }
245         if (write(sp_fd, params, parmlen) != (parmlen)) {
246                 msg_perr("Error: cannot write parameters: %s\n", strerror(errno));
247                 return 1;
248         }
249         if (read(sp_fd, &c, 1) != 1) {
250                 msg_perr("Error: cannot read from device: %s\n", strerror(errno));
251                 return 1;
252         }
253         if (c == S_NAK)
254                 return 1;
255         if (c != S_ACK) {
256                 msg_perr("Error: invalid response 0x%02X from device\n", c);
257                 return 1;
258         }
259         if (retlen) {
260                 int rd_bytes = 0;
261                 do {
262                         int r;
263                         r = read(sp_fd, retparms + rd_bytes,
264                                  retlen - rd_bytes);
265                         if (r <= 0) {
266                                 msg_perr("Error: cannot read return parameters: %s\n", strerror(errno));
267                                 return 1;
268                         }
269                         rd_bytes += r;
270                 } while (rd_bytes != retlen);
271         }
272         return 0;
273 }
274
275 static void sp_flush_stream(void)
276 {
277         if (sp_streamed_transmit_ops)
278                 do {
279                         unsigned char c;
280                         if (read(sp_fd, &c, 1) != 1) {
281                                 sp_die("Error: cannot read from device (flushing stream)");
282                         }
283                         if (c == S_NAK) {
284                                 msg_perr("Error: NAK to a stream buffer operation\n");
285                                 exit(1);
286                         }
287                         if (c != S_ACK) {
288                                 msg_perr("Error: Invalid reply 0x%02X from device\n", c);
289                                 exit(1);
290                         }
291                 } while (--sp_streamed_transmit_ops);
292         sp_streamed_transmit_ops = 0;
293         sp_streamed_transmit_bytes = 0;
294 }
295
296 static int sp_stream_buffer_op(uint8_t cmd, uint32_t parmlen, uint8_t * parms)
297 {
298         uint8_t *sp;
299         if (sp_automatic_cmdcheck(cmd))
300                 return 1;
301         sp = malloc(1 + parmlen);
302         if (!sp) sp_die("Error: cannot malloc command buffer");
303         sp[0] = cmd;
304         memcpy(&(sp[1]), parms, parmlen);
305         if (sp_streamed_transmit_bytes >= (1 + parmlen + sp_device_serbuf_size))
306                 sp_flush_stream();
307         if (write(sp_fd, sp, 1 + parmlen) != (1 + parmlen))
308                 sp_die("Error: cannot write command");
309         free(sp);
310         sp_streamed_transmit_ops += 1;
311         sp_streamed_transmit_bytes += 1 + parmlen;
312         return 0;
313 }
314
315 static int serprog_spi_send_command(struct flashctx *flash,
316                                     unsigned int writecnt, unsigned int readcnt,
317                                     const unsigned char *writearr,
318                                     unsigned char *readarr);
319 static int serprog_spi_read(struct flashctx *flash, uint8_t *buf,
320                             unsigned int start, unsigned int len);
321 static struct spi_programmer spi_programmer_serprog = {
322         .type           = SPI_CONTROLLER_SERPROG,
323         .max_data_read  = MAX_DATA_READ_UNLIMITED,
324         .max_data_write = MAX_DATA_WRITE_UNLIMITED,
325         .command        = serprog_spi_send_command,
326         .multicommand   = default_spi_send_multicommand,
327         .read           = serprog_spi_read,
328         .write_256      = default_spi_write_256,
329         .write_aai      = default_spi_write_aai,
330 };
331
332 static void serprog_chip_writeb(const struct flashctx *flash, uint8_t val,
333                                 chipaddr addr);
334 static uint8_t serprog_chip_readb(const struct flashctx *flash,
335                                   const chipaddr addr);
336 static void serprog_chip_readn(const struct flashctx *flash, uint8_t *buf,
337                                const chipaddr addr, size_t len);
338 static const struct par_programmer par_programmer_serprog = {
339                 .chip_readb             = serprog_chip_readb,
340                 .chip_readw             = fallback_chip_readw,
341                 .chip_readl             = fallback_chip_readl,
342                 .chip_readn             = serprog_chip_readn,
343                 .chip_writeb            = serprog_chip_writeb,
344                 .chip_writew            = fallback_chip_writew,
345                 .chip_writel            = fallback_chip_writel,
346                 .chip_writen            = fallback_chip_writen,
347 };
348
349 static enum chipbustype serprog_buses_supported = BUS_NONE;
350
351 int serprog_init(void)
352 {
353         uint16_t iface;
354         unsigned char pgmname[17];
355         unsigned char rbuf[3];
356         unsigned char c;
357         char *device;
358         char *baudport;
359         int have_device = 0;
360
361         /* the parameter is either of format "dev=/dev/device:baud" or "ip=ip:port" */
362         device = extract_programmer_param("dev");
363         if (device && strlen(device)) {
364                 baudport = strstr(device, ":");
365                 if (baudport) {
366                         /* Split device from baudrate. */
367                         *baudport = '\0';
368                         baudport++;
369                 }
370                 if (!baudport || !strlen(baudport)) {
371                         msg_perr("Error: No baudrate specified.\n"
372                                  "Use flashrom -p serprog:dev=/dev/device:baud\n");
373                         free(device);
374                         return 1;
375                 }
376                 if (strlen(device)) {
377                         sp_fd = sp_openserport(device, atoi(baudport));
378                         if (sp_fd < 0) {
379                                 free(device);
380                                 return 1;
381                         }
382                         have_device++;
383                 }
384         }
385         if (device && !strlen(device)) {
386                 msg_perr("Error: No device specified.\n"
387                          "Use flashrom -p serprog:dev=/dev/device:baud\n");
388                 free(device);
389                 return 1;
390         }
391         free(device);
392
393         device = extract_programmer_param("ip");
394         if (have_device && device) {
395                 msg_perr("Error: Both host and device specified.\n"
396                          "Please use either dev= or ip= but not both.\n");
397                 free(device);
398                 return 1;
399         }
400         if (device && strlen(device)) {
401                 baudport = strstr(device, ":");
402                 if (baudport) {
403                         /* Split host from port. */
404                         *baudport = '\0';
405                         baudport++;
406                 }
407                 if (!baudport || !strlen(baudport)) {
408                         msg_perr("Error: No port specified.\n"
409                                  "Use flashrom -p serprog:ip=ipaddr:port\n");
410                         free(device);
411                         return 1;
412                 }
413                 if (strlen(device)) {
414                         sp_fd = sp_opensocket(device, atoi(baudport));
415                         if (sp_fd < 0) {
416                                 free(device);
417                                 return 1;
418                         }
419                         have_device++;
420                 }
421         }
422         if (device && !strlen(device)) {
423                 msg_perr("Error: No host specified.\n"
424                          "Use flashrom -p serprog:ip=ipaddr:port\n");
425                 free(device);
426                 return 1;
427         }
428         free(device);
429
430         if (!have_device) {
431                 msg_perr("Error: Neither host nor device specified.\n"
432                          "Use flashrom -p serprog:dev=/dev/device:baud or "
433                          "flashrom -p serprog:ip=ipaddr:port\n");
434                 return 1;
435         }
436
437         if (register_shutdown(serprog_shutdown, NULL))
438                 return 1;
439
440         msg_pdbg(MSGHEADER "connected - attempting to synchronize\n");
441
442         sp_check_avail_automatic = 0;
443
444         sp_synchronize();
445
446         msg_pdbg(MSGHEADER "Synchronized\n");
447
448         if (sp_docommand(S_CMD_Q_IFACE, 0, NULL, 2, &iface)) {
449                 msg_perr("Error: NAK to query interface version\n");
450                 return 1;
451         }
452
453         if (iface != 1) {
454                 msg_perr("Error: Unknown interface version: %d\n", iface);
455                 return 1;
456         }
457
458         msg_pdbg(MSGHEADER "Interface version ok.\n");
459
460         if (sp_docommand(S_CMD_Q_CMDMAP, 0, NULL, 32, sp_cmdmap)) {
461                 msg_perr("Error: query command map not supported\n");
462                 return 1;
463         }
464
465         sp_check_avail_automatic = 1;
466
467         /* FIXME: This assumes that serprog device bustypes are always
468          * identical with flashrom bustype enums and that they all fit
469          * in a single byte.
470          */
471         if (sp_docommand(S_CMD_Q_BUSTYPE, 0, NULL, 1, &c)) {
472                 msg_perr("Warning: NAK to query supported buses\n");
473                 c = BUS_NONSPI; /* A reasonable default for now. */
474         }
475         serprog_buses_supported = c;
476
477         msg_pdbg(MSGHEADER "Bus support: parallel=%s, LPC=%s, FWH=%s, SPI=%s\n",
478                  (c & BUS_PARALLEL) ? "on" : "off",
479                  (c & BUS_LPC) ? "on" : "off",
480                  (c & BUS_FWH) ? "on" : "off",
481                  (c & BUS_SPI) ? "on" : "off");
482         /* Check for the minimum operational set of commands. */
483         if (serprog_buses_supported & BUS_SPI) {
484                 uint8_t bt = BUS_SPI;
485                 if (sp_check_commandavail(S_CMD_O_SPIOP) == 0) {
486                         msg_perr("Error: SPI operation not supported while the "
487                                  "bustype is SPI\n");
488                         return 1;
489                 }
490                 if (sp_docommand(S_CMD_S_BUSTYPE, 1, &bt, 0, NULL))
491                         return 1;
492                 /* Success of any of these commands is optional. We don't need
493                    the programmer to tell us its limits, but if it doesn't, we
494                    will assume stuff, so it's in the programmers best interest
495                    to tell us. */
496                 if (!sp_docommand(S_CMD_Q_WRNMAXLEN, 0, NULL, 3, rbuf)) {
497                         uint32_t v;
498                         v = ((unsigned int)(rbuf[0]) << 0);
499                         v |= ((unsigned int)(rbuf[1]) << 8);
500                         v |= ((unsigned int)(rbuf[2]) << 16);
501                         if (v == 0)
502                                 v = (1 << 24) - 1; /* SPI-op maximum. */
503                         spi_programmer_serprog.max_data_write = v;
504                         msg_pdbg(MSGHEADER "Maximum write-n length is %d\n", v);
505                 }
506                 if (!sp_docommand(S_CMD_Q_RDNMAXLEN, 0, NULL, 3, rbuf)) {
507                         uint32_t v;
508                         v = ((unsigned int)(rbuf[0]) << 0);
509                         v |= ((unsigned int)(rbuf[1]) << 8);
510                         v |= ((unsigned int)(rbuf[2]) << 16);
511                         if (v == 0)
512                                 v = (1 << 24) - 1; /* SPI-op maximum. */
513                         spi_programmer_serprog.max_data_read = v;
514                         msg_pdbg(MSGHEADER "Maximum read-n length is %d\n", v);
515                 }
516                 bt = serprog_buses_supported;
517                 if (sp_docommand(S_CMD_S_BUSTYPE, 1, &bt, 0, NULL))
518                         return 1;
519         }
520
521         if (serprog_buses_supported & BUS_NONSPI) {
522                 if (sp_check_commandavail(S_CMD_O_INIT) == 0) {
523                         msg_perr("Error: Initialize operation buffer "
524                                  "not supported\n");
525                         return 1;
526                 }
527
528                 if (sp_check_commandavail(S_CMD_O_DELAY) == 0) {
529                         msg_perr("Error: Write to opbuf: "
530                                  "delay not supported\n");
531                         return 1;
532                 }
533
534                 /* S_CMD_O_EXEC availability checked later. */
535
536                 if (sp_check_commandavail(S_CMD_R_BYTE) == 0) {
537                         msg_perr("Error: Single byte read not supported\n");
538                         return 1;
539                 }
540                 /* This could be translated to single byte reads (if missing),
541                  * but now we don't support that. */
542                 if (sp_check_commandavail(S_CMD_R_NBYTES) == 0) {
543                         msg_perr("Error: Read n bytes not supported\n");
544                         return 1;
545                 }
546                 if (sp_check_commandavail(S_CMD_O_WRITEB) == 0) {
547                         msg_perr("Error: Write to opbuf: "
548                                  "write byte not supported\n");
549                         return 1;
550                 }
551
552                 if (sp_docommand(S_CMD_Q_WRNMAXLEN, 0, NULL, 3, rbuf)) {
553                         msg_pdbg(MSGHEADER "Write-n not supported");
554                         sp_max_write_n = 0;
555                 } else {
556                         sp_max_write_n = ((unsigned int)(rbuf[0]) << 0);
557                         sp_max_write_n |= ((unsigned int)(rbuf[1]) << 8);
558                         sp_max_write_n |= ((unsigned int)(rbuf[2]) << 16);
559                         if (!sp_max_write_n) {
560                                 sp_max_write_n = (1 << 24);
561                         }
562                         msg_pdbg(MSGHEADER "Maximum write-n length is %d\n",
563                                  sp_max_write_n);
564                         sp_write_n_buf = malloc(sp_max_write_n);
565                         if (!sp_write_n_buf) {
566                                 msg_perr("Error: cannot allocate memory for "
567                                          "Write-n buffer\n");
568                                 return 1;
569                         }
570                         sp_write_n_bytes = 0;
571                 }
572
573                 if (sp_check_commandavail(S_CMD_Q_RDNMAXLEN) &&
574                     (sp_docommand(S_CMD_Q_RDNMAXLEN, 0, NULL, 3, rbuf) == 0)) {
575                         sp_max_read_n = ((unsigned int)(rbuf[0]) << 0);
576                         sp_max_read_n |= ((unsigned int)(rbuf[1]) << 8);
577                         sp_max_read_n |= ((unsigned int)(rbuf[2]) << 16);
578                         msg_pdbg(MSGHEADER "Maximum read-n length is %d\n",
579                                  sp_max_read_n ? sp_max_read_n : (1 << 24));
580                 } else {
581                         msg_pdbg(MSGHEADER "Maximum read-n length "
582                                  "not reported\n");
583                         sp_max_read_n = 0;
584                 }
585
586         }
587
588         if (sp_docommand(S_CMD_Q_PGMNAME, 0, NULL, 16, pgmname)) {
589                 msg_perr("Warning: NAK to query programmer name\n");
590                 strcpy((char *)pgmname, "(unknown)");
591         }
592         pgmname[16] = 0;
593         msg_pinfo(MSGHEADER "Programmer name is \"%s\"\n", pgmname);
594
595         if (sp_docommand(S_CMD_Q_SERBUF, 0, NULL, 2, &sp_device_serbuf_size)) {
596                 msg_perr("Warning: NAK to query serial buffer size\n");
597         }
598         msg_pdbg(MSGHEADER "Serial buffer size is %d\n",
599                      sp_device_serbuf_size);
600
601         if (sp_check_commandavail(S_CMD_O_INIT)) {
602                 /* This would be inconsistent. */
603                 if (sp_check_commandavail(S_CMD_O_EXEC) == 0) {
604                         msg_perr("Error: Execute operation buffer not "
605                                  "supported\n");
606                         return 1;
607                 }
608
609                 if (sp_docommand(S_CMD_O_INIT, 0, NULL, 0, NULL)) {
610                         msg_perr("Error: NAK to initialize operation buffer\n");
611                         return 1;
612                 }
613
614                 if (sp_docommand(S_CMD_Q_OPBUF, 0, NULL, 2,
615                     &sp_device_opbuf_size)) {
616                         msg_perr("Warning: NAK to query operation buffer "
617                                  "size\n");
618                 }
619                 msg_pdbg(MSGHEADER "operation buffer size is %d\n",
620                          sp_device_opbuf_size);
621         }
622
623         sp_prev_was_write = 0;
624         sp_streamed_transmit_ops = 0;
625         sp_streamed_transmit_bytes = 0;
626         sp_opbuf_usage = 0;
627         if (serprog_buses_supported & BUS_SPI)
628                 register_spi_programmer(&spi_programmer_serprog);
629         if (serprog_buses_supported & BUS_NONSPI)
630                 register_par_programmer(&par_programmer_serprog,
631                                         serprog_buses_supported & BUS_NONSPI);
632         return 0;
633 }
634
635 /* Move an in flashrom buffer existing write-n operation to     *
636  * the on-device operation buffer.                              */
637 static void sp_pass_writen(void)
638 {
639         unsigned char header[7];
640         msg_pspew(MSGHEADER "Passing write-n bytes=%d addr=0x%x\n",
641                   sp_write_n_bytes, sp_write_n_addr);
642         if (sp_streamed_transmit_bytes >=
643             (7 + sp_write_n_bytes + sp_device_serbuf_size))
644                 sp_flush_stream();
645         /* In case it's just a single byte send it as a single write. */
646         if (sp_write_n_bytes == 1) {
647                 sp_write_n_bytes = 0;
648                 header[0] = (sp_write_n_addr >> 0) & 0xFF;
649                 header[1] = (sp_write_n_addr >> 8) & 0xFF;
650                 header[2] = (sp_write_n_addr >> 16) & 0xFF;
651                 header[3] = sp_write_n_buf[0];
652                 sp_stream_buffer_op(S_CMD_O_WRITEB, 4, header);
653                 sp_opbuf_usage += 5;
654                 return;
655         }
656         header[0] = S_CMD_O_WRITEN;
657         header[1] = (sp_write_n_bytes >> 0) & 0xFF;
658         header[2] = (sp_write_n_bytes >> 8) & 0xFF;
659         header[3] = (sp_write_n_bytes >> 16) & 0xFF;
660         header[4] = (sp_write_n_addr >> 0) & 0xFF;
661         header[5] = (sp_write_n_addr >> 8) & 0xFF;
662         header[6] = (sp_write_n_addr >> 16) & 0xFF;
663         if (write(sp_fd, header, 7) != 7)
664                 sp_die("Error: cannot write write-n command\n");
665         if (write(sp_fd, sp_write_n_buf, sp_write_n_bytes) !=
666             sp_write_n_bytes)
667                 sp_die("Error: cannot write write-n data");
668         sp_streamed_transmit_bytes += 7 + sp_write_n_bytes;
669         sp_streamed_transmit_ops += 1;
670         sp_opbuf_usage += 7 + sp_write_n_bytes;
671         sp_write_n_bytes = 0;
672         sp_prev_was_write = 0;
673 }
674
675 static void sp_execute_opbuf_noflush(void)
676 {
677         if ((sp_max_write_n) && (sp_write_n_bytes))
678                 sp_pass_writen();
679         sp_stream_buffer_op(S_CMD_O_EXEC, 0, NULL);
680         msg_pspew(MSGHEADER "Executed operation buffer of %d bytes\n",
681                      sp_opbuf_usage);
682         sp_opbuf_usage = 0;
683         sp_prev_was_write = 0;
684         return;
685 }
686
687 static void sp_execute_opbuf(void)
688 {
689         sp_execute_opbuf_noflush();
690         sp_flush_stream();
691 }
692
693 static int serprog_shutdown(void *data)
694 {
695         msg_pspew("%s\n", __func__);
696         if ((sp_opbuf_usage) || (sp_max_write_n && sp_write_n_bytes))
697                 sp_execute_opbuf();
698         close(sp_fd);
699         if (sp_max_write_n)
700                 free(sp_write_n_buf);
701         return 0;
702 }
703
704 static void sp_check_opbuf_usage(int bytes_to_be_added)
705 {
706         if (sp_device_opbuf_size <= (sp_opbuf_usage + bytes_to_be_added)) {
707                 sp_execute_opbuf();
708                 /* If this happens in the mid of an page load the page load *
709                  * will probably fail.                                      */
710                 msg_pdbg(MSGHEADER "Warning: executed operation buffer due to size reasons\n");
711         }
712 }
713
714 static void serprog_chip_writeb(const struct flashctx *flash, uint8_t val,
715                                 chipaddr addr)
716 {
717         msg_pspew("%s\n", __func__);
718         if (sp_max_write_n) {
719                 if ((sp_prev_was_write)
720                     && (addr == (sp_write_n_addr + sp_write_n_bytes))) {
721                         sp_write_n_buf[sp_write_n_bytes++] = val;
722                 } else {
723                         if ((sp_prev_was_write) && (sp_write_n_bytes))
724                                 sp_pass_writen();
725                         sp_prev_was_write = 1;
726                         sp_write_n_addr = addr;
727                         sp_write_n_bytes = 1;
728                         sp_write_n_buf[0] = val;
729                 }
730                 sp_check_opbuf_usage(7 + sp_write_n_bytes);
731                 if (sp_write_n_bytes >= sp_max_write_n)
732                         sp_pass_writen();
733         } else {
734                 /* We will have to do single writeb ops. */
735                 unsigned char writeb_parm[4];
736                 sp_check_opbuf_usage(6);
737                 writeb_parm[0] = (addr >> 0) & 0xFF;
738                 writeb_parm[1] = (addr >> 8) & 0xFF;
739                 writeb_parm[2] = (addr >> 16) & 0xFF;
740                 writeb_parm[3] = val;
741                 sp_stream_buffer_op(S_CMD_O_WRITEB, 4, writeb_parm);
742                 sp_opbuf_usage += 5;
743         }
744 }
745
746 static uint8_t serprog_chip_readb(const struct flashctx *flash,
747                                   const chipaddr addr)
748 {
749         unsigned char c;
750         unsigned char buf[3];
751         /* Will stream the read operation - eg. add it to the stream buffer, *
752          * then flush the buffer, then read the read answer.                 */
753         if ((sp_opbuf_usage) || (sp_max_write_n && sp_write_n_bytes))
754                 sp_execute_opbuf_noflush();
755         buf[0] = ((addr >> 0) & 0xFF);
756         buf[1] = ((addr >> 8) & 0xFF);
757         buf[2] = ((addr >> 16) & 0xFF);
758         sp_stream_buffer_op(S_CMD_R_BYTE, 3, buf);
759         sp_flush_stream();
760         if (read(sp_fd, &c, 1) != 1)
761                 sp_die("readb byteread");
762         msg_pspew("%s addr=0x%lx returning 0x%02X\n", __func__, addr, c);
763         return c;
764 }
765
766 /* Local version that really does the job, doesn't care of max_read_n. */
767 static void sp_do_read_n(uint8_t * buf, const chipaddr addr, size_t len)
768 {
769         int rd_bytes = 0;
770         unsigned char sbuf[6];
771         msg_pspew("%s: addr=0x%lx len=%lu\n", __func__, addr, (unsigned long)len);
772         /* Stream the read-n -- as above. */
773         if ((sp_opbuf_usage) || (sp_max_write_n && sp_write_n_bytes))
774                 sp_execute_opbuf_noflush();
775         sbuf[0] = ((addr >> 0) & 0xFF);
776         sbuf[1] = ((addr >> 8) & 0xFF);
777         sbuf[2] = ((addr >> 16) & 0xFF);
778         sbuf[3] = ((len >> 0) & 0xFF);
779         sbuf[4] = ((len >> 8) & 0xFF);
780         sbuf[5] = ((len >> 16) & 0xFF);
781         sp_stream_buffer_op(S_CMD_R_NBYTES, 6, sbuf);
782         sp_flush_stream();
783         do {
784                 int r = read(sp_fd, buf + rd_bytes, len - rd_bytes);
785                 if (r <= 0)
786                         sp_die("Error: cannot read read-n data");
787                 rd_bytes += r;
788         } while (rd_bytes != len);
789         return;
790 }
791
792 /* The externally called version that makes sure that max_read_n is obeyed. */
793 static void serprog_chip_readn(const struct flashctx *flash, uint8_t * buf,
794                                const chipaddr addr, size_t len)
795 {
796         size_t lenm = len;
797         chipaddr addrm = addr;
798         while ((sp_max_read_n != 0) && (lenm > sp_max_read_n)) {
799                 sp_do_read_n(&(buf[addrm-addr]), addrm, sp_max_read_n);
800                 addrm += sp_max_read_n;
801                 lenm -= sp_max_read_n;
802         }
803         if (lenm)
804                 sp_do_read_n(&(buf[addrm-addr]), addrm, lenm);
805 }
806
807 void serprog_delay(int usecs)
808 {
809         unsigned char buf[4];
810         msg_pspew("%s usecs=%d\n", __func__, usecs);
811         if (!sp_check_commandavail(S_CMD_O_DELAY)) {
812                 msg_pdbg("Note: serprog_delay used, but the programmer doesn't "
813                          "support delay\n");
814                 internal_delay(usecs);
815                 return;
816         }
817         if ((sp_max_write_n) && (sp_write_n_bytes))
818                 sp_pass_writen();
819         sp_check_opbuf_usage(5);
820         buf[0] = ((usecs >> 0) & 0xFF);
821         buf[1] = ((usecs >> 8) & 0xFF);
822         buf[2] = ((usecs >> 16) & 0xFF);
823         buf[3] = ((usecs >> 24) & 0xFF);
824         sp_stream_buffer_op(S_CMD_O_DELAY, 4, buf);
825         sp_opbuf_usage += 5;
826         sp_prev_was_write = 0;
827 }
828
829 static int serprog_spi_send_command(struct flashctx *flash,
830                                     unsigned int writecnt, unsigned int readcnt,
831                                     const unsigned char *writearr,
832                                     unsigned char *readarr)
833 {
834         unsigned char *parmbuf;
835         int ret;
836         msg_pspew("%s, writecnt=%i, readcnt=%i\n", __func__, writecnt, readcnt);
837         if ((sp_opbuf_usage) || (sp_max_write_n && sp_write_n_bytes))
838                 sp_execute_opbuf();
839         parmbuf = malloc(writecnt + 6);
840         if (!parmbuf)
841                 sp_die("Error: cannot malloc SPI send param buffer");
842         parmbuf[0] = (writecnt >> 0) & 0xFF;
843         parmbuf[1] = (writecnt >> 8) & 0xFF;
844         parmbuf[2] = (writecnt >> 16) & 0xFF;
845         parmbuf[3] = (readcnt >> 0) & 0xFF;
846         parmbuf[4] = (readcnt >> 8) & 0xFF;
847         parmbuf[5] = (readcnt >> 16) & 0xFF;
848         memcpy(parmbuf + 6, writearr, writecnt);
849         ret = sp_docommand(S_CMD_O_SPIOP, writecnt + 6, parmbuf, readcnt,
850                            readarr);
851         free(parmbuf);
852         return ret;
853 }
854
855 /* FIXME: This function is optimized so that it does not split each transaction
856  * into chip page_size long blocks unnecessarily like spi_read_chunked. This has
857  * the advantage that it is much faster for most chips, but breaks those with
858  * non-contiguous address space (like AT45DB161D). When spi_read_chunked is
859  * fixed this method can be removed. */
860 static int serprog_spi_read(struct flashctx *flash, uint8_t *buf,
861                             unsigned int start, unsigned int len)
862 {
863         unsigned int i, cur_len;
864         const unsigned int max_read = spi_programmer_serprog.max_data_read;
865         for (i = 0; i < len; i += cur_len) {
866                 int ret;
867                 cur_len = min(max_read, (len - i));
868                 ret = spi_nbyte_read(flash, start + i, buf + i, cur_len);
869                 if (ret)
870                         return ret;
871         }
872         return 0;
873 }