1 /*
2  * avrdude - A Downloader/Uploader for AVR device programmers
3  *
4  * avrdude support for The Bus Pirate - universal serial interface
5  *
6  * Copyright (C) 2009 Michal Ludvig <mludvig@logix.net.nz>
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  * You should have received a copy of the GNU General Public License
19  * along with this program. If not, see <http://www.gnu.org/licenses/>.
20  */
21 
22 /*
23  * BusPirate       AVR Chip
24  * ---------       --------
25  *       GND  <->  GND
26  *       +5V  <->  Vcc
27  *        CS  <->  RESET
28  *      MOSI  <->  MOSI
29  *      MISO  <->  MISO
30  *   SCL/CLK  <->  SCK
31  *     ( AUX  <->  XTAL1 )
32  *
33  * Tested with BusPirate PTH, firmware version 2.1 programming ATmega328P
34  */
35 
36 /* $Id: buspirate.c 1455 2021-11-06 22:34:29Z joerg_wunsch $ */
37 
38 #include "ac_cfg.h"
39 
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <unistd.h>
44 #if defined(WIN32NATIVE)
45 #  include <malloc.h>  /* for alloca() */
46 #endif
47 
48 #include "avrdude.h"
49 #include "libavrdude.h"
50 
51 #include "bitbang.h"
52 #include "buspirate.h"
53 
54 /* ====== Private data structure ====== */
55 /* CS and AUX pin bitmasks in
56  * 0100wxyz - Configure peripherals command */
57 #define BP_RESET_CS     0x01
58 #define BP_RESET_AUX    0x02
59 #define BP_RESET_AUX2   0x04
60 
61 #define BP_FLAG_IN_BINMODE          (1<<0)
62 #define BP_FLAG_XPARM_FORCE_ASCII   (1<<1)
63 #define BP_FLAG_XPARM_RESET         (1<<2)
64 #define BP_FLAG_XPARM_SPIFREQ       (1<<3)
65 #define BP_FLAG_NOPAGEDWRITE        (1<<4)
66 #define BP_FLAG_XPARM_CPUFREQ       (1<<5)
67 #define BP_FLAG_XPARM_RAWFREQ       (1<<6)
68 #define BP_FLAG_NOPAGEDREAD         (1<<7)
69 
70 struct pdata
71 {
72 	int	binmode_version;
73 	int	submode_version;
74 	int	current_peripherals_config;
75 	int	spifreq;		/* For "set speed" commands */
76 	int	cpufreq;		/* (125)..4000 kHz - see buspirate manual */
77 	int	serial_recv_timeout;    /* timeout in ms, default 100 */
78 	int	reset;			/* See BP_RESET_* above */
79 	unsigned char pin_dir;		/* Last written pin direction for bitbang mode */
80 	unsigned char pin_val;		/* Last written pin values for bitbang mode */
81 	int     unread_bytes;		/* How many bytes we expected, but ignored */
82 };
83 #define PDATA(pgm) ((struct pdata *)(pgm->cookie))
84 
85 /* ====== Feature checks ====== */
86 static inline int
buspirate_uses_ascii(struct programmer_t * pgm)87 buspirate_uses_ascii(struct programmer_t *pgm)
88 {
89 	return (pgm->flag & BP_FLAG_XPARM_FORCE_ASCII);
90 }
91 
92 /* ====== Serial talker functions - binmode ====== */
93 
dump_mem(const int msglvl,const unsigned char * buf,size_t len)94 static void dump_mem(const int msglvl, const unsigned char *buf, size_t len)
95 {
96 	size_t i;
97 
98 	for (i = 0; i<len; i++) {
99 		if (i % 8 == 0)
100 			avrdude_message(msglvl, "\t");
101 		avrdude_message(msglvl, "0x%02x ", buf[i]);
102 		if (i % 8 == 3)
103 			avrdude_message(msglvl, "  ");
104 		else if (i % 8 == 7)
105 			avrdude_message(msglvl, "\n");
106 	}
107 	if (i % 8 != 7)
108 		avrdude_message(msglvl, "\n");
109 }
110 
buspirate_send_bin(struct programmer_t * pgm,const unsigned char * data,size_t len)111 static int buspirate_send_bin(struct programmer_t *pgm, const unsigned char *data, size_t len)
112 {
113 	int rc;
114 
115 	avrdude_message(MSG_DEBUG, "%s: buspirate_send_bin():\n", progname);
116 	dump_mem(MSG_DEBUG, data, len);
117 
118 	rc = serial_send(&pgm->fd, data, len);
119 
120 	return rc;
121 }
122 
buspirate_recv_bin(struct programmer_t * pgm,unsigned char * buf,size_t len)123 static int buspirate_recv_bin(struct programmer_t *pgm, unsigned char *buf, size_t len)
124 {
125 	int rc;
126 
127 	rc = serial_recv(&pgm->fd, buf, len);
128 	if (rc < 0)
129 		return EOF;
130 
131 	avrdude_message(MSG_DEBUG, "%s: buspirate_recv_bin():\n", progname);
132 	dump_mem(MSG_DEBUG, buf, len);
133 
134 	return len;
135 }
136 
buspirate_expect_bin(struct programmer_t * pgm,unsigned char * send_data,size_t send_len,unsigned char * expect_data,size_t expect_len)137 static int buspirate_expect_bin(struct programmer_t *pgm,
138 				unsigned char *send_data, size_t send_len,
139 				unsigned char *expect_data, size_t expect_len)
140 {
141 	unsigned char *recv_buf = alloca(expect_len);
142 	if ((pgm->flag & BP_FLAG_IN_BINMODE) == 0) {
143 		avrdude_message(MSG_INFO, "BusPirate: Internal error: buspirate_send_bin() called from ascii mode\n");
144 		return -1;
145 	}
146 
147 	buspirate_send_bin(pgm, send_data, send_len);
148 	buspirate_recv_bin(pgm, recv_buf, expect_len);
149 	if (memcmp(expect_data, recv_buf, expect_len) != 0)
150 		return 0;
151 	return 1;
152 }
153 
buspirate_expect_bin_byte(struct programmer_t * pgm,unsigned char send_byte,unsigned char expect_byte)154 static int buspirate_expect_bin_byte(struct programmer_t *pgm,
155 					unsigned char send_byte, unsigned char expect_byte)
156 {
157 	return buspirate_expect_bin(pgm, &send_byte, 1, &expect_byte, 1);
158 }
159 
160 /* ====== Serial talker functions - ascii mode ====== */
161 
buspirate_getc(struct programmer_t * pgm)162 static int buspirate_getc(struct programmer_t *pgm)
163 {
164 	int rc;
165 	unsigned char ch = 0;
166 
167 	if (pgm->flag & BP_FLAG_IN_BINMODE) {
168 		avrdude_message(MSG_INFO, "BusPirate: Internal error: buspirate_getc() called from binmode\n");
169 		return EOF;
170 	}
171 
172 	rc = serial_recv(&pgm->fd, &ch, 1);
173 	if (rc < 0)
174 		return EOF;
175 	return ch;
176 }
177 
buspirate_readline_noexit(struct programmer_t * pgm,char * buf,size_t len)178 static char *buspirate_readline_noexit(struct programmer_t *pgm, char *buf, size_t len)
179 {
180 	char *buf_p;
181 	long orig_serial_recv_timeout = serial_recv_timeout;
182 
183 	/* Static local buffer - this may come handy at times */
184 	static char buf_local[100];
185 
186 	if (buf == NULL) {
187 		buf = buf_local;
188 		len = sizeof(buf_local);
189 	}
190 	buf_p = buf;
191 	memset(buf, 0, len);
192 	while (buf_p < (buf + len - 1)) { /* keep the very last byte == 0 */
193 		*buf_p = buspirate_getc(pgm);
194 		if (*buf_p == '\r')
195 			continue;
196 		if (*buf_p == '\n')
197 			break;
198 		if (*buf_p == EOF) {
199 			*buf_p = '\0';
200 			break;
201 		}
202 		buf_p++;
203 		serial_recv_timeout = PDATA(pgm)->serial_recv_timeout;
204 	}
205 	serial_recv_timeout = orig_serial_recv_timeout;
206 	avrdude_message(MSG_DEBUG, "%s: buspirate_readline(): %s%s",
207 	                progname, buf,
208 	                buf[strlen(buf) - 1] == '\n' ? "" : "\n");
209 	if (! buf[0])
210 		return NULL;
211 
212 	return buf;
213 }
214 
buspirate_readline(struct programmer_t * pgm,char * buf,size_t len)215 static char *buspirate_readline(struct programmer_t *pgm, char *buf, size_t len)
216 {
217 	char *ret;
218 
219 	ret = buspirate_readline_noexit(pgm, buf, len);
220 	if (! ret) {
221 		avrdude_message(MSG_INFO, "%s: buspirate_readline(): programmer is not responding\n",
222                                 progname);
223 		return NULL;
224 	}
225 	return ret;
226 }
buspirate_send(struct programmer_t * pgm,const char * str)227 static int buspirate_send(struct programmer_t *pgm, const char *str)
228 {
229 	int rc;
230 	const char * readline;
231 
232 	avrdude_message(MSG_DEBUG, "%s: buspirate_send(): %s", progname, str);
233 
234 	if (pgm->flag & BP_FLAG_IN_BINMODE) {
235 		avrdude_message(MSG_INFO, "BusPirate: Internal error: buspirate_send() called from binmode\n");
236 		return -1;
237 	}
238 
239 	rc = serial_send(&pgm->fd, (const unsigned char*)str, strlen(str));
240 	if (rc)
241 		return rc;
242 	do {
243 		readline = buspirate_readline(pgm, NULL, 0);
244 		if (readline == NULL)
245 			return -1;
246 	/* keep reading until we get what we sent there */
247 	} while (strcmp(readline, str) != 0);
248 
249 	/* by now we should be in sync */
250 	return 0;
251 }
252 
buspirate_is_prompt(const char * str)253 static int buspirate_is_prompt(const char *str)
254 {
255 	int strlen_str = strlen(str);
256 	/* Prompt ends with '>' or '> '
257 	 * all other input probably ends with '\n' */
258 	return (str[strlen_str - 1] == '>' || str[strlen_str - 2] == '>');
259 }
260 
buspirate_expect(struct programmer_t * pgm,char * send,char * expect,int wait_for_prompt)261 static int buspirate_expect(struct programmer_t *pgm, char *send,
262 				char *expect, int wait_for_prompt)
263 {
264 	int got_it = 0;
265 	size_t expect_len = strlen(expect);
266 	char *rcvd;
267 
268 	buspirate_send(pgm, send);
269 	while (1) {
270 		rcvd = buspirate_readline(pgm, NULL, 0);
271 		if (rcvd == NULL) {
272 			return -1;
273 		}
274 		if (strncmp(rcvd, expect, expect_len) == 0) {
275 			if (! wait_for_prompt) {
276 				serial_drain(&pgm->fd, 0);
277 				return 1;
278 			} else {
279 				got_it = 1;
280 			}
281 		}
282 
283 		if (buspirate_is_prompt(rcvd))
284 			break;
285 	}
286 	return got_it;
287 }
288 
289 /* ====== Do-nothing functions ====== */
buspirate_dummy_6(struct programmer_t * pgm,const char * p)290 static void buspirate_dummy_6(struct programmer_t *pgm, const char *p)
291 {
292 }
293 
294 /* ====== Config / parameters handling functions ====== */
295 static int
buspirate_parseextparms(struct programmer_t * pgm,LISTID extparms)296 buspirate_parseextparms(struct programmer_t *pgm, LISTID extparms)
297 {
298 	LNODEID ln;
299 	const char *extended_param;
300 	char reset[10];
301 	char *preset = reset; /* for strtok() */
302 	unsigned int spifreq;
303 	unsigned int rawfreq;
304 	unsigned int cpufreq;
305 	int serial_recv_timeout;
306 
307 	for (ln = lfirst(extparms); ln; ln = lnext(ln)) {
308 		extended_param = ldata(ln);
309 		if (strcmp(extended_param, "ascii") == 0) {
310 			pgm->flag |= BP_FLAG_XPARM_FORCE_ASCII;
311 			continue;
312 		}
313 
314 		if (sscanf(extended_param, "spifreq=%u", &spifreq) == 1) {
315 			if (spifreq & (~0x07)) {
316 				avrdude_message(MSG_INFO, "BusPirate: spifreq must be between 0 and 7.\n");
317 				avrdude_message(MSG_INFO, "BusPirate: see BusPirate manual for details.\n");
318 				return -1;
319 			}
320 			if (pgm->flag & BP_FLAG_XPARM_RAWFREQ) {
321 				avrdude_message(MSG_INFO, "BusPirate: set either spifreq or rawfreq\n");
322 				return -1;
323 			}
324 			pgm->flag |=  BP_FLAG_XPARM_SPIFREQ;
325 			PDATA(pgm)->spifreq = spifreq;
326 			continue;
327 		}
328 
329 		if (sscanf(extended_param, "rawfreq=%u", &rawfreq) == 1) {
330 			if (rawfreq >= 4) {
331 				avrdude_message(MSG_INFO, "BusPirate: rawfreq must be "
332 				                "between 0 and 3.\n");
333 				return -1;
334 			}
335 			if (pgm->flag & BP_FLAG_XPARM_SPIFREQ) {
336 				avrdude_message(MSG_INFO, "BusPirate: set either spifreq or rawfreq\n");
337 				return -1;
338 			}
339 			pgm->flag |=  BP_FLAG_XPARM_RAWFREQ;
340 			PDATA(pgm)->spifreq = rawfreq;
341 			continue;
342 		}
343 
344 		if (sscanf(extended_param, "cpufreq=%u", &cpufreq) == 1) {
345 			/* lower limit comes from 'cpufreq > 4 * spifreq', spifreq in ascii mode is 30kHz. */
346 			if (cpufreq < 125 || cpufreq > 4000) {
347 				avrdude_message(MSG_INFO, "BusPirate: cpufreq must be between 125 and 4000 kHz.\n");
348 				avrdude_message(MSG_INFO, "BusPirate: see BusPirate manual for details.\n");
349 				return -1;
350 			}
351 			PDATA(pgm)->cpufreq = cpufreq;
352 			pgm->flag |= BP_FLAG_XPARM_CPUFREQ;
353 			continue;
354 		}
355 
356 		if (sscanf(extended_param, "reset=%9s", reset) == 1) {
357 			char *resetpin;
358 			while ((resetpin = strtok(preset, ","))) {
359 				preset = NULL; /* for subsequent strtok() calls */
360 				if (strcasecmp(resetpin, "cs") == 0)
361 					PDATA(pgm)->reset |= BP_RESET_CS;
362 				else if (strcasecmp(resetpin, "aux") == 0 || strcasecmp(reset, "aux1") == 0)
363 					PDATA(pgm)->reset |= BP_RESET_AUX;
364 				else if (strcasecmp(resetpin, "aux2") == 0)
365 					PDATA(pgm)->reset |= BP_RESET_AUX2;
366 				else {
367 					avrdude_message(MSG_INFO, "BusPirate: reset must be either CS or AUX.\n");
368 					return -1;
369 				}
370 			}
371 			pgm->flag |= BP_FLAG_XPARM_RESET;
372 			continue;
373 		}
374 
375 		if (strcmp(extended_param, "nopagedwrite") == 0) {
376 			pgm->flag |= BP_FLAG_NOPAGEDWRITE;
377 			continue;
378 		}
379 
380 		if (strcmp(extended_param, "nopagedread") == 0) {
381 			pgm->flag |= BP_FLAG_NOPAGEDREAD;
382 			continue;
383 		}
384 
385 		if (sscanf(extended_param, "serial_recv_timeout=%d", &serial_recv_timeout) == 1) {
386 			if (serial_recv_timeout < 1) {
387 				avrdude_message(MSG_INFO, "BusPirate: serial_recv_timeout must be greater 0.\n");
388 				return -1;
389 			}
390 			PDATA(pgm)->serial_recv_timeout = serial_recv_timeout;
391 			continue;
392 		}
393 
394 		avrdude_message(MSG_INFO, "BusPirate: do not understand extended param '%s'.\n", extended_param);
395 		return -1;
396 	}
397 
398 	return 0;
399 }
400 
401 static int
buspirate_verifyconfig(struct programmer_t * pgm)402 buspirate_verifyconfig(struct programmer_t *pgm)
403 {
404 	/* Default reset pin is CS */
405 	if (PDATA(pgm)->reset == 0x00)
406 		PDATA(pgm)->reset |= BP_RESET_CS;
407 
408 	if ((PDATA(pgm)->reset != BP_RESET_CS) && buspirate_uses_ascii(pgm)) {
409 		avrdude_message(MSG_INFO, "BusPirate: RESET pin other than CS is not supported in ASCII mode\n");
410 		return -1;
411 	}
412 
413 	if (  ((pgm->flag & BP_FLAG_XPARM_SPIFREQ) || (pgm->flag & BP_FLAG_XPARM_RAWFREQ))
414 	   && buspirate_uses_ascii(pgm)) {
415 		avrdude_message(MSG_INFO, "BusPirate: SPI speed selection is not supported in ASCII mode\n");
416 		return -1;
417 	}
418 
419 	return 0;
420 }
421 
422 /* ====== Programmer methods ======= */
buspirate_open(struct programmer_t * pgm,char * port)423 static int buspirate_open(struct programmer_t *pgm, char * port)
424 {
425 	union pinfo pinfo;
426 	/* BusPirate runs at 115200 by default */
427 	if(pgm->baudrate == 0)
428 		pgm->baudrate = 115200;
429 
430 	pinfo.baud = pgm->baudrate;
431 	strcpy(pgm->port, port);
432 	if (serial_open(port, pinfo, &pgm->fd)==-1) {
433 		return -1;
434 	}
435 
436 	/* drain any extraneous input */
437 	serial_drain(&pgm->fd, 0);
438 
439 	return 0;
440 }
441 
buspirate_close(struct programmer_t * pgm)442 static void buspirate_close(struct programmer_t *pgm)
443 {
444 	serial_close(&pgm->fd);
445 	pgm->fd.ifd = -1;
446 }
447 
buspirate_reset_from_binmode(struct programmer_t * pgm)448 static void buspirate_reset_from_binmode(struct programmer_t *pgm)
449 {
450 	unsigned char buf[10];
451 
452 	buf[0] = 0x00;	/* BinMode: revert to raw bitbang mode */
453 	buspirate_send_bin(pgm, buf, 1);
454 	buspirate_recv_bin(pgm, buf, 5);
455 
456 	if (pgm->flag & BP_FLAG_XPARM_CPUFREQ) {
457 		/* disable pwm */
458 		if (buspirate_expect_bin_byte(pgm, 0x13, 0x01) != 1) {
459 			avrdude_message(MSG_INFO, "%s: warning: did not get a response to stop PWM command.\n", progname);
460 		}
461 	}
462 	/* 0b0100wxyz - Configure peripherals w=power, x=pull-ups, y=AUX, z=CS
463 	 * we want everything off -- 0b01000000 = 0x40 */
464 	if (buspirate_expect_bin_byte(pgm, 0x40, 0x00) == 1) {
465 		avrdude_message(MSG_INFO, "%s: warning: did not get a response to power off command.\n", progname);
466 	}
467 
468 	buf[0] = 0x0F;	/* BinMode: reset */
469 	buspirate_send_bin(pgm, buf, 1);
470 
471 	/* read back all output */
472 	memset(buf, '\0', sizeof(buf));
473 	for (;;) {
474 		int rc;
475 		rc = buspirate_recv_bin(pgm, buf, sizeof(buf) - 1);
476 
477 		if (buspirate_is_prompt((const char*)buf)) {
478 			pgm->flag &= ~BP_FLAG_IN_BINMODE;
479 			break;
480 		}
481 		if (rc == EOF)
482 			break;
483 		memset(buf, '\0', sizeof(buf));
484 	}
485 
486 	if (pgm->flag & BP_FLAG_IN_BINMODE) {
487 		avrdude_message(MSG_INFO, "BusPirate reset failed. You may need to powercycle it.\n");
488 		return;
489 	}
490 
491 	avrdude_message(MSG_NOTICE, "BusPirate is back in the text mode\n");
492 }
493 
buspirate_start_mode_bin(struct programmer_t * pgm)494 static int buspirate_start_mode_bin(struct programmer_t *pgm)
495 {
496 	struct submode {
497 		const char *name;  /* Name of mode for user messages */
498 		char enter;  /* Command to enter from base binary mode */
499 		const char *entered_format;  /* Response, for "scanf" */
500 		char config;  /* Command to setup submode parameters */
501 	} submode;
502 
503 	if (pgm->flag & BP_FLAG_XPARM_RAWFREQ) {
504 		submode.name = "Raw-wire";
505 		submode.enter = 0x05;
506 		submode.entered_format = "RAW%1d";
507 		submode.config = 0x8C;
508 		pgm->flag |= BP_FLAG_NOPAGEDWRITE;
509 		pgm->flag |= BP_FLAG_NOPAGEDREAD;
510 	} else {
511 		submode.name = "SPI";
512 		submode.enter = 0x01;
513 		submode.entered_format = "SPI%1d";
514 
515 		/* 1000wxyz - SPI config, w=HiZ(0)/3.3v(1), x=CLK idle, y=CLK edge, z=SMP sample
516 		 * we want: 3.3V(1), idle low(0), data change on
517 		 *          trailing edge (1), sample in the middle
518 		 *          of the pulse (0)
519 		 *       => 0b10001010 = 0x8a */
520 		submode.config = 0x8A;
521 	}
522 
523 	unsigned char buf[20] = { '\0' };
524 
525 	/* == Switch to binmode - send 20x '\0' == */
526 	buspirate_send_bin(pgm, buf, sizeof(buf));
527 
528 	/* Expecting 'BBIOx' reply */
529 	memset(buf, 0, sizeof(buf));
530 	buspirate_recv_bin(pgm, buf, 5);
531 	if (sscanf((const char*)buf, "BBIO%1d", &PDATA(pgm)->binmode_version) != 1) {
532 		avrdude_message(MSG_INFO, "Binary mode not confirmed: '%s'\n", buf);
533 		buspirate_reset_from_binmode(pgm);
534 		return -1;
535 	}
536 	avrdude_message(MSG_NOTICE, "BusPirate binmode version: %d\n",
537                 PDATA(pgm)->binmode_version);
538 
539 	pgm->flag |= BP_FLAG_IN_BINMODE;
540 
541 	if (pgm->flag & BP_FLAG_XPARM_CPUFREQ) {
542 		unsigned short pwm_duty;
543 		unsigned short pwm_period;
544 
545 		pwm_period = 16000/(PDATA(pgm)->cpufreq) - 1; // oscillator runs at 32MHz, we don't use a prescaler
546 		pwm_duty = pwm_period/2; // 50% duty cycle
547 
548 		avrdude_message(MSG_NOTICE, "Setting up PWM for cpufreq\n");
549 		avrdude_message(MSG_DEBUG, "PWM settings: Prescaler=1, Duty Cycle=%hd, Period=%hd\n", pwm_duty, pwm_period);
550 
551 		buf[0] = 0x12; // pwm setup
552 		buf[1] = 0; // prescaler 1
553 		buf[2] = (char) ((pwm_duty >> 8) & 0xff); // duty cycle register, high byte
554 		buf[3] = (char) pwm_duty & 0xff; // duty cycle register, low byte
555 		buf[4] = (char) ((pwm_period >> 8) & 0xff); // period register, high byte
556 		buf[5] = (char) pwm_period & 0xff; // period register, low byte
557 		buspirate_send_bin(pgm, buf, 6);
558 
559 		buspirate_recv_bin(pgm, buf, 1);
560 		if (buf[0] != 0x01)
561 			avrdude_message(MSG_INFO, "cpufreq (PWM) setup failed\n");
562 	}
563 
564 	/* == Set protocol sub-mode of binary mode == */
565 	buf[0] = submode.enter;
566 	buspirate_send_bin(pgm, buf, 1);
567 	memset(buf, 0, sizeof(buf));
568 	buspirate_recv_bin(pgm, buf, 4);
569 	if (sscanf((const char*)buf, submode.entered_format, &PDATA(pgm)->submode_version) != 1) {
570 		avrdude_message(MSG_INFO, "%s mode not confirmed: '%s'\n",
571 		                submode.name, buf);
572 		buspirate_reset_from_binmode(pgm);
573 		return -1;
574 	}
575 	avrdude_message(MSG_NOTICE, "BusPirate %s version: %d\n",
576 	                submode.name, PDATA(pgm)->submode_version);
577 
578 	if (pgm->flag & BP_FLAG_NOPAGEDWRITE) {
579                 avrdude_message(MSG_NOTICE, "%s: Paged flash write disabled.\n", progname);
580 		pgm->paged_write = NULL;
581 	} else {
582 		/* Check for write-then-read without !CS/CS and disable paged_write if absent: */
583 		static const unsigned char buf2[] = {5,0,0,0,0};
584 		buspirate_send_bin(pgm, buf2, sizeof(buf2));
585 		buspirate_recv_bin(pgm, buf, 1);
586 		if (buf[0] != 0x01) {
587 
588 			/* Disable paged write: */
589 			pgm->flag |= BP_FLAG_NOPAGEDWRITE;
590 			pgm->paged_write = NULL;
591 
592 			/* Return to SPI mode (0x00s have landed us back in binary bitbang mode): */
593 			buf[0] = 0x1;
594 			buspirate_send_bin(pgm, buf, 1);
595 
596 			avrdude_message(MSG_NOTICE, "%s: Disabling paged flash write. (Need BusPirate firmware >=v5.10.)\n", progname);
597 
598 			/* Flush serial buffer: */
599 			serial_drain(&pgm->fd, 0);
600 		} else {
601 			avrdude_message(MSG_INFO, "%s: Paged flash write enabled.\n", progname);
602 		}
603 	}
604 
605 	/* 0b0100wxyz - Configure peripherals w=power, x=pull-ups/aux2, y=AUX, z=CS
606 	 * we want power (0x48) and all reset pins high. */
607 	PDATA(pgm)->current_peripherals_config  = 0x48 | PDATA(pgm)->reset;
608 	if (buspirate_expect_bin_byte(pgm, PDATA(pgm)->current_peripherals_config, 0x01) < 0)
609 		return -1;
610 	usleep(50000); // sleep for 50ms after power up
611 
612 	/* 01100xxx -  Set speed */
613 	if (buspirate_expect_bin_byte(pgm, 0x60 | PDATA(pgm)->spifreq, 0x01) < 0)
614 		return -1;
615 
616 	/* Submode config */
617 	if (buspirate_expect_bin_byte(pgm, submode.config, 0x01) < 0)
618 		return -1;
619 
620 	/* AVR Extended Commands - test for existence */
621 	if (pgm->flag & BP_FLAG_NOPAGEDREAD) {
622                 avrdude_message(MSG_NOTICE, "%s: Paged flash read disabled.\n", progname);
623 		pgm->paged_load = NULL;
624 	} else {
625 		int rv = buspirate_expect_bin_byte(pgm, 0x06, 0x01);
626 		if (rv < 0)
627 			return -1;
628 		if (rv) {
629 			unsigned int ver = 0;
630 			static const unsigned char buf2[] = {1};
631 			buspirate_send_bin(pgm, buf2, sizeof(buf2));
632 			buspirate_recv_bin(pgm, buf, 3);
633 			ver = buf[1] << 8 | buf[2];
634 			avrdude_message(MSG_NOTICE, "AVR Extended Commands version %d\n", ver);
635 		} else {
636 			avrdude_message(MSG_NOTICE, "AVR Extended Commands not found.\n");
637 			pgm->flag |= BP_FLAG_NOPAGEDREAD;
638 			pgm->paged_load = NULL;
639 		}
640 	}
641 
642 	return 0;
643 }
644 
buspirate_start_spi_mode_ascii(struct programmer_t * pgm)645 static int buspirate_start_spi_mode_ascii(struct programmer_t *pgm)
646 {
647 	int spi_cmd = -1;
648 	int cmd;
649 	char *rcvd;
650 	char buf[5];
651 	char mode[11];
652 
653 	buspirate_send(pgm, "m\n");
654 	while(1) {
655 		rcvd = buspirate_readline(pgm, NULL, 0);
656 		if (rcvd == NULL) {
657 			return -1;
658 		}
659 		if (spi_cmd == -1 && sscanf(rcvd, "%2d. %10s", &cmd, mode)) {
660 			if (strcmp(mode, "SPI") == 0)
661 				spi_cmd = cmd;
662 		}
663 		if (buspirate_is_prompt(rcvd))
664 			break;
665 	}
666 	if (spi_cmd == -1) {
667 		avrdude_message(MSG_INFO, "%s: SPI mode number not found. Does your BusPirate support SPI?\n",
668 				progname);
669 		avrdude_message(MSG_INFO, "%s: Try powercycling your BusPirate and try again.\n",
670 				progname);
671 		return -1;
672 	}
673 	snprintf(buf, sizeof(buf), "%d\n", spi_cmd);
674 	buspirate_send(pgm, buf);
675 	buf[0] = '\0';
676 	while (1) {
677 		rcvd = buspirate_readline(pgm, NULL, 0);
678 		if (rcvd == NULL) {
679 			return -1;
680 		}
681 		if (strstr(rcvd, "Normal (H=3.3V, L=GND)")) {
682 			/* BP firmware 2.1 defaults to Open-drain output.
683 			 * That doesn't work on my board, even with pull-up
684 			 * resistors. Select 3.3V output mode instead. */
685 			sscanf(rcvd, " %2d.", &cmd);
686 			snprintf(buf, sizeof(buf), "%d\n", cmd);
687 		}
688 		if (buspirate_is_prompt(rcvd)) {
689 			if (strncmp(rcvd, "SPI>", 4) == 0) {
690 				avrdude_message(MSG_INFO, "BusPirate is now configured for SPI\n");
691 				break;
692 			}
693 			/* Not yet 'SPI>' prompt */
694 			if (buf[0]) {
695 				buspirate_send(pgm, buf);
696 				buf[0] = '\0';
697 			} else
698 				buspirate_send(pgm, "\n");
699 		}
700 	}
701 	return 0;
702 }
703 
buspirate_enable(struct programmer_t * pgm)704 static void buspirate_enable(struct programmer_t *pgm)
705 {
706 	static const char *reset_str = "#\n";
707 	static const char *accept_str = "y\n";
708 	char *rcvd;
709 	int rc, print_banner = 0;
710 
711 	/* Ensure configuration is self-consistant: */
712 	if (buspirate_verifyconfig(pgm)<0)
713 		return;         /* XXX should handle error */
714 
715 	/* Attempt to start binary SPI mode unless explicitly told otherwise: */
716 	if (!buspirate_uses_ascii(pgm)) {
717 		avrdude_message(MSG_INFO, "Attempting to initiate BusPirate binary mode...\n");
718 
719 		/* Send two CRs to ensure we're not in a sub-menu of the UI if we're in ASCII mode: */
720 		buspirate_send_bin(pgm, (const unsigned char*)"\n\n", 2);
721 
722 		/* Clear input buffer: */
723 		serial_drain(&pgm->fd, 0);
724 
725 		/* Attempt to enter binary mode: */
726 		if (buspirate_start_mode_bin(pgm) >= 0)
727 			return;
728 		else
729 			avrdude_message(MSG_INFO, "%s: Failed to start binary mode, falling back to ASCII...\n", progname);
730 	}
731 
732 	avrdude_message(MSG_INFO, "Attempting to initiate BusPirate ASCII mode...\n");
733 
734 	/* Call buspirate_send_bin() instead of buspirate_send()
735 	 * because we don't know if BP is in text or bin mode */
736 	rc = buspirate_send_bin(pgm, (const unsigned char*)reset_str, strlen(reset_str));
737 	if (rc) {
738 		avrdude_message(MSG_INFO, "BusPirate is not responding. Serial port error: %d\n", rc);
739 		return;
740 	}
741 
742 	while(1) {
743 		rcvd = buspirate_readline_noexit(pgm, NULL, 0);
744 		if (! rcvd) {
745 			avrdude_message(MSG_INFO, "%s: Fatal: Programmer is not responding.\n", progname);
746 			return;
747 		}
748 		if (strncmp(rcvd, "Are you sure?", 13) == 0) {
749 			buspirate_send_bin(pgm, (const unsigned char*)accept_str, strlen(accept_str));
750 		}
751 		if (strncmp(rcvd, "RESET", 5) == 0) {
752 			print_banner = 1;
753 			continue;
754 		}
755 		if (buspirate_is_prompt(rcvd)) {
756 			avrdude_message(MSG_DEBUG, "**\n");
757 			break;
758 		}
759 		if (print_banner)
760 			avrdude_message(MSG_DEBUG, "**  %s", rcvd);
761 	}
762 
763 	if (!(pgm->flag & BP_FLAG_IN_BINMODE)) {
764 		avrdude_message(MSG_INFO, "BusPirate: using ASCII mode\n");
765 		if (buspirate_start_spi_mode_ascii(pgm) < 0) {
766 			avrdude_message(MSG_INFO, "%s: Failed to start ascii SPI mode\n", progname);
767 			return;
768 		}
769 	}
770 }
771 
buspirate_disable(struct programmer_t * pgm)772 static void buspirate_disable(struct programmer_t *pgm)
773 {
774 	if (pgm->flag & BP_FLAG_IN_BINMODE) {
775 		serial_recv_timeout = 100;
776 		buspirate_reset_from_binmode(pgm);
777 	} else {
778 		buspirate_expect(pgm, "#\n", "RESET", 1);
779 	}
780 }
781 
buspirate_initialize(struct programmer_t * pgm,AVRPART * p)782 static int buspirate_initialize(struct programmer_t *pgm, AVRPART * p)
783 {
784 	pgm->powerup(pgm);
785 
786 	return pgm->program_enable(pgm, p);
787 }
788 
buspirate_powerup(struct programmer_t * pgm)789 static void buspirate_powerup(struct programmer_t *pgm)
790 {
791 	if (pgm->flag & BP_FLAG_IN_BINMODE) {
792 		/* Powerup in BinMode is handled in binary mode init */
793 		return;
794 	} else {
795 		if (buspirate_expect(pgm, "W\n", "POWER SUPPLIES ON", 1)) {
796 			if (pgm->flag & BP_FLAG_XPARM_CPUFREQ) {
797 				char buf[25];
798 				int ok = 0;
799 				snprintf(buf, sizeof(buf), "%d\n", PDATA(pgm)->cpufreq);
800 				if (buspirate_expect(pgm, "g\n", "Frequency in kHz", 1)) {
801 					if (buspirate_expect(pgm, buf, "Duty cycle in %", 1)) {
802 						if (buspirate_expect(pgm, "50\n", "PWM active", 1)) {
803 							ok = 1;
804 						}
805 					}
806 				}
807 				if(!ok) {
808 					avrdude_message(MSG_INFO, "%s: warning: did not get a response to start PWM command.\n", progname);
809 				}
810 			}
811 			return;
812 		}
813 	}
814 
815 	avrdude_message(MSG_INFO, "%s: warning: did not get a response to PowerUp command.\n", progname);
816 	avrdude_message(MSG_INFO, "%s: warning: Trying to continue anyway...\n", progname);
817 }
818 
buspirate_powerdown(struct programmer_t * pgm)819 static void buspirate_powerdown(struct programmer_t *pgm)
820 {
821 	if (pgm->flag & BP_FLAG_IN_BINMODE) {
822 		/* Powerdown in BinMode is handled in binary mode init */
823 		return;
824 	} else {
825 		if (pgm->flag & BP_FLAG_XPARM_CPUFREQ) {
826 			if (!buspirate_expect(pgm, "g\n", "PWM disabled", 1)) {
827 				avrdude_message(MSG_INFO, "%s: warning: did not get a response to stop PWM command.\n", progname);
828 			}
829 		}
830 		if (buspirate_expect(pgm, "w\n", "POWER SUPPLIES OFF", 1))
831 			return;
832 	}
833 
834 	avrdude_message(MSG_INFO, "%s: warning: did not get a response to PowerDown command.\n", progname);
835 }
836 
buspirate_cmd_bin(struct programmer_t * pgm,const unsigned char * cmd,unsigned char * res)837 static int buspirate_cmd_bin(struct programmer_t *pgm,
838 				const unsigned char *cmd,
839 				unsigned char *res)
840 {
841 	/* 0001xxxx - Bulk transfer, send/read 1-16 bytes (0=1byte!)
842 	 * we are sending 4 bytes -> 0x13 */
843 	int rv = buspirate_expect_bin_byte(pgm, 0x13, 0x01);
844 	if (rv < 0)
845 		return -1;
846 	if (rv == 0)
847 		return -1;
848 
849 	buspirate_send_bin(pgm, cmd, 4);
850 	buspirate_recv_bin(pgm, res, 4);
851 
852 	return 0;
853 }
854 
buspirate_cmd_ascii(struct programmer_t * pgm,const unsigned char * cmd,unsigned char * res)855 static int buspirate_cmd_ascii(struct programmer_t *pgm,
856 				const unsigned char *cmd,
857 				unsigned char *res)
858 {
859 	char buf[25];
860 	char *rcvd;
861 	int spi_write, spi_read, i = 0;
862 
863 	snprintf(buf, sizeof(buf), "0x%02x 0x%02x 0x%02x 0x%02x\n",
864 		cmd[0], cmd[1], cmd[2], cmd[3]);
865 	buspirate_send(pgm, buf);
866 	while (i < 4) {
867 		rcvd = buspirate_readline(pgm, NULL, 0);
868 		if (rcvd == NULL) {
869 			return -1;
870 		}
871 		/* WRITE: 0xAC READ: 0x04 */
872 		if (sscanf(rcvd, "WRITE: 0x%2x READ: 0x%2x", &spi_write, &spi_read) == 2) {
873 			res[i++] = spi_read;
874 		}
875 		if (buspirate_is_prompt(rcvd))
876 			break;
877 	}
878 
879 	if (i != 4) {
880 		avrdude_message(MSG_INFO, "%s: error: SPI has not read 4 bytes back\n", progname);
881 		return -1;
882 	}
883 
884 	/* wait for prompt */
885 	while (buspirate_getc(pgm) != '>')
886 		/* do nothing */;
887 
888 	return 0;
889 }
890 
buspirate_cmd(struct programmer_t * pgm,const unsigned char * cmd,unsigned char * res)891 static int buspirate_cmd(struct programmer_t *pgm,
892 				const unsigned char *cmd,
893 				unsigned char *res)
894 {
895 	if (pgm->flag & BP_FLAG_IN_BINMODE)
896 		return buspirate_cmd_bin(pgm, cmd, res);
897 	else
898 		return buspirate_cmd_ascii(pgm, cmd, res);
899 }
900 
901 /* Paged load function which utilizes the AVR Extended Commands set */
buspirate_paged_load(PROGRAMMER * pgm,AVRPART * p,AVRMEM * m,unsigned int page_size,unsigned int address,unsigned int n_bytes)902 static int buspirate_paged_load(
903 		PROGRAMMER *pgm,
904 		AVRPART *p,
905 		AVRMEM *m,
906 		unsigned int page_size,
907 		unsigned int address,
908 		unsigned int n_bytes)
909 {
910 	unsigned char commandbuf[10];
911 	unsigned char buf[275];
912 	unsigned int addr = 0;
913 
914 	avrdude_message(MSG_NOTICE, "BusPirate: buspirate_paged_load(..,%s,%d,%d,%d)\n",m->desc,m->page_size,address,n_bytes);
915 
916 	// This should never happen, but still...
917 	if (pgm->flag & BP_FLAG_NOPAGEDREAD) {
918 		avrdude_message(MSG_INFO, "BusPirate: buspirate_paged_load() called while in nopagedread mode!\n");
919 		return -1;
920 	}
921 
922 	// determine what type of memory to read, only flash is supported
923 	if (strcmp(m->desc, "flash") != 0) {
924 		return -1;
925 	}
926 
927 	// send command to read data
928 	commandbuf[0] = 6;
929 	commandbuf[1] = 2;
930 
931 	// send start address (in WORDS, not bytes!)
932 	commandbuf[2] = (address >> 1 >> 24) & 0xff;
933 	commandbuf[3] = (address >> 1>> 16) & 0xff;
934 	commandbuf[4] = (address >> 1 >> 8) & 0xff;
935 	commandbuf[5] = (address >> 1) & 0xff;
936 
937 	// send number of bytes to fetch (in BYTES)
938 	commandbuf[6] = (n_bytes >> 24) & 0xff;
939 	commandbuf[7] = (n_bytes >> 16) & 0xff;
940 	commandbuf[8] = (n_bytes >> 8) & 0xff;
941 	commandbuf[9] = (n_bytes) & 0xff;
942 
943 	buspirate_send_bin(pgm, commandbuf, 10);
944 	buspirate_recv_bin(pgm, buf, 1);
945 	buspirate_recv_bin(pgm, buf, 1);
946 
947 	if (buf[0] != 0x01) {
948 		avrdude_message(MSG_INFO, "BusPirate: Paged Read command returned zero.\n");
949 		return -1;
950 	}
951 
952 	for (addr = 0; addr < n_bytes; addr++) {
953 		buspirate_recv_bin(pgm, &m->buf[addr+address], 1);
954 	}
955 
956 	return n_bytes;
957 }
958 /* Paged write function which utilizes the Bus Pirate's "Write then Read" binary SPI instruction */
buspirate_paged_write(struct programmer_t * pgm,AVRPART * p,AVRMEM * m,unsigned int page_size,unsigned int base_addr,unsigned int n_data_bytes)959 static int buspirate_paged_write(struct programmer_t *pgm,
960 		AVRPART *p,
961 		AVRMEM *m,
962 		unsigned int page_size,
963 		unsigned int base_addr,
964 		unsigned int n_data_bytes)
965 {
966 	int page, i;
967 	int addr = base_addr;
968 	int n_page_writes;
969 	int this_page_size;
970 	unsigned char cmd_buf[4096] = {'\0'};
971 	unsigned char send_byte, recv_byte;
972 
973 	if (!(pgm->flag & BP_FLAG_IN_BINMODE)) {
974 		/* Return if we are not in binary mode. */
975 		return -1;
976 	}
977 
978 	if (pgm->flag & BP_FLAG_NOPAGEDWRITE) {
979 		/* Return if we've nominated not to use paged writes. */
980 		return -1;
981 	}
982 
983 	if (page_size>1024) {
984 		/* Page sizes greater than 1kB not yet supported. */
985 		return -1;
986 	}
987 
988 	if (strcmp(m->desc,"flash") != 0) {
989 		/* Only flash memory currently supported. */
990 		return -1;
991 	}
992 
993 	/* pre-check opcodes */
994 	if (m->op[AVR_OP_LOADPAGE_LO] == NULL) {
995 		avrdude_message(MSG_INFO, "%s failure: %s command not defined for %s\n",
996 		                progname, "AVR_OP_LOADPAGE_LO", p->desc);
997 		return -1;
998 	}
999 	if (m->op[AVR_OP_LOADPAGE_HI] == NULL) {
1000 		avrdude_message(MSG_INFO, "%s failure: %s command not defined for %s\n",
1001 		                progname, "AVR_OP_LOADPAGE_HI", p->desc);
1002 		return -1;
1003 	}
1004 
1005 	/* Calculate total number of page writes needed: */
1006 	n_page_writes = n_data_bytes/page_size;
1007 	if (n_data_bytes%page_size >0)
1008 		n_page_writes++;
1009 
1010 	/* Ensure error LED is off: */
1011 	pgm->err_led(pgm, OFF);
1012 
1013 	/* Loop over pages: */
1014 	for (page=0; page<n_page_writes; page++) {
1015 
1016 		/* Determine bytes to write in this page: */
1017 		this_page_size = page_size;
1018 		if (page == n_page_writes-1)
1019 			this_page_size = n_data_bytes - page_size*page;
1020 
1021 		/* Set up command buffer: */
1022 		memset(cmd_buf, 0, 4*this_page_size);
1023 		for (i=0; i<this_page_size; i++) {
1024 
1025 			addr = base_addr + page*page_size + i;
1026 
1027 			if (i%2 == 0) {
1028 				avr_set_bits(m->op[AVR_OP_LOADPAGE_LO], &(cmd_buf[4*i]));
1029 				avr_set_addr(m->op[AVR_OP_LOADPAGE_LO], &(cmd_buf[4*i]), addr/2);
1030 				avr_set_input(m->op[AVR_OP_LOADPAGE_LO], &(cmd_buf[4*i]), m->buf[addr]);
1031 			} else {
1032 				avr_set_bits(m->op[AVR_OP_LOADPAGE_HI], &(cmd_buf[4*i]));
1033 				avr_set_addr(m->op[AVR_OP_LOADPAGE_HI], &(cmd_buf[4*i]), addr/2);
1034 				avr_set_input(m->op[AVR_OP_LOADPAGE_HI], &(cmd_buf[4*i]), m->buf[addr]);
1035 			}
1036 		}
1037 
1038 		/* 00000100 - Write then read */
1039 		send_byte = 0x05;
1040 		buspirate_send_bin(pgm, &send_byte, 1);
1041 
1042 		/* Number of bytes to write: */
1043 		send_byte = (4*this_page_size)/0x100;
1044 		buspirate_send_bin(pgm, &send_byte, 1); /* High byte */
1045 		send_byte = (4*this_page_size)%0x100;
1046 		buspirate_send_bin(pgm, &send_byte, 1); /* Low byte */
1047 
1048 		/* Number of bytes to read: */
1049 		send_byte = 0x0;
1050 		buspirate_send_bin(pgm, &send_byte, 1); /* High byte */
1051 		buspirate_send_bin(pgm, &send_byte, 1); /* Low byte */
1052 
1053 		/* Set programming LED: */
1054 		pgm->pgm_led(pgm, ON);
1055 
1056 		/* Send command buffer: */
1057 		buspirate_send_bin(pgm, cmd_buf, 4*this_page_size);
1058 
1059 		/* Check for write failure: */
1060 		if ((buspirate_recv_bin(pgm, &recv_byte, 1) == EOF) || (recv_byte != 0x01)) {
1061 			avrdude_message(MSG_INFO, "BusPirate: Fatal error: Write Then Read did not succeed.\n");
1062 			pgm->pgm_led(pgm, OFF);
1063 			pgm->err_led(pgm, ON);
1064 			return -1;
1065 		}
1066 
1067 		/* Unset programming LED: */
1068 		pgm->pgm_led(pgm, OFF);
1069 
1070 		/* Write loaded page to flash: */
1071 		avr_write_page(pgm, p, m, addr);
1072 	}
1073 
1074 	return n_data_bytes;
1075 }
1076 
buspirate_program_enable(struct programmer_t * pgm,AVRPART * p)1077 static int buspirate_program_enable(struct programmer_t *pgm, AVRPART * p)
1078 {
1079 	unsigned char cmd[4];
1080 	unsigned char res[4];
1081 
1082 	if (pgm->flag & BP_FLAG_IN_BINMODE) {
1083 		/* Clear configured reset pin(s): CS and/or AUX and/or AUX2 */
1084 		PDATA(pgm)->current_peripherals_config &= ~PDATA(pgm)->reset;
1085 		if (buspirate_expect_bin_byte(pgm, PDATA(pgm)->current_peripherals_config, 0x01) < 0)
1086 			return -1;
1087 	}
1088 	else
1089 		buspirate_expect(pgm, "{\n", "CS ENABLED", 1);
1090 
1091 	if (p->op[AVR_OP_PGM_ENABLE] == NULL) {
1092 		avrdude_message(MSG_INFO, "program enable instruction not defined for part \"%s\"\n",
1093 		                p->desc);
1094 		return -1;
1095 	}
1096 
1097 	memset(cmd, 0, sizeof(cmd));
1098 	avr_set_bits(p->op[AVR_OP_PGM_ENABLE], cmd);
1099 	pgm->cmd(pgm, cmd, res);
1100 
1101 	if (res[2] != cmd[1])
1102 		return -2;
1103 
1104 	return 0;
1105 }
1106 
buspirate_chip_erase(struct programmer_t * pgm,AVRPART * p)1107 static int buspirate_chip_erase(struct programmer_t *pgm, AVRPART * p)
1108 {
1109 	unsigned char cmd[4];
1110 	unsigned char res[4];
1111 
1112 	if (p->op[AVR_OP_CHIP_ERASE] == NULL) {
1113 		avrdude_message(MSG_INFO, "chip erase instruction not defined for part \"%s\"\n",
1114 		                p->desc);
1115 		return -1;
1116 	}
1117 
1118 	pgm->pgm_led(pgm, ON);
1119 
1120 	memset(cmd, 0, sizeof(cmd));
1121 
1122 	avr_set_bits(p->op[AVR_OP_CHIP_ERASE], cmd);
1123 	pgm->cmd(pgm, cmd, res);
1124 	usleep(p->chip_erase_delay);
1125 	pgm->initialize(pgm, p);
1126 
1127 	pgm->pgm_led(pgm, OFF);
1128 
1129 	return 0;
1130 }
1131 
1132 /* Interface - management */
buspirate_setup(struct programmer_t * pgm)1133 static void buspirate_setup(struct programmer_t *pgm)
1134 {
1135 	/* Allocate private data */
1136 	if ((pgm->cookie = calloc(1, sizeof(struct pdata))) == 0) {
1137 		avrdude_message(MSG_INFO, "%s: buspirate_initpgm(): Out of memory allocating private data\n",
1138 		                progname);
1139 		exit(1);
1140 	}
1141 	PDATA(pgm)->serial_recv_timeout = 100;
1142 }
1143 
buspirate_teardown(struct programmer_t * pgm)1144 static void buspirate_teardown(struct programmer_t *pgm)
1145 {
1146 	free(pgm->cookie);
1147 }
1148 const char buspirate_desc[] = "Using the Bus Pirate's SPI interface for programming";
1149 
buspirate_initpgm(struct programmer_t * pgm)1150 void buspirate_initpgm(struct programmer_t *pgm)
1151 {
1152 	strcpy(pgm->type, "BusPirate");
1153 
1154 	pgm->display        = buspirate_dummy_6;
1155 
1156 	/* BusPirate itself related methods */
1157 	pgm->open           = buspirate_open;
1158 	pgm->close          = buspirate_close;
1159 	pgm->enable         = buspirate_enable;
1160 	pgm->disable        = buspirate_disable;
1161 	pgm->initialize     = buspirate_initialize;
1162 
1163 	/* Chip related methods */
1164 	pgm->powerup        = buspirate_powerup;
1165 	pgm->powerdown      = buspirate_powerdown;
1166 	pgm->program_enable = buspirate_program_enable;
1167 	pgm->chip_erase     = buspirate_chip_erase;
1168 	pgm->cmd            = buspirate_cmd;
1169 	pgm->read_byte      = avr_read_byte_default;
1170 	pgm->write_byte     = avr_write_byte_default;
1171 
1172 	pgm->paged_write    = buspirate_paged_write;
1173 	pgm->paged_load	    = buspirate_paged_load;
1174 
1175 	/* Support functions */
1176 	pgm->parseextparams = buspirate_parseextparms;
1177 
1178 	pgm->setup          = buspirate_setup;
1179 	pgm->teardown       = buspirate_teardown;
1180 }
1181 
1182 /* Bitbang support */
1183 
buspirate_bb_enable(struct programmer_t * pgm)1184 static void buspirate_bb_enable(struct programmer_t *pgm)
1185 {
1186 	unsigned char buf[20] = { '\0' };
1187 
1188 	if (bitbang_check_prerequisites(pgm) < 0)
1189 		return;             /* XXX should treat as error */
1190 
1191 	avrdude_message(MSG_INFO, "Attempting to initiate BusPirate bitbang binary mode...\n");
1192 
1193 	/* Send two CRs to ensure we're not in a sub-menu of the UI if we're in ASCII mode: */
1194 	buspirate_send_bin(pgm, (const unsigned char*)"\n\n", 2);
1195 
1196 	/* Clear input buffer: */
1197 	serial_drain(&pgm->fd, 0);
1198 
1199 	/* == Switch to binmode - send 20x '\0' == */
1200 	buspirate_send_bin(pgm, buf, sizeof(buf));
1201 
1202 	/* Expecting 'BBIOx' reply */
1203 	memset(buf, 0, sizeof(buf));
1204 	buspirate_recv_bin(pgm, buf, 5);
1205 	if (sscanf((char*)buf, "BBIO%1d", &PDATA(pgm)->binmode_version) != 1) {
1206 		avrdude_message(MSG_INFO, "Binary mode not confirmed: '%s'\n", buf);
1207 		buspirate_reset_from_binmode(pgm);
1208 		return;
1209 	}
1210 	avrdude_message(MSG_INFO, "BusPirate binmode version: %d\n",
1211 	                PDATA(pgm)->binmode_version);
1212 
1213 	pgm->flag |= BP_FLAG_IN_BINMODE;
1214 
1215 	/* Set pin directions and an initial pin status (all high) */
1216 	PDATA(pgm)->pin_dir = 0x12;  /* AUX, MISO input; everything else output */
1217 	buf[0] = PDATA(pgm)->pin_dir | 0x40;
1218 	buspirate_send_bin(pgm, buf, 1);
1219 	buspirate_recv_bin(pgm, buf, 1);
1220 
1221 	PDATA(pgm)->pin_val = 0x3f; /* PULLUP, AUX, MOSI, CLK, MISO, CS high */
1222 	buf[0] = PDATA(pgm)->pin_val | 0x80;
1223 	buspirate_send_bin(pgm, buf, 1);
1224 	buspirate_recv_bin(pgm, buf, 1);
1225 
1226 	/* Done */
1227 	return;
1228 }
1229 
1230 /*
1231    Direction:
1232    010xxxxx
1233    Input (1) or output (0):
1234    AUX|MOSI|CLK|MISO|CS
1235 
1236    Output value:
1237    1xxxxxxx
1238    High (1) or low(0):
1239    1|POWER|PULLUP|AUX|MOSI|CLK|MISO|CS
1240 
1241    Both respond with a byte with current status:
1242    0|POWER|PULLUP|AUX|MOSI|CLK|MISO|CS
1243 */
buspirate_bb_getpin(struct programmer_t * pgm,int pinfunc)1244 static int buspirate_bb_getpin(struct programmer_t *pgm, int pinfunc)
1245 {
1246 	unsigned char buf[10];
1247 	int value = 0;
1248 	int pin = pgm->pinno[pinfunc];
1249 
1250 	if (pin & PIN_INVERSE) {
1251 		pin &= PIN_MASK;
1252 		value = 1;
1253 	}
1254 
1255 	if (pin < 1 || pin > 5)
1256 		return -1;
1257 
1258 	buf[0] = PDATA(pgm)->pin_dir | 0x40;
1259 	if (buspirate_send_bin(pgm, buf, 1) < 0)
1260 		return -1;
1261 	/* Read all of the previously-expected-but-unread bytes */
1262 	while (PDATA(pgm)->unread_bytes > 0) {
1263 		if (buspirate_recv_bin(pgm, buf, 1) < 0)
1264 			return -1;
1265 		PDATA(pgm)->unread_bytes--;
1266 	}
1267 
1268 	/* Now read the actual response */
1269 	if (buspirate_recv_bin(pgm, buf, 1) < 0)
1270 		return -1;
1271 
1272 	if (buf[0] & (1 << (pin - 1)))
1273 		value ^= 1;
1274 
1275 	avrdude_message(MSG_DEBUG, "get pin %d = %d\n", pin, value);
1276 
1277 	return value;
1278 }
1279 
buspirate_bb_setpin_internal(struct programmer_t * pgm,int pin,int value)1280 static int buspirate_bb_setpin_internal(struct programmer_t *pgm, int pin, int value)
1281 {
1282 	unsigned char buf[10];
1283 
1284 	if (pin & PIN_INVERSE) {
1285 		value = !value;
1286 		pin &= PIN_MASK;
1287 	}
1288 
1289 	if ((pin < 1 || pin > 5) && (pin != 7)) // 7 is POWER
1290 		return -1;
1291 
1292 	avrdude_message(MSG_DEBUG, "set pin %d = %d\n", pin, value);
1293 
1294 	if (value)
1295 		PDATA(pgm)->pin_val |= (1 << (pin - 1));
1296 	else
1297 		PDATA(pgm)->pin_val &= ~(1 << (pin - 1));
1298 
1299 	buf[0] = PDATA(pgm)->pin_val | 0x80;
1300 	if (buspirate_send_bin(pgm, buf, 1) < 0)
1301 		return -1;
1302 	/* We'll get a byte back, but we don't need to read it now.
1303 	   This is just a quick optimization that saves some USB
1304 	   round trips, improving read times by a factor of 3. */
1305 	PDATA(pgm)->unread_bytes++;
1306 
1307 	return 0;
1308 }
1309 
buspirate_bb_setpin(struct programmer_t * pgm,int pinfunc,int value)1310 static int buspirate_bb_setpin(struct programmer_t *pgm, int pinfunc, int value)
1311 {
1312 	return buspirate_bb_setpin_internal(pgm, pgm->pinno[pinfunc], value);
1313 }
1314 
1315 
buspirate_bb_highpulsepin(struct programmer_t * pgm,int pinfunc)1316 static int buspirate_bb_highpulsepin(struct programmer_t *pgm, int pinfunc)
1317 {
1318 	int ret;
1319 	ret = buspirate_bb_setpin(pgm, pinfunc, 1);
1320 	if (ret < 0)
1321 		return ret;
1322 	return buspirate_bb_setpin(pgm, pinfunc, 0);
1323 }
1324 
buspirate_bb_powerup(struct programmer_t * pgm)1325 static void buspirate_bb_powerup(struct programmer_t *pgm)
1326 {
1327 	buspirate_bb_setpin_internal(pgm, 7, 1);
1328 }
1329 
buspirate_bb_powerdown(struct programmer_t * pgm)1330 static void buspirate_bb_powerdown(struct programmer_t *pgm)
1331 {
1332 	buspirate_bb_setpin_internal(pgm, 7, 0);
1333 }
1334 
1335 const char buspirate_bb_desc[] = "Using the Bus Pirate's bitbang interface for programming";
1336 
buspirate_bb_initpgm(struct programmer_t * pgm)1337 void buspirate_bb_initpgm(struct programmer_t *pgm)
1338 {
1339 	strcpy(pgm->type, "BusPirate_BB");
1340 
1341 	pgm_fill_old_pins(pgm); // TODO to be removed if old pin data no longer needed
1342 
1343 	pgm->display        = buspirate_dummy_6;
1344 
1345 	/* BusPirate itself related methods */
1346 	pgm->setup          = buspirate_setup;
1347 	pgm->teardown       = buspirate_teardown;
1348 	pgm->open           = buspirate_open;
1349 	pgm->close          = buspirate_close;
1350 	pgm->enable         = buspirate_bb_enable;
1351 	pgm->disable        = buspirate_disable;
1352 
1353 	/* Chip related methods */
1354 	pgm->initialize     = bitbang_initialize;
1355 	pgm->rdy_led        = bitbang_rdy_led;
1356 	pgm->err_led        = bitbang_err_led;
1357 	pgm->pgm_led        = bitbang_pgm_led;
1358 	pgm->vfy_led        = bitbang_vfy_led;
1359 	pgm->program_enable = bitbang_program_enable;
1360 	pgm->chip_erase     = bitbang_chip_erase;
1361 	pgm->cmd            = bitbang_cmd;
1362 	pgm->cmd_tpi        = bitbang_cmd_tpi;
1363 	pgm->powerup        = buspirate_bb_powerup;
1364 	pgm->powerdown      = buspirate_bb_powerdown;
1365 	pgm->setpin         = buspirate_bb_setpin;
1366 	pgm->getpin         = buspirate_bb_getpin;
1367 	pgm->highpulsepin   = buspirate_bb_highpulsepin;
1368 	pgm->read_byte      = avr_read_byte_default;
1369 	pgm->write_byte     = avr_write_byte_default;
1370 }
1371