libftdi: (tomj) first shot at doxygen documentation
[libftdi] / src / ftdi.c
1 /***************************************************************************
2                           ftdi.c  -  description
3                              -------------------
4     begin                : Fri Apr 4 2003
5     copyright            : (C) 2003 by Intra2net AG
6     email                : opensource@intra2net.com
7  ***************************************************************************/
8
9 /***************************************************************************
10  *                                                                         *
11  *   This program is free software; you can redistribute it and/or modify  *
12  *   it under the terms of the GNU Lesser General Public License           *
13  *   version 2.1 as published by the Free Software Foundation;             *
14  *                                                                         *
15  ***************************************************************************/
16
17 #include <usb.h>
18 #include <string.h>
19 #include <errno.h>
20
21 #include "ftdi.h"
22
23 #define ftdi_error_return(code, str) do {  \
24         ftdi->error_str = str;             \
25         return code;                       \
26    } while(0);
27
28
29 /**
30     Initializes a ftdi_context.
31
32     \param ftdi pointer to ftdi_context
33
34     \retval  0: all fine
35     \retval -1: couldn't allocate read buffer
36
37     \remark This should be called before all functions
38 */
39 int ftdi_init(struct ftdi_context *ftdi)
40 {
41     ftdi->usb_dev = NULL;
42     ftdi->usb_read_timeout = 5000;
43     ftdi->usb_write_timeout = 5000;
44
45     ftdi->type = TYPE_BM;    /* chip type */
46     ftdi->baudrate = -1;
47     ftdi->bitbang_enabled = 0;
48
49     ftdi->readbuffer = NULL;
50     ftdi->readbuffer_offset = 0;
51     ftdi->readbuffer_remaining = 0;
52     ftdi->writebuffer_chunksize = 4096;
53
54     ftdi->interface = 0;
55     ftdi->index = 0;
56     ftdi->in_ep = 0x02;
57     ftdi->out_ep = 0x81;
58     ftdi->bitbang_mode = 1; /* 1: Normal bitbang mode, 2: SPI bitbang mode */
59
60     ftdi->error_str = NULL;
61
62     /* All fine. Now allocate the readbuffer */
63     return ftdi_read_data_set_chunksize(ftdi, 4096);
64 }
65
66 /**
67     Open selected channels on a chip, otherwise use first channel.
68
69     \param ftdi pointer to ftdi_context
70     \param interface Interface to use for FT2232C chips.
71
72     \retval  0: all fine
73     \retval -1: unknown interface
74 */
75 int ftdi_set_interface(struct ftdi_context *ftdi, enum ftdi_interface interface)
76 {
77     switch (interface) {
78     case INTERFACE_ANY:
79     case INTERFACE_A:
80         /* ftdi_usb_open_desc cares to set the right index, depending on the found chip */
81         break;
82     case INTERFACE_B:
83         ftdi->interface = 1;
84         ftdi->index     = INTERFACE_B;
85         ftdi->in_ep     = 0x04;
86         ftdi->out_ep    = 0x83;
87         break;
88     default:
89         ftdi_error_return(-1, "Unknown interface");
90     }
91     return 0;
92 }
93
94 /**
95     Deinitializes a ftdi_context.
96
97     \param ftdi pointer to ftdi_context
98 */
99 void ftdi_deinit(struct ftdi_context *ftdi)
100 {
101     if (ftdi->readbuffer != NULL) {
102         free(ftdi->readbuffer);
103         ftdi->readbuffer = NULL;
104     }
105 }
106
107 /**
108     Use an already open libusb device.
109
110     \param ftdi pointer to ftdi_context
111     \param usb libusb usb_dev_handle to use
112 */
113 void ftdi_set_usbdev (struct ftdi_context *ftdi, usb_dev_handle *usb)
114 {
115     ftdi->usb_dev = usb;
116 }
117
118
119 /**
120     Finds all ftdi devices on the usb bus. Creates a new ftdi_device_list which
121     needs to be deallocated by ftdi_list_free() after use.
122
123     \param ftdi pointer to ftdi_context
124     \param devlist Pointer where to store list of found devices
125     \param vendor Vendor ID to search for
126     \param product Product ID to search for
127
128     \retval >0: number of devices found
129     \retval -1: usb_find_busses() failed
130     \retval -2: usb_find_devices() failed
131     \retval -3: out of memory
132 */
133 int ftdi_usb_find_all(struct ftdi_context *ftdi, struct ftdi_device_list **devlist, int vendor, int product)
134 {
135     struct ftdi_device_list **curdev;
136     struct usb_bus *bus;
137     struct usb_device *dev;
138     int count = 0;
139
140     usb_init();
141     if (usb_find_busses() < 0)
142         ftdi_error_return(-1, "usb_find_busses() failed");
143     if (usb_find_devices() < 0)
144         ftdi_error_return(-2, "usb_find_devices() failed");
145
146     curdev = devlist;
147     for (bus = usb_busses; bus; bus = bus->next) {
148         for (dev = bus->devices; dev; dev = dev->next) {
149             if (dev->descriptor.idVendor == vendor
150                     && dev->descriptor.idProduct == product)
151             {
152                 *curdev = (struct ftdi_device_list*)malloc(sizeof(struct ftdi_device_list));
153                 if (!*curdev)
154                     ftdi_error_return(-3, "out of memory");
155
156                 (*curdev)->next = NULL;
157                 (*curdev)->dev = dev;
158
159                 curdev = &(*curdev)->next;
160                 count++;
161             }
162         }
163     }
164
165     return count;
166 }
167
168 /**
169     Frees a usb device list.
170
171     \param devlist USB device list created by ftdi_usb_find_all()
172 */
173 void ftdi_list_free(struct ftdi_device_list **devlist)
174 {
175     struct ftdi_device_list **curdev;
176     for (; *devlist == NULL; devlist = curdev) {
177         curdev = &(*devlist)->next;
178         free(*devlist);
179     }
180
181     devlist = NULL;
182 }
183
184 /**
185     Opens a ftdi device given by a usb_device.
186
187     \param ftdi pointer to ftdi_context
188     \param dev libusb usb_dev to use
189
190     \retval  0: all fine
191     \retval -4: unable to open device
192     \retval -5: unable to claim device
193     \retval -6: reset failed
194     \retval -7: set baudrate failed
195 */
196 int ftdi_usb_open_dev(struct ftdi_context *ftdi, struct usb_device *dev)
197 {
198     int detach_errno = 0;
199     if (!(ftdi->usb_dev = usb_open(dev)))
200         ftdi_error_return(-4, "usb_open() failed");
201
202 #ifdef LIBUSB_HAS_GET_DRIVER_NP
203     // Try to detach ftdi_sio kernel module
204     // Returns ENODATA if driver is not loaded
205     if (usb_detach_kernel_driver_np(ftdi->usb_dev, ftdi->interface) != 0 && errno != ENODATA)
206         detach_errno = errno;
207 #endif
208
209     if (usb_claim_interface(ftdi->usb_dev, ftdi->interface) != 0) {
210         usb_close (ftdi->usb_dev);
211         if (detach_errno == EPERM) {
212             ftdi_error_return(-8, "inappropriate permissions on device!");
213         } else {
214             ftdi_error_return(-5, "unable to claim usb device. Make sure ftdi_sio is unloaded!");
215         }
216     }
217
218     if (ftdi_usb_reset (ftdi) != 0) {
219         usb_close (ftdi->usb_dev);
220         ftdi_error_return(-6, "ftdi_usb_reset failed");
221     }
222
223     if (ftdi_set_baudrate (ftdi, 9600) != 0) {
224         usb_close (ftdi->usb_dev);
225         ftdi_error_return(-7, "set baudrate failed");
226     }
227
228     // Try to guess chip type
229     // Bug in the BM type chips: bcdDevice is 0x200 for serial == 0
230     if (dev->descriptor.bcdDevice == 0x400 || (dev->descriptor.bcdDevice == 0x200
231             && dev->descriptor.iSerialNumber == 0))
232         ftdi->type = TYPE_BM;
233     else if (dev->descriptor.bcdDevice == 0x200)
234         ftdi->type = TYPE_AM;
235     else if (dev->descriptor.bcdDevice == 0x500) {
236         ftdi->type = TYPE_2232C;
237         if (!ftdi->index)
238             ftdi->index = INTERFACE_A;
239     }
240
241     ftdi_error_return(0, "all fine");
242 }
243
244 /**
245     Opens the first device with a given vendor and product ids.
246
247     \param ftdi pointer to ftdi_context
248     \param vendor Vendor ID
249     \param product Product ID
250
251     \retval \see ftdi_usb_open_desc()
252 */
253 int ftdi_usb_open(struct ftdi_context *ftdi, int vendor, int product)
254 {
255     return ftdi_usb_open_desc(ftdi, vendor, product, NULL, NULL);
256 }
257
258 /**
259     Opens the first device with a given, vendor id, product id,
260     description and serial.
261
262     \param ftdi pointer to ftdi_context
263     \param vendor Vendor ID
264     \param product Product ID
265     \param description Description to search for. Use NULL if not needed.
266     \param serial Serial to search for. Use NULL if not needed.
267
268     \retval  0: all fine
269     \retval -1: usb_find_busses() failed
270     \retval -2: usb_find_devices() failed
271     \retval -3: usb device not found
272     \retval -4: unable to open device
273     \retval -5: unable to claim device
274     \retval -6: reset failed
275     \retval -7: set baudrate failed
276     \retval -8: get product description failed
277     \retval -9: get serial number failed
278     \retval -10: unable to close device
279 */
280 int ftdi_usb_open_desc(struct ftdi_context *ftdi, int vendor, int product,
281                        const char* description, const char* serial)
282 {
283     struct usb_bus *bus;
284     struct usb_device *dev;
285     char string[256];
286
287     usb_init();
288
289     if (usb_find_busses() < 0)
290         ftdi_error_return(-1, "usb_find_busses() failed");
291     if (usb_find_devices() < 0)
292         ftdi_error_return(-2, "usb_find_devices() failed");
293
294     for (bus = usb_busses; bus; bus = bus->next) {
295         for (dev = bus->devices; dev; dev = dev->next) {
296             if (dev->descriptor.idVendor == vendor
297                     && dev->descriptor.idProduct == product) {
298                 if (!(ftdi->usb_dev = usb_open(dev)))
299                     ftdi_error_return(-4, "usb_open() failed");
300
301                 if (description != NULL) {
302                     if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iProduct, string, sizeof(string)) <= 0) {
303                         usb_close (ftdi->usb_dev);
304                         ftdi_error_return(-8, "unable to fetch product description");
305                     }
306                     if (strncmp(string, description, sizeof(string)) != 0) {
307                         if (usb_close (ftdi->usb_dev) != 0)
308                             ftdi_error_return(-10, "unable to close device");
309                         continue;
310                     }
311                 }
312                 if (serial != NULL) {
313                     if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iSerialNumber, string, sizeof(string)) <= 0) {
314                         usb_close (ftdi->usb_dev);
315                         ftdi_error_return(-9, "unable to fetch serial number");
316                     }
317                     if (strncmp(string, serial, sizeof(string)) != 0) {
318                         if (usb_close (ftdi->usb_dev) != 0)
319                             ftdi_error_return(-10, "unable to close device");
320                         continue;
321                     }
322                 }
323
324                 if (usb_close (ftdi->usb_dev) != 0)
325                     ftdi_error_return(-10, "unable to close device");
326
327                 return ftdi_usb_open_dev(ftdi, dev);
328             }
329         }
330     }
331
332     // device not found
333     ftdi_error_return(-3, "device not found");
334 }
335
336 /**
337     Resets the ftdi device.
338
339     \param ftdi pointer to ftdi_context
340
341     \retval  0: all fine
342     \retval -1: FTDI reset failed
343 */
344 int ftdi_usb_reset(struct ftdi_context *ftdi)
345 {
346     if (usb_control_msg(ftdi->usb_dev, 0x40, 0, 0, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
347         ftdi_error_return(-1,"FTDI reset failed");
348
349     // Invalidate data in the readbuffer
350     ftdi->readbuffer_offset = 0;
351     ftdi->readbuffer_remaining = 0;
352
353     return 0;
354 }
355
356 /**
357     Clears the buffers on the chip.
358
359     \param ftdi pointer to ftdi_context
360
361     \retval  0: all fine
362     \retval -1: write buffer purge failed
363     \retval -2: read buffer purge failed
364 */
365 int ftdi_usb_purge_buffers(struct ftdi_context *ftdi)
366 {
367     if (usb_control_msg(ftdi->usb_dev, 0x40, 0, 1, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
368         ftdi_error_return(-1, "FTDI purge of RX buffer failed");
369
370     // Invalidate data in the readbuffer
371     ftdi->readbuffer_offset = 0;
372     ftdi->readbuffer_remaining = 0;
373
374     if (usb_control_msg(ftdi->usb_dev, 0x40, 0, 2, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
375         ftdi_error_return(-2, "FTDI purge of TX buffer failed");
376
377     return 0;
378 }
379
380 /**
381     Closes the ftdi device. Call ftdi_deinit() if you're cleaning up.
382
383     \param ftdi pointer to ftdi_context
384
385     \retval  0: all fine
386     \retval -1: usb_release failed
387     \retval -2: usb_close failed
388 */
389 int ftdi_usb_close(struct ftdi_context *ftdi)
390 {
391     int rtn = 0;
392
393     if (usb_release_interface(ftdi->usb_dev, ftdi->interface) != 0)
394         rtn = -1;
395
396     if (usb_close (ftdi->usb_dev) != 0)
397         rtn = -2;
398
399     return rtn;
400 }
401
402 /*
403     ftdi_convert_baudrate returns nearest supported baud rate to that requested.
404     Function is only used internally
405 */
406 static int ftdi_convert_baudrate(int baudrate, struct ftdi_context *ftdi,
407                                  unsigned short *value, unsigned short *index)
408 {
409     static const char am_adjust_up[8] = {0, 0, 0, 1, 0, 3, 2, 1};
410     static const char am_adjust_dn[8] = {0, 0, 0, 1, 0, 1, 2, 3};
411     static const char frac_code[8] = {0, 3, 2, 4, 1, 5, 6, 7};
412     int divisor, best_divisor, best_baud, best_baud_diff;
413     unsigned long encoded_divisor;
414     int i;
415
416     if (baudrate <= 0) {
417         // Return error
418         return -1;
419     }
420
421     divisor = 24000000 / baudrate;
422
423     if (ftdi->type == TYPE_AM) {
424         // Round down to supported fraction (AM only)
425         divisor -= am_adjust_dn[divisor & 7];
426     }
427
428     // Try this divisor and the one above it (because division rounds down)
429     best_divisor = 0;
430     best_baud = 0;
431     best_baud_diff = 0;
432     for (i = 0; i < 2; i++) {
433         int try_divisor = divisor + i;
434         int baud_estimate;
435         int baud_diff;
436
437         // Round up to supported divisor value
438         if (try_divisor <= 8) {
439             // Round up to minimum supported divisor
440             try_divisor = 8;
441         } else if (ftdi->type != TYPE_AM && try_divisor < 12) {
442             // BM doesn't support divisors 9 through 11 inclusive
443             try_divisor = 12;
444         } else if (divisor < 16) {
445             // AM doesn't support divisors 9 through 15 inclusive
446             try_divisor = 16;
447         } else {
448             if (ftdi->type == TYPE_AM) {
449                 // Round up to supported fraction (AM only)
450                 try_divisor += am_adjust_up[try_divisor & 7];
451                 if (try_divisor > 0x1FFF8) {
452                     // Round down to maximum supported divisor value (for AM)
453                     try_divisor = 0x1FFF8;
454                 }
455             } else {
456                 if (try_divisor > 0x1FFFF) {
457                     // Round down to maximum supported divisor value (for BM)
458                     try_divisor = 0x1FFFF;
459                 }
460             }
461         }
462         // Get estimated baud rate (to nearest integer)
463         baud_estimate = (24000000 + (try_divisor / 2)) / try_divisor;
464         // Get absolute difference from requested baud rate
465         if (baud_estimate < baudrate) {
466             baud_diff = baudrate - baud_estimate;
467         } else {
468             baud_diff = baud_estimate - baudrate;
469         }
470         if (i == 0 || baud_diff < best_baud_diff) {
471             // Closest to requested baud rate so far
472             best_divisor = try_divisor;
473             best_baud = baud_estimate;
474             best_baud_diff = baud_diff;
475             if (baud_diff == 0) {
476                 // Spot on! No point trying
477                 break;
478             }
479         }
480     }
481     // Encode the best divisor value
482     encoded_divisor = (best_divisor >> 3) | (frac_code[best_divisor & 7] << 14);
483     // Deal with special cases for encoded value
484     if (encoded_divisor == 1) {
485         encoded_divisor = 0;    // 3000000 baud
486     } else if (encoded_divisor == 0x4001) {
487         encoded_divisor = 1;    // 2000000 baud (BM only)
488     }
489     // Split into "value" and "index" values
490     *value = (unsigned short)(encoded_divisor & 0xFFFF);
491     if(ftdi->type == TYPE_2232C) {
492         *index = (unsigned short)(encoded_divisor >> 8);
493         *index &= 0xFF00;
494         *index |= ftdi->index;
495     }
496     else
497         *index = (unsigned short)(encoded_divisor >> 16);
498
499     // Return the nearest baud rate
500     return best_baud;
501 }
502
503 /**
504     Sets the chip baudrate
505
506     \param ftdi pointer to ftdi_context
507
508     \retval  0: all fine
509     \retval -1: invalid baudrate
510     \retval -2: setting baudrate failed
511 */
512 int ftdi_set_baudrate(struct ftdi_context *ftdi, int baudrate)
513 {
514     unsigned short value, index;
515     int actual_baudrate;
516
517     if (ftdi->bitbang_enabled) {
518         baudrate = baudrate*4;
519     }
520
521     actual_baudrate = ftdi_convert_baudrate(baudrate, ftdi, &value, &index);
522     if (actual_baudrate <= 0)
523         ftdi_error_return (-1, "Silly baudrate <= 0.");
524
525     // Check within tolerance (about 5%)
526     if ((actual_baudrate * 2 < baudrate /* Catch overflows */ )
527             || ((actual_baudrate < baudrate)
528                 ? (actual_baudrate * 21 < baudrate * 20)
529                 : (baudrate * 21 < actual_baudrate * 20)))
530         ftdi_error_return (-1, "Unsupported baudrate. Note: bitbang baudrates are automatically multiplied by 4");
531
532     if (usb_control_msg(ftdi->usb_dev, 0x40, 3, value, index, NULL, 0, ftdi->usb_write_timeout) != 0)
533         ftdi_error_return (-2, "Setting new baudrate failed");
534
535     ftdi->baudrate = baudrate;
536     return 0;
537 }
538
539 /**
540     Set (RS232) line characteristics by Alain Abbas
541
542     \param ftdi pointer to ftdi_context
543     \param bits Number of bits
544     \param sbit Number of stop bits
545     \param parity Parity mode
546
547     \retval  0: all fine
548     \retval -1: Setting line property failed
549 */
550 int ftdi_set_line_property(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
551                            enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity)
552 {
553     unsigned short value = bits;
554
555     switch(parity) {
556     case NONE:
557         value |= (0x00 << 8);
558         break;
559     case ODD:
560         value |= (0x01 << 8);
561         break;
562     case EVEN:
563         value |= (0x02 << 8);
564         break;
565     case MARK:
566         value |= (0x03 << 8);
567         break;
568     case SPACE:
569         value |= (0x04 << 8);
570         break;
571     }
572
573     switch(sbit) {
574     case STOP_BIT_1:
575         value |= (0x00 << 11);
576         break;
577     case STOP_BIT_15:
578         value |= (0x01 << 11);
579         break;
580     case STOP_BIT_2:
581         value |= (0x02 << 11);
582         break;
583     }
584
585     if (usb_control_msg(ftdi->usb_dev, 0x40, 0x04, value, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
586         ftdi_error_return (-1, "Setting new line property failed");
587
588     return 0;
589 }
590
591 /**
592     Writes data in chunks (see ftdi_write_data_set_chunksize()) to the chip
593
594     \param ftdi pointer to ftdi_context
595     \param buf Buffer with the data
596     \param size Size of the buffer
597
598     \retval <0: error code from usb_bulk_write()
599     \retval >0: number of bytes written
600 */
601 int ftdi_write_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
602 {
603     int ret;
604     int offset = 0;
605     int total_written = 0;
606
607     while (offset < size) {
608         int write_size = ftdi->writebuffer_chunksize;
609
610         if (offset+write_size > size)
611             write_size = size-offset;
612
613         ret = usb_bulk_write(ftdi->usb_dev, ftdi->in_ep, buf+offset, write_size, ftdi->usb_write_timeout);
614         if (ret < 0)
615             ftdi_error_return(ret, "usb bulk write failed");
616
617         total_written += ret;
618         offset += write_size;
619     }
620
621     return total_written;
622 }
623
624 /**
625     Configure write buffer chunk size.
626     Default is 4096.
627
628     \param ftdi pointer to ftdi_context
629     \param chunksize Chunk size
630
631     \retval 0: all fine
632 */
633 int ftdi_write_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
634 {
635     ftdi->writebuffer_chunksize = chunksize;
636     return 0;
637 }
638
639 /**
640     Get write buffer chunk size.
641
642     \param ftdi pointer to ftdi_context
643     \param chunksize Pointer to store chunk size in
644
645     \retval 0: all fine
646 */
647 int ftdi_write_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
648 {
649     *chunksize = ftdi->writebuffer_chunksize;
650     return 0;
651 }
652
653 /**
654     Reads data in chunks (see ftdi_read_data_set_chunksize()) from the chip.
655
656     Automatically strips the two modem status bytes transfered during every read.
657
658     \param ftdi pointer to ftdi_context
659     \param buf Buffer to store data in
660     \param size Size of the buffer
661
662     \retval <0: error code from usb_bulk_read()
663     \retval >0: number of bytes read
664
665     \remark This function is not useful in bitbang mode.
666             Use ftdi_read_pins() to get the current state of the pins.
667 */
668 int ftdi_read_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
669 {
670     int offset = 0, ret = 1, i, num_of_chunks, chunk_remains;
671
672     // everything we want is still in the readbuffer?
673     if (size <= ftdi->readbuffer_remaining) {
674         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);
675
676         // Fix offsets
677         ftdi->readbuffer_remaining -= size;
678         ftdi->readbuffer_offset += size;
679
680         /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */
681
682         return size;
683     }
684     // something still in the readbuffer, but not enough to satisfy 'size'?
685     if (ftdi->readbuffer_remaining != 0) {
686         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);
687
688         // Fix offset
689         offset += ftdi->readbuffer_remaining;
690     }
691     // do the actual USB read
692     while (offset < size && ret > 0) {
693         ftdi->readbuffer_remaining = 0;
694         ftdi->readbuffer_offset = 0;
695         /* returns how much received */
696         ret = usb_bulk_read (ftdi->usb_dev, ftdi->out_ep, ftdi->readbuffer, ftdi->readbuffer_chunksize, ftdi->usb_read_timeout);
697         if (ret < 0)
698             ftdi_error_return(ret, "usb bulk read failed");
699
700         if (ret > 2) {
701             // skip FTDI status bytes.
702             // Maybe stored in the future to enable modem use
703             num_of_chunks = ret / 64;
704             chunk_remains = ret % 64;
705             //printf("ret = %X, num_of_chunks = %X, chunk_remains = %X, readbuffer_offset = %X\n", ret, num_of_chunks, chunk_remains, ftdi->readbuffer_offset);
706
707             ftdi->readbuffer_offset += 2;
708             ret -= 2;
709
710             if (ret > 62) {
711                 for (i = 1; i < num_of_chunks; i++)
712                     memmove (ftdi->readbuffer+ftdi->readbuffer_offset+62*i,
713                              ftdi->readbuffer+ftdi->readbuffer_offset+64*i,
714                              62);
715                 if (chunk_remains > 2) {
716                     memmove (ftdi->readbuffer+ftdi->readbuffer_offset+62*i,
717                              ftdi->readbuffer+ftdi->readbuffer_offset+64*i,
718                              chunk_remains-2);
719                     ret -= 2*num_of_chunks;
720                 } else
721                     ret -= 2*(num_of_chunks-1)+chunk_remains;
722             }
723         } else if (ret <= 2) {
724             // no more data to read?
725             return offset;
726         }
727         if (ret > 0) {
728             // data still fits in buf?
729             if (offset+ret <= size) {
730                 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, ret);
731                 //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
732                 offset += ret;
733
734                 /* Did we read exactly the right amount of bytes? */
735                 if (offset == size)
736                     //printf("read_data exact rem %d offset %d\n",
737                     //ftdi->readbuffer_remaining, offset);
738                     return offset;
739             } else {
740                 // only copy part of the data or size <= readbuffer_chunksize
741                 int part_size = size-offset;
742                 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, part_size);
743
744                 ftdi->readbuffer_offset += part_size;
745                 ftdi->readbuffer_remaining = ret-part_size;
746                 offset += part_size;
747
748                 /* printf("Returning part: %d - size: %d - offset: %d - ret: %d - remaining: %d\n",
749                 part_size, size, offset, ret, ftdi->readbuffer_remaining); */
750
751                 return offset;
752             }
753         }
754     }
755     // never reached
756     return -127;
757 }
758
759 /**
760     Configure read buffer chunk size.
761     Default is 4096.
762
763     Automatically reallocates the buffer.
764
765     \param ftdi pointer to ftdi_context
766     \param chunksize Chunk size
767
768     \retval 0: all fine
769 */
770 int ftdi_read_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
771 {
772     unsigned char *new_buf;
773
774     // Invalidate all remaining data
775     ftdi->readbuffer_offset = 0;
776     ftdi->readbuffer_remaining = 0;
777
778     if ((new_buf = (unsigned char *)realloc(ftdi->readbuffer, chunksize)) == NULL)
779         ftdi_error_return(-1, "out of memory for readbuffer");
780
781     ftdi->readbuffer = new_buf;
782     ftdi->readbuffer_chunksize = chunksize;
783
784     return 0;
785 }
786
787 /**
788     Get read buffer chunk size.
789
790     \param ftdi pointer to ftdi_context
791     \param chunksize Pointer to store chunk size in
792
793     \retval 0: all fine
794 */
795 int ftdi_read_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
796 {
797     *chunksize = ftdi->readbuffer_chunksize;
798     return 0;
799 }
800
801
802 /**
803     Enable bitbang mode.
804
805     For advanced bitbang modes of the FT2232C chip use ftdi_set_bitmode().
806
807     \param ftdi pointer to ftdi_context
808     \param bitmask Bitmask to configure lines.
809            HIGH/ON value configures a line as output.
810
811     \retval  0: all fine
812     \retval -1: can't enable bitbang mode
813 */
814 int ftdi_enable_bitbang(struct ftdi_context *ftdi, unsigned char bitmask)
815 {
816     unsigned short usb_val;
817
818     usb_val = bitmask; // low byte: bitmask
819     /* FT2232C: Set bitbang_mode to 2 to enable SPI */
820     usb_val |= (ftdi->bitbang_mode << 8);
821
822     if (usb_control_msg(ftdi->usb_dev, 0x40, 0x0B, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
823         ftdi_error_return(-1, "unable to enter bitbang mode. Perhaps not a BM type chip?");
824
825     ftdi->bitbang_enabled = 1;
826     return 0;
827 }
828
829 /**
830     Disable bitbang mode.
831
832     \param ftdi pointer to ftdi_context
833
834     \retval  0: all fine
835     \retval -1: can't disable bitbang mode
836 */
837 int ftdi_disable_bitbang(struct ftdi_context *ftdi)
838 {
839     if (usb_control_msg(ftdi->usb_dev, 0x40, 0x0B, 0, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
840         ftdi_error_return(-1, "unable to leave bitbang mode. Perhaps not a BM type chip?");
841
842     ftdi->bitbang_enabled = 0;
843     return 0;
844 }
845
846 /**
847     Enable advanced bitbang mode for FT2232C chips.
848
849     \param ftdi pointer to ftdi_context
850     \param bitmask Bitmask to configure lines.
851            HIGH/ON value configures a line as output.
852     \param mode Bitbang mode: 1 for normal mode, 2 for SPI mode
853
854     \retval  0: all fine
855     \retval -1: can't enable bitbang mode
856 */
857 int ftdi_set_bitmode(struct ftdi_context *ftdi, unsigned char bitmask, unsigned char mode)
858 {
859     unsigned short usb_val;
860
861     usb_val = bitmask; // low byte: bitmask
862     usb_val |= (mode << 8);
863     if (usb_control_msg(ftdi->usb_dev, 0x40, 0x0B, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
864         ftdi_error_return(-1, "unable to configure bitbang mode. Perhaps not a 2232C type chip?");
865
866     ftdi->bitbang_mode = mode;
867     ftdi->bitbang_enabled = (mode == BITMODE_BITBANG || mode == BITMODE_SYNCBB)?1:0;
868     return 0;
869 }
870
871 /**
872     Directly read pin state. Useful for bitbang mode.
873
874     \param ftdi pointer to ftdi_context
875     \param pins Pointer to store pins into
876
877     \retval  0: all fine
878     \retval -1: read pins failed
879 */
880 int ftdi_read_pins(struct ftdi_context *ftdi, unsigned char *pins)
881 {
882     if (usb_control_msg(ftdi->usb_dev, 0xC0, 0x0C, 0, ftdi->index, (char *)pins, 1, ftdi->usb_read_timeout) != 1)
883         ftdi_error_return(-1, "read pins failed");
884
885     return 0;
886 }
887
888 /**
889     Set latency timer
890
891     The FTDI chip keeps data in the internal buffer for a specific
892     amount of time if the buffer is not full yet to decrease
893     load on the usb bus.
894
895     \param ftdi pointer to ftdi_context
896     \param latency Value between 1 and 255
897
898     \retval  0: all fine
899     \retval -1: latency out of range
900     \retval -2: unable to set latency timer
901 */
902 int ftdi_set_latency_timer(struct ftdi_context *ftdi, unsigned char latency)
903 {
904     unsigned short usb_val;
905
906     if (latency < 1)
907         ftdi_error_return(-1, "latency out of range. Only valid for 1-255");
908
909     usb_val = latency;
910     if (usb_control_msg(ftdi->usb_dev, 0x40, 0x09, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
911         ftdi_error_return(-2, "unable to set latency timer");
912
913     return 0;
914 }
915
916 /**
917     Get latency timer
918
919     \param ftdi pointer to ftdi_context
920     \param latency Pointer to store latency value in
921
922     \retval  0: all fine
923     \retval -1: unable to get latency timer
924 */
925 int ftdi_get_latency_timer(struct ftdi_context *ftdi, unsigned char *latency)
926 {
927     unsigned short usb_val;
928     if (usb_control_msg(ftdi->usb_dev, 0xC0, 0x0A, 0, ftdi->index, (char *)&usb_val, 1, ftdi->usb_read_timeout) != 1)
929         ftdi_error_return(-1, "reading latency timer failed");
930
931     *latency = (unsigned char)usb_val;
932     return 0;
933 }
934
935 /**
936     Init eeprom with default values.
937
938     \param eeprom Pointer to ftdi_eeprom
939 */
940 void ftdi_eeprom_initdefaults(struct ftdi_eeprom *eeprom)
941 {
942     eeprom->vendor_id = 0x0403;
943     eeprom->product_id = 0x6001;
944
945     eeprom->self_powered = 1;
946     eeprom->remote_wakeup = 1;
947     eeprom->BM_type_chip = 1;
948
949     eeprom->in_is_isochronous = 0;
950     eeprom->out_is_isochronous = 0;
951     eeprom->suspend_pull_downs = 0;
952
953     eeprom->use_serial = 0;
954     eeprom->change_usb_version = 0;
955     eeprom->usb_version = 0x0200;
956     eeprom->max_power = 0;
957
958     eeprom->manufacturer = NULL;
959     eeprom->product = NULL;
960     eeprom->serial = NULL;
961 }
962
963 /**
964    Build binary output from ftdi_eeprom structure.
965    Output is suitable for ftdi_write_eeprom().
966
967    \param eeprom Pointer to ftdi_eeprom
968    \param output Buffer of 128 bytes to store eeprom image to
969
970    \retval >0: used eeprom size
971    \retval -1: eeprom size (128 bytes) exceeded by custom strings
972 */
973 int ftdi_eeprom_build(struct ftdi_eeprom *eeprom, unsigned char *output)
974 {
975     unsigned char i, j;
976     unsigned short checksum, value;
977     unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
978     int size_check;
979
980     if (eeprom->manufacturer != NULL)
981         manufacturer_size = strlen(eeprom->manufacturer);
982     if (eeprom->product != NULL)
983         product_size = strlen(eeprom->product);
984     if (eeprom->serial != NULL)
985         serial_size = strlen(eeprom->serial);
986
987     size_check = 128; // eeprom is 128 bytes
988     size_check -= 28; // 28 are always in use (fixed)
989     size_check -= manufacturer_size*2;
990     size_check -= product_size*2;
991     size_check -= serial_size*2;
992
993     // eeprom size exceeded?
994     if (size_check < 0)
995         return (-1);
996
997     // empty eeprom
998     memset (output, 0, 128);
999
1000     // Addr 00: Stay 00 00
1001     // Addr 02: Vendor ID
1002     output[0x02] = eeprom->vendor_id;
1003     output[0x03] = eeprom->vendor_id >> 8;
1004
1005     // Addr 04: Product ID
1006     output[0x04] = eeprom->product_id;
1007     output[0x05] = eeprom->product_id >> 8;
1008
1009     // Addr 06: Device release number (0400h for BM features)
1010     output[0x06] = 0x00;
1011
1012     if (eeprom->BM_type_chip == 1)
1013         output[0x07] = 0x04;
1014     else
1015         output[0x07] = 0x02;
1016
1017     // Addr 08: Config descriptor
1018     // Bit 1: remote wakeup if 1
1019     // Bit 0: self powered if 1
1020     //
1021     j = 0;
1022     if (eeprom->self_powered == 1)
1023         j = j | 1;
1024     if (eeprom->remote_wakeup == 1)
1025         j = j | 2;
1026     output[0x08] = j;
1027
1028     // Addr 09: Max power consumption: max power = value * 2 mA
1029     output[0x09] = eeprom->max_power;
1030     ;
1031
1032     // Addr 0A: Chip configuration
1033     // Bit 7: 0 - reserved
1034     // Bit 6: 0 - reserved
1035     // Bit 5: 0 - reserved
1036     // Bit 4: 1 - Change USB version
1037     // Bit 3: 1 - Use the serial number string
1038     // Bit 2: 1 - Enable suspend pull downs for lower power
1039     // Bit 1: 1 - Out EndPoint is Isochronous
1040     // Bit 0: 1 - In EndPoint is Isochronous
1041     //
1042     j = 0;
1043     if (eeprom->in_is_isochronous == 1)
1044         j = j | 1;
1045     if (eeprom->out_is_isochronous == 1)
1046         j = j | 2;
1047     if (eeprom->suspend_pull_downs == 1)
1048         j = j | 4;
1049     if (eeprom->use_serial == 1)
1050         j = j | 8;
1051     if (eeprom->change_usb_version == 1)
1052         j = j | 16;
1053     output[0x0A] = j;
1054
1055     // Addr 0B: reserved
1056     output[0x0B] = 0x00;
1057
1058     // Addr 0C: USB version low byte when 0x0A bit 4 is set
1059     // Addr 0D: USB version high byte when 0x0A bit 4 is set
1060     if (eeprom->change_usb_version == 1) {
1061         output[0x0C] = eeprom->usb_version;
1062         output[0x0D] = eeprom->usb_version >> 8;
1063     }
1064
1065
1066     // Addr 0E: Offset of the manufacturer string + 0x80
1067     output[0x0E] = 0x14 + 0x80;
1068
1069     // Addr 0F: Length of manufacturer string
1070     output[0x0F] = manufacturer_size*2 + 2;
1071
1072     // Addr 10: Offset of the product string + 0x80, calculated later
1073     // Addr 11: Length of product string
1074     output[0x11] = product_size*2 + 2;
1075
1076     // Addr 12: Offset of the serial string + 0x80, calculated later
1077     // Addr 13: Length of serial string
1078     output[0x13] = serial_size*2 + 2;
1079
1080     // Dynamic content
1081     output[0x14] = manufacturer_size*2 + 2;
1082     output[0x15] = 0x03; // type: string
1083
1084     i = 0x16, j = 0;
1085
1086     // Output manufacturer
1087     for (j = 0; j < manufacturer_size; j++) {
1088         output[i] = eeprom->manufacturer[j], i++;
1089         output[i] = 0x00, i++;
1090     }
1091
1092     // Output product name
1093     output[0x10] = i + 0x80;  // calculate offset
1094     output[i] = product_size*2 + 2, i++;
1095     output[i] = 0x03, i++;
1096     for (j = 0; j < product_size; j++) {
1097         output[i] = eeprom->product[j], i++;
1098         output[i] = 0x00, i++;
1099     }
1100
1101     // Output serial
1102     output[0x12] = i + 0x80; // calculate offset
1103     output[i] = serial_size*2 + 2, i++;
1104     output[i] = 0x03, i++;
1105     for (j = 0; j < serial_size; j++) {
1106         output[i] = eeprom->serial[j], i++;
1107         output[i] = 0x00, i++;
1108     }
1109
1110     // calculate checksum
1111     checksum = 0xAAAA;
1112
1113     for (i = 0; i < 63; i++) {
1114         value = output[i*2];
1115         value += output[(i*2)+1] << 8;
1116
1117         checksum = value^checksum;
1118         checksum = (checksum << 1) | (checksum >> 15);
1119     }
1120
1121     output[0x7E] = checksum;
1122     output[0x7F] = checksum >> 8;
1123
1124     return size_check;
1125 }
1126
1127 /**
1128     Read eeprom
1129
1130     \param ftdi pointer to ftdi_context
1131     \param eeprom Pointer to store eeprom into
1132
1133     \retval  0: all fine
1134     \retval -1: read failed
1135 */
1136 int ftdi_read_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
1137 {
1138     int i;
1139
1140     for (i = 0; i < 64; i++) {
1141         if (usb_control_msg(ftdi->usb_dev, 0xC0, 0x90, 0, i, eeprom+(i*2), 2, ftdi->usb_read_timeout) != 2)
1142             ftdi_error_return(-1, "reading eeprom failed");
1143     }
1144
1145     return 0;
1146 }
1147
1148 /**
1149     Write eeprom
1150
1151     \param ftdi pointer to ftdi_context
1152     \param eeprom Pointer to read eeprom from
1153
1154     \retval  0: all fine
1155     \retval -1: read failed
1156 */
1157 int ftdi_write_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
1158 {
1159     unsigned short usb_val;
1160     int i;
1161
1162     for (i = 0; i < 64; i++) {
1163         usb_val = eeprom[i*2];
1164         usb_val += eeprom[(i*2)+1] << 8;
1165         if (usb_control_msg(ftdi->usb_dev, 0x40, 0x91, usb_val, i, NULL, 0, ftdi->usb_write_timeout) != 0)
1166             ftdi_error_return(-1, "unable to write eeprom");
1167     }
1168
1169     return 0;
1170 }
1171
1172 /**
1173     Erase eeprom
1174
1175     \param ftdi pointer to ftdi_context
1176
1177     \retval  0: all fine
1178     \retval -1: erase failed
1179 */
1180 int ftdi_erase_eeprom(struct ftdi_context *ftdi)
1181 {
1182     if (usb_control_msg(ftdi->usb_dev, 0x40, 0x92, 0, 0, NULL, 0, ftdi->usb_write_timeout) != 0)
1183         ftdi_error_return(-1, "unable to erase eeprom");
1184
1185     return 0;
1186 }
1187
1188 /**
1189     Get string representation for last error code
1190
1191     \param ftdi pointer to ftdi_context
1192
1193     \retval Pointer to error string
1194 */
1195 char *ftdi_get_error_string (struct ftdi_context *ftdi)
1196 {
1197     return ftdi->error_str;
1198 }
1199
1200 /**
1201     Set flowcontrol for ftdi chip
1202
1203     \param ftdi pointer to ftdi_context
1204     \param flowctrl flow control to use. should be 
1205            SIO_DISABLE_FLOW_CTRL, SIO_RTS_CTS_HS, SIO_DTR_DSR_HS or SIO_XON_XOFF_HS   
1206
1207     \retval  0: all fine
1208     \retval -1: set flow control failed
1209 */
1210 int ftdi_setflowctrl(struct ftdi_context *ftdi, int flowctrl)
1211 {
1212     if (usb_control_msg(ftdi->usb_dev, SIO_SET_FLOW_CTRL_REQUEST_TYPE,
1213                         SIO_SET_FLOW_CTRL_REQUEST, 0, (flowctrl | ftdi->interface),
1214                         NULL, 0, ftdi->usb_write_timeout) != 0)
1215         ftdi_error_return(-1, "set flow control failed");
1216
1217     return 0;
1218 }
1219
1220 /**
1221     Set dtr line
1222
1223     \param ftdi pointer to ftdi_context
1224     \param state state to set line to (1 or 0)
1225
1226     \retval  0: all fine
1227     \retval -1: set dtr failed
1228 */
1229 int ftdi_setdtr(struct ftdi_context *ftdi, int state)
1230 {
1231     unsigned short usb_val;
1232
1233     if (state)
1234         usb_val = SIO_SET_DTR_HIGH;
1235     else
1236         usb_val = SIO_SET_DTR_LOW;
1237
1238     if (usb_control_msg(ftdi->usb_dev, SIO_SET_MODEM_CTRL_REQUEST_TYPE,
1239                         SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->interface,
1240                         NULL, 0, ftdi->usb_write_timeout) != 0)
1241         ftdi_error_return(-1, "set dtr failed");
1242
1243     return 0;
1244 }
1245
1246 /**
1247     Set rts line
1248
1249     \param ftdi pointer to ftdi_context
1250     \param state state to set line to (1 or 0)
1251
1252     \retval  0: all fine
1253     \retval -1 set rts failed
1254 */
1255 int ftdi_setrts(struct ftdi_context *ftdi, int state)
1256 {
1257     unsigned short usb_val;
1258
1259     if (state)
1260         usb_val = SIO_SET_RTS_HIGH;
1261     else
1262         usb_val = SIO_SET_RTS_LOW;
1263
1264     if (usb_control_msg(ftdi->usb_dev, SIO_SET_MODEM_CTRL_REQUEST_TYPE,
1265                         SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->interface,
1266                         NULL, 0, ftdi->usb_write_timeout) != 0)
1267         ftdi_error_return(-1, "set of rts failed");
1268
1269     return 0;
1270 }