more documentation. Let's find out how we can group things with doxygen
[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 same as 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 baud rate
505
506     \param ftdi pointer to ftdi_context
507     \param baudrate baud rate to set
508
509     \retval  0: all fine
510     \retval -1: invalid baudrate
511     \retval -2: setting baudrate failed
512 */
513 int ftdi_set_baudrate(struct ftdi_context *ftdi, int baudrate)
514 {
515     unsigned short value, index;
516     int actual_baudrate;
517
518     if (ftdi->bitbang_enabled) {
519         baudrate = baudrate*4;
520     }
521
522     actual_baudrate = ftdi_convert_baudrate(baudrate, ftdi, &value, &index);
523     if (actual_baudrate <= 0)
524         ftdi_error_return (-1, "Silly baudrate <= 0.");
525
526     // Check within tolerance (about 5%)
527     if ((actual_baudrate * 2 < baudrate /* Catch overflows */ )
528             || ((actual_baudrate < baudrate)
529                 ? (actual_baudrate * 21 < baudrate * 20)
530                 : (baudrate * 21 < actual_baudrate * 20)))
531         ftdi_error_return (-1, "Unsupported baudrate. Note: bitbang baudrates are automatically multiplied by 4");
532
533     if (usb_control_msg(ftdi->usb_dev, 0x40, 3, value, index, NULL, 0, ftdi->usb_write_timeout) != 0)
534         ftdi_error_return (-2, "Setting new baudrate failed");
535
536     ftdi->baudrate = baudrate;
537     return 0;
538 }
539
540 /**
541     Set (RS232) line characteristics by Alain Abbas
542
543     \param ftdi pointer to ftdi_context
544     \param bits Number of bits
545     \param sbit Number of stop bits
546     \param parity Parity mode
547
548     \retval  0: all fine
549     \retval -1: Setting line property failed
550 */
551 int ftdi_set_line_property(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
552                            enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity)
553 {
554     unsigned short value = bits;
555
556     switch(parity) {
557     case NONE:
558         value |= (0x00 << 8);
559         break;
560     case ODD:
561         value |= (0x01 << 8);
562         break;
563     case EVEN:
564         value |= (0x02 << 8);
565         break;
566     case MARK:
567         value |= (0x03 << 8);
568         break;
569     case SPACE:
570         value |= (0x04 << 8);
571         break;
572     }
573
574     switch(sbit) {
575     case STOP_BIT_1:
576         value |= (0x00 << 11);
577         break;
578     case STOP_BIT_15:
579         value |= (0x01 << 11);
580         break;
581     case STOP_BIT_2:
582         value |= (0x02 << 11);
583         break;
584     }
585
586     if (usb_control_msg(ftdi->usb_dev, 0x40, 0x04, value, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
587         ftdi_error_return (-1, "Setting new line property failed");
588
589     return 0;
590 }
591
592 /**
593     Writes data in chunks (see ftdi_write_data_set_chunksize()) to the chip
594
595     \param ftdi pointer to ftdi_context
596     \param buf Buffer with the data
597     \param size Size of the buffer
598
599     \retval <0: error code from usb_bulk_write()
600     \retval >0: number of bytes written
601 */
602 int ftdi_write_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
603 {
604     int ret;
605     int offset = 0;
606     int total_written = 0;
607
608     while (offset < size) {
609         int write_size = ftdi->writebuffer_chunksize;
610
611         if (offset+write_size > size)
612             write_size = size-offset;
613
614         ret = usb_bulk_write(ftdi->usb_dev, ftdi->in_ep, buf+offset, write_size, ftdi->usb_write_timeout);
615         if (ret < 0)
616             ftdi_error_return(ret, "usb bulk write failed");
617
618         total_written += ret;
619         offset += write_size;
620     }
621
622     return total_written;
623 }
624
625 /**
626     Configure write buffer chunk size.
627     Default is 4096.
628
629     \param ftdi pointer to ftdi_context
630     \param chunksize Chunk size
631
632     \retval 0: all fine
633 */
634 int ftdi_write_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
635 {
636     ftdi->writebuffer_chunksize = chunksize;
637     return 0;
638 }
639
640 /**
641     Get write buffer chunk size.
642
643     \param ftdi pointer to ftdi_context
644     \param chunksize Pointer to store chunk size in
645
646     \retval 0: all fine
647 */
648 int ftdi_write_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
649 {
650     *chunksize = ftdi->writebuffer_chunksize;
651     return 0;
652 }
653
654 /**
655     Reads data in chunks (see ftdi_read_data_set_chunksize()) from the chip.
656
657     Automatically strips the two modem status bytes transfered during every read.
658
659     \param ftdi pointer to ftdi_context
660     \param buf Buffer to store data in
661     \param size Size of the buffer
662
663     \retval <0: error code from usb_bulk_read()
664     \retval >0: number of bytes read
665
666     \remark This function is not useful in bitbang mode.
667             Use ftdi_read_pins() to get the current state of the pins.
668 */
669 int ftdi_read_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
670 {
671     int offset = 0, ret = 1, i, num_of_chunks, chunk_remains;
672
673     // everything we want is still in the readbuffer?
674     if (size <= ftdi->readbuffer_remaining) {
675         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);
676
677         // Fix offsets
678         ftdi->readbuffer_remaining -= size;
679         ftdi->readbuffer_offset += size;
680
681         /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */
682
683         return size;
684     }
685     // something still in the readbuffer, but not enough to satisfy 'size'?
686     if (ftdi->readbuffer_remaining != 0) {
687         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);
688
689         // Fix offset
690         offset += ftdi->readbuffer_remaining;
691     }
692     // do the actual USB read
693     while (offset < size && ret > 0) {
694         ftdi->readbuffer_remaining = 0;
695         ftdi->readbuffer_offset = 0;
696         /* returns how much received */
697         ret = usb_bulk_read (ftdi->usb_dev, ftdi->out_ep, ftdi->readbuffer, ftdi->readbuffer_chunksize, ftdi->usb_read_timeout);
698         if (ret < 0)
699             ftdi_error_return(ret, "usb bulk read failed");
700
701         if (ret > 2) {
702             // skip FTDI status bytes.
703             // Maybe stored in the future to enable modem use
704             num_of_chunks = ret / 64;
705             chunk_remains = ret % 64;
706             //printf("ret = %X, num_of_chunks = %X, chunk_remains = %X, readbuffer_offset = %X\n", ret, num_of_chunks, chunk_remains, ftdi->readbuffer_offset);
707
708             ftdi->readbuffer_offset += 2;
709             ret -= 2;
710
711             if (ret > 62) {
712                 for (i = 1; i < num_of_chunks; i++)
713                     memmove (ftdi->readbuffer+ftdi->readbuffer_offset+62*i,
714                              ftdi->readbuffer+ftdi->readbuffer_offset+64*i,
715                              62);
716                 if (chunk_remains > 2) {
717                     memmove (ftdi->readbuffer+ftdi->readbuffer_offset+62*i,
718                              ftdi->readbuffer+ftdi->readbuffer_offset+64*i,
719                              chunk_remains-2);
720                     ret -= 2*num_of_chunks;
721                 } else
722                     ret -= 2*(num_of_chunks-1)+chunk_remains;
723             }
724         } else if (ret <= 2) {
725             // no more data to read?
726             return offset;
727         }
728         if (ret > 0) {
729             // data still fits in buf?
730             if (offset+ret <= size) {
731                 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, ret);
732                 //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
733                 offset += ret;
734
735                 /* Did we read exactly the right amount of bytes? */
736                 if (offset == size)
737                     //printf("read_data exact rem %d offset %d\n",
738                     //ftdi->readbuffer_remaining, offset);
739                     return offset;
740             } else {
741                 // only copy part of the data or size <= readbuffer_chunksize
742                 int part_size = size-offset;
743                 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, part_size);
744
745                 ftdi->readbuffer_offset += part_size;
746                 ftdi->readbuffer_remaining = ret-part_size;
747                 offset += part_size;
748
749                 /* printf("Returning part: %d - size: %d - offset: %d - ret: %d - remaining: %d\n",
750                 part_size, size, offset, ret, ftdi->readbuffer_remaining); */
751
752                 return offset;
753             }
754         }
755     }
756     // never reached
757     return -127;
758 }
759
760 /**
761     Configure read buffer chunk size.
762     Default is 4096.
763
764     Automatically reallocates the buffer.
765
766     \param ftdi pointer to ftdi_context
767     \param chunksize Chunk size
768
769     \retval 0: all fine
770 */
771 int ftdi_read_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
772 {
773     unsigned char *new_buf;
774
775     // Invalidate all remaining data
776     ftdi->readbuffer_offset = 0;
777     ftdi->readbuffer_remaining = 0;
778
779     if ((new_buf = (unsigned char *)realloc(ftdi->readbuffer, chunksize)) == NULL)
780         ftdi_error_return(-1, "out of memory for readbuffer");
781
782     ftdi->readbuffer = new_buf;
783     ftdi->readbuffer_chunksize = chunksize;
784
785     return 0;
786 }
787
788 /**
789     Get read buffer chunk size.
790
791     \param ftdi pointer to ftdi_context
792     \param chunksize Pointer to store chunk size in
793
794     \retval 0: all fine
795 */
796 int ftdi_read_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
797 {
798     *chunksize = ftdi->readbuffer_chunksize;
799     return 0;
800 }
801
802
803 /**
804     Enable bitbang mode.
805
806     For advanced bitbang modes of the FT2232C chip use ftdi_set_bitmode().
807
808     \param ftdi pointer to ftdi_context
809     \param bitmask Bitmask to configure lines.
810            HIGH/ON value configures a line as output.
811
812     \retval  0: all fine
813     \retval -1: can't enable bitbang mode
814 */
815 int ftdi_enable_bitbang(struct ftdi_context *ftdi, unsigned char bitmask)
816 {
817     unsigned short usb_val;
818
819     usb_val = bitmask; // low byte: bitmask
820     /* FT2232C: Set bitbang_mode to 2 to enable SPI */
821     usb_val |= (ftdi->bitbang_mode << 8);
822
823     if (usb_control_msg(ftdi->usb_dev, 0x40, 0x0B, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
824         ftdi_error_return(-1, "unable to enter bitbang mode. Perhaps not a BM type chip?");
825
826     ftdi->bitbang_enabled = 1;
827     return 0;
828 }
829
830 /**
831     Disable bitbang mode.
832
833     \param ftdi pointer to ftdi_context
834
835     \retval  0: all fine
836     \retval -1: can't disable bitbang mode
837 */
838 int ftdi_disable_bitbang(struct ftdi_context *ftdi)
839 {
840     if (usb_control_msg(ftdi->usb_dev, 0x40, 0x0B, 0, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
841         ftdi_error_return(-1, "unable to leave bitbang mode. Perhaps not a BM type chip?");
842
843     ftdi->bitbang_enabled = 0;
844     return 0;
845 }
846
847 /**
848     Enable advanced bitbang mode for FT2232C chips.
849
850     \param ftdi pointer to ftdi_context
851     \param bitmask Bitmask to configure lines.
852            HIGH/ON value configures a line as output.
853     \param mode Bitbang mode: 1 for normal mode, 2 for SPI mode
854
855     \retval  0: all fine
856     \retval -1: can't enable bitbang mode
857 */
858 int ftdi_set_bitmode(struct ftdi_context *ftdi, unsigned char bitmask, unsigned char mode)
859 {
860     unsigned short usb_val;
861
862     usb_val = bitmask; // low byte: bitmask
863     usb_val |= (mode << 8);
864     if (usb_control_msg(ftdi->usb_dev, 0x40, 0x0B, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
865         ftdi_error_return(-1, "unable to configure bitbang mode. Perhaps not a 2232C type chip?");
866
867     ftdi->bitbang_mode = mode;
868     ftdi->bitbang_enabled = (mode == BITMODE_BITBANG || mode == BITMODE_SYNCBB)?1:0;
869     return 0;
870 }
871
872 /**
873     Directly read pin state. Useful for bitbang mode.
874
875     \param ftdi pointer to ftdi_context
876     \param pins Pointer to store pins into
877
878     \retval  0: all fine
879     \retval -1: read pins failed
880 */
881 int ftdi_read_pins(struct ftdi_context *ftdi, unsigned char *pins)
882 {
883     if (usb_control_msg(ftdi->usb_dev, 0xC0, 0x0C, 0, ftdi->index, (char *)pins, 1, ftdi->usb_read_timeout) != 1)
884         ftdi_error_return(-1, "read pins failed");
885
886     return 0;
887 }
888
889 /**
890     Set latency timer
891
892     The FTDI chip keeps data in the internal buffer for a specific
893     amount of time if the buffer is not full yet to decrease
894     load on the usb bus.
895
896     \param ftdi pointer to ftdi_context
897     \param latency Value between 1 and 255
898
899     \retval  0: all fine
900     \retval -1: latency out of range
901     \retval -2: unable to set latency timer
902 */
903 int ftdi_set_latency_timer(struct ftdi_context *ftdi, unsigned char latency)
904 {
905     unsigned short usb_val;
906
907     if (latency < 1)
908         ftdi_error_return(-1, "latency out of range. Only valid for 1-255");
909
910     usb_val = latency;
911     if (usb_control_msg(ftdi->usb_dev, 0x40, 0x09, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
912         ftdi_error_return(-2, "unable to set latency timer");
913
914     return 0;
915 }
916
917 /**
918     Get latency timer
919
920     \param ftdi pointer to ftdi_context
921     \param latency Pointer to store latency value in
922
923     \retval  0: all fine
924     \retval -1: unable to get latency timer
925 */
926 int ftdi_get_latency_timer(struct ftdi_context *ftdi, unsigned char *latency)
927 {
928     unsigned short usb_val;
929     if (usb_control_msg(ftdi->usb_dev, 0xC0, 0x0A, 0, ftdi->index, (char *)&usb_val, 1, ftdi->usb_read_timeout) != 1)
930         ftdi_error_return(-1, "reading latency timer failed");
931
932     *latency = (unsigned char)usb_val;
933     return 0;
934 }
935
936 /**
937     Init eeprom with default values.
938
939     \param eeprom Pointer to ftdi_eeprom
940 */
941 void ftdi_eeprom_initdefaults(struct ftdi_eeprom *eeprom)
942 {
943     eeprom->vendor_id = 0x0403;
944     eeprom->product_id = 0x6001;
945
946     eeprom->self_powered = 1;
947     eeprom->remote_wakeup = 1;
948     eeprom->BM_type_chip = 1;
949
950     eeprom->in_is_isochronous = 0;
951     eeprom->out_is_isochronous = 0;
952     eeprom->suspend_pull_downs = 0;
953
954     eeprom->use_serial = 0;
955     eeprom->change_usb_version = 0;
956     eeprom->usb_version = 0x0200;
957     eeprom->max_power = 0;
958
959     eeprom->manufacturer = NULL;
960     eeprom->product = NULL;
961     eeprom->serial = NULL;
962 }
963
964 /**
965    Build binary output from ftdi_eeprom structure.
966    Output is suitable for ftdi_write_eeprom().
967
968    \param eeprom Pointer to ftdi_eeprom
969    \param output Buffer of 128 bytes to store eeprom image to
970
971    \retval >0: used eeprom size
972    \retval -1: eeprom size (128 bytes) exceeded by custom strings
973 */
974 int ftdi_eeprom_build(struct ftdi_eeprom *eeprom, unsigned char *output)
975 {
976     unsigned char i, j;
977     unsigned short checksum, value;
978     unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
979     int size_check;
980
981     if (eeprom->manufacturer != NULL)
982         manufacturer_size = strlen(eeprom->manufacturer);
983     if (eeprom->product != NULL)
984         product_size = strlen(eeprom->product);
985     if (eeprom->serial != NULL)
986         serial_size = strlen(eeprom->serial);
987
988     size_check = 128; // eeprom is 128 bytes
989     size_check -= 28; // 28 are always in use (fixed)
990     size_check -= manufacturer_size*2;
991     size_check -= product_size*2;
992     size_check -= serial_size*2;
993
994     // eeprom size exceeded?
995     if (size_check < 0)
996         return (-1);
997
998     // empty eeprom
999     memset (output, 0, 128);
1000
1001     // Addr 00: Stay 00 00
1002     // Addr 02: Vendor ID
1003     output[0x02] = eeprom->vendor_id;
1004     output[0x03] = eeprom->vendor_id >> 8;
1005
1006     // Addr 04: Product ID
1007     output[0x04] = eeprom->product_id;
1008     output[0x05] = eeprom->product_id >> 8;
1009
1010     // Addr 06: Device release number (0400h for BM features)
1011     output[0x06] = 0x00;
1012
1013     if (eeprom->BM_type_chip == 1)
1014         output[0x07] = 0x04;
1015     else
1016         output[0x07] = 0x02;
1017
1018     // Addr 08: Config descriptor
1019     // Bit 1: remote wakeup if 1
1020     // Bit 0: self powered if 1
1021     //
1022     j = 0;
1023     if (eeprom->self_powered == 1)
1024         j = j | 1;
1025     if (eeprom->remote_wakeup == 1)
1026         j = j | 2;
1027     output[0x08] = j;
1028
1029     // Addr 09: Max power consumption: max power = value * 2 mA
1030     output[0x09] = eeprom->max_power;
1031     ;
1032
1033     // Addr 0A: Chip configuration
1034     // Bit 7: 0 - reserved
1035     // Bit 6: 0 - reserved
1036     // Bit 5: 0 - reserved
1037     // Bit 4: 1 - Change USB version
1038     // Bit 3: 1 - Use the serial number string
1039     // Bit 2: 1 - Enable suspend pull downs for lower power
1040     // Bit 1: 1 - Out EndPoint is Isochronous
1041     // Bit 0: 1 - In EndPoint is Isochronous
1042     //
1043     j = 0;
1044     if (eeprom->in_is_isochronous == 1)
1045         j = j | 1;
1046     if (eeprom->out_is_isochronous == 1)
1047         j = j | 2;
1048     if (eeprom->suspend_pull_downs == 1)
1049         j = j | 4;
1050     if (eeprom->use_serial == 1)
1051         j = j | 8;
1052     if (eeprom->change_usb_version == 1)
1053         j = j | 16;
1054     output[0x0A] = j;
1055
1056     // Addr 0B: reserved
1057     output[0x0B] = 0x00;
1058
1059     // Addr 0C: USB version low byte when 0x0A bit 4 is set
1060     // Addr 0D: USB version high byte when 0x0A bit 4 is set
1061     if (eeprom->change_usb_version == 1) {
1062         output[0x0C] = eeprom->usb_version;
1063         output[0x0D] = eeprom->usb_version >> 8;
1064     }
1065
1066
1067     // Addr 0E: Offset of the manufacturer string + 0x80
1068     output[0x0E] = 0x14 + 0x80;
1069
1070     // Addr 0F: Length of manufacturer string
1071     output[0x0F] = manufacturer_size*2 + 2;
1072
1073     // Addr 10: Offset of the product string + 0x80, calculated later
1074     // Addr 11: Length of product string
1075     output[0x11] = product_size*2 + 2;
1076
1077     // Addr 12: Offset of the serial string + 0x80, calculated later
1078     // Addr 13: Length of serial string
1079     output[0x13] = serial_size*2 + 2;
1080
1081     // Dynamic content
1082     output[0x14] = manufacturer_size*2 + 2;
1083     output[0x15] = 0x03; // type: string
1084
1085     i = 0x16, j = 0;
1086
1087     // Output manufacturer
1088     for (j = 0; j < manufacturer_size; j++) {
1089         output[i] = eeprom->manufacturer[j], i++;
1090         output[i] = 0x00, i++;
1091     }
1092
1093     // Output product name
1094     output[0x10] = i + 0x80;  // calculate offset
1095     output[i] = product_size*2 + 2, i++;
1096     output[i] = 0x03, i++;
1097     for (j = 0; j < product_size; j++) {
1098         output[i] = eeprom->product[j], i++;
1099         output[i] = 0x00, i++;
1100     }
1101
1102     // Output serial
1103     output[0x12] = i + 0x80; // calculate offset
1104     output[i] = serial_size*2 + 2, i++;
1105     output[i] = 0x03, i++;
1106     for (j = 0; j < serial_size; j++) {
1107         output[i] = eeprom->serial[j], i++;
1108         output[i] = 0x00, i++;
1109     }
1110
1111     // calculate checksum
1112     checksum = 0xAAAA;
1113
1114     for (i = 0; i < 63; i++) {
1115         value = output[i*2];
1116         value += output[(i*2)+1] << 8;
1117
1118         checksum = value^checksum;
1119         checksum = (checksum << 1) | (checksum >> 15);
1120     }
1121
1122     output[0x7E] = checksum;
1123     output[0x7F] = checksum >> 8;
1124
1125     return size_check;
1126 }
1127
1128 /**
1129     Read eeprom
1130
1131     \param ftdi pointer to ftdi_context
1132     \param eeprom Pointer to store eeprom into
1133
1134     \retval  0: all fine
1135     \retval -1: read failed
1136 */
1137 int ftdi_read_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
1138 {
1139     int i;
1140
1141     for (i = 0; i < 64; i++) {
1142         if (usb_control_msg(ftdi->usb_dev, 0xC0, 0x90, 0, i, eeprom+(i*2), 2, ftdi->usb_read_timeout) != 2)
1143             ftdi_error_return(-1, "reading eeprom failed");
1144     }
1145
1146     return 0;
1147 }
1148
1149 /**
1150     Write eeprom
1151
1152     \param ftdi pointer to ftdi_context
1153     \param eeprom Pointer to read eeprom from
1154
1155     \retval  0: all fine
1156     \retval -1: read failed
1157 */
1158 int ftdi_write_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
1159 {
1160     unsigned short usb_val;
1161     int i;
1162
1163     for (i = 0; i < 64; i++) {
1164         usb_val = eeprom[i*2];
1165         usb_val += eeprom[(i*2)+1] << 8;
1166         if (usb_control_msg(ftdi->usb_dev, 0x40, 0x91, usb_val, i, NULL, 0, ftdi->usb_write_timeout) != 0)
1167             ftdi_error_return(-1, "unable to write eeprom");
1168     }
1169
1170     return 0;
1171 }
1172
1173 /**
1174     Erase eeprom
1175
1176     \param ftdi pointer to ftdi_context
1177
1178     \retval  0: all fine
1179     \retval -1: erase failed
1180 */
1181 int ftdi_erase_eeprom(struct ftdi_context *ftdi)
1182 {
1183     if (usb_control_msg(ftdi->usb_dev, 0x40, 0x92, 0, 0, NULL, 0, ftdi->usb_write_timeout) != 0)
1184         ftdi_error_return(-1, "unable to erase eeprom");
1185
1186     return 0;
1187 }
1188
1189 /**
1190     Get string representation for last error code
1191
1192     \param ftdi pointer to ftdi_context
1193
1194     \retval Pointer to error string
1195 */
1196 char *ftdi_get_error_string (struct ftdi_context *ftdi)
1197 {
1198     return ftdi->error_str;
1199 }
1200
1201 /*
1202     Flow control code by Lorenz Moesenlechner (lorenz@hcilab.org)
1203     and Matthias Kranz  (matthias@hcilab.org)
1204 */
1205 /**
1206     Set flowcontrol for ftdi chip
1207
1208     \param ftdi pointer to ftdi_context
1209     \param flowctrl flow control to use. should be 
1210            SIO_DISABLE_FLOW_CTRL, SIO_RTS_CTS_HS, SIO_DTR_DSR_HS or SIO_XON_XOFF_HS   
1211
1212     \retval  0: all fine
1213     \retval -1: set flow control failed
1214 */
1215 int ftdi_setflowctrl(struct ftdi_context *ftdi, int flowctrl)
1216 {
1217     if (usb_control_msg(ftdi->usb_dev, SIO_SET_FLOW_CTRL_REQUEST_TYPE,
1218                         SIO_SET_FLOW_CTRL_REQUEST, 0, (flowctrl | ftdi->interface),
1219                         NULL, 0, ftdi->usb_write_timeout) != 0)
1220         ftdi_error_return(-1, "set flow control failed");
1221
1222     return 0;
1223 }
1224
1225 /**
1226     Set dtr line
1227
1228     \param ftdi pointer to ftdi_context
1229     \param state state to set line to (1 or 0)
1230
1231     \retval  0: all fine
1232     \retval -1: set dtr failed
1233 */
1234 int ftdi_setdtr(struct ftdi_context *ftdi, int state)
1235 {
1236     unsigned short usb_val;
1237
1238     if (state)
1239         usb_val = SIO_SET_DTR_HIGH;
1240     else
1241         usb_val = SIO_SET_DTR_LOW;
1242
1243     if (usb_control_msg(ftdi->usb_dev, SIO_SET_MODEM_CTRL_REQUEST_TYPE,
1244                         SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->interface,
1245                         NULL, 0, ftdi->usb_write_timeout) != 0)
1246         ftdi_error_return(-1, "set dtr failed");
1247
1248     return 0;
1249 }
1250
1251 /**
1252     Set rts line
1253
1254     \param ftdi pointer to ftdi_context
1255     \param state state to set line to (1 or 0)
1256
1257     \retval  0: all fine
1258     \retval -1 set rts failed
1259 */
1260 int ftdi_setrts(struct ftdi_context *ftdi, int state)
1261 {
1262     unsigned short usb_val;
1263
1264     if (state)
1265         usb_val = SIO_SET_RTS_HIGH;
1266     else
1267         usb_val = SIO_SET_RTS_LOW;
1268
1269     if (usb_control_msg(ftdi->usb_dev, SIO_SET_MODEM_CTRL_REQUEST_TYPE,
1270                         SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->interface,
1271                         NULL, 0, ftdi->usb_write_timeout) != 0)
1272         ftdi_error_return(-1, "set of rts failed");
1273
1274     return 0;
1275 }