1 /*
2  * avrdude - A Downloader/Uploader for AVR device programmers
3  * Copyright (C) 2007 Dick Streefland, adapted for 5.4 by Limor Fried
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  */
18 
19 /*
20  * Driver for "usbtiny"-type programmers
21  * Please see http://www.xs4all.nl/~dicks/avr/usbtiny/
22  *        and http://www.ladyada.net/make/usbtinyisp/
23  * For example schematics and detailed documentation
24  */
25 
26 #include "ac_cfg.h"
27 
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <errno.h>
32 #include <sys/time.h>
33 #include <unistd.h>
34 
35 #include "avrdude.h"
36 #include "libavrdude.h"
37 
38 #include "usbtiny.h"
39 #include "usbdevs.h"
40 
41 #if defined(HAVE_LIBUSB)      // we use LIBUSB to talk to the board
42 #if defined(HAVE_USB_H)
43 #  include <usb.h>
44 #elif defined(HAVE_LUSB0_USB_H)
45 #  include <lusb0_usb.h>
46 #else
47 #  error "libusb needs either <usb.h> or <lusb0_usb.h>"
48 #endif
49 
50 #include "tpi.h"
51 
52 #define TPIPCR_GT_0b	0x07
53 #define TPI_STOP_BITS	0x03
54 
55 #ifdef HAVE_NETINET_IN_H
56 #  include <netinet/in.h>
57 #  define LITTLE_TO_BIG_16(x) (htons(x))
58 #else
59 // WIN32
60 #  define LITTLE_TO_BIG_16(x) ((((x) << 8) & 0xFF00) | (((x) >> 8) & 0x00FF))
61 #endif
62 
63 #ifndef HAVE_UINT_T
64 typedef	unsigned int	uint_t;
65 #endif
66 #ifndef HAVE_ULONG_T
67 typedef	unsigned long	ulong_t;
68 #endif
69 
70 extern int avr_write_byte_default ( PROGRAMMER* pgm, AVRPART* p,
71 				    AVRMEM* mem, ulong_t addr,
72 				    unsigned char data );
73 /*
74  * Private data for this programmer.
75  */
76 struct pdata
77 {
78   usb_dev_handle *usb_handle;
79   int sck_period;
80   int chunk_size;
81   int retries;
82 };
83 
84 #define PDATA(pgm) ((struct pdata *)(pgm->cookie))
85 
86 // ----------------------------------------------------------------------
87 
usbtiny_setup(PROGRAMMER * pgm)88 static void usbtiny_setup(PROGRAMMER * pgm)
89 {
90   if ((pgm->cookie = malloc(sizeof(struct pdata))) == 0) {
91     avrdude_message(MSG_INFO, "%s: usbtiny_setup(): Out of memory allocating private data\n",
92                     progname);
93     exit(1);
94   }
95   memset(pgm->cookie, 0, sizeof(struct pdata));
96 }
97 
usbtiny_teardown(PROGRAMMER * pgm)98 static void usbtiny_teardown(PROGRAMMER * pgm)
99 {
100   free(pgm->cookie);
101 }
102 
103 // Wrapper for simple usb_control_msg messages
usb_control(PROGRAMMER * pgm,unsigned int requestid,unsigned int val,unsigned int index)104 static int usb_control (PROGRAMMER * pgm,
105 			unsigned int requestid, unsigned int val, unsigned int index )
106 {
107   int nbytes;
108   nbytes = usb_control_msg( PDATA(pgm)->usb_handle,
109 			    USB_ENDPOINT_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
110 			    requestid,
111 			    val, index,           // 2 bytes each of data
112 			    NULL, 0,              // no data buffer in control messge
113 			    USB_TIMEOUT );        // default timeout
114   if(nbytes < 0){
115     avrdude_message(MSG_INFO, "\n%s: error: usbtiny_transmit: %s\n", progname, usb_strerror());
116     return -1;
117   }
118 
119   return nbytes;
120 }
121 
122 // Wrapper for simple usb_control_msg messages to receive data from programmer
usb_in(PROGRAMMER * pgm,unsigned int requestid,unsigned int val,unsigned int index,unsigned char * buffer,int buflen,int bitclk)123 static int usb_in (PROGRAMMER * pgm,
124 		   unsigned int requestid, unsigned int val, unsigned int index,
125 		   unsigned char* buffer, int buflen, int bitclk )
126 {
127   int nbytes;
128   int timeout;
129   int i;
130 
131   // calculate the amout of time we expect the process to take by
132   // figuring the bit-clock time and buffer size and adding to the standard USB timeout.
133   timeout = USB_TIMEOUT + (buflen * bitclk) / 1000;
134 
135   for (i = 0; i < 10; i++) {
136     nbytes = usb_control_msg( PDATA(pgm)->usb_handle,
137 			      USB_ENDPOINT_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
138 			      requestid,
139 			      val, index,
140 			      (char *)buffer, buflen,
141 			      timeout);
142     if (nbytes == buflen) {
143       return nbytes;
144     }
145     PDATA(pgm)->retries++;
146   }
147   avrdude_message(MSG_INFO, "\n%s: error: usbtiny_receive: %s (expected %d, got %d)\n",
148           progname, usb_strerror(), buflen, nbytes);
149   return -1;
150 }
151 
152 // Report the number of retries, and reset the counter.
check_retries(PROGRAMMER * pgm,const char * operation)153 static void check_retries (PROGRAMMER * pgm, const char* operation)
154 {
155   if (PDATA(pgm)->retries > 0 && quell_progress < 2) {
156     avrdude_message(MSG_INFO, "%s: %d retries during %s\n", progname,
157            PDATA(pgm)->retries, operation);
158   }
159   PDATA(pgm)->retries = 0;
160 }
161 
162 // Wrapper for simple usb_control_msg messages to send data to programmer
usb_out(PROGRAMMER * pgm,unsigned int requestid,unsigned int val,unsigned int index,unsigned char * buffer,int buflen,int bitclk)163 static int usb_out (PROGRAMMER * pgm,
164 		    unsigned int requestid, unsigned int val, unsigned int index,
165 		    unsigned char* buffer, int buflen, int bitclk )
166 {
167   int nbytes;
168   int timeout;
169 
170   // calculate the amout of time we expect the process to take by
171   // figuring the bit-clock time and buffer size and adding to the standard USB timeout.
172   timeout = USB_TIMEOUT + (buflen * bitclk) / 1000;
173 
174   nbytes = usb_control_msg( PDATA(pgm)->usb_handle,
175 			    USB_ENDPOINT_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
176 			    requestid,
177 			    val, index,
178 			    (char *)buffer, buflen,
179 			    timeout);
180   if (nbytes != buflen) {
181     avrdude_message(MSG_INFO, "\n%s: error: usbtiny_send: %s (expected %d, got %d)\n",
182 	    progname, usb_strerror(), buflen, nbytes);
183     return -1;
184   }
185 
186   return nbytes;
187 }
188 
189 /* Reverse the bits in a byte.  Needed since TPI uses little-endian
190    bit order (LSB first) whereas SPI uses big-endian (MSB first).*/
reverse(unsigned char b)191 static unsigned char reverse(unsigned char b) {
192   return
193     (  (b & 0x01) << 7)
194     | ((b & 0x02) << 5)
195     | ((b & 0x04) << 3)
196     | ((b & 0x08) << 1)
197     | ((b & 0x10) >> 1)
198     | ((b & 0x20) >> 3)
199     | ((b & 0x40) >> 5)
200     | ((b & 0x80) >> 7);
201 }
202 
203 /* Calculate even parity.  */
tpi_parity(unsigned char b)204 static unsigned char tpi_parity(unsigned char b)
205 {
206   unsigned char parity = 0;
207   int i;
208 
209   for (i = 0; i < 8; ++i) {
210     if (b & 1)
211       parity ^= 1;
212     b >>= 1;
213   }
214   return parity;
215 }
216 
217 /* Encode 1 start bit (0), 8 data bits, 1 parity, 2 stop bits (1)
218    inside 16 bits.  The data is padded to 16 bits by 4 leading 1s
219    (which will be ignored since they're not start bits).  This layout
220    enables a write to be followed by a read.  */
tpi_frame(unsigned char b)221 static unsigned short tpi_frame(unsigned char b) {
222   return LITTLE_TO_BIG_16(0xf000 |
223 			  (reverse(b) << 3) |
224 			  tpi_parity(b) << 2 |
225 			  TPI_STOP_BITS);
226 }
227 
228 /* Transmit a single byte encapsulated in a 32-bit transfer.  Unused
229    bits are padded with 1s.  */
usbtiny_tpi_tx(PROGRAMMER * pgm,unsigned char b0)230 static int usbtiny_tpi_tx(PROGRAMMER *pgm, unsigned char b0)
231 {
232   unsigned char res[4];
233 
234   if (usb_in(pgm, USBTINY_SPI, tpi_frame(b0), 0xffff,
235 	     res, sizeof(res), 8 * sizeof(res) * PDATA(pgm)->sck_period) < 0)
236     return -1;
237   if (verbose > 1)
238     fprintf(stderr, "CMD_TPI_TX: [0x%02x]\n", b0);
239   return 1;
240 }
241 
242 /* Transmit a two bytes encapsulated in a 32-bit transfer.  Unused
243    bits are padded with 1s.  */
usbtiny_tpi_txtx(PROGRAMMER * pgm,unsigned char b0,unsigned char b1)244 static int usbtiny_tpi_txtx(PROGRAMMER *pgm,
245 			    unsigned char b0, unsigned char b1)
246 {
247   unsigned char res[4];
248 
249   if (usb_in(pgm, USBTINY_SPI, tpi_frame(b0), tpi_frame(b1),
250 	     res, sizeof(res), 8 * sizeof(res) * PDATA(pgm)->sck_period) < 0)
251     return -1;
252   if (verbose > 1)
253     fprintf(stderr, "CMD_TPI_TX_TX: [0x%02x 0x%02x]\n", b0, b1);
254   return 1;
255 }
256 
257 /* Transmit a byte then receive a byte, all encapsulated in a 32-bit
258    transfer.  Unused bits are padded with 1s.  This code assumes that
259    the start bit of the byte being received arrives within at most 2
260    TPICLKs.  We ensure this by calling avr_tpi_program_enable() with
261    delay==TPIPCR_GT_0b.  */
usbtiny_tpi_txrx(PROGRAMMER * pgm,unsigned char b0)262 static int usbtiny_tpi_txrx(PROGRAMMER *pgm, unsigned char b0)
263 {
264   unsigned char res[4], r;
265   short w;
266 
267   if (usb_in(pgm, USBTINY_SPI, tpi_frame(b0), 0xffff,
268 	     res, sizeof(res), 8 * sizeof(res) * PDATA(pgm)->sck_period) < 0)
269     return -1;
270 
271   w = (res[2] << 8) | res[3];
272   /* Look for start bit (there shoule be no more than two 1 bits): */
273   while (w < 0)
274     w <<= 1;
275   /* Now that we found the start bit, the top 9 bits contain the start
276      bit and the 8 data bits, but the latter in reverse order.  */
277   r = reverse(w >> 7);
278   if (tpi_parity(r) != ((w >> 6) & 1)) {
279     fprintf(stderr, "%s: parity bit is wrong\n", __func__);
280     return -1;
281   }
282   if (((w >> 4) & 0x3) != TPI_STOP_BITS) {
283     fprintf(stderr, "%s: stop bits not received correctly\n", __func__);
284     return -1;
285   }
286 
287   if (verbose > 1)
288     fprintf(stderr, "CMD_TPI_TX_RX: [0x%02x -> 0x%02x]\n", b0, r);
289   return r;
290 }
291 
292 // Sometimes we just need to know the SPI command for the part to perform
293 // a function. Here we wrap this request for an operation so that we
294 // can just specify the part and operation and it'll do the right stuff
295 // to get the information from AvrDude and send to the USBtiny
usbtiny_avr_op(PROGRAMMER * pgm,AVRPART * p,int op,unsigned char * res)296 static int usbtiny_avr_op (PROGRAMMER * pgm, AVRPART * p,
297 			   int op,
298 			   unsigned char *res)
299 {
300   unsigned char	cmd[4];
301 
302   if (p->op[op] == NULL) {
303     avrdude_message(MSG_INFO, "Operation %d not defined for this chip!\n", op );
304     return -1;
305   }
306   memset(cmd, 0, sizeof(cmd));
307   avr_set_bits(p->op[op], cmd);
308 
309   return pgm->cmd(pgm, cmd, res);
310 }
311 
312 // ----------------------------------------------------------------------
313 
314 /* Find a device with the correct VID/PID match for USBtiny */
315 
usbtiny_open(PROGRAMMER * pgm,char * name)316 static	int	usbtiny_open(PROGRAMMER* pgm, char* name)
317 {
318   struct usb_bus      *bus;
319   struct usb_device   *dev = 0;
320   char *bus_name = NULL;
321   char *dev_name = NULL;
322   int vid, pid;
323 
324   // if no -P was given or '-P usb' was given
325   if(strcmp(name, "usb") == 0)
326     name = NULL;
327   else {
328     // calculate bus and device names from -P option
329     const size_t usb_len = strlen("usb");
330     if(strncmp(name, "usb", usb_len) == 0 && ':' == name[usb_len]) {
331         bus_name = name + usb_len + 1;
332         dev_name = strchr(bus_name, ':');
333         if(NULL != dev_name)
334           *dev_name++ = '\0';
335     }
336   }
337 
338   usb_init();                    // initialize the libusb system
339   usb_find_busses();             // have libusb scan all the usb busses available
340   usb_find_devices();            // have libusb scan all the usb devices available
341 
342   PDATA(pgm)->usb_handle = NULL;
343 
344   if (pgm->usbvid)
345     vid = pgm->usbvid;
346   else
347     vid = USBTINY_VENDOR_DEFAULT;
348 
349   LNODEID usbpid = lfirst(pgm->usbpid);
350   if (usbpid) {
351     pid = *(int *)(ldata(usbpid));
352     if (lnext(usbpid))
353       avrdude_message(MSG_INFO, "%s: Warning: using PID 0x%04x, ignoring remaining PIDs in list\n",
354                       progname, pid);
355   } else {
356     pid = USBTINY_PRODUCT_DEFAULT;
357   }
358 
359 
360   // now we iterate through all the busses and devices
361   for ( bus = usb_busses; bus; bus = bus->next ) {
362     for	( dev = bus->devices; dev; dev = dev->next ) {
363       if (dev->descriptor.idVendor == vid
364 	  && dev->descriptor.idProduct == pid ) {   // found match?
365     avrdude_message(MSG_NOTICE, "%s: usbdev_open(): Found USBtinyISP, bus:device: %s:%s\n",
366                       progname, bus->dirname, dev->filename);
367     // if -P was given, match device by device name and bus name
368     if(name != NULL &&
369       (NULL == dev_name ||
370        strcmp(bus->dirname, bus_name) ||
371        strcmp(dev->filename, dev_name)))
372       continue;
373 	PDATA(pgm)->usb_handle = usb_open(dev);           // attempt to connect to device
374 
375 	// wrong permissions or something?
376 	if (!PDATA(pgm)->usb_handle) {
377 	  avrdude_message(MSG_INFO, "%s: Warning: cannot open USB device: %s\n",
378 		  progname, usb_strerror());
379 	  continue;
380 	}
381       }
382     }
383   }
384 
385   if(NULL != name && NULL == dev_name) {
386     avrdude_message(MSG_INFO, "%s: Error: Invalid -P value: '%s'\n", progname, name);
387     avrdude_message(MSG_INFO, "%sUse -P usb:bus:device\n", progbuf);
388     return -1;
389   }
390   if (!PDATA(pgm)->usb_handle) {
391     avrdude_message(MSG_INFO, "%s: Error: Could not find USBtiny device (0x%x/0x%x)\n",
392 	     progname, vid, pid );
393     return -1;
394   }
395 
396   return 0;                  // If we got here, we must have found a good USB device
397 }
398 
399 /* Clean up the handle for the usbtiny */
usbtiny_close(PROGRAMMER * pgm)400 static	void usbtiny_close ( PROGRAMMER* pgm )
401 {
402   if (! PDATA(pgm)->usb_handle) {
403     return;                // not a valid handle, bail!
404   }
405   usb_close(PDATA(pgm)->usb_handle);   // ask libusb to clean up
406   PDATA(pgm)->usb_handle = NULL;
407 }
408 
409 /* A simple calculator function determines the maximum size of data we can
410    shove through a USB connection without getting errors */
usbtiny_set_chunk_size(PROGRAMMER * pgm,int period)411 static void usbtiny_set_chunk_size (PROGRAMMER * pgm, int period)
412 {
413   PDATA(pgm)->chunk_size = CHUNK_SIZE;       // start with the maximum (default)
414   while	(PDATA(pgm)->chunk_size > 8 && period > 16) {
415     // Reduce the chunk size for a slow SCK to reduce
416     // the maximum time of a single USB transfer.
417     PDATA(pgm)->chunk_size >>= 1;
418     period >>= 1;
419   }
420 }
421 
422 /* Given a SCK bit-clock speed (in useconds) we verify its an OK speed and tell the
423    USBtiny to update itself to the new frequency */
usbtiny_set_sck_period(PROGRAMMER * pgm,double v)424 static int usbtiny_set_sck_period (PROGRAMMER *pgm, double v)
425 {
426   PDATA(pgm)->sck_period = (int)(v * 1e6 + 0.5);   // convert from us to 'int', the 0.5 is for rounding up
427 
428   // Make sure its not 0, as that will confuse the usbtiny
429   if (PDATA(pgm)->sck_period < SCK_MIN)
430     PDATA(pgm)->sck_period = SCK_MIN;
431 
432   // We can't go slower, due to the byte-size of the clock variable
433   if  (PDATA(pgm)->sck_period > SCK_MAX)
434     PDATA(pgm)->sck_period = SCK_MAX;
435 
436   avrdude_message(MSG_NOTICE, "%s: Setting SCK period to %d usec\n", progname,
437 	    PDATA(pgm)->sck_period );
438 
439   // send the command to the usbtiny device.
440   // MEME: for at90's fix resetstate?
441   if (usb_control(pgm, USBTINY_POWERUP, PDATA(pgm)->sck_period, RESET_LOW) < 0)
442     return -1;
443 
444   // with the new speed, we'll have to update how much data we send per usb transfer
445   usbtiny_set_chunk_size(pgm, PDATA(pgm)->sck_period);
446   return 0;
447 }
448 
449 
usbtiny_initialize(PROGRAMMER * pgm,AVRPART * p)450 static int usbtiny_initialize (PROGRAMMER *pgm, AVRPART *p )
451 {
452   unsigned char res[4];        // store the response from usbtinyisp
453   int tries;
454 
455   // Check for bit-clock and tell the usbtiny to adjust itself
456   if (pgm->bitclock > 0.0) {
457     // -B option specified: convert to valid range for sck_period
458     usbtiny_set_sck_period(pgm, pgm->bitclock);
459   } else {
460     // -B option not specified: use default
461     PDATA(pgm)->sck_period = SCK_DEFAULT;
462     avrdude_message(MSG_NOTICE, "%s: Using SCK period of %d usec\n",
463 	      progname, PDATA(pgm)->sck_period );
464     if (usb_control(pgm,  USBTINY_POWERUP,
465 		    PDATA(pgm)->sck_period, RESET_LOW ) < 0)
466       return -1;
467     usbtiny_set_chunk_size(pgm, PDATA(pgm)->sck_period);
468   }
469 
470   // Let the device wake up.
471   usleep(50000);
472 
473   if (p->flags & AVRPART_HAS_TPI) {
474     /* Since there is a single TPIDATA line, MOSI and MISO must be
475        linked together through a 1kOhm resistor.  Verify that
476        everything we send on MOSI gets mirrored back on MISO.  */
477     if (verbose >= 2)
478       fprintf(stderr, "doing MOSI-MISO link check\n");
479 
480     memset(res, 0xaa, sizeof(res));
481     if (usb_in(pgm, USBTINY_SPI, LITTLE_TO_BIG_16(0x1234), LITTLE_TO_BIG_16(0x5678),
482 	       res, 4, 32 * PDATA(pgm)->sck_period) < 0) {
483       fprintf(stderr, "usb_in() failed\n");
484       return -1;
485     }
486     if (res[0] != 0x12 || res[1] != 0x34 || res[2] != 0x56 || res[3] != 0x78) {
487       fprintf(stderr,
488 	      "MOSI->MISO check failed (got 0x%02x 0x%02x 0x%02x 0x%02x)\n"
489 	      "\tPlease verify that MISO is connected directly to TPIDATA and\n"
490 	      "\tMOSI is connected to TPIDATA through a 1kOhm resistor.\n",
491 	      res[0], res[1], res[2], res[3]);
492       return -1;
493     }
494 
495     /* keep TPIDATA high for >= 16 clock cycles: */
496     if (usb_in(pgm, USBTINY_SPI, 0xffff, 0xffff, res, 4,
497 	       32 * PDATA(pgm)->sck_period) < 0)
498     {
499       fprintf(stderr, "Unable to switch chip into TPI mode\n");
500       return -1;
501     }
502   }
503 
504   for (tries = 0; tries < 4; ++tries) {
505     if (pgm->program_enable(pgm, p) >= 0)
506       break;
507     // no response, RESET and try again
508     if (usb_control(pgm, USBTINY_POWERUP,
509 		    PDATA(pgm)->sck_period, RESET_HIGH) < 0 ||
510 	usb_control(pgm, USBTINY_POWERUP,
511 		    PDATA(pgm)->sck_period, RESET_LOW) < 0)
512       return -1;
513     usleep(50000);
514   }
515   if (tries >= 4)
516     return -1;
517   return 0;
518 }
519 
520 /* Tell the USBtiny to release the output pins, etc */
usbtiny_powerdown(PROGRAMMER * pgm)521 static void usbtiny_powerdown(PROGRAMMER * pgm)
522 {
523   if (!PDATA(pgm)->usb_handle) {
524     return;                 // wasn't connected in the first place
525   }
526   usb_control(pgm, USBTINY_POWERDOWN, 0, 0);      // Send USB control command to device
527 }
528 
529 /* Send a 4-byte SPI command to the USBtinyISP for execution
530    This procedure is used by higher-level Avrdude procedures */
usbtiny_cmd(PROGRAMMER * pgm,const unsigned char * cmd,unsigned char * res)531 static int usbtiny_cmd(PROGRAMMER * pgm, const unsigned char *cmd, unsigned char *res)
532 {
533   int nbytes;
534 
535   // Make sure its empty so we don't read previous calls if it fails
536   memset(res, '\0', 4 );
537 
538   nbytes = usb_in( pgm, USBTINY_SPI,
539 		   (cmd[1] << 8) | cmd[0],  // convert to 16-bit words
540 		   (cmd[3] << 8) | cmd[2],  //  "
541 			res, 4, 8 * PDATA(pgm)->sck_period );
542   if (nbytes < 0)
543     return -1;
544   check_retries(pgm, "SPI command");
545   // print out the data we sent and received
546   avrdude_message(MSG_NOTICE2, "CMD: [%02x %02x %02x %02x] [%02x %02x %02x %02x]\n",
547 	    cmd[0], cmd[1], cmd[2], cmd[3],
548 	    res[0], res[1], res[2], res[3] );
549   return ((nbytes == 4) &&      // should have read 4 bytes
550 	  res[2] == cmd[1]);              // AVR's do a delayed-echo thing
551 }
552 
usbtiny_cmd_tpi(PROGRAMMER * pgm,const unsigned char * cmd,int cmd_len,unsigned char * res,int res_len)553 int usbtiny_cmd_tpi(PROGRAMMER * pgm, const unsigned char *cmd,
554 			int cmd_len, unsigned char *res, int res_len)
555 {
556   unsigned char b0, b1;
557   int tx, rx, r;
558 
559   /* Transmits command two bytes at the time until we're down to 0 or
560      1 command byte.  Then we're either done or we transmit the final
561      byte optionally followed by reading 1 byte.  With the current TPI
562      protocol, we never receive more than one byte.  */
563   for (tx = rx = 0; tx < cmd_len; ) {
564     b0 = cmd[tx++];
565     if (tx < cmd_len) {
566       b1 = cmd[tx++];
567       if (usbtiny_tpi_txtx(pgm, b0, b1) < 0)
568 	return -1;
569     } else {
570       if (res_len > 0) {
571 	if ((r = usbtiny_tpi_txrx(pgm, b0)) < 0)
572 	  return -1;
573 	res[rx++] = r;
574       } else {
575 	if (usbtiny_tpi_tx(pgm, b0) < 0)
576 	  return -1;
577       }
578     }
579   }
580 
581   if (rx < res_len) {
582     fprintf(stderr, "%s: unexpected cmd_len=%d/res_len=%d\n",
583 	    __func__, cmd_len, res_len);
584     return -1;
585   }
586   return 0;
587 }
588 
589 /* Send the chip-erase command */
usbtiny_chip_erase(PROGRAMMER * pgm,AVRPART * p)590 static int usbtiny_chip_erase(PROGRAMMER * pgm, AVRPART * p)
591 {
592   unsigned char res[4];
593 
594   if (p->flags & AVRPART_HAS_TPI)
595     return avr_tpi_chip_erase(pgm, p);
596 
597   if (p->op[AVR_OP_CHIP_ERASE] == NULL) {
598     avrdude_message(MSG_INFO, "Chip erase instruction not defined for part \"%s\"\n",
599             p->desc);
600     return -1;
601   }
602 
603   // get the command for erasing this chip and transmit to avrdude
604   if (! usbtiny_avr_op( pgm, p, AVR_OP_CHIP_ERASE, res )) {
605     return -1;
606   }
607   usleep( p->chip_erase_delay );
608 
609   // prepare for further instruction
610   pgm->initialize(pgm, p);
611 
612   return 0;
613 }
614 
615 // These are required functions but don't actually do anything
usbtiny_enable(PROGRAMMER * pgm)616 static	void	usbtiny_enable ( PROGRAMMER* pgm ) {}
617 
usbtiny_disable(PROGRAMMER * pgm)618 static void usbtiny_disable ( PROGRAMMER* pgm ) {}
619 
620 
621 /* To speed up programming and reading, we do a 'chunked' read.
622  *  We request just the data itself and the USBtiny uses the SPI function
623  *  given to read in the data. Much faster than sending a 4-byte SPI request
624  *  per byte
625 */
usbtiny_paged_load(PROGRAMMER * pgm,AVRPART * p,AVRMEM * m,unsigned int page_size,unsigned int addr,unsigned int n_bytes)626 static int usbtiny_paged_load (PROGRAMMER * pgm, AVRPART * p, AVRMEM* m,
627                                unsigned int page_size,
628                                unsigned int addr, unsigned int n_bytes)
629 {
630   unsigned int maxaddr = addr + n_bytes;
631   int chunk;
632   int function;
633 
634 
635   // First determine what we're doing
636   if (strcmp( m->desc, "flash" ) == 0) {
637     function = USBTINY_FLASH_READ;
638   } else {
639     function = USBTINY_EEPROM_READ;
640   }
641 
642   for (; addr < maxaddr; addr += chunk) {
643     chunk = PDATA(pgm)->chunk_size;         // start with the maximum chunk size possible
644     if (addr + chunk > maxaddr) {
645         chunk = maxaddr - addr;
646     }
647 
648     // Send the chunk of data to the USBtiny with the function we want
649     // to perform
650     if (usb_in(pgm,
651 	       function,          // EEPROM or flash
652 	       0,                 // delay between SPI commands
653 	       addr,              // address in memory
654 	       m->buf + addr,     // pointer to where we store data
655 	       chunk,             // number of bytes
656 	       32 * PDATA(pgm)->sck_period)  // each byte gets turned into a 4-byte SPI cmd
657 	< 0) {
658                               // usb_in() multiplies this per byte.
659       return -1;
660     }
661   }
662 
663   check_retries(pgm, "read");
664   return n_bytes;
665 }
666 
667 /* To speed up programming and reading, we do a 'chunked' write.
668  *  We send just the data itself and the USBtiny uses the SPI function
669  *  given to write the data. Much faster than sending a 4-byte SPI request
670  *  per byte.
671 */
usbtiny_paged_write(PROGRAMMER * pgm,AVRPART * p,AVRMEM * m,unsigned int page_size,unsigned int addr,unsigned int n_bytes)672 static int usbtiny_paged_write(PROGRAMMER * pgm, AVRPART * p, AVRMEM * m,
673                                unsigned int page_size,
674                                unsigned int addr, unsigned int n_bytes)
675 {
676   unsigned int maxaddr = addr + n_bytes;
677   int chunk;        // Size of data to write at once
678   int next;
679   int function;     // which SPI command to use
680   int delay;        // delay required between SPI commands
681 
682   // First determine what we're doing
683   if (strcmp( m->desc, "flash" ) == 0) {
684     function = USBTINY_FLASH_WRITE;
685   } else {
686     function = USBTINY_EEPROM_WRITE;
687   }
688 
689   delay = 0;
690   if (! m->paged) {
691     unsigned int poll_value;
692     // Does this chip not support paged writes?
693     poll_value = (m->readback[1] << 8) | m->readback[0];
694     if (usb_control(pgm, USBTINY_POLL_BYTES, poll_value, 0 ) < 0)
695       return -1;
696     delay = m->max_write_delay;
697   }
698 
699   for (; addr < maxaddr; addr += chunk) {
700     // start with the max chunk size
701     chunk = PDATA(pgm)->chunk_size;
702     if (addr + chunk > maxaddr) {
703         chunk = maxaddr - addr;
704     }
705 
706     // we can only write a page at a time anyways
707     if (m->paged && chunk > page_size)
708       chunk = page_size;
709 
710     if (usb_out(pgm,
711 		function,       // Flash or EEPROM
712 		delay,          // How much to wait between each byte
713 		addr,           // Address in memory
714 		m->buf + addr,  // Pointer to data
715 		chunk,          // Number of bytes to write
716 		32 * PDATA(pgm)->sck_period + delay  // each byte gets turned into a
717 	                             // 4-byte SPI cmd  usb_out() multiplies
718 	                             // this per byte. Then add the cmd-delay
719 		) < 0) {
720       return -1;
721     }
722 
723     next = addr + chunk;       // Calculate what address we're at now
724     if (m->paged
725 	&& ((next % page_size) == 0 || next == maxaddr) ) {
726       // If we're at a page boundary, send the SPI command to flush it.
727       avr_write_page(pgm, p, m, (unsigned long) addr);
728     }
729   }
730   return n_bytes;
731 }
732 
usbtiny_program_enable(PROGRAMMER * pgm,AVRPART * p)733 static int usbtiny_program_enable(PROGRAMMER *pgm, AVRPART *p)
734 {
735   unsigned char buf[4];
736 
737   if (p->flags & AVRPART_HAS_TPI)
738     return avr_tpi_program_enable(pgm, p, TPIPCR_GT_0b);
739   else
740     return usbtiny_avr_op(pgm, p, AVR_OP_PGM_ENABLE, buf);
741 }
742 
usbtiny_initpgm(PROGRAMMER * pgm)743 void usbtiny_initpgm ( PROGRAMMER* pgm )
744 {
745   strcpy(pgm->type, "USBtiny");
746 
747   /* Mandatory Functions */
748   pgm->initialize	= usbtiny_initialize;
749   pgm->enable	        = usbtiny_enable;
750   pgm->disable	        = usbtiny_disable;
751   pgm->program_enable	= usbtiny_program_enable;
752   pgm->chip_erase	= usbtiny_chip_erase;
753   pgm->cmd		= usbtiny_cmd;
754   pgm->cmd_tpi		= usbtiny_cmd_tpi;
755   pgm->open		= usbtiny_open;
756   pgm->close		= usbtiny_close;
757   pgm->read_byte        = avr_read_byte_default;
758   pgm->write_byte       = avr_write_byte_default;
759 
760   /* Optional Functions */
761   pgm->powerup	        = NULL;
762   pgm->powerdown	= usbtiny_powerdown;
763   pgm->paged_load	= usbtiny_paged_load;
764   pgm->paged_write	= usbtiny_paged_write;
765   pgm->set_sck_period	= usbtiny_set_sck_period;
766   pgm->setup            = usbtiny_setup;
767   pgm->teardown         = usbtiny_teardown;
768 }
769 
770 #else  /* !HAVE_LIBUSB */
771 
772 // Give a proper error if we were not compiled with libusb
773 
usbtiny_nousb_open(struct programmer_t * pgm,char * name)774 static int usbtiny_nousb_open(struct programmer_t *pgm, char * name)
775 {
776   avrdude_message(MSG_INFO, "%s: error: no usb support. Please compile again with libusb installed.\n",
777 	  progname);
778 
779   return -1;
780 }
781 
usbtiny_initpgm(PROGRAMMER * pgm)782 void usbtiny_initpgm(PROGRAMMER * pgm)
783 {
784   strcpy(pgm->type, "usbtiny");
785 
786   pgm->open = usbtiny_nousb_open;
787 }
788 
789 #endif /* HAVE_LIBUSB */
790 
791 const char usbtiny_desc[] = "Driver for \"usbtiny\"-type programmers";
792 
793