1 
2 /*
3  * avrdude - A Downloader/Uploader for AVR device programmers
4  * Copyright (C) 2003-2004  Theodore A. Roth  <troth@openavr.org>
5  * some code:
6  * Copyright (C) 2011-2012 Roger E. Wolff <R.E.Wolff@BitWizard.nl>
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 /* $Id$ */
24 
25 /* ft245r -- FT245R/FT232R Synchronous BitBangMode Programmer
26   default pin assign
27                FT232R / FT245R
28   miso  = 1;  # RxD   / D1
29   sck   = 0;  # RTS   / D0
30   mosi  = 2;  # TxD   / D2
31   reset = 4;  # DTR   / D4
32 */
33 
34 /*
35   The ft232r is very similar, or even "identical" in the synchronous
36   bitbang mode that we use here.
37 
38   This allows boards that have an ft232r for communication and an avr
39   as the processor to function as their own "ICSP". Boards that fit
40   this description include the Arduino Duemilanove, Arduino Diecimila,
41   Arduino NG (http://arduino.cc/it/main/boards) and the BitWizard
42   ftdi_atmega board (http://www.bitwizard.nl/wiki/index.php/FTDI_ATmega)
43 
44   The Arduinos have to be patched to bring some of the control lines
45   to the ICSP header. The BitWizard board already has the neccessary
46   wiring on the PCB.
47 
48   How to add the wires to an arduino is documented here:
49   http://www.geocities.jp/arduino_diecimila/bootloader/index_en.html
50 */
51 
52 
53 #include "ac_cfg.h"
54 
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <string.h>
58 #include <errno.h>
59 #include <sys/time.h>
60 #include <unistd.h>
61 #include <stdint.h>
62 
63 #include "avrdude.h"
64 #include "libavrdude.h"
65 
66 #include "bitbang.h"
67 #include "ft245r.h"
68 #include "usbdevs.h"
69 
70 #if defined(_WIN32)
71 #include <windows.h>
72 #endif
73 
74 #if defined(HAVE_LIBFTDI1) && defined(HAVE_LIBUSB_1_0)
75 # if defined(HAVE_LIBUSB_1_0_LIBUSB_H)
76 #  include <libusb-1.0/libusb.h>
77 # else
78 #  include <libusb.h>
79 # endif
80 # include <libftdi1/ftdi.h>
81 #elif defined(HAVE_LIBFTDI) && defined(HAVE_USB_H)
82 /* ftdi.h includes usb.h */
83 #include <ftdi.h>
84 #else
85 #warning No libftdi or libusb support. Install libftdi1/libusb-1.0 or libftdi/libusb and run configure/make again.
86 #define DO_NOT_BUILD_FT245R
87 #endif
88 
89 #ifndef HAVE_PTHREAD_H
90 
ft245r_nopthread_open(struct programmer_t * pgm,char * name)91 static int ft245r_nopthread_open (struct programmer_t *pgm, char * name) {
92     avrdude_message(MSG_INFO, "%s: error: no pthread support. Please compile again with pthread installed."
93 #if defined(_WIN32)
94             " See http://sourceware.org/pthreads-win32/."
95 #endif
96             "\n",
97             progname);
98 
99     return -1;
100 }
101 
ft245r_initpgm(PROGRAMMER * pgm)102 void ft245r_initpgm(PROGRAMMER * pgm) {
103     strcpy(pgm->type, "ftdi_syncbb");
104     pgm->open = ft245r_nopthread_open;
105 }
106 
107 #elif defined(DO_NOT_BUILD_FT245R)
108 
ft245r_noftdi_open(struct programmer_t * pgm,char * name)109 static int ft245r_noftdi_open (struct programmer_t *pgm, char * name) {
110     avrdude_message(MSG_INFO, "%s: error: no libftdi or libusb support. Install libftdi1/libusb-1.0 or libftdi/libusb and run configure/make again.\n",
111                     progname);
112 
113     return -1;
114 }
115 
ft245r_initpgm(PROGRAMMER * pgm)116 void ft245r_initpgm(PROGRAMMER * pgm) {
117     strcpy(pgm->type, "ftdi_syncbb");
118     pgm->open = ft245r_noftdi_open;
119 }
120 
121 #else
122 
123 #include <pthread.h>
124 
125 #ifdef __APPLE__
126 /* Mac OS X defines sem_init but actually does not implement them */
127 #include <dispatch/dispatch.h>
128 
129 typedef dispatch_semaphore_t	sem_t;
130 
131 #define sem_init(psem,x,val)	*psem = dispatch_semaphore_create(val)
132 #define sem_post(psem)		dispatch_semaphore_signal(*psem)
133 #define sem_wait(psem)		dispatch_semaphore_wait(*psem, DISPATCH_TIME_FOREVER)
134 #else
135 #include <semaphore.h>
136 #endif
137 
138 #define FT245R_CYCLES	2
139 #define FT245R_FRAGMENT_SIZE  512
140 #define REQ_OUTSTANDINGS	10
141 //#define USE_INLINE_WRITE_PAGE
142 
143 #define FT245R_DEBUG	0
144 
145 static struct ftdi_context *handle;
146 
147 static unsigned char ft245r_ddr;
148 static unsigned char ft245r_out;
149 static unsigned char ft245r_in;
150 
151 #define BUFSIZE 0x2000
152 
153 // libftdi / libftd2xx compatibility functions.
154 
155 static pthread_t readerthread;
156 static sem_t buf_data, buf_space;
157 static unsigned char buffer[BUFSIZE];
158 static int head, tail;
159 
add_to_buf(unsigned char c)160 static void add_to_buf (unsigned char c) {
161     int nh;
162 
163     sem_wait (&buf_space);
164     if (head == (BUFSIZE -1)) nh = 0;
165     else                      nh = head + 1;
166 
167     if (nh == tail) {
168         avrdude_message(MSG_INFO, "buffer overflow. Cannot happen!\n");
169     }
170     buffer[head] = c;
171     head = nh;
172     sem_post (&buf_data);
173 }
174 
reader(void * arg)175 static void *reader (void *arg) {
176     pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,NULL);
177     struct ftdi_context *handle = (struct ftdi_context *)(arg);
178     unsigned char buf[0x1000];
179     int br, i;
180 
181     while (1) {
182         pthread_testcancel();
183         br = ftdi_read_data (handle, buf, sizeof(buf));
184         for (i=0; i<br; i++)
185             add_to_buf (buf[i]);
186     }
187     return NULL;
188 }
189 
ft245r_send(PROGRAMMER * pgm,unsigned char * buf,size_t len)190 static int ft245r_send(PROGRAMMER * pgm, unsigned char * buf, size_t len) {
191     int rv;
192 
193     rv = ftdi_write_data(handle, buf, len);
194     if (len != rv) return -1;
195     return 0;
196 }
197 
ft245r_recv(PROGRAMMER * pgm,unsigned char * buf,size_t len)198 static int ft245r_recv(PROGRAMMER * pgm, unsigned char * buf, size_t len) {
199     int i;
200 
201     // Copy over data from the circular buffer..
202     // XXX This should timeout, and return error if there isn't enough
203     // data.
204     for (i=0; i<len; i++) {
205         sem_wait (&buf_data);
206         buf[i] = buffer[tail];
207         if (tail == (BUFSIZE -1)) tail = 0;
208         else                      tail++;
209         sem_post (&buf_space);
210     }
211 
212     return 0;
213 }
214 
215 
ft245r_drain(PROGRAMMER * pgm,int display)216 static int ft245r_drain(PROGRAMMER * pgm, int display) {
217     int r;
218     unsigned char t;
219 
220     // flush the buffer in the chip by changing the mode.....
221     r = ftdi_set_bitmode(handle, 0, BITMODE_RESET); 	// reset
222     if (r) return -1;
223     r = ftdi_set_bitmode(handle, ft245r_ddr, BITMODE_SYNCBB); // set Synchronuse BitBang
224     if (r) return -1;
225 
226     // drain our buffer.
227     while (head != tail) {
228         ft245r_recv (pgm, &t, 1);
229     }
230     return 0;
231 }
232 
233 
ft245r_chip_erase(PROGRAMMER * pgm,AVRPART * p)234 static int ft245r_chip_erase(PROGRAMMER * pgm, AVRPART * p) {
235     unsigned char cmd[4] = {0,0,0,0};
236     unsigned char res[4];
237 
238     if (p->op[AVR_OP_CHIP_ERASE] == NULL) {
239         avrdude_message(MSG_INFO, "chip erase instruction not defined for part \"%s\"\n",
240                 p->desc);
241         return -1;
242     }
243 
244     avr_set_bits(p->op[AVR_OP_CHIP_ERASE], cmd);
245     pgm->cmd(pgm, cmd, res);
246     usleep(p->chip_erase_delay);
247     return pgm->initialize(pgm, p);
248 }
249 
250 
ft245r_set_bitclock(PROGRAMMER * pgm)251 static int ft245r_set_bitclock(PROGRAMMER * pgm) {
252     int r;
253     int rate = 0;
254 
255     /* bitclock is second. 1us = 0.000001. Max rate for ft232r 750000 */
256     if(pgm->bitclock) {
257         rate = (uint32_t)(1.0/pgm->bitclock) * 2;
258     } else if (pgm->baudrate) {
259         rate = pgm->baudrate * 2;
260     } else {
261         rate = 150000; /* should work for all ftdi chips and the avr default internal clock of 1MHz */
262     }
263 
264     if (FT245R_DEBUG) {
265         avrdude_message(MSG_NOTICE2, " ft245r:  spi bitclk %d -> ft baudrate %d\n",
266                 rate / 2, rate);
267     }
268     r = ftdi_set_baudrate(handle, rate);
269     if (r) {
270         avrdude_message(MSG_INFO, "Set baudrate (%d) failed with error '%s'.\n",
271                 rate, ftdi_get_error_string (handle));
272         return -1;
273     }
274     return 0;
275 }
276 
set_pin(PROGRAMMER * pgm,int pinname,int val)277 static int set_pin(PROGRAMMER * pgm, int pinname, int val) {
278     unsigned char buf[1];
279 
280     if (pgm->pin[pinname].mask[0] == 0) {
281         // ignore not defined pins (might be the led or vcc or buff if not needed)
282         return 0;
283     }
284 
285     ft245r_out = SET_BITS_0(ft245r_out,pgm,pinname,val);
286     buf[0] = ft245r_out;
287 
288     ft245r_send (pgm, buf, 1);
289     ft245r_recv (pgm, buf, 1);
290 
291     ft245r_in = buf[0];
292     return 0;
293 }
294 
set_sck(PROGRAMMER * pgm,int value)295 static int set_sck(PROGRAMMER * pgm, int value) {
296     return set_pin(pgm, PIN_AVR_SCK, value);
297 }
298 
set_reset(PROGRAMMER * pgm,int value)299 static int set_reset(PROGRAMMER * pgm, int value) {
300     return set_pin(pgm, PIN_AVR_RESET, value);
301 }
302 
set_buff(PROGRAMMER * pgm,int value)303 static int set_buff(PROGRAMMER * pgm, int value) {
304     return set_pin(pgm, PPI_AVR_BUFF, value);
305 }
306 
set_vcc(PROGRAMMER * pgm,int value)307 static int set_vcc(PROGRAMMER * pgm, int value) {
308     return set_pin(pgm, PPI_AVR_VCC, value);
309 }
310 
311 /* these functions are callbacks, which go into the
312  * PROGRAMMER data structure ("optional functions")
313  */
set_led_pgm(struct programmer_t * pgm,int value)314 static int set_led_pgm(struct programmer_t * pgm, int value) {
315     return set_pin(pgm, PIN_LED_PGM, value);
316 }
317 
set_led_rdy(struct programmer_t * pgm,int value)318 static int set_led_rdy(struct programmer_t * pgm, int value) {
319     return set_pin(pgm, PIN_LED_RDY, value);
320 }
321 
set_led_err(struct programmer_t * pgm,int value)322 static int set_led_err(struct programmer_t * pgm, int value) {
323     return set_pin(pgm, PIN_LED_ERR, value);
324 }
325 
set_led_vfy(struct programmer_t * pgm,int value)326 static int set_led_vfy(struct programmer_t * pgm, int value) {
327     return set_pin(pgm, PIN_LED_VFY, value);
328 }
329 
330 /*
331  * apply power to the AVR processor
332  */
ft245r_powerup(PROGRAMMER * pgm)333 static void ft245r_powerup(PROGRAMMER * pgm)
334 {
335     set_vcc(pgm, ON); /* power up */
336     usleep(100);
337 }
338 
339 
340 /*
341  * remove power from the AVR processor
342  */
ft245r_powerdown(PROGRAMMER * pgm)343 static void ft245r_powerdown(PROGRAMMER * pgm)
344 {
345     set_vcc(pgm, OFF); /* power down */
346 }
347 
348 
ft245r_disable(PROGRAMMER * pgm)349 static void ft245r_disable(PROGRAMMER * pgm) {
350     set_buff(pgm, OFF);
351 }
352 
353 
ft245r_enable(PROGRAMMER * pgm)354 static void ft245r_enable(PROGRAMMER * pgm) {
355   /*
356    * Prepare to start talking to the connected device - pull reset low
357    * first, delay a few milliseconds, then enable the buffer.  This
358    * sequence allows the AVR to be reset before the buffer is enabled
359    * to avoid a short period of time where the AVR may be driving the
360    * programming lines at the same time the programmer tries to.  Of
361    * course, if a buffer is being used, then the /RESET line from the
362    * programmer needs to be directly connected to the AVR /RESET line
363    * and not via the buffer chip.
364    */
365     set_reset(pgm, OFF);
366     usleep(1);
367     set_buff(pgm, ON);
368 }
369 
370 static int ft245r_cmd(PROGRAMMER * pgm, const unsigned char *cmd,
371                       unsigned char *res);
372 /*
373  * issue the 'program enable' command to the AVR device
374  */
ft245r_program_enable(PROGRAMMER * pgm,AVRPART * p)375 static int ft245r_program_enable(PROGRAMMER * pgm, AVRPART * p) {
376     unsigned char cmd[4] = {0,0,0,0};
377     unsigned char res[4];
378     int i;
379 
380     if (p->op[AVR_OP_PGM_ENABLE] == NULL) {
381         avrdude_message(MSG_INFO, "%s: AVR_OP_PGM_ENABLE command not defined for %s\n",
382                         progname, p->desc);
383         fflush(stderr);
384         return -1;
385     }
386 
387     avr_set_bits(p->op[AVR_OP_PGM_ENABLE], cmd);
388 
389     for(i = 0; i < 4; i++) {
390         ft245r_cmd(pgm, cmd, res);
391 
392         if (res[p->pollindex-1] == p->pollvalue) return 0;
393 
394         if (FT245R_DEBUG) {
395             avrdude_message(MSG_NOTICE, "%s: Program enable command not successful. Retrying.\n",
396                             progname);
397             fflush(stderr);
398         }
399         set_pin(pgm, PIN_AVR_RESET, ON);
400         usleep(20);
401         set_pin(pgm, PIN_AVR_RESET, OFF);
402 
403         if (i == 3) {
404             ft245r_drain(pgm, 0);
405             tail = head;
406         }
407     }
408 
409     avrdude_message(MSG_INFO, "%s: Device is not responding to program enable. Check connection.\n",
410                     progname);
411     fflush(stderr);
412 
413     return -1;
414 }
415 
416 /*
417  * initialize the AVR device and prepare it to accept commands
418  */
ft245r_initialize(PROGRAMMER * pgm,AVRPART * p)419 static int ft245r_initialize(PROGRAMMER * pgm, AVRPART * p) {
420 
421     /* Apply power between VCC and GND while RESET and SCK are set to “0”. In some systems,
422      * the programmer can not guarantee that SCK is held low during power-up. In this
423      * case, RESET must be given a positive pulse of at least two CPU clock cycles duration
424      * after SCK has been set to “0”.
425      */
426     set_sck(pgm, OFF);
427     ft245r_powerup(pgm);
428 
429     set_reset(pgm, OFF);
430     usleep(5000); // 5ms
431     set_reset(pgm, ON);
432     usleep(5000); // 5ms
433     set_reset(pgm, OFF);
434 
435     /* Wait for at least 20 ms and enable serial programming by sending the Programming
436      * Enable serial instruction to pin MOSI.
437      */
438     usleep(20000); // 20ms
439 
440     return ft245r_program_enable(pgm, p);
441 }
442 
set_data(PROGRAMMER * pgm,unsigned char * buf,unsigned char data)443 static inline int set_data(PROGRAMMER * pgm, unsigned char *buf, unsigned char data) {
444     int j;
445     int buf_pos = 0;
446     unsigned char bit = 0x80;
447 
448     for (j=0; j<8; j++) {
449         ft245r_out = SET_BITS_0(ft245r_out,pgm,PIN_AVR_MOSI,data & bit);
450 
451         ft245r_out = SET_BITS_0(ft245r_out,pgm,PIN_AVR_SCK,0);
452         buf[buf_pos] = ft245r_out;
453         buf_pos++;
454 
455         ft245r_out = SET_BITS_0(ft245r_out,pgm,PIN_AVR_SCK,1);
456         buf[buf_pos] = ft245r_out;
457         buf_pos++;
458 
459         bit >>= 1;
460     }
461     return buf_pos;
462 }
463 
extract_data(PROGRAMMER * pgm,unsigned char * buf,int offset)464 static inline unsigned char extract_data(PROGRAMMER * pgm, unsigned char *buf, int offset) {
465     int j;
466     int buf_pos = 1;
467     unsigned char bit = 0x80;
468     unsigned char r = 0;
469 
470     buf += offset * (8 * FT245R_CYCLES);
471     for (j=0; j<8; j++) {
472         if (GET_BITS_0(buf[buf_pos],pgm,PIN_AVR_MISO)) {
473             r |= bit;
474         }
475         buf_pos += FT245R_CYCLES;
476         bit >>= 1;
477     }
478     return r;
479 }
480 
481 /* to check data */
extract_data_out(PROGRAMMER * pgm,unsigned char * buf,int offset)482 static inline unsigned char extract_data_out(PROGRAMMER * pgm, unsigned char *buf, int offset) {
483     int j;
484     int buf_pos = 1;
485     unsigned char bit = 0x80;
486     unsigned char r = 0;
487 
488     buf += offset * (8 * FT245R_CYCLES);
489     for (j=0; j<8; j++) {
490         if (GET_BITS_0(buf[buf_pos],pgm,PIN_AVR_MOSI)) {
491             r |= bit;
492         }
493         buf_pos += FT245R_CYCLES;
494         bit >>= 1;
495     }
496     return r;
497 }
498 
499 
500 /*
501  * transmit an AVR device command and return the results; 'cmd' and
502  * 'res' must point to at least a 4 byte data buffer
503  */
ft245r_cmd(PROGRAMMER * pgm,const unsigned char * cmd,unsigned char * res)504 static int ft245r_cmd(PROGRAMMER * pgm, const unsigned char *cmd,
505                       unsigned char *res) {
506     int i,buf_pos;
507     unsigned char buf[128];
508 
509     buf_pos = 0;
510     for (i=0; i<4; i++) {
511         buf_pos += set_data(pgm, buf+buf_pos, cmd[i]);
512     }
513     buf[buf_pos] = 0;
514     buf_pos++;
515 
516     ft245r_send (pgm, buf, buf_pos);
517     ft245r_recv (pgm, buf, buf_pos);
518     res[0] = extract_data(pgm, buf, 0);
519     res[1] = extract_data(pgm, buf, 1);
520     res[2] = extract_data(pgm, buf, 2);
521     res[3] = extract_data(pgm, buf, 3);
522 
523     return 0;
524 }
525 
526 /* lower 8 pins are accepted, they might be also inverted */
527 static const struct pindef_t valid_pins = {{0xff},{0xff}} ;
528 
529 static const struct pin_checklist_t pin_checklist[] = {
530     { PIN_AVR_SCK,  1, &valid_pins},
531     { PIN_AVR_MOSI, 1, &valid_pins},
532     { PIN_AVR_MISO, 1, &valid_pins},
533     { PIN_AVR_RESET,1, &valid_pins},
534     { PPI_AVR_BUFF, 0, &valid_pins},
535 };
536 
ft245r_open(PROGRAMMER * pgm,char * port)537 static int ft245r_open(PROGRAMMER * pgm, char * port) {
538     int rv;
539     int devnum = -1;
540 
541     rv = pins_check(pgm,pin_checklist,sizeof(pin_checklist)/sizeof(pin_checklist[0]), true);
542     if(rv) {
543         pgm->display(pgm, progbuf);
544         return rv;
545     }
546 
547     strcpy(pgm->port, port);
548 
549     if (strcmp(port,DEFAULT_USB) != 0) {
550         if (strncasecmp("ft", port, 2) == 0) {
551             char *startptr = port + 2;
552             char *endptr = NULL;
553             devnum = strtol(startptr,&endptr,10);
554             if ((startptr==endptr) || (*endptr != '\0')) {
555                 devnum = -1;
556             }
557         }
558         if (devnum < 0) {
559             avrdude_message(MSG_INFO, "%s: invalid portname '%s': use 'ft[0-9]+'\n",
560                             progname,port);
561             return -1;
562         }
563     } else {
564         devnum = 0;
565     }
566 
567     handle = malloc (sizeof (struct ftdi_context));
568     ftdi_init(handle);
569     LNODEID usbpid = lfirst(pgm->usbpid);
570     int pid;
571     if (usbpid) {
572       pid = *(int *)(ldata(usbpid));
573       if (lnext(usbpid))
574 	avrdude_message(MSG_INFO, "%s: Warning: using PID 0x%04x, ignoring remaining PIDs in list\n",
575 		progname, pid);
576     } else {
577       pid = USB_DEVICE_FT245;
578     }
579     rv = ftdi_usb_open_desc_index(handle,
580                                   pgm->usbvid?pgm->usbvid:USB_VENDOR_FTDI,
581                                   pid,
582                                   pgm->usbproduct[0]?pgm->usbproduct:NULL,
583                                   pgm->usbsn[0]?pgm->usbsn:NULL,
584                                   devnum);
585     if (rv) {
586         avrdude_message(MSG_INFO, "can't open ftdi device %d. (%s)\n", devnum, ftdi_get_error_string(handle));
587         goto cleanup_no_usb;
588     }
589 
590     ft245r_ddr =
591          pgm->pin[PIN_AVR_SCK].mask[0]
592        | pgm->pin[PIN_AVR_MOSI].mask[0]
593        | pgm->pin[PIN_AVR_RESET].mask[0]
594        | pgm->pin[PPI_AVR_BUFF].mask[0]
595        | pgm->pin[PPI_AVR_VCC].mask[0]
596        | pgm->pin[PIN_LED_ERR].mask[0]
597        | pgm->pin[PIN_LED_RDY].mask[0]
598        | pgm->pin[PIN_LED_PGM].mask[0]
599        | pgm->pin[PIN_LED_VFY].mask[0];
600 
601     /* set initial values for outputs, no reset everything else is off */
602     ft245r_out = 0;
603     ft245r_out = SET_BITS_0(ft245r_out,pgm,PIN_AVR_RESET,1);
604     ft245r_out = SET_BITS_0(ft245r_out,pgm,PIN_AVR_SCK,0);
605     ft245r_out = SET_BITS_0(ft245r_out,pgm,PIN_AVR_MOSI,0);
606     ft245r_out = SET_BITS_0(ft245r_out,pgm,PPI_AVR_BUFF,0);
607     ft245r_out = SET_BITS_0(ft245r_out,pgm,PPI_AVR_VCC,0);
608     ft245r_out = SET_BITS_0(ft245r_out,pgm,PIN_LED_ERR,0);
609     ft245r_out = SET_BITS_0(ft245r_out,pgm,PIN_LED_RDY,0);
610     ft245r_out = SET_BITS_0(ft245r_out,pgm,PIN_LED_PGM,0);
611     ft245r_out = SET_BITS_0(ft245r_out,pgm,PIN_LED_VFY,0);
612 
613 
614     rv = ftdi_set_bitmode(handle, ft245r_ddr, BITMODE_SYNCBB); // set Synchronous BitBang
615     if (rv) {
616         avrdude_message(MSG_INFO, "%s: Synchronous BitBangMode is not supported (%s)\n",
617                         progname, ftdi_get_error_string(handle));
618         goto cleanup;
619     }
620 
621     rv = ft245r_set_bitclock(pgm);
622     if (rv) {
623         goto cleanup;
624     }
625 
626     /* We start a new thread to read the output from the FTDI. This is
627      * necessary because otherwise we'll deadlock. We cannot finish
628      * writing because the ftdi cannot send the results because we
629      * haven't provided a read buffer yet. */
630 
631     sem_init (&buf_data, 0, 0);
632     sem_init (&buf_space, 0, BUFSIZE);
633     pthread_create (&readerthread, NULL, reader, handle);
634 
635     /*
636      * drain any extraneous input
637      */
638     ft245r_drain (pgm, 0);
639 
640     ft245r_send (pgm, &ft245r_out, 1);
641     ft245r_recv (pgm, &ft245r_in, 1);
642 
643     return 0;
644 
645 cleanup:
646     ftdi_usb_close(handle);
647 cleanup_no_usb:
648     ftdi_deinit (handle);
649     free(handle);
650     handle = NULL;
651     return -1;
652 }
653 
654 
ft245r_close(PROGRAMMER * pgm)655 static void ft245r_close(PROGRAMMER * pgm) {
656     if (handle) {
657         // I think the switch to BB mode and back flushes the buffer.
658         ftdi_set_bitmode(handle, 0, BITMODE_SYNCBB); // set Synchronous BitBang, all in puts
659         ftdi_set_bitmode(handle, 0, BITMODE_RESET); // disable Synchronous BitBang
660         ftdi_usb_close(handle);
661         ftdi_deinit (handle);
662         pthread_cancel(readerthread);
663         pthread_join(readerthread, NULL);
664         free(handle);
665         handle = NULL;
666     }
667 }
668 
ft245r_display(PROGRAMMER * pgm,const char * p)669 static void ft245r_display(PROGRAMMER * pgm, const char * p) {
670     avrdude_message(MSG_INFO, "%sPin assignment  : 0..7 = DBUS0..7\n",p);/* , 8..11 = GPIO0..3\n",p);*/
671     pgm_display_generic_mask(pgm, p, SHOW_ALL_PINS);
672 }
673 
ft245r_paged_write_gen(PROGRAMMER * pgm,AVRPART * p,AVRMEM * m,unsigned int page_size,unsigned int addr,unsigned int n_bytes)674 static int ft245r_paged_write_gen(PROGRAMMER * pgm, AVRPART * p, AVRMEM * m,
675                                   unsigned int page_size, unsigned int addr,
676                                   unsigned int n_bytes) {
677     unsigned long i, pa;
678     int rc;
679 
680     for (i=0; i<n_bytes; i++, addr++) {
681         rc = avr_write_byte_default(pgm, p, m, addr, m->buf[addr]);
682         if (rc != 0) {
683             return -2;
684         }
685 
686         if (m->paged) {
687             // Can this piece of code ever be activated?? Do AVRs exist that
688             // have paged non-flash memories? -- REW
689             // XXX Untested code below.
690             /*
691              * check to see if it is time to flush the page with a page
692              * write
693              */
694 
695             if (((addr % m->page_size) == m->page_size-1) || (i == n_bytes-1)) {
696                 pa = addr - (addr % m->page_size);
697 
698                 rc = avr_write_page(pgm, p, m, pa);
699                 if (rc != 0) {
700                     return -2;
701                 }
702             }
703         }
704     }
705     return i;
706 }
707 
708 static struct ft245r_request {
709     int addr;
710     int bytes;
711     int n;
712     struct ft245r_request *next;
713 } *req_head,*req_tail,*req_pool;
714 
put_request(int addr,int bytes,int n)715 static void put_request(int addr, int bytes, int n) {
716     struct ft245r_request *p;
717     if (req_pool) {
718         p = req_pool;
719         req_pool = p->next;
720     } else {
721         p = malloc(sizeof(struct ft245r_request));
722         if (!p) {
723             avrdude_message(MSG_INFO, "can't alloc memory\n");
724             exit(1);
725         }
726     }
727     memset(p, 0, sizeof(struct ft245r_request));
728     p->addr = addr;
729     p->bytes = bytes;
730     p->n = n;
731     if (req_tail) {
732         req_tail->next = p;
733         req_tail = p;
734     } else {
735         req_head = req_tail = p;
736     }
737 }
738 
do_request(PROGRAMMER * pgm,AVRMEM * m)739 static int do_request(PROGRAMMER * pgm, AVRMEM *m) {
740     struct ft245r_request *p;
741     int addr, bytes, j, n;
742     unsigned char buf[FT245R_FRAGMENT_SIZE+1+128];
743 
744     if (!req_head) return 0;
745     p = req_head;
746     req_head = p->next;
747     if (!req_head) req_tail = req_head;
748 
749     addr = p->addr;
750     bytes = p->bytes;
751     n = p->n;
752     memset(p, 0, sizeof(struct ft245r_request));
753     p->next = req_pool;
754     req_pool = p;
755 
756     ft245r_recv(pgm, buf, bytes);
757     for (j=0; j<n; j++) {
758         m->buf[addr++] = extract_data(pgm, buf , (j * 4 + 3));
759     }
760     return 1;
761 }
762 
ft245r_paged_write_flash(PROGRAMMER * pgm,AVRPART * p,AVRMEM * m,int page_size,int addr,int n_bytes)763 static int ft245r_paged_write_flash(PROGRAMMER * pgm, AVRPART * p, AVRMEM * m,
764                                     int page_size, int addr, int n_bytes) {
765     unsigned int    i,j;
766     int addr_save,buf_pos,do_page_write,req_count;
767     unsigned char buf[FT245R_FRAGMENT_SIZE+1+128];
768 
769     req_count = 0;
770     for (i=0; i<n_bytes; ) {
771         addr_save = addr;
772         buf_pos = 0;
773         do_page_write = 0;
774         for (j=0; j< FT245R_FRAGMENT_SIZE/8/FT245R_CYCLES/4; j++) {
775             buf_pos += set_data(pgm, buf+buf_pos, (addr & 1)?0x48:0x40 );
776             buf_pos += set_data(pgm, buf+buf_pos, (addr >> 9) & 0xff );
777             buf_pos += set_data(pgm, buf+buf_pos, (addr >> 1) & 0xff );
778             buf_pos += set_data(pgm, buf+buf_pos, m->buf[addr]);
779             addr ++;
780             i++;
781             if ( (m->paged) &&
782                     (((i % m->page_size) == 0) || (i == n_bytes))) {
783                 do_page_write = 1;
784                 break;
785             }
786         }
787 #if defined(USE_INLINE_WRITE_PAGE)
788         if (do_page_write) {
789             int addr_wk = addr_save - (addr_save % m->page_size);
790             /* If this device has a "load extended address" command, issue it. */
791             if (m->op[AVR_OP_LOAD_EXT_ADDR]) {
792                 unsigned char cmd[4];
793                 OPCODE *lext = m->op[AVR_OP_LOAD_EXT_ADDR];
794 
795                 memset(cmd, 0, 4);
796                 avr_set_bits(lext, cmd);
797                 avr_set_addr(lext, cmd, addr_wk/2);
798                 buf_pos += set_data(pgm, buf+buf_pos, cmd[0]);
799                 buf_pos += set_data(pgm, buf+buf_pos, cmd[1]);
800                 buf_pos += set_data(pgm, buf+buf_pos, cmd[2]);
801                 buf_pos += set_data(pgm, buf+buf_pos, cmd[3]);
802             }
803             buf_pos += set_data(pgm, buf+buf_pos, 0x4C); /* Issue Page Write */
804             buf_pos += set_data(pgm, buf+buf_pos,(addr_wk >> 9) & 0xff);
805             buf_pos += set_data(pgm, buf+buf_pos,(addr_wk >> 1) & 0xff);
806             buf_pos += set_data(pgm, buf+buf_pos, 0);
807         }
808 #endif
809         if (i >= n_bytes) {
810             ft245r_out = SET_BITS_0(ft245r_out,pgm,PIN_AVR_SCK,0); // sck down
811             buf[buf_pos++] = ft245r_out;
812         }
813         ft245r_send(pgm, buf, buf_pos);
814         put_request(addr_save, buf_pos, 0);
815         //ft245r_sync(pgm);
816 #if 0
817         avrdude_message(MSG_INFO, "send addr 0x%04x bufsize %d [%02x %02x] page_write %d\n",
818                 addr_save,buf_pos,
819                 extract_data_out(pgm, buf , (0*4 + 3) ),
820                 extract_data_out(pgm, buf , (1*4 + 3) ),
821                 do_page_write);
822 #endif
823         req_count++;
824         if (req_count > REQ_OUTSTANDINGS)
825             do_request(pgm, m);
826         if (do_page_write) {
827 #if defined(USE_INLINE_WRITE_PAGE)
828             while (do_request(pgm, m))
829                 ;
830             usleep(m->max_write_delay);
831 #else
832             int addr_wk = addr_save - (addr_save % m->page_size);
833             int rc;
834             while (do_request(pgm, m))
835                 ;
836             rc = avr_write_page(pgm, p, m, addr_wk);
837             if (rc != 0) {
838                 return -2;
839             }
840 #endif
841             req_count = 0;
842         }
843     }
844     while (do_request(pgm, m))
845         ;
846     return i;
847 }
848 
849 
ft245r_paged_write(PROGRAMMER * pgm,AVRPART * p,AVRMEM * m,unsigned int page_size,unsigned int addr,unsigned int n_bytes)850 static int ft245r_paged_write(PROGRAMMER * pgm, AVRPART * p, AVRMEM * m,
851                               unsigned int page_size, unsigned int addr, unsigned int n_bytes) {
852     if (strcmp(m->desc, "flash") == 0) {
853         return ft245r_paged_write_flash(pgm, p, m, page_size, addr, n_bytes);
854     } else if (strcmp(m->desc, "eeprom") == 0) {
855         return ft245r_paged_write_gen(pgm, p, m, page_size, addr, n_bytes);
856     } else {
857         return -2;
858     }
859 }
860 
ft245r_paged_load_gen(PROGRAMMER * pgm,AVRPART * p,AVRMEM * m,unsigned int page_size,unsigned int addr,int n_bytes)861 static int ft245r_paged_load_gen(PROGRAMMER * pgm, AVRPART * p, AVRMEM * m,
862                                  unsigned int page_size, unsigned int addr,
863                                  int n_bytes) {
864     unsigned char    rbyte;
865     unsigned long    i;
866     int rc;
867 
868     for (i=0; i<n_bytes; i++) {
869         rc = avr_read_byte_default(pgm, p, m, i+addr, &rbyte);
870         if (rc != 0) {
871             return -2;
872         }
873         m->buf[i+addr] = rbyte;
874     }
875     return 0;
876 }
877 
ft245r_paged_load_flash(PROGRAMMER * pgm,AVRPART * p,AVRMEM * m,unsigned int page_size,unsigned int addr,unsigned int n_bytes)878 static int ft245r_paged_load_flash(PROGRAMMER * pgm, AVRPART * p, AVRMEM * m,
879                                    unsigned int page_size, unsigned int addr,
880                                    unsigned int n_bytes) {
881     unsigned long    i,j,n;
882     int addr_save,buf_pos;
883     int req_count = 0;
884     unsigned char buf[FT245R_FRAGMENT_SIZE+1];
885 
886     for (i=0; i<n_bytes; ) {
887         buf_pos = 0;
888         addr_save = addr;
889         for (j=0; j< FT245R_FRAGMENT_SIZE/8/FT245R_CYCLES/4; j++) {
890             if (i >= n_bytes) break;
891             buf_pos += set_data(pgm, buf+buf_pos, (addr & 1)?0x28:0x20 );
892             buf_pos += set_data(pgm, buf+buf_pos, (addr >> 9) & 0xff );
893             buf_pos += set_data(pgm, buf+buf_pos, (addr >> 1) & 0xff );
894             buf_pos += set_data(pgm, buf+buf_pos, 0);
895             addr ++;
896             i++;
897         }
898         if (i >= n_bytes) {
899             ft245r_out = SET_BITS_0(ft245r_out,pgm,PIN_AVR_SCK,0); // sck down
900             buf[buf_pos++] = ft245r_out;
901         }
902         n = j;
903         ft245r_send(pgm, buf, buf_pos);
904         put_request(addr_save, buf_pos, n);
905         req_count++;
906         if (req_count > REQ_OUTSTANDINGS)
907             do_request(pgm, m);
908 
909     }
910     while (do_request(pgm, m))
911         ;
912     return 0;
913 }
914 
ft245r_paged_load(PROGRAMMER * pgm,AVRPART * p,AVRMEM * m,unsigned int page_size,unsigned int addr,unsigned int n_bytes)915 static int ft245r_paged_load(PROGRAMMER * pgm, AVRPART * p, AVRMEM * m,
916                              unsigned int page_size, unsigned int addr,
917                              unsigned int n_bytes) {
918     if (strcmp(m->desc, "flash") == 0) {
919         return ft245r_paged_load_flash(pgm, p, m, page_size, addr, n_bytes);
920     } else if (strcmp(m->desc, "eeprom") == 0) {
921         return ft245r_paged_load_gen(pgm, p, m, page_size, addr, n_bytes);
922     } else {
923         return -2;
924     }
925 }
926 
ft245r_initpgm(PROGRAMMER * pgm)927 void ft245r_initpgm(PROGRAMMER * pgm) {
928     strcpy(pgm->type, "ftdi_syncbb");
929 
930     /*
931      * mandatory functions
932      */
933     pgm->initialize     = ft245r_initialize;
934     pgm->display        = ft245r_display;
935     pgm->enable         = ft245r_enable;
936     pgm->disable        = ft245r_disable;
937     pgm->program_enable = ft245r_program_enable;
938     pgm->chip_erase     = ft245r_chip_erase;
939     pgm->cmd            = ft245r_cmd;
940     pgm->open           = ft245r_open;
941     pgm->close          = ft245r_close;
942     pgm->read_byte      = avr_read_byte_default;
943     pgm->write_byte     = avr_write_byte_default;
944 
945     /*
946      * optional functions
947      */
948     pgm->paged_write = ft245r_paged_write;
949     pgm->paged_load = ft245r_paged_load;
950 
951     pgm->rdy_led        = set_led_rdy;
952     pgm->err_led        = set_led_err;
953     pgm->pgm_led        = set_led_pgm;
954     pgm->vfy_led        = set_led_vfy;
955     pgm->powerup        = ft245r_powerup;
956     pgm->powerdown      = ft245r_powerdown;
957 
958     handle = NULL;
959 }
960 
961 #endif
962 
963 const char ft245r_desc[] = "FT245R/FT232R Synchronous BitBangMode Programmer";
964