Allow to search for all FTDI standard VID/PID
[libftdi] / src / ftdi.c
1 /***************************************************************************
2                           ftdi.c  -  description
3                              -------------------
4     begin                : Fri Apr 4 2003
5     copyright            : (C) 2003-2011 by Intra2net AG and the libftdi developers
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 /**
18     \mainpage libftdi API documentation
19
20     Library to talk to FTDI chips. You find the latest versions of libftdi at
21     http://www.intra2net.com/en/developer/libftdi/
22
23     The library is easy to use. Have a look at this short example:
24     \include simple.c
25
26     More examples can be found in the "examples" directory.
27 */
28 /** \addtogroup libftdi */
29 /* @{ */
30
31 #include <libusb.h>
32 #include <string.h>
33 #include <errno.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36
37 #include "ftdi.h"
38
39 #define ftdi_error_return(code, str) do {  \
40         ftdi->error_str = str;             \
41         return code;                       \
42    } while(0);
43
44 #define ftdi_error_return_free_device_list(code, str, devs) do {    \
45         libusb_free_device_list(devs,1);   \
46         ftdi->error_str = str;             \
47         return code;                       \
48    } while(0);
49
50
51 /**
52     Internal function to close usb device pointer.
53     Sets ftdi->usb_dev to NULL.
54     \internal
55
56     \param ftdi pointer to ftdi_context
57
58     \retval none
59 */
60 static void ftdi_usb_close_internal (struct ftdi_context *ftdi)
61 {
62     if (ftdi && ftdi->usb_dev)
63     {
64         libusb_close (ftdi->usb_dev);
65         ftdi->usb_dev = NULL;
66     }
67 }
68
69 /**
70     Initializes a ftdi_context.
71
72     \param ftdi pointer to ftdi_context
73
74     \retval  0: all fine
75     \retval -1: couldn't allocate read buffer
76     \retval -2: couldn't allocate struct  buffer
77     \retval -3: libusb_init() failed
78
79     \remark This should be called before all functions
80 */
81 int ftdi_init(struct ftdi_context *ftdi)
82 {
83     struct ftdi_eeprom* eeprom = (struct ftdi_eeprom *)malloc(sizeof(struct ftdi_eeprom));
84     ftdi->usb_ctx = NULL;
85     ftdi->usb_dev = NULL;
86     ftdi->usb_read_timeout = 5000;
87     ftdi->usb_write_timeout = 5000;
88
89     ftdi->type = TYPE_BM;    /* chip type */
90     ftdi->baudrate = -1;
91     ftdi->bitbang_enabled = 0;  /* 0: normal mode 1: any of the bitbang modes enabled */
92
93     ftdi->readbuffer = NULL;
94     ftdi->readbuffer_offset = 0;
95     ftdi->readbuffer_remaining = 0;
96     ftdi->writebuffer_chunksize = 4096;
97     ftdi->max_packet_size = 0;
98     ftdi->error_str = NULL;
99     ftdi->module_detach_mode = AUTO_DETACH_SIO_MODULE;
100
101     if (libusb_init(&ftdi->usb_ctx) < 0)
102         ftdi_error_return(-3, "libusb_init() failed");
103
104     ftdi_set_interface(ftdi, INTERFACE_ANY);
105     ftdi->bitbang_mode = 1; /* when bitbang is enabled this holds the number of the mode  */
106
107     if (eeprom == 0)
108         ftdi_error_return(-2, "Can't malloc struct ftdi_eeprom");
109     memset(eeprom, 0, sizeof(struct ftdi_eeprom));
110     ftdi->eeprom = eeprom;
111
112     /* All fine. Now allocate the readbuffer */
113     return ftdi_read_data_set_chunksize(ftdi, 4096);
114 }
115
116 /**
117     Allocate and initialize a new ftdi_context
118
119     \return a pointer to a new ftdi_context, or NULL on failure
120 */
121 struct ftdi_context *ftdi_new(void)
122 {
123     struct ftdi_context * ftdi = (struct ftdi_context *)malloc(sizeof(struct ftdi_context));
124
125     if (ftdi == NULL)
126     {
127         return NULL;
128     }
129
130     if (ftdi_init(ftdi) != 0)
131     {
132         free(ftdi);
133         return NULL;
134     }
135
136     return ftdi;
137 }
138
139 /**
140     Open selected channels on a chip, otherwise use first channel.
141
142     \param ftdi pointer to ftdi_context
143     \param interface Interface to use for FT2232C/2232H/4232H chips.
144
145     \retval  0: all fine
146     \retval -1: unknown interface
147     \retval -2: USB device unavailable
148 */
149 int ftdi_set_interface(struct ftdi_context *ftdi, enum ftdi_interface interface)
150 {
151     if (ftdi == NULL)
152         ftdi_error_return(-2, "USB device unavailable");
153
154     switch (interface)
155     {
156         case INTERFACE_ANY:
157         case INTERFACE_A:
158             ftdi->interface = 0;
159             ftdi->index     = INTERFACE_A;
160             ftdi->in_ep     = 0x02;
161             ftdi->out_ep    = 0x81;
162             break;
163         case INTERFACE_B:
164             ftdi->interface = 1;
165             ftdi->index     = INTERFACE_B;
166             ftdi->in_ep     = 0x04;
167             ftdi->out_ep    = 0x83;
168             break;
169         case INTERFACE_C:
170             ftdi->interface = 2;
171             ftdi->index     = INTERFACE_C;
172             ftdi->in_ep     = 0x06;
173             ftdi->out_ep    = 0x85;
174             break;
175         case INTERFACE_D:
176             ftdi->interface = 3;
177             ftdi->index     = INTERFACE_D;
178             ftdi->in_ep     = 0x08;
179             ftdi->out_ep    = 0x87;
180             break;
181         default:
182             ftdi_error_return(-1, "Unknown interface");
183     }
184     return 0;
185 }
186
187 /**
188     Deinitializes a ftdi_context.
189
190     \param ftdi pointer to ftdi_context
191 */
192 void ftdi_deinit(struct ftdi_context *ftdi)
193 {
194     if (ftdi == NULL)
195         return;
196
197     ftdi_usb_close_internal (ftdi);
198
199     if (ftdi->readbuffer != NULL)
200     {
201         free(ftdi->readbuffer);
202         ftdi->readbuffer = NULL;
203     }
204
205     if (ftdi->eeprom != NULL)
206     {
207         if (ftdi->eeprom->manufacturer != 0)
208         {
209             free(ftdi->eeprom->manufacturer);
210             ftdi->eeprom->manufacturer = 0;
211         }
212         if (ftdi->eeprom->product != 0)
213         {
214             free(ftdi->eeprom->product);
215             ftdi->eeprom->product = 0;
216         }
217         if (ftdi->eeprom->serial != 0)
218         {
219             free(ftdi->eeprom->serial);
220             ftdi->eeprom->serial = 0;
221         }
222         free(ftdi->eeprom);
223         ftdi->eeprom = NULL;
224     }
225
226     if (ftdi->usb_ctx)
227     {
228         libusb_exit(ftdi->usb_ctx);
229         ftdi->usb_ctx = NULL;
230     }
231 }
232
233 /**
234     Deinitialize and free an ftdi_context.
235
236     \param ftdi pointer to ftdi_context
237 */
238 void ftdi_free(struct ftdi_context *ftdi)
239 {
240     ftdi_deinit(ftdi);
241     free(ftdi);
242 }
243
244 /**
245     Use an already open libusb device.
246
247     \param ftdi pointer to ftdi_context
248     \param usb libusb libusb_device_handle to use
249 */
250 void ftdi_set_usbdev (struct ftdi_context *ftdi, libusb_device_handle *usb)
251 {
252     if (ftdi == NULL)
253         return;
254
255     ftdi->usb_dev = usb;
256 }
257
258
259 /**
260     Finds all ftdi devices with given VID:PID on the usb bus. Creates a new
261     ftdi_device_list which needs to be deallocated by ftdi_list_free() after
262     use.  With VID:PID 0:0, search for the default devices
263     (0x403:0x6001, 0x403:0x6010, 0x403:0x6011, 0x403:0x6014) 
264
265     \param ftdi pointer to ftdi_context
266     \param devlist Pointer where to store list of found devices
267     \param vendor Vendor ID to search for
268     \param product Product ID to search for
269
270     \retval >0: number of devices found
271     \retval -3: out of memory
272     \retval -5: libusb_get_device_list() failed
273     \retval -6: libusb_get_device_descriptor() failed
274 */
275 int ftdi_usb_find_all(struct ftdi_context *ftdi, struct ftdi_device_list **devlist, int vendor, int product)
276 {
277     struct ftdi_device_list **curdev;
278     libusb_device *dev;
279     libusb_device **devs;
280     int count = 0;
281     int i = 0;
282
283     if (libusb_get_device_list(ftdi->usb_ctx, &devs) < 0)
284         ftdi_error_return(-5, "libusb_get_device_list() failed");
285
286     curdev = devlist;
287     *curdev = NULL;
288
289     while ((dev = devs[i++]) != NULL)
290     {
291         struct libusb_device_descriptor desc;
292
293         if (libusb_get_device_descriptor(dev, &desc) < 0)
294             ftdi_error_return_free_device_list(-6, "libusb_get_device_descriptor() failed", devs);
295
296         if ((vendor != 0 && product != 0 && desc.idVendor == vendor && desc.idProduct == product) ||
297             ((desc.idVendor == 0x403) && (desc.idProduct == 0x6001 || desc.idProduct == 0x6010
298                                           || desc.idProduct == 0x6011 || desc.idProduct == 0x6014)))
299         {
300             *curdev = (struct ftdi_device_list*)malloc(sizeof(struct ftdi_device_list));
301             if (!*curdev)
302                 ftdi_error_return_free_device_list(-3, "out of memory", devs);
303
304             (*curdev)->next = NULL;
305             (*curdev)->dev = dev;
306             libusb_ref_device(dev);
307             curdev = &(*curdev)->next;
308             count++;
309         }
310     }
311     libusb_free_device_list(devs,1);
312     return count;
313 }
314
315 /**
316     Frees a usb device list.
317
318     \param devlist USB device list created by ftdi_usb_find_all()
319 */
320 void ftdi_list_free(struct ftdi_device_list **devlist)
321 {
322     struct ftdi_device_list *curdev, *next;
323
324     for (curdev = *devlist; curdev != NULL;)
325     {
326         next = curdev->next;
327         libusb_unref_device(curdev->dev);
328         free(curdev);
329         curdev = next;
330     }
331
332     *devlist = NULL;
333 }
334
335 /**
336     Frees a usb device list.
337
338     \param devlist USB device list created by ftdi_usb_find_all()
339 */
340 void ftdi_list_free2(struct ftdi_device_list *devlist)
341 {
342     ftdi_list_free(&devlist);
343 }
344
345 /**
346     Return device ID strings from the usb device.
347
348     The parameters manufacturer, description and serial may be NULL
349     or pointer to buffers to store the fetched strings.
350
351     \note Use this function only in combination with ftdi_usb_find_all()
352           as it closes the internal "usb_dev" after use.
353
354     \param ftdi pointer to ftdi_context
355     \param dev libusb usb_dev to use
356     \param manufacturer Store manufacturer string here if not NULL
357     \param mnf_len Buffer size of manufacturer string
358     \param description Store product description string here if not NULL
359     \param desc_len Buffer size of product description string
360     \param serial Store serial string here if not NULL
361     \param serial_len Buffer size of serial string
362
363     \retval   0: all fine
364     \retval  -1: wrong arguments
365     \retval  -4: unable to open device
366     \retval  -7: get product manufacturer failed
367     \retval  -8: get product description failed
368     \retval  -9: get serial number failed
369     \retval -11: libusb_get_device_descriptor() failed
370 */
371 int ftdi_usb_get_strings(struct ftdi_context * ftdi, struct libusb_device * dev,
372                          char * manufacturer, int mnf_len, char * description, int desc_len, char * serial, int serial_len)
373 {
374     struct libusb_device_descriptor desc;
375
376     if ((ftdi==NULL) || (dev==NULL))
377         return -1;
378
379     if (libusb_open(dev, &ftdi->usb_dev) < 0)
380         ftdi_error_return(-4, "libusb_open() failed");
381
382     if (libusb_get_device_descriptor(dev, &desc) < 0)
383         ftdi_error_return(-11, "libusb_get_device_descriptor() failed");
384
385     if (manufacturer != NULL)
386     {
387         if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iManufacturer, (unsigned char *)manufacturer, mnf_len) < 0)
388         {
389             ftdi_usb_close_internal (ftdi);
390             ftdi_error_return(-7, "libusb_get_string_descriptor_ascii() failed");
391         }
392     }
393
394     if (description != NULL)
395     {
396         if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iProduct, (unsigned char *)description, desc_len) < 0)
397         {
398             ftdi_usb_close_internal (ftdi);
399             ftdi_error_return(-8, "libusb_get_string_descriptor_ascii() failed");
400         }
401     }
402
403     if (serial != NULL)
404     {
405         if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iSerialNumber, (unsigned char *)serial, serial_len) < 0)
406         {
407             ftdi_usb_close_internal (ftdi);
408             ftdi_error_return(-9, "libusb_get_string_descriptor_ascii() failed");
409         }
410     }
411
412     ftdi_usb_close_internal (ftdi);
413
414     return 0;
415 }
416
417 /**
418  * Internal function to determine the maximum packet size.
419  * \param ftdi pointer to ftdi_context
420  * \param dev libusb usb_dev to use
421  * \retval Maximum packet size for this device
422  */
423 static unsigned int _ftdi_determine_max_packet_size(struct ftdi_context *ftdi, libusb_device *dev)
424 {
425     struct libusb_device_descriptor desc;
426     struct libusb_config_descriptor *config0;
427     unsigned int packet_size;
428
429     // Sanity check
430     if (ftdi == NULL || dev == NULL)
431         return 64;
432
433     // Determine maximum packet size. Init with default value.
434     // New hi-speed devices from FTDI use a packet size of 512 bytes
435     // but could be connected to a normal speed USB hub -> 64 bytes packet size.
436     if (ftdi->type == TYPE_2232H || ftdi->type == TYPE_4232H || ftdi->type == TYPE_232H )
437         packet_size = 512;
438     else
439         packet_size = 64;
440
441     if (libusb_get_device_descriptor(dev, &desc) < 0)
442         return packet_size;
443
444     if (libusb_get_config_descriptor(dev, 0, &config0) < 0)
445         return packet_size;
446
447     if (desc.bNumConfigurations > 0)
448     {
449         if (ftdi->interface < config0->bNumInterfaces)
450         {
451             struct libusb_interface interface = config0->interface[ftdi->interface];
452             if (interface.num_altsetting > 0)
453             {
454                 struct libusb_interface_descriptor descriptor = interface.altsetting[0];
455                 if (descriptor.bNumEndpoints > 0)
456                 {
457                     packet_size = descriptor.endpoint[0].wMaxPacketSize;
458                 }
459             }
460         }
461     }
462
463     libusb_free_config_descriptor (config0);
464     return packet_size;
465 }
466
467 /**
468     Opens a ftdi device given by an usb_device.
469
470     \param ftdi pointer to ftdi_context
471     \param dev libusb usb_dev to use
472
473     \retval  0: all fine
474     \retval -3: unable to config device
475     \retval -4: unable to open device
476     \retval -5: unable to claim device
477     \retval -6: reset failed
478     \retval -7: set baudrate failed
479     \retval -8: ftdi context invalid
480     \retval -9: libusb_get_device_descriptor() failed
481     \retval -10: libusb_get_config_descriptor() failed
482     \retval -11: libusb_detach_kernel_driver() failed
483     \retval -12: libusb_get_configuration() failed
484 */
485 int ftdi_usb_open_dev(struct ftdi_context *ftdi, libusb_device *dev)
486 {
487     struct libusb_device_descriptor desc;
488     struct libusb_config_descriptor *config0;
489     int cfg, cfg0, detach_errno = 0;
490
491     if (ftdi == NULL)
492         ftdi_error_return(-8, "ftdi context invalid");
493
494     if (libusb_open(dev, &ftdi->usb_dev) < 0)
495         ftdi_error_return(-4, "libusb_open() failed");
496
497     if (libusb_get_device_descriptor(dev, &desc) < 0)
498         ftdi_error_return(-9, "libusb_get_device_descriptor() failed");
499
500     if (libusb_get_config_descriptor(dev, 0, &config0) < 0)
501         ftdi_error_return(-10, "libusb_get_config_descriptor() failed");
502     cfg0 = config0->bConfigurationValue;
503     libusb_free_config_descriptor (config0);
504
505     // Try to detach ftdi_sio kernel module.
506     //
507     // The return code is kept in a separate variable and only parsed
508     // if usb_set_configuration() or usb_claim_interface() fails as the
509     // detach operation might be denied and everything still works fine.
510     // Likely scenario is a static ftdi_sio kernel module.
511     if (ftdi->module_detach_mode == AUTO_DETACH_SIO_MODULE)
512     {
513         if (libusb_detach_kernel_driver(ftdi->usb_dev, ftdi->interface) !=0)
514             detach_errno = errno;
515     }
516
517     if (libusb_get_configuration (ftdi->usb_dev, &cfg) < 0)
518         ftdi_error_return(-12, "libusb_get_configuration () failed");
519     // set configuration (needed especially for windows)
520     // tolerate EBUSY: one device with one configuration, but two interfaces
521     //    and libftdi sessions to both interfaces (e.g. FT2232)
522     if (desc.bNumConfigurations > 0 && cfg != cfg0)
523     {
524         if (libusb_set_configuration(ftdi->usb_dev, cfg0) < 0)
525         {
526             ftdi_usb_close_internal (ftdi);
527             if (detach_errno == EPERM)
528             {
529                 ftdi_error_return(-8, "inappropriate permissions on device!");
530             }
531             else
532             {
533                 ftdi_error_return(-3, "unable to set usb configuration. Make sure the default FTDI driver is not in use");
534             }
535         }
536     }
537
538     if (libusb_claim_interface(ftdi->usb_dev, ftdi->interface) < 0)
539     {
540         ftdi_usb_close_internal (ftdi);
541         if (detach_errno == EPERM)
542         {
543             ftdi_error_return(-8, "inappropriate permissions on device!");
544         }
545         else
546         {
547             ftdi_error_return(-5, "unable to claim usb device. Make sure the default FTDI driver is not in use");
548         }
549     }
550
551     if (ftdi_usb_reset (ftdi) != 0)
552     {
553         ftdi_usb_close_internal (ftdi);
554         ftdi_error_return(-6, "ftdi_usb_reset failed");
555     }
556
557     // Try to guess chip type
558     // Bug in the BM type chips: bcdDevice is 0x200 for serial == 0
559     if (desc.bcdDevice == 0x400 || (desc.bcdDevice == 0x200
560                                     && desc.iSerialNumber == 0))
561         ftdi->type = TYPE_BM;
562     else if (desc.bcdDevice == 0x200)
563         ftdi->type = TYPE_AM;
564     else if (desc.bcdDevice == 0x500)
565         ftdi->type = TYPE_2232C;
566     else if (desc.bcdDevice == 0x600)
567         ftdi->type = TYPE_R;
568     else if (desc.bcdDevice == 0x700)
569         ftdi->type = TYPE_2232H;
570     else if (desc.bcdDevice == 0x800)
571         ftdi->type = TYPE_4232H;
572     else if (desc.bcdDevice == 0x900)
573         ftdi->type = TYPE_232H;
574
575     // Determine maximum packet size
576     ftdi->max_packet_size = _ftdi_determine_max_packet_size(ftdi, dev);
577
578     if (ftdi_set_baudrate (ftdi, 9600) != 0)
579     {
580         ftdi_usb_close_internal (ftdi);
581         ftdi_error_return(-7, "set baudrate failed");
582     }
583
584     ftdi_error_return(0, "all fine");
585 }
586
587 /**
588     Opens the first device with a given vendor and product ids.
589
590     \param ftdi pointer to ftdi_context
591     \param vendor Vendor ID
592     \param product Product ID
593
594     \retval same as ftdi_usb_open_desc()
595 */
596 int ftdi_usb_open(struct ftdi_context *ftdi, int vendor, int product)
597 {
598     return ftdi_usb_open_desc(ftdi, vendor, product, NULL, NULL);
599 }
600
601 /**
602     Opens the first device with a given, vendor id, product id,
603     description and serial.
604
605     \param ftdi pointer to ftdi_context
606     \param vendor Vendor ID
607     \param product Product ID
608     \param description Description to search for. Use NULL if not needed.
609     \param serial Serial to search for. Use NULL if not needed.
610
611     \retval  0: all fine
612     \retval -3: usb device not found
613     \retval -4: unable to open device
614     \retval -5: unable to claim device
615     \retval -6: reset failed
616     \retval -7: set baudrate failed
617     \retval -8: get product description failed
618     \retval -9: get serial number failed
619     \retval -12: libusb_get_device_list() failed
620     \retval -13: libusb_get_device_descriptor() failed
621 */
622 int ftdi_usb_open_desc(struct ftdi_context *ftdi, int vendor, int product,
623                        const char* description, const char* serial)
624 {
625     return ftdi_usb_open_desc_index(ftdi,vendor,product,description,serial,0);
626 }
627
628 /**
629     Opens the index-th device with a given, vendor id, product id,
630     description and serial.
631
632     \param ftdi pointer to ftdi_context
633     \param vendor Vendor ID
634     \param product Product ID
635     \param description Description to search for. Use NULL if not needed.
636     \param serial Serial to search for. Use NULL if not needed.
637     \param index Number of matching device to open if there are more than one, starts with 0.
638
639     \retval  0: all fine
640     \retval -1: usb_find_busses() failed
641     \retval -2: usb_find_devices() failed
642     \retval -3: usb device not found
643     \retval -4: unable to open device
644     \retval -5: unable to claim device
645     \retval -6: reset failed
646     \retval -7: set baudrate failed
647     \retval -8: get product description failed
648     \retval -9: get serial number failed
649     \retval -10: unable to close device
650     \retval -11: ftdi context invalid
651 */
652 int ftdi_usb_open_desc_index(struct ftdi_context *ftdi, int vendor, int product,
653                              const char* description, const char* serial, unsigned int index)
654 {
655     libusb_device *dev;
656     libusb_device **devs;
657     char string[256];
658     int i = 0;
659
660     if (ftdi == NULL)
661         ftdi_error_return(-11, "ftdi context invalid");
662
663     if (libusb_get_device_list(ftdi->usb_ctx, &devs) < 0)
664         ftdi_error_return(-12, "libusb_get_device_list() failed");
665
666     while ((dev = devs[i++]) != NULL)
667     {
668         struct libusb_device_descriptor desc;
669         int res;
670
671         if (libusb_get_device_descriptor(dev, &desc) < 0)
672             ftdi_error_return_free_device_list(-13, "libusb_get_device_descriptor() failed", devs);
673
674         if (desc.idVendor == vendor && desc.idProduct == product)
675         {
676             if (libusb_open(dev, &ftdi->usb_dev) < 0)
677                 ftdi_error_return_free_device_list(-4, "usb_open() failed", devs);
678
679             if (description != NULL)
680             {
681                 if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iProduct, (unsigned char *)string, sizeof(string)) < 0)
682                 {
683                     ftdi_usb_close_internal (ftdi);
684                     ftdi_error_return_free_device_list(-8, "unable to fetch product description", devs);
685                 }
686                 if (strncmp(string, description, sizeof(string)) != 0)
687                 {
688                     ftdi_usb_close_internal (ftdi);
689                     continue;
690                 }
691             }
692             if (serial != NULL)
693             {
694                 if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iSerialNumber, (unsigned char *)string, sizeof(string)) < 0)
695                 {
696                     ftdi_usb_close_internal (ftdi);
697                     ftdi_error_return_free_device_list(-9, "unable to fetch serial number", devs);
698                 }
699                 if (strncmp(string, serial, sizeof(string)) != 0)
700                 {
701                     ftdi_usb_close_internal (ftdi);
702                     continue;
703                 }
704             }
705
706             ftdi_usb_close_internal (ftdi);
707
708             if (index > 0)
709             {
710                 index--;
711                 continue;
712             }
713
714             res = ftdi_usb_open_dev(ftdi, dev);
715             libusb_free_device_list(devs,1);
716             return res;
717         }
718     }
719
720     // device not found
721     ftdi_error_return_free_device_list(-3, "device not found", devs);
722 }
723
724 /**
725     Opens the ftdi-device described by a description-string.
726     Intended to be used for parsing a device-description given as commandline argument.
727
728     \param ftdi pointer to ftdi_context
729     \param description NULL-terminated description-string, using this format:
730         \li <tt>d:\<devicenode></tt> path of bus and device-node (e.g. "003/001") within usb device tree (usually at /proc/bus/usb/)
731         \li <tt>i:\<vendor>:\<product></tt> first device with given vendor and product id, ids can be decimal, octal (preceded by "0") or hex (preceded by "0x")
732         \li <tt>i:\<vendor>:\<product>:\<index></tt> as above with index being the number of the device (starting with 0) if there are more than one
733         \li <tt>s:\<vendor>:\<product>:\<serial></tt> first device with given vendor id, product id and serial string
734
735     \note The description format may be extended in later versions.
736
737     \retval  0: all fine
738     \retval -2: libusb_get_device_list() failed
739     \retval -3: usb device not found
740     \retval -4: unable to open device
741     \retval -5: unable to claim device
742     \retval -6: reset failed
743     \retval -7: set baudrate failed
744     \retval -8: get product description failed
745     \retval -9: get serial number failed
746     \retval -10: unable to close device
747     \retval -11: illegal description format
748     \retval -12: ftdi context invalid
749 */
750 int ftdi_usb_open_string(struct ftdi_context *ftdi, const char* description)
751 {
752     if (ftdi == NULL)
753         ftdi_error_return(-12, "ftdi context invalid");
754
755     if (description[0] == 0 || description[1] != ':')
756         ftdi_error_return(-11, "illegal description format");
757
758     if (description[0] == 'd')
759     {
760         libusb_device *dev;
761         libusb_device **devs;
762         unsigned int bus_number, device_address;
763         int i = 0;
764
765         if (libusb_get_device_list(ftdi->usb_ctx, &devs) < 0)
766             ftdi_error_return(-2, "libusb_get_device_list() failed");
767
768         /* XXX: This doesn't handle symlinks/odd paths/etc... */
769         if (sscanf (description + 2, "%u/%u", &bus_number, &device_address) != 2)
770             ftdi_error_return_free_device_list(-11, "illegal description format", devs);
771
772         while ((dev = devs[i++]) != NULL)
773         {
774             int ret;
775             if (bus_number == libusb_get_bus_number (dev)
776                     && device_address == libusb_get_device_address (dev))
777             {
778                 ret = ftdi_usb_open_dev(ftdi, dev);
779                 libusb_free_device_list(devs,1);
780                 return ret;
781             }
782         }
783
784         // device not found
785         ftdi_error_return_free_device_list(-3, "device not found", devs);
786     }
787     else if (description[0] == 'i' || description[0] == 's')
788     {
789         unsigned int vendor;
790         unsigned int product;
791         unsigned int index=0;
792         const char *serial=NULL;
793         const char *startp, *endp;
794
795         errno=0;
796         startp=description+2;
797         vendor=strtoul((char*)startp,(char**)&endp,0);
798         if (*endp != ':' || endp == startp || errno != 0)
799             ftdi_error_return(-11, "illegal description format");
800
801         startp=endp+1;
802         product=strtoul((char*)startp,(char**)&endp,0);
803         if (endp == startp || errno != 0)
804             ftdi_error_return(-11, "illegal description format");
805
806         if (description[0] == 'i' && *endp != 0)
807         {
808             /* optional index field in i-mode */
809             if (*endp != ':')
810                 ftdi_error_return(-11, "illegal description format");
811
812             startp=endp+1;
813             index=strtoul((char*)startp,(char**)&endp,0);
814             if (*endp != 0 || endp == startp || errno != 0)
815                 ftdi_error_return(-11, "illegal description format");
816         }
817         if (description[0] == 's')
818         {
819             if (*endp != ':')
820                 ftdi_error_return(-11, "illegal description format");
821
822             /* rest of the description is the serial */
823             serial=endp+1;
824         }
825
826         return ftdi_usb_open_desc_index(ftdi, vendor, product, NULL, serial, index);
827     }
828     else
829     {
830         ftdi_error_return(-11, "illegal description format");
831     }
832 }
833
834 /**
835     Resets the ftdi device.
836
837     \param ftdi pointer to ftdi_context
838
839     \retval  0: all fine
840     \retval -1: FTDI reset failed
841     \retval -2: USB device unavailable
842 */
843 int ftdi_usb_reset(struct ftdi_context *ftdi)
844 {
845     if (ftdi == NULL || ftdi->usb_dev == NULL)
846         ftdi_error_return(-2, "USB device unavailable");
847
848     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
849                                 SIO_RESET_REQUEST, SIO_RESET_SIO,
850                                 ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
851         ftdi_error_return(-1,"FTDI reset failed");
852
853     // Invalidate data in the readbuffer
854     ftdi->readbuffer_offset = 0;
855     ftdi->readbuffer_remaining = 0;
856
857     return 0;
858 }
859
860 /**
861     Clears the read buffer on the chip and the internal read buffer.
862
863     \param ftdi pointer to ftdi_context
864
865     \retval  0: all fine
866     \retval -1: read buffer purge failed
867     \retval -2: USB device unavailable
868 */
869 int ftdi_usb_purge_rx_buffer(struct ftdi_context *ftdi)
870 {
871     if (ftdi == NULL || ftdi->usb_dev == NULL)
872         ftdi_error_return(-2, "USB device unavailable");
873
874     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
875                                 SIO_RESET_REQUEST, SIO_RESET_PURGE_RX,
876                                 ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
877         ftdi_error_return(-1, "FTDI purge of RX buffer failed");
878
879     // Invalidate data in the readbuffer
880     ftdi->readbuffer_offset = 0;
881     ftdi->readbuffer_remaining = 0;
882
883     return 0;
884 }
885
886 /**
887     Clears the write buffer on the chip.
888
889     \param ftdi pointer to ftdi_context
890
891     \retval  0: all fine
892     \retval -1: write buffer purge failed
893     \retval -2: USB device unavailable
894 */
895 int ftdi_usb_purge_tx_buffer(struct ftdi_context *ftdi)
896 {
897     if (ftdi == NULL || ftdi->usb_dev == NULL)
898         ftdi_error_return(-2, "USB device unavailable");
899
900     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
901                                 SIO_RESET_REQUEST, SIO_RESET_PURGE_TX,
902                                 ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
903         ftdi_error_return(-1, "FTDI purge of TX buffer failed");
904
905     return 0;
906 }
907
908 /**
909     Clears the buffers on the chip and the internal read buffer.
910
911     \param ftdi pointer to ftdi_context
912
913     \retval  0: all fine
914     \retval -1: read buffer purge failed
915     \retval -2: write buffer purge failed
916     \retval -3: USB device unavailable
917 */
918 int ftdi_usb_purge_buffers(struct ftdi_context *ftdi)
919 {
920     int result;
921
922     if (ftdi == NULL || ftdi->usb_dev == NULL)
923         ftdi_error_return(-3, "USB device unavailable");
924
925     result = ftdi_usb_purge_rx_buffer(ftdi);
926     if (result < 0)
927         return -1;
928
929     result = ftdi_usb_purge_tx_buffer(ftdi);
930     if (result < 0)
931         return -2;
932
933     return 0;
934 }
935
936
937
938 /**
939     Closes the ftdi device. Call ftdi_deinit() if you're cleaning up.
940
941     \param ftdi pointer to ftdi_context
942
943     \retval  0: all fine
944     \retval -1: usb_release failed
945     \retval -3: ftdi context invalid
946 */
947 int ftdi_usb_close(struct ftdi_context *ftdi)
948 {
949     int rtn = 0;
950
951     if (ftdi == NULL)
952         ftdi_error_return(-3, "ftdi context invalid");
953
954     if (ftdi->usb_dev != NULL)
955         if (libusb_release_interface(ftdi->usb_dev, ftdi->interface) < 0)
956             rtn = -1;
957
958     ftdi_usb_close_internal (ftdi);
959
960     return rtn;
961 }
962
963 /**
964     ftdi_convert_baudrate returns nearest supported baud rate to that requested.
965     Function is only used internally
966     \internal
967 */
968 static int ftdi_convert_baudrate(int baudrate, struct ftdi_context *ftdi,
969                                  unsigned short *value, unsigned short *index)
970 {
971     static const char am_adjust_up[8] = {0, 0, 0, 1, 0, 3, 2, 1};
972     static const char am_adjust_dn[8] = {0, 0, 0, 1, 0, 1, 2, 3};
973     static const char frac_code[8] = {0, 3, 2, 4, 1, 5, 6, 7};
974     int divisor, best_divisor, best_baud, best_baud_diff;
975     unsigned long encoded_divisor;
976     int i;
977
978     if (baudrate <= 0)
979     {
980         // Return error
981         return -1;
982     }
983
984     divisor = 24000000 / baudrate;
985
986     if (ftdi->type == TYPE_AM)
987     {
988         // Round down to supported fraction (AM only)
989         divisor -= am_adjust_dn[divisor & 7];
990     }
991
992     // Try this divisor and the one above it (because division rounds down)
993     best_divisor = 0;
994     best_baud = 0;
995     best_baud_diff = 0;
996     for (i = 0; i < 2; i++)
997     {
998         int try_divisor = divisor + i;
999         int baud_estimate;
1000         int baud_diff;
1001
1002         // Round up to supported divisor value
1003         if (try_divisor <= 8)
1004         {
1005             // Round up to minimum supported divisor
1006             try_divisor = 8;
1007         }
1008         else if (ftdi->type != TYPE_AM && try_divisor < 12)
1009         {
1010             // BM doesn't support divisors 9 through 11 inclusive
1011             try_divisor = 12;
1012         }
1013         else if (divisor < 16)
1014         {
1015             // AM doesn't support divisors 9 through 15 inclusive
1016             try_divisor = 16;
1017         }
1018         else
1019         {
1020             if (ftdi->type == TYPE_AM)
1021             {
1022                 // Round up to supported fraction (AM only)
1023                 try_divisor += am_adjust_up[try_divisor & 7];
1024                 if (try_divisor > 0x1FFF8)
1025                 {
1026                     // Round down to maximum supported divisor value (for AM)
1027                     try_divisor = 0x1FFF8;
1028                 }
1029             }
1030             else
1031             {
1032                 if (try_divisor > 0x1FFFF)
1033                 {
1034                     // Round down to maximum supported divisor value (for BM)
1035                     try_divisor = 0x1FFFF;
1036                 }
1037             }
1038         }
1039         // Get estimated baud rate (to nearest integer)
1040         baud_estimate = (24000000 + (try_divisor / 2)) / try_divisor;
1041         // Get absolute difference from requested baud rate
1042         if (baud_estimate < baudrate)
1043         {
1044             baud_diff = baudrate - baud_estimate;
1045         }
1046         else
1047         {
1048             baud_diff = baud_estimate - baudrate;
1049         }
1050         if (i == 0 || baud_diff < best_baud_diff)
1051         {
1052             // Closest to requested baud rate so far
1053             best_divisor = try_divisor;
1054             best_baud = baud_estimate;
1055             best_baud_diff = baud_diff;
1056             if (baud_diff == 0)
1057             {
1058                 // Spot on! No point trying
1059                 break;
1060             }
1061         }
1062     }
1063     // Encode the best divisor value
1064     encoded_divisor = (best_divisor >> 3) | (frac_code[best_divisor & 7] << 14);
1065     // Deal with special cases for encoded value
1066     if (encoded_divisor == 1)
1067     {
1068         encoded_divisor = 0;    // 3000000 baud
1069     }
1070     else if (encoded_divisor == 0x4001)
1071     {
1072         encoded_divisor = 1;    // 2000000 baud (BM only)
1073     }
1074     // Split into "value" and "index" values
1075     *value = (unsigned short)(encoded_divisor & 0xFFFF);
1076     if (ftdi->type == TYPE_2232C || ftdi->type == TYPE_2232H || ftdi->type == TYPE_4232H)
1077     {
1078         *index = (unsigned short)(encoded_divisor >> 8);
1079         *index &= 0xFF00;
1080         *index |= ftdi->index;
1081     }
1082     else
1083         *index = (unsigned short)(encoded_divisor >> 16);
1084
1085     // Return the nearest baud rate
1086     return best_baud;
1087 }
1088
1089 /**
1090     Sets the chip baud rate
1091
1092     \param ftdi pointer to ftdi_context
1093     \param baudrate baud rate to set
1094
1095     \retval  0: all fine
1096     \retval -1: invalid baudrate
1097     \retval -2: setting baudrate failed
1098     \retval -3: USB device unavailable
1099 */
1100 int ftdi_set_baudrate(struct ftdi_context *ftdi, int baudrate)
1101 {
1102     unsigned short value, index;
1103     int actual_baudrate;
1104
1105     if (ftdi == NULL || ftdi->usb_dev == NULL)
1106         ftdi_error_return(-3, "USB device unavailable");
1107
1108     if (ftdi->bitbang_enabled)
1109     {
1110         baudrate = baudrate*4;
1111     }
1112
1113     actual_baudrate = ftdi_convert_baudrate(baudrate, ftdi, &value, &index);
1114     if (actual_baudrate <= 0)
1115         ftdi_error_return (-1, "Silly baudrate <= 0.");
1116
1117     // Check within tolerance (about 5%)
1118     if ((actual_baudrate * 2 < baudrate /* Catch overflows */ )
1119             || ((actual_baudrate < baudrate)
1120                 ? (actual_baudrate * 21 < baudrate * 20)
1121                 : (baudrate * 21 < actual_baudrate * 20)))
1122         ftdi_error_return (-1, "Unsupported baudrate. Note: bitbang baudrates are automatically multiplied by 4");
1123
1124     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1125                                 SIO_SET_BAUDRATE_REQUEST, value,
1126                                 index, NULL, 0, ftdi->usb_write_timeout) < 0)
1127         ftdi_error_return (-2, "Setting new baudrate failed");
1128
1129     ftdi->baudrate = baudrate;
1130     return 0;
1131 }
1132
1133 /**
1134     Set (RS232) line characteristics.
1135     The break type can only be set via ftdi_set_line_property2()
1136     and defaults to "off".
1137
1138     \param ftdi pointer to ftdi_context
1139     \param bits Number of bits
1140     \param sbit Number of stop bits
1141     \param parity Parity mode
1142
1143     \retval  0: all fine
1144     \retval -1: Setting line property failed
1145 */
1146 int ftdi_set_line_property(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
1147                            enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity)
1148 {
1149     return ftdi_set_line_property2(ftdi, bits, sbit, parity, BREAK_OFF);
1150 }
1151
1152 /**
1153     Set (RS232) line characteristics
1154
1155     \param ftdi pointer to ftdi_context
1156     \param bits Number of bits
1157     \param sbit Number of stop bits
1158     \param parity Parity mode
1159     \param break_type Break type
1160
1161     \retval  0: all fine
1162     \retval -1: Setting line property failed
1163     \retval -2: USB device unavailable
1164 */
1165 int ftdi_set_line_property2(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
1166                             enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity,
1167                             enum ftdi_break_type break_type)
1168 {
1169     unsigned short value = bits;
1170
1171     if (ftdi == NULL || ftdi->usb_dev == NULL)
1172         ftdi_error_return(-2, "USB device unavailable");
1173
1174     switch (parity)
1175     {
1176         case NONE:
1177             value |= (0x00 << 8);
1178             break;
1179         case ODD:
1180             value |= (0x01 << 8);
1181             break;
1182         case EVEN:
1183             value |= (0x02 << 8);
1184             break;
1185         case MARK:
1186             value |= (0x03 << 8);
1187             break;
1188         case SPACE:
1189             value |= (0x04 << 8);
1190             break;
1191     }
1192
1193     switch (sbit)
1194     {
1195         case STOP_BIT_1:
1196             value |= (0x00 << 11);
1197             break;
1198         case STOP_BIT_15:
1199             value |= (0x01 << 11);
1200             break;
1201         case STOP_BIT_2:
1202             value |= (0x02 << 11);
1203             break;
1204     }
1205
1206     switch (break_type)
1207     {
1208         case BREAK_OFF:
1209             value |= (0x00 << 14);
1210             break;
1211         case BREAK_ON:
1212             value |= (0x01 << 14);
1213             break;
1214     }
1215
1216     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1217                                 SIO_SET_DATA_REQUEST, value,
1218                                 ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
1219         ftdi_error_return (-1, "Setting new line property failed");
1220
1221     return 0;
1222 }
1223
1224 /**
1225     Writes data in chunks (see ftdi_write_data_set_chunksize()) to the chip
1226
1227     \param ftdi pointer to ftdi_context
1228     \param buf Buffer with the data
1229     \param size Size of the buffer
1230
1231     \retval -666: USB device unavailable
1232     \retval <0: error code from usb_bulk_write()
1233     \retval >0: number of bytes written
1234 */
1235 int ftdi_write_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
1236 {
1237     int offset = 0;
1238     int actual_length;
1239
1240     if (ftdi == NULL || ftdi->usb_dev == NULL)
1241         ftdi_error_return(-666, "USB device unavailable");
1242
1243     while (offset < size)
1244     {
1245         int write_size = ftdi->writebuffer_chunksize;
1246
1247         if (offset+write_size > size)
1248             write_size = size-offset;
1249
1250         if (libusb_bulk_transfer(ftdi->usb_dev, ftdi->in_ep, buf+offset, write_size, &actual_length, ftdi->usb_write_timeout) < 0)
1251             ftdi_error_return(-1, "usb bulk write failed");
1252
1253         offset += actual_length;
1254     }
1255
1256     return offset;
1257 }
1258
1259 static void ftdi_read_data_cb(struct libusb_transfer *transfer)
1260 {
1261     struct ftdi_transfer_control *tc = (struct ftdi_transfer_control *) transfer->user_data;
1262     struct ftdi_context *ftdi = tc->ftdi;
1263     int packet_size, actual_length, num_of_chunks, chunk_remains, i, ret;
1264
1265     packet_size = ftdi->max_packet_size;
1266
1267     actual_length = transfer->actual_length;
1268
1269     if (actual_length > 2)
1270     {
1271         // skip FTDI status bytes.
1272         // Maybe stored in the future to enable modem use
1273         num_of_chunks = actual_length / packet_size;
1274         chunk_remains = actual_length % packet_size;
1275         //printf("actual_length = %X, num_of_chunks = %X, chunk_remains = %X, readbuffer_offset = %X\n", actual_length, num_of_chunks, chunk_remains, ftdi->readbuffer_offset);
1276
1277         ftdi->readbuffer_offset += 2;
1278         actual_length -= 2;
1279
1280         if (actual_length > packet_size - 2)
1281         {
1282             for (i = 1; i < num_of_chunks; i++)
1283                 memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1284                          ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1285                          packet_size - 2);
1286             if (chunk_remains > 2)
1287             {
1288                 memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1289                          ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1290                          chunk_remains-2);
1291                 actual_length -= 2*num_of_chunks;
1292             }
1293             else
1294                 actual_length -= 2*(num_of_chunks-1)+chunk_remains;
1295         }
1296
1297         if (actual_length > 0)
1298         {
1299             // data still fits in buf?
1300             if (tc->offset + actual_length <= tc->size)
1301             {
1302                 memcpy (tc->buf + tc->offset, ftdi->readbuffer + ftdi->readbuffer_offset, actual_length);
1303                 //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
1304                 tc->offset += actual_length;
1305
1306                 ftdi->readbuffer_offset = 0;
1307                 ftdi->readbuffer_remaining = 0;
1308
1309                 /* Did we read exactly the right amount of bytes? */
1310                 if (tc->offset == tc->size)
1311                 {
1312                     //printf("read_data exact rem %d offset %d\n",
1313                     //ftdi->readbuffer_remaining, offset);
1314                     tc->completed = 1;
1315                     return;
1316                 }
1317             }
1318             else
1319             {
1320                 // only copy part of the data or size <= readbuffer_chunksize
1321                 int part_size = tc->size - tc->offset;
1322                 memcpy (tc->buf + tc->offset, ftdi->readbuffer + ftdi->readbuffer_offset, part_size);
1323                 tc->offset += part_size;
1324
1325                 ftdi->readbuffer_offset += part_size;
1326                 ftdi->readbuffer_remaining = actual_length - part_size;
1327
1328                 /* printf("Returning part: %d - size: %d - offset: %d - actual_length: %d - remaining: %d\n",
1329                 part_size, size, offset, actual_length, ftdi->readbuffer_remaining); */
1330                 tc->completed = 1;
1331                 return;
1332             }
1333         }
1334     }
1335     ret = libusb_submit_transfer (transfer);
1336     if (ret < 0)
1337         tc->completed = 1;
1338 }
1339
1340
1341 static void ftdi_write_data_cb(struct libusb_transfer *transfer)
1342 {
1343     struct ftdi_transfer_control *tc = (struct ftdi_transfer_control *) transfer->user_data;
1344     struct ftdi_context *ftdi = tc->ftdi;
1345
1346     tc->offset += transfer->actual_length;
1347
1348     if (tc->offset == tc->size)
1349     {
1350         tc->completed = 1;
1351     }
1352     else
1353     {
1354         int write_size = ftdi->writebuffer_chunksize;
1355         int ret;
1356
1357         if (tc->offset + write_size > tc->size)
1358             write_size = tc->size - tc->offset;
1359
1360         transfer->length = write_size;
1361         transfer->buffer = tc->buf + tc->offset;
1362         ret = libusb_submit_transfer (transfer);
1363         if (ret < 0)
1364             tc->completed = 1;
1365     }
1366 }
1367
1368
1369 /**
1370     Writes data to the chip. Does not wait for completion of the transfer
1371     nor does it make sure that the transfer was successful.
1372
1373     Use libusb 1.0 asynchronous API.
1374
1375     \param ftdi pointer to ftdi_context
1376     \param buf Buffer with the data
1377     \param size Size of the buffer
1378
1379     \retval NULL: Some error happens when submit transfer
1380     \retval !NULL: Pointer to a ftdi_transfer_control
1381 */
1382
1383 struct ftdi_transfer_control *ftdi_write_data_submit(struct ftdi_context *ftdi, unsigned char *buf, int size)
1384 {
1385     struct ftdi_transfer_control *tc;
1386     struct libusb_transfer *transfer;
1387     int write_size, ret;
1388
1389     if (ftdi == NULL || ftdi->usb_dev == NULL)
1390         return NULL;
1391
1392     tc = (struct ftdi_transfer_control *) malloc (sizeof (*tc));
1393     if (!tc)
1394         return NULL;
1395
1396     transfer = libusb_alloc_transfer(0);
1397     if (!transfer)
1398     {
1399         free(tc);
1400         return NULL;
1401     }
1402
1403     tc->ftdi = ftdi;
1404     tc->completed = 0;
1405     tc->buf = buf;
1406     tc->size = size;
1407     tc->offset = 0;
1408
1409     if (size < ftdi->writebuffer_chunksize)
1410         write_size = size;
1411     else
1412         write_size = ftdi->writebuffer_chunksize;
1413
1414     libusb_fill_bulk_transfer(transfer, ftdi->usb_dev, ftdi->in_ep, buf,
1415                               write_size, ftdi_write_data_cb, tc,
1416                               ftdi->usb_write_timeout);
1417     transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
1418
1419     ret = libusb_submit_transfer(transfer);
1420     if (ret < 0)
1421     {
1422         libusb_free_transfer(transfer);
1423         free(tc);
1424         return NULL;
1425     }
1426     tc->transfer = transfer;
1427
1428     return tc;
1429 }
1430
1431 /**
1432     Reads data from the chip. Does not wait for completion of the transfer
1433     nor does it make sure that the transfer was successful.
1434
1435     Use libusb 1.0 asynchronous API.
1436
1437     \param ftdi pointer to ftdi_context
1438     \param buf Buffer with the data
1439     \param size Size of the buffer
1440
1441     \retval NULL: Some error happens when submit transfer
1442     \retval !NULL: Pointer to a ftdi_transfer_control
1443 */
1444
1445 struct ftdi_transfer_control *ftdi_read_data_submit(struct ftdi_context *ftdi, unsigned char *buf, int size)
1446 {
1447     struct ftdi_transfer_control *tc;
1448     struct libusb_transfer *transfer;
1449     int ret;
1450
1451     if (ftdi == NULL || ftdi->usb_dev == NULL)
1452         return NULL;
1453
1454     tc = (struct ftdi_transfer_control *) malloc (sizeof (*tc));
1455     if (!tc)
1456         return NULL;
1457
1458     tc->ftdi = ftdi;
1459     tc->buf = buf;
1460     tc->size = size;
1461
1462     if (size <= ftdi->readbuffer_remaining)
1463     {
1464         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);
1465
1466         // Fix offsets
1467         ftdi->readbuffer_remaining -= size;
1468         ftdi->readbuffer_offset += size;
1469
1470         /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */
1471
1472         tc->completed = 1;
1473         tc->offset = size;
1474         tc->transfer = NULL;
1475         return tc;
1476     }
1477
1478     tc->completed = 0;
1479     if (ftdi->readbuffer_remaining != 0)
1480     {
1481         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);
1482
1483         tc->offset = ftdi->readbuffer_remaining;
1484     }
1485     else
1486         tc->offset = 0;
1487
1488     transfer = libusb_alloc_transfer(0);
1489     if (!transfer)
1490     {
1491         free (tc);
1492         return NULL;
1493     }
1494
1495     ftdi->readbuffer_remaining = 0;
1496     ftdi->readbuffer_offset = 0;
1497
1498     libusb_fill_bulk_transfer(transfer, ftdi->usb_dev, ftdi->out_ep, ftdi->readbuffer, ftdi->readbuffer_chunksize, ftdi_read_data_cb, tc, ftdi->usb_read_timeout);
1499     transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
1500
1501     ret = libusb_submit_transfer(transfer);
1502     if (ret < 0)
1503     {
1504         libusb_free_transfer(transfer);
1505         free (tc);
1506         return NULL;
1507     }
1508     tc->transfer = transfer;
1509
1510     return tc;
1511 }
1512
1513 /**
1514     Wait for completion of the transfer.
1515
1516     Use libusb 1.0 asynchronous API.
1517
1518     \param tc pointer to ftdi_transfer_control
1519
1520     \retval < 0: Some error happens
1521     \retval >= 0: Data size transferred
1522 */
1523
1524 int ftdi_transfer_data_done(struct ftdi_transfer_control *tc)
1525 {
1526     int ret;
1527
1528     while (!tc->completed)
1529     {
1530         ret = libusb_handle_events(tc->ftdi->usb_ctx);
1531         if (ret < 0)
1532         {
1533             if (ret == LIBUSB_ERROR_INTERRUPTED)
1534                 continue;
1535             libusb_cancel_transfer(tc->transfer);
1536             while (!tc->completed)
1537                 if (libusb_handle_events(tc->ftdi->usb_ctx) < 0)
1538                     break;
1539             libusb_free_transfer(tc->transfer);
1540             free (tc);
1541             return ret;
1542         }
1543     }
1544
1545     ret = tc->offset;
1546     /**
1547      * tc->transfer could be NULL if "(size <= ftdi->readbuffer_remaining)"
1548      * at ftdi_read_data_submit(). Therefore, we need to check it here.
1549      **/
1550     if (tc->transfer)
1551     {
1552         if (tc->transfer->status != LIBUSB_TRANSFER_COMPLETED)
1553             ret = -1;
1554         libusb_free_transfer(tc->transfer);
1555     }
1556     free(tc);
1557     return ret;
1558 }
1559
1560 /**
1561     Configure write buffer chunk size.
1562     Default is 4096.
1563
1564     \param ftdi pointer to ftdi_context
1565     \param chunksize Chunk size
1566
1567     \retval 0: all fine
1568     \retval -1: ftdi context invalid
1569 */
1570 int ftdi_write_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
1571 {
1572     if (ftdi == NULL)
1573         ftdi_error_return(-1, "ftdi context invalid");
1574
1575     ftdi->writebuffer_chunksize = chunksize;
1576     return 0;
1577 }
1578
1579 /**
1580     Get write buffer chunk size.
1581
1582     \param ftdi pointer to ftdi_context
1583     \param chunksize Pointer to store chunk size in
1584
1585     \retval 0: all fine
1586     \retval -1: ftdi context invalid
1587 */
1588 int ftdi_write_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
1589 {
1590     if (ftdi == NULL)
1591         ftdi_error_return(-1, "ftdi context invalid");
1592
1593     *chunksize = ftdi->writebuffer_chunksize;
1594     return 0;
1595 }
1596
1597 /**
1598     Reads data in chunks (see ftdi_read_data_set_chunksize()) from the chip.
1599
1600     Automatically strips the two modem status bytes transfered during every read.
1601
1602     \param ftdi pointer to ftdi_context
1603     \param buf Buffer to store data in
1604     \param size Size of the buffer
1605
1606     \retval -666: USB device unavailable
1607     \retval <0: error code from libusb_bulk_transfer()
1608     \retval  0: no data was available
1609     \retval >0: number of bytes read
1610
1611 */
1612 int ftdi_read_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
1613 {
1614     int offset = 0, ret, i, num_of_chunks, chunk_remains;
1615     int packet_size = ftdi->max_packet_size;
1616     int actual_length = 1;
1617
1618     if (ftdi == NULL || ftdi->usb_dev == NULL)
1619         ftdi_error_return(-666, "USB device unavailable");
1620
1621     // Packet size sanity check (avoid division by zero)
1622     if (packet_size == 0)
1623         ftdi_error_return(-1, "max_packet_size is bogus (zero)");
1624
1625     // everything we want is still in the readbuffer?
1626     if (size <= ftdi->readbuffer_remaining)
1627     {
1628         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);
1629
1630         // Fix offsets
1631         ftdi->readbuffer_remaining -= size;
1632         ftdi->readbuffer_offset += size;
1633
1634         /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */
1635
1636         return size;
1637     }
1638     // something still in the readbuffer, but not enough to satisfy 'size'?
1639     if (ftdi->readbuffer_remaining != 0)
1640     {
1641         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);
1642
1643         // Fix offset
1644         offset += ftdi->readbuffer_remaining;
1645     }
1646     // do the actual USB read
1647     while (offset < size && actual_length > 0)
1648     {
1649         ftdi->readbuffer_remaining = 0;
1650         ftdi->readbuffer_offset = 0;
1651         /* returns how much received */
1652         ret = libusb_bulk_transfer (ftdi->usb_dev, ftdi->out_ep, ftdi->readbuffer, ftdi->readbuffer_chunksize, &actual_length, ftdi->usb_read_timeout);
1653         if (ret < 0)
1654             ftdi_error_return(ret, "usb bulk read failed");
1655
1656         if (actual_length > 2)
1657         {
1658             // skip FTDI status bytes.
1659             // Maybe stored in the future to enable modem use
1660             num_of_chunks = actual_length / packet_size;
1661             chunk_remains = actual_length % packet_size;
1662             //printf("actual_length = %X, num_of_chunks = %X, chunk_remains = %X, readbuffer_offset = %X\n", actual_length, num_of_chunks, chunk_remains, ftdi->readbuffer_offset);
1663
1664             ftdi->readbuffer_offset += 2;
1665             actual_length -= 2;
1666
1667             if (actual_length > packet_size - 2)
1668             {
1669                 for (i = 1; i < num_of_chunks; i++)
1670                     memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1671                              ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1672                              packet_size - 2);
1673                 if (chunk_remains > 2)
1674                 {
1675                     memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1676                              ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1677                              chunk_remains-2);
1678                     actual_length -= 2*num_of_chunks;
1679                 }
1680                 else
1681                     actual_length -= 2*(num_of_chunks-1)+chunk_remains;
1682             }
1683         }
1684         else if (actual_length <= 2)
1685         {
1686             // no more data to read?
1687             return offset;
1688         }
1689         if (actual_length > 0)
1690         {
1691             // data still fits in buf?
1692             if (offset+actual_length <= size)
1693             {
1694                 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, actual_length);
1695                 //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
1696                 offset += actual_length;
1697
1698                 /* Did we read exactly the right amount of bytes? */
1699                 if (offset == size)
1700                     //printf("read_data exact rem %d offset %d\n",
1701                     //ftdi->readbuffer_remaining, offset);
1702                     return offset;
1703             }
1704             else
1705             {
1706                 // only copy part of the data or size <= readbuffer_chunksize
1707                 int part_size = size-offset;
1708                 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, part_size);
1709
1710                 ftdi->readbuffer_offset += part_size;
1711                 ftdi->readbuffer_remaining = actual_length-part_size;
1712                 offset += part_size;
1713
1714                 /* printf("Returning part: %d - size: %d - offset: %d - actual_length: %d - remaining: %d\n",
1715                 part_size, size, offset, actual_length, ftdi->readbuffer_remaining); */
1716
1717                 return offset;
1718             }
1719         }
1720     }
1721     // never reached
1722     return -127;
1723 }
1724
1725 /**
1726     Configure read buffer chunk size.
1727     Default is 4096.
1728
1729     Automatically reallocates the buffer.
1730
1731     \param ftdi pointer to ftdi_context
1732     \param chunksize Chunk size
1733
1734     \retval 0: all fine
1735     \retval -1: ftdi context invalid
1736 */
1737 int ftdi_read_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
1738 {
1739     unsigned char *new_buf;
1740
1741     if (ftdi == NULL)
1742         ftdi_error_return(-1, "ftdi context invalid");
1743
1744     // Invalidate all remaining data
1745     ftdi->readbuffer_offset = 0;
1746     ftdi->readbuffer_remaining = 0;
1747 #ifdef __linux__
1748     /* We can't set readbuffer_chunksize larger than MAX_BULK_BUFFER_LENGTH,
1749        which is defined in libusb-1.0.  Otherwise, each USB read request will
1750        be divided into multiple URBs.  This will cause issues on Linux kernel
1751        older than 2.6.32.  */
1752     if (chunksize > 16384)
1753         chunksize = 16384;
1754 #endif
1755
1756     if ((new_buf = (unsigned char *)realloc(ftdi->readbuffer, chunksize)) == NULL)
1757         ftdi_error_return(-1, "out of memory for readbuffer");
1758
1759     ftdi->readbuffer = new_buf;
1760     ftdi->readbuffer_chunksize = chunksize;
1761
1762     return 0;
1763 }
1764
1765 /**
1766     Get read buffer chunk size.
1767
1768     \param ftdi pointer to ftdi_context
1769     \param chunksize Pointer to store chunk size in
1770
1771     \retval 0: all fine
1772     \retval -1: FTDI context invalid
1773 */
1774 int ftdi_read_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
1775 {
1776     if (ftdi == NULL)
1777         ftdi_error_return(-1, "FTDI context invalid");
1778
1779     *chunksize = ftdi->readbuffer_chunksize;
1780     return 0;
1781 }
1782
1783
1784 /**
1785     Enable bitbang mode.
1786
1787     \deprecated use \ref ftdi_set_bitmode with mode BITMODE_BITBANG instead
1788
1789     \param ftdi pointer to ftdi_context
1790     \param bitmask Bitmask to configure lines.
1791            HIGH/ON value configures a line as output.
1792
1793     \retval  0: all fine
1794     \retval -1: can't enable bitbang mode
1795     \retval -2: USB device unavailable
1796 */
1797 int ftdi_enable_bitbang(struct ftdi_context *ftdi, unsigned char bitmask)
1798 {
1799     unsigned short usb_val;
1800
1801     if (ftdi == NULL || ftdi->usb_dev == NULL)
1802         ftdi_error_return(-2, "USB device unavailable");
1803
1804     usb_val = bitmask; // low byte: bitmask
1805     /* FT2232C: Set bitbang_mode to 2 to enable SPI */
1806     usb_val |= (ftdi->bitbang_mode << 8);
1807
1808     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1809                                 SIO_SET_BITMODE_REQUEST, usb_val, ftdi->index,
1810                                 NULL, 0, ftdi->usb_write_timeout) < 0)
1811         ftdi_error_return(-1, "unable to enter bitbang mode. Perhaps not a BM type chip?");
1812
1813     ftdi->bitbang_enabled = 1;
1814     return 0;
1815 }
1816
1817 /**
1818     Disable bitbang mode.
1819
1820     \param ftdi pointer to ftdi_context
1821
1822     \retval  0: all fine
1823     \retval -1: can't disable bitbang mode
1824     \retval -2: USB device unavailable
1825 */
1826 int ftdi_disable_bitbang(struct ftdi_context *ftdi)
1827 {
1828     if (ftdi == NULL || ftdi->usb_dev == NULL)
1829         ftdi_error_return(-2, "USB device unavailable");
1830
1831     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_SET_BITMODE_REQUEST, 0, ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
1832         ftdi_error_return(-1, "unable to leave bitbang mode. Perhaps not a BM type chip?");
1833
1834     ftdi->bitbang_enabled = 0;
1835     return 0;
1836 }
1837
1838 /**
1839     Enable/disable bitbang modes.
1840
1841     \param ftdi pointer to ftdi_context
1842     \param bitmask Bitmask to configure lines.
1843            HIGH/ON value configures a line as output.
1844     \param mode Bitbang mode: use the values defined in \ref ftdi_mpsse_mode
1845
1846     \retval  0: all fine
1847     \retval -1: can't enable bitbang mode
1848     \retval -2: USB device unavailable
1849 */
1850 int ftdi_set_bitmode(struct ftdi_context *ftdi, unsigned char bitmask, unsigned char mode)
1851 {
1852     unsigned short usb_val;
1853
1854     if (ftdi == NULL || ftdi->usb_dev == NULL)
1855         ftdi_error_return(-2, "USB device unavailable");
1856
1857     usb_val = bitmask; // low byte: bitmask
1858     usb_val |= (mode << 8);
1859     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_SET_BITMODE_REQUEST, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
1860         ftdi_error_return(-1, "unable to configure bitbang mode. Perhaps not a 2232C type chip?");
1861
1862     ftdi->bitbang_mode = mode;
1863     ftdi->bitbang_enabled = (mode == BITMODE_RESET) ? 0 : 1;
1864     return 0;
1865 }
1866
1867 /**
1868     Directly read pin state, circumventing the read buffer. Useful for bitbang mode.
1869
1870     \param ftdi pointer to ftdi_context
1871     \param pins Pointer to store pins into
1872
1873     \retval  0: all fine
1874     \retval -1: read pins failed
1875     \retval -2: USB device unavailable
1876 */
1877 int ftdi_read_pins(struct ftdi_context *ftdi, unsigned char *pins)
1878 {
1879     if (ftdi == NULL || ftdi->usb_dev == NULL)
1880         ftdi_error_return(-2, "USB device unavailable");
1881
1882     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_READ_PINS_REQUEST, 0, ftdi->index, (unsigned char *)pins, 1, ftdi->usb_read_timeout) != 1)
1883         ftdi_error_return(-1, "read pins failed");
1884
1885     return 0;
1886 }
1887
1888 /**
1889     Set latency timer
1890
1891     The FTDI chip keeps data in the internal buffer for a specific
1892     amount of time if the buffer is not full yet to decrease
1893     load on the usb bus.
1894
1895     \param ftdi pointer to ftdi_context
1896     \param latency Value between 1 and 255
1897
1898     \retval  0: all fine
1899     \retval -1: latency out of range
1900     \retval -2: unable to set latency timer
1901     \retval -3: USB device unavailable
1902 */
1903 int ftdi_set_latency_timer(struct ftdi_context *ftdi, unsigned char latency)
1904 {
1905     unsigned short usb_val;
1906
1907     if (latency < 1)
1908         ftdi_error_return(-1, "latency out of range. Only valid for 1-255");
1909
1910     if (ftdi == NULL || ftdi->usb_dev == NULL)
1911         ftdi_error_return(-3, "USB device unavailable");
1912
1913     usb_val = latency;
1914     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_SET_LATENCY_TIMER_REQUEST, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
1915         ftdi_error_return(-2, "unable to set latency timer");
1916
1917     return 0;
1918 }
1919
1920 /**
1921     Get latency timer
1922
1923     \param ftdi pointer to ftdi_context
1924     \param latency Pointer to store latency value in
1925
1926     \retval  0: all fine
1927     \retval -1: unable to get latency timer
1928     \retval -2: USB device unavailable
1929 */
1930 int ftdi_get_latency_timer(struct ftdi_context *ftdi, unsigned char *latency)
1931 {
1932     unsigned short usb_val;
1933
1934     if (ftdi == NULL || ftdi->usb_dev == NULL)
1935         ftdi_error_return(-2, "USB device unavailable");
1936
1937     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_GET_LATENCY_TIMER_REQUEST, 0, ftdi->index, (unsigned char *)&usb_val, 1, ftdi->usb_read_timeout) != 1)
1938         ftdi_error_return(-1, "reading latency timer failed");
1939
1940     *latency = (unsigned char)usb_val;
1941     return 0;
1942 }
1943
1944 /**
1945     Poll modem status information
1946
1947     This function allows the retrieve the two status bytes of the device.
1948     The device sends these bytes also as a header for each read access
1949     where they are discarded by ftdi_read_data(). The chip generates
1950     the two stripped status bytes in the absence of data every 40 ms.
1951
1952     Layout of the first byte:
1953     - B0..B3 - must be 0
1954     - B4       Clear to send (CTS)
1955                  0 = inactive
1956                  1 = active
1957     - B5       Data set ready (DTS)
1958                  0 = inactive
1959                  1 = active
1960     - B6       Ring indicator (RI)
1961                  0 = inactive
1962                  1 = active
1963     - B7       Receive line signal detect (RLSD)
1964                  0 = inactive
1965                  1 = active
1966
1967     Layout of the second byte:
1968     - B0       Data ready (DR)
1969     - B1       Overrun error (OE)
1970     - B2       Parity error (PE)
1971     - B3       Framing error (FE)
1972     - B4       Break interrupt (BI)
1973     - B5       Transmitter holding register (THRE)
1974     - B6       Transmitter empty (TEMT)
1975     - B7       Error in RCVR FIFO
1976
1977     \param ftdi pointer to ftdi_context
1978     \param status Pointer to store status information in. Must be two bytes.
1979
1980     \retval  0: all fine
1981     \retval -1: unable to retrieve status information
1982     \retval -2: USB device unavailable
1983 */
1984 int ftdi_poll_modem_status(struct ftdi_context *ftdi, unsigned short *status)
1985 {
1986     char usb_val[2];
1987
1988     if (ftdi == NULL || ftdi->usb_dev == NULL)
1989         ftdi_error_return(-2, "USB device unavailable");
1990
1991     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_POLL_MODEM_STATUS_REQUEST, 0, ftdi->index, (unsigned char *)usb_val, 2, ftdi->usb_read_timeout) != 2)
1992         ftdi_error_return(-1, "getting modem status failed");
1993
1994     *status = (usb_val[1] << 8) | (usb_val[0] & 0xFF);
1995
1996     return 0;
1997 }
1998
1999 /**
2000     Set flowcontrol for ftdi chip
2001
2002     \param ftdi pointer to ftdi_context
2003     \param flowctrl flow control to use. should be
2004            SIO_DISABLE_FLOW_CTRL, SIO_RTS_CTS_HS, SIO_DTR_DSR_HS or SIO_XON_XOFF_HS
2005
2006     \retval  0: all fine
2007     \retval -1: set flow control failed
2008     \retval -2: USB device unavailable
2009 */
2010 int ftdi_setflowctrl(struct ftdi_context *ftdi, int flowctrl)
2011 {
2012     if (ftdi == NULL || ftdi->usb_dev == NULL)
2013         ftdi_error_return(-2, "USB device unavailable");
2014
2015     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
2016                                 SIO_SET_FLOW_CTRL_REQUEST, 0, (flowctrl | ftdi->index),
2017                                 NULL, 0, ftdi->usb_write_timeout) < 0)
2018         ftdi_error_return(-1, "set flow control failed");
2019
2020     return 0;
2021 }
2022
2023 /**
2024     Set dtr line
2025
2026     \param ftdi pointer to ftdi_context
2027     \param state state to set line to (1 or 0)
2028
2029     \retval  0: all fine
2030     \retval -1: set dtr failed
2031     \retval -2: USB device unavailable
2032 */
2033 int ftdi_setdtr(struct ftdi_context *ftdi, int state)
2034 {
2035     unsigned short usb_val;
2036
2037     if (ftdi == NULL || ftdi->usb_dev == NULL)
2038         ftdi_error_return(-2, "USB device unavailable");
2039
2040     if (state)
2041         usb_val = SIO_SET_DTR_HIGH;
2042     else
2043         usb_val = SIO_SET_DTR_LOW;
2044
2045     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
2046                                 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
2047                                 NULL, 0, ftdi->usb_write_timeout) < 0)
2048         ftdi_error_return(-1, "set dtr failed");
2049
2050     return 0;
2051 }
2052
2053 /**
2054     Set rts line
2055
2056     \param ftdi pointer to ftdi_context
2057     \param state state to set line to (1 or 0)
2058
2059     \retval  0: all fine
2060     \retval -1: set rts failed
2061     \retval -2: USB device unavailable
2062 */
2063 int ftdi_setrts(struct ftdi_context *ftdi, int state)
2064 {
2065     unsigned short usb_val;
2066
2067     if (ftdi == NULL || ftdi->usb_dev == NULL)
2068         ftdi_error_return(-2, "USB device unavailable");
2069
2070     if (state)
2071         usb_val = SIO_SET_RTS_HIGH;
2072     else
2073         usb_val = SIO_SET_RTS_LOW;
2074
2075     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
2076                                 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
2077                                 NULL, 0, ftdi->usb_write_timeout) < 0)
2078         ftdi_error_return(-1, "set of rts failed");
2079
2080     return 0;
2081 }
2082
2083 /**
2084     Set dtr and rts line in one pass
2085
2086     \param ftdi pointer to ftdi_context
2087     \param dtr  DTR state to set line to (1 or 0)
2088     \param rts  RTS state to set line to (1 or 0)
2089
2090     \retval  0: all fine
2091     \retval -1: set dtr/rts failed
2092     \retval -2: USB device unavailable
2093  */
2094 int ftdi_setdtr_rts(struct ftdi_context *ftdi, int dtr, int rts)
2095 {
2096     unsigned short usb_val;
2097
2098     if (ftdi == NULL || ftdi->usb_dev == NULL)
2099         ftdi_error_return(-2, "USB device unavailable");
2100
2101     if (dtr)
2102         usb_val = SIO_SET_DTR_HIGH;
2103     else
2104         usb_val = SIO_SET_DTR_LOW;
2105
2106     if (rts)
2107         usb_val |= SIO_SET_RTS_HIGH;
2108     else
2109         usb_val |= SIO_SET_RTS_LOW;
2110
2111     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
2112                                 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
2113                                 NULL, 0, ftdi->usb_write_timeout) < 0)
2114         ftdi_error_return(-1, "set of rts/dtr failed");
2115
2116     return 0;
2117 }
2118
2119 /**
2120     Set the special event character
2121
2122     \param ftdi pointer to ftdi_context
2123     \param eventch Event character
2124     \param enable 0 to disable the event character, non-zero otherwise
2125
2126     \retval  0: all fine
2127     \retval -1: unable to set event character
2128     \retval -2: USB device unavailable
2129 */
2130 int ftdi_set_event_char(struct ftdi_context *ftdi,
2131                         unsigned char eventch, unsigned char enable)
2132 {
2133     unsigned short usb_val;
2134
2135     if (ftdi == NULL || ftdi->usb_dev == NULL)
2136         ftdi_error_return(-2, "USB device unavailable");
2137
2138     usb_val = eventch;
2139     if (enable)
2140         usb_val |= 1 << 8;
2141
2142     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_SET_EVENT_CHAR_REQUEST, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
2143         ftdi_error_return(-1, "setting event character failed");
2144
2145     return 0;
2146 }
2147
2148 /**
2149     Set error character
2150
2151     \param ftdi pointer to ftdi_context
2152     \param errorch Error character
2153     \param enable 0 to disable the error character, non-zero otherwise
2154
2155     \retval  0: all fine
2156     \retval -1: unable to set error character
2157     \retval -2: USB device unavailable
2158 */
2159 int ftdi_set_error_char(struct ftdi_context *ftdi,
2160                         unsigned char errorch, unsigned char enable)
2161 {
2162     unsigned short usb_val;
2163
2164     if (ftdi == NULL || ftdi->usb_dev == NULL)
2165         ftdi_error_return(-2, "USB device unavailable");
2166
2167     usb_val = errorch;
2168     if (enable)
2169         usb_val |= 1 << 8;
2170
2171     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_SET_ERROR_CHAR_REQUEST, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
2172         ftdi_error_return(-1, "setting error character failed");
2173
2174     return 0;
2175 }
2176
2177 /**
2178     Init eeprom with default values.
2179     \param ftdi pointer to ftdi_context
2180     \param manufacturer String to use as Manufacturer
2181     \param product String to use as Product description
2182     \param serial String to use as Serial number description
2183
2184     \retval  0: all fine
2185     \retval -1: No struct ftdi_context
2186     \retval -2: No struct ftdi_eeprom
2187 */
2188 int ftdi_eeprom_initdefaults(struct ftdi_context *ftdi, char * manufacturer,
2189                              char * product, char * serial)
2190 {
2191     struct ftdi_eeprom *eeprom;
2192
2193     if (ftdi == NULL)
2194         ftdi_error_return(-1, "No struct ftdi_context");
2195
2196     if (ftdi->eeprom == NULL)
2197         ftdi_error_return(-2,"No struct ftdi_eeprom");
2198
2199     eeprom = ftdi->eeprom;
2200     memset(eeprom, 0, sizeof(struct ftdi_eeprom));
2201
2202     eeprom->vendor_id = 0x0403;
2203     eeprom->use_serial = USE_SERIAL_NUM;
2204     if ((ftdi->type == TYPE_AM) || (ftdi->type == TYPE_BM) ||
2205             (ftdi->type == TYPE_R))
2206         eeprom->product_id = 0x6001;
2207     else if (ftdi->type == TYPE_4232H)
2208         eeprom->product_id = 0x6011;
2209     else if (ftdi->type == TYPE_232H)
2210         eeprom->product_id = 0x6014;
2211     else
2212         eeprom->product_id = 0x6010;
2213     if (ftdi->type == TYPE_AM)
2214         eeprom->usb_version = 0x0101;
2215     else
2216         eeprom->usb_version = 0x0200;
2217     eeprom->max_power = 100;
2218
2219     if (eeprom->manufacturer)
2220         free (eeprom->manufacturer);
2221     eeprom->manufacturer = NULL;
2222     if (manufacturer)
2223     {
2224         eeprom->manufacturer = malloc(strlen(manufacturer)+1);
2225         if (eeprom->manufacturer)
2226             strcpy(eeprom->manufacturer, manufacturer);
2227     }
2228
2229     if (eeprom->product)
2230         free (eeprom->product);
2231     eeprom->product = NULL;
2232     if(product)
2233     {
2234         eeprom->product = malloc(strlen(product)+1);
2235         if (eeprom->product)
2236             strcpy(eeprom->product, product);
2237     }
2238
2239     if (eeprom->serial)
2240         free (eeprom->serial);
2241     eeprom->serial = NULL;
2242     if (serial)
2243     {
2244         eeprom->serial = malloc(strlen(serial)+1);
2245         if (eeprom->serial)
2246             strcpy(eeprom->serial, serial);
2247     }
2248
2249
2250     if (ftdi->type == TYPE_R)
2251     {
2252         eeprom->max_power = 90;
2253         eeprom->size = 0x80;
2254         eeprom->cbus_function[0] = CBUS_TXLED;
2255         eeprom->cbus_function[1] = CBUS_RXLED;
2256         eeprom->cbus_function[2] = CBUS_TXDEN;
2257         eeprom->cbus_function[3] = CBUS_PWREN;
2258         eeprom->cbus_function[4] = CBUS_SLEEP;
2259     }
2260     else
2261     {
2262         if(ftdi->type == TYPE_232H)
2263         {
2264             int i;
2265             for (i=0; i<10; i++)
2266                 eeprom->cbus_function[i] = CBUSH_TRISTATE;
2267         }
2268         eeprom->size = -1;
2269     }
2270     return 0;
2271 }
2272 /*FTD2XX doesn't check for values not fitting in the ACBUS Signal oprtions*/
2273 void set_ft232h_cbus(struct ftdi_eeprom *eeprom, unsigned char * output)
2274 {
2275     int i;
2276     for(i=0; i<5;i++)
2277     {
2278         int mode_low, mode_high;
2279         if (eeprom->cbus_function[2*i]> CBUSH_CLK7_5)
2280             mode_low = CBUSH_TRISTATE;
2281         else
2282             mode_low = eeprom->cbus_function[2*i];
2283         if (eeprom->cbus_function[2*i+1]> CBUSH_CLK7_5)
2284             mode_high = CBUSH_TRISTATE;
2285         else
2286             mode_high = eeprom->cbus_function[2*i];
2287
2288         output[0x18+i] = mode_high <<4 | mode_low;
2289     }
2290 }
2291 /**
2292     Build binary buffer from ftdi_eeprom structure.
2293     Output is suitable for ftdi_write_eeprom().
2294
2295     \param ftdi pointer to ftdi_context
2296
2297     \retval >=0: size of eeprom user area in bytes
2298     \retval -1: eeprom size (128 bytes) exceeded by custom strings
2299     \retval -2: Invalid eeprom or ftdi pointer
2300     \retval -3: Invalid cbus function setting     (FIXME: Not in the code?)
2301     \retval -4: Chip doesn't support invert       (FIXME: Not in the code?)
2302     \retval -5: Chip doesn't support high current drive         (FIXME: Not in the code?)
2303     \retval -6: No connected EEPROM or EEPROM Type unknown
2304 */
2305 int ftdi_eeprom_build(struct ftdi_context *ftdi)
2306 {
2307     unsigned char i, j, eeprom_size_mask;
2308     unsigned short checksum, value;
2309     unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
2310     int user_area_size;
2311     struct ftdi_eeprom *eeprom;
2312     unsigned char * output;
2313
2314     if (ftdi == NULL)
2315         ftdi_error_return(-2,"No context");
2316     if (ftdi->eeprom == NULL)
2317         ftdi_error_return(-2,"No eeprom structure");
2318
2319     eeprom= ftdi->eeprom;
2320     output = eeprom->buf;
2321
2322     if (eeprom->chip == -1)
2323         ftdi_error_return(-6,"No connected EEPROM or EEPROM type unknown");
2324
2325     if ((eeprom->chip == 0x56) || (eeprom->chip == 0x66))
2326         eeprom->size = 0x100;
2327     else
2328         eeprom->size = 0x80;
2329
2330     if (eeprom->manufacturer != NULL)
2331         manufacturer_size = strlen(eeprom->manufacturer);
2332     if (eeprom->product != NULL)
2333         product_size = strlen(eeprom->product);
2334     if (eeprom->serial != NULL)
2335         serial_size = strlen(eeprom->serial);
2336
2337     // eeprom size check
2338     switch (ftdi->type)
2339     {
2340         case TYPE_AM:
2341         case TYPE_BM:
2342             user_area_size = 96;    // base size for strings (total of 48 characters)
2343             break;
2344         case TYPE_2232C:
2345             user_area_size = 90;     // two extra config bytes and 4 bytes PnP stuff
2346             break;
2347         case TYPE_R:
2348             user_area_size = 88;     // four extra config bytes + 4 bytes PnP stuff
2349             break;
2350         case TYPE_2232H:            // six extra config bytes + 4 bytes PnP stuff
2351         case TYPE_4232H:
2352             user_area_size = 86;
2353             break;
2354         default:
2355             user_area_size = 0;
2356             break;
2357     }
2358     user_area_size  -= (manufacturer_size + product_size + serial_size) * 2;
2359
2360     if (user_area_size < 0)
2361         ftdi_error_return(-1,"eeprom size exceeded");
2362
2363     // empty eeprom
2364     memset (ftdi->eeprom->buf, 0, FTDI_MAX_EEPROM_SIZE);
2365
2366     // Bytes and Bits set for all Types
2367
2368     // Addr 02: Vendor ID
2369     output[0x02] = eeprom->vendor_id;
2370     output[0x03] = eeprom->vendor_id >> 8;
2371
2372     // Addr 04: Product ID
2373     output[0x04] = eeprom->product_id;
2374     output[0x05] = eeprom->product_id >> 8;
2375
2376     // Addr 06: Device release number (0400h for BM features)
2377     output[0x06] = 0x00;
2378     switch (ftdi->type)
2379     {
2380         case TYPE_AM:
2381             output[0x07] = 0x02;
2382             break;
2383         case TYPE_BM:
2384             output[0x07] = 0x04;
2385             break;
2386         case TYPE_2232C:
2387             output[0x07] = 0x05;
2388             break;
2389         case TYPE_R:
2390             output[0x07] = 0x06;
2391             break;
2392         case TYPE_2232H:
2393             output[0x07] = 0x07;
2394             break;
2395         case TYPE_4232H:
2396             output[0x07] = 0x08;
2397             break;
2398         case TYPE_232H:
2399             output[0x07] = 0x09;
2400             break;
2401         default:
2402             output[0x07] = 0x00;
2403     }
2404
2405     // Addr 08: Config descriptor
2406     // Bit 7: always 1
2407     // Bit 6: 1 if this device is self powered, 0 if bus powered
2408     // Bit 5: 1 if this device uses remote wakeup
2409     // Bit 4-0: reserved - 0
2410     j = 0x80;
2411     if (eeprom->self_powered == 1)
2412         j |= 0x40;
2413     if (eeprom->remote_wakeup == 1)
2414         j |= 0x20;
2415     output[0x08] = j;
2416
2417     // Addr 09: Max power consumption: max power = value * 2 mA
2418     output[0x09] = eeprom->max_power>>1;
2419
2420     if (ftdi->type != TYPE_AM)
2421     {
2422         // Addr 0A: Chip configuration
2423         // Bit 7: 0 - reserved
2424         // Bit 6: 0 - reserved
2425         // Bit 5: 0 - reserved
2426         // Bit 4: 1 - Change USB version
2427         // Bit 3: 1 - Use the serial number string
2428         // Bit 2: 1 - Enable suspend pull downs for lower power
2429         // Bit 1: 1 - Out EndPoint is Isochronous
2430         // Bit 0: 1 - In EndPoint is Isochronous
2431         //
2432         j = 0;
2433         if (eeprom->in_is_isochronous == 1)
2434             j = j | 1;
2435         if (eeprom->out_is_isochronous == 1)
2436             j = j | 2;
2437         output[0x0A] = j;
2438     }
2439
2440     // Dynamic content
2441     // Strings start at 0x94 (TYPE_AM, TYPE_BM)
2442     // 0x96 (TYPE_2232C), 0x98 (TYPE_R) and 0x9a (TYPE_x232H)
2443     // 0xa0 (TYPE_232H)
2444     i = 0;
2445     switch (ftdi->type)
2446     {
2447         case TYPE_232H:
2448             i += 2;
2449         case TYPE_2232H:
2450         case TYPE_4232H:
2451             i += 2;
2452         case TYPE_R:
2453             i += 2;
2454         case TYPE_2232C:
2455             i += 2;
2456         case TYPE_AM:
2457         case TYPE_BM:
2458             i += 0x94;
2459     }
2460     /* Wrap around 0x80 for 128 byte EEPROMS (Internale and 93x46) */
2461     eeprom_size_mask = eeprom->size -1;
2462
2463     // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
2464     // Addr 0F: Length of manufacturer string
2465     // Output manufacturer
2466     output[0x0E] = i;  // calculate offset
2467     output[i & eeprom_size_mask] = manufacturer_size*2 + 2, i++;
2468     output[i & eeprom_size_mask] = 0x03, i++; // type: string
2469     for (j = 0; j < manufacturer_size; j++)
2470     {
2471         output[i & eeprom_size_mask] = eeprom->manufacturer[j], i++;
2472         output[i & eeprom_size_mask] = 0x00, i++;
2473     }
2474     output[0x0F] = manufacturer_size*2 + 2;
2475
2476     // Addr 10: Offset of the product string + 0x80, calculated later
2477     // Addr 11: Length of product string
2478     output[0x10] = i | 0x80;  // calculate offset
2479     output[i & eeprom_size_mask] = product_size*2 + 2, i++;
2480     output[i & eeprom_size_mask] = 0x03, i++;
2481     for (j = 0; j < product_size; j++)
2482     {
2483         output[i & eeprom_size_mask] = eeprom->product[j], i++;
2484         output[i & eeprom_size_mask] = 0x00, i++;
2485     }
2486     output[0x11] = product_size*2 + 2;
2487
2488     // Addr 12: Offset of the serial string + 0x80, calculated later
2489     // Addr 13: Length of serial string
2490     output[0x12] = i | 0x80; // calculate offset
2491     output[i & eeprom_size_mask] = serial_size*2 + 2, i++;
2492     output[i & eeprom_size_mask] = 0x03, i++;
2493     for (j = 0; j < serial_size; j++)
2494     {
2495         output[i & eeprom_size_mask] = eeprom->serial[j], i++;
2496         output[i & eeprom_size_mask] = 0x00, i++;
2497     }
2498
2499     // Legacy port name and PnP fields for FT2232 and newer chips
2500     if (ftdi->type > TYPE_BM)
2501     {
2502         output[i & eeprom_size_mask] = 0x02; /* as seen when written with FTD2XX */
2503         i++;
2504         output[i & eeprom_size_mask] = 0x03; /* as seen when written with FTD2XX */
2505         i++;
2506         output[i & eeprom_size_mask] = eeprom->is_not_pnp; /* as seen when written with FTD2XX */
2507         i++;
2508     }
2509
2510     output[0x13] = serial_size*2 + 2;
2511
2512     if (ftdi->type > TYPE_AM) /* use_serial not used in AM devices */
2513     {
2514         if (eeprom->use_serial == USE_SERIAL_NUM )
2515             output[0x0A] |= USE_SERIAL_NUM;
2516         else
2517             output[0x0A] &= ~USE_SERIAL_NUM;
2518     }
2519
2520     /* Bytes and Bits specific to (some) types
2521        Write linear, as this allows easier fixing*/
2522     switch (ftdi->type)
2523     {
2524         case TYPE_AM:
2525             break;
2526         case TYPE_BM:
2527             output[0x0C] = eeprom->usb_version & 0xff;
2528             output[0x0D] = (eeprom->usb_version>>8) & 0xff;
2529             if (eeprom->use_usb_version == USE_USB_VERSION_BIT)
2530                 output[0x0A] |= USE_USB_VERSION_BIT;
2531             else
2532                 output[0x0A] &= ~USE_USB_VERSION_BIT;
2533
2534             break;
2535         case TYPE_2232C:
2536
2537             output[0x00] = (eeprom->channel_a_type)?((1<<(eeprom->channel_a_type)) & 0x7):0;
2538             if ( eeprom->channel_a_driver == DRIVER_VCP)
2539                 output[0x00] |= DRIVER_VCP;
2540             else
2541                 output[0x00] &= ~DRIVER_VCP;
2542
2543             if ( eeprom->high_current_a == HIGH_CURRENT_DRIVE)
2544                 output[0x00] |= HIGH_CURRENT_DRIVE;
2545             else
2546                 output[0x00] &= ~HIGH_CURRENT_DRIVE;
2547
2548             output[0x01] = (eeprom->channel_b_type)?((1<<(eeprom->channel_b_type)) & 0x7):0;
2549             if ( eeprom->channel_b_driver == DRIVER_VCP)
2550                 output[0x01] |= DRIVER_VCP;
2551             else
2552                 output[0x01] &= ~DRIVER_VCP;
2553
2554             if ( eeprom->high_current_b == HIGH_CURRENT_DRIVE)
2555                 output[0x01] |= HIGH_CURRENT_DRIVE;
2556             else
2557                 output[0x01] &= ~HIGH_CURRENT_DRIVE;
2558
2559             if (eeprom->in_is_isochronous == 1)
2560                 output[0x0A] |= 0x1;
2561             else
2562                 output[0x0A] &= ~0x1;
2563             if (eeprom->out_is_isochronous == 1)
2564                 output[0x0A] |= 0x2;
2565             else
2566                 output[0x0A] &= ~0x2;
2567             if (eeprom->suspend_pull_downs == 1)
2568                 output[0x0A] |= 0x4;
2569             else
2570                 output[0x0A] &= ~0x4;
2571             if (eeprom->use_usb_version == USE_USB_VERSION_BIT)
2572                 output[0x0A] |= USE_USB_VERSION_BIT;
2573             else
2574                 output[0x0A] &= ~USE_USB_VERSION_BIT;
2575
2576             output[0x0C] = eeprom->usb_version & 0xff;
2577             output[0x0D] = (eeprom->usb_version>>8) & 0xff;
2578             output[0x14] = eeprom->chip;
2579             break;
2580         case TYPE_R:
2581             if (eeprom->high_current == HIGH_CURRENT_DRIVE_R)
2582                 output[0x00] |= HIGH_CURRENT_DRIVE_R;
2583             output[0x01] = 0x40; /* Hard coded Endpoint Size*/
2584
2585             if (eeprom->suspend_pull_downs == 1)
2586                 output[0x0A] |= 0x4;
2587             else
2588                 output[0x0A] &= ~0x4;
2589             output[0x0B] = eeprom->invert;
2590             output[0x0C] = eeprom->usb_version & 0xff;
2591             output[0x0D] = (eeprom->usb_version>>8) & 0xff;
2592
2593             if (eeprom->cbus_function[0] > CBUS_BB)
2594                 output[0x14] = CBUS_TXLED;
2595             else
2596                 output[0x14] = eeprom->cbus_function[0];
2597
2598             if (eeprom->cbus_function[1] > CBUS_BB)
2599                 output[0x14] |= CBUS_RXLED<<4;
2600             else
2601                 output[0x14] |= eeprom->cbus_function[1]<<4;
2602
2603             if (eeprom->cbus_function[2] > CBUS_BB)
2604                 output[0x15] = CBUS_TXDEN;
2605             else
2606                 output[0x15] = eeprom->cbus_function[2];
2607
2608             if (eeprom->cbus_function[3] > CBUS_BB)
2609                 output[0x15] |= CBUS_PWREN<<4;
2610             else
2611                 output[0x15] |= eeprom->cbus_function[3]<<4;
2612
2613             if (eeprom->cbus_function[4] > CBUS_CLK6)
2614                 output[0x16] = CBUS_SLEEP;
2615             else
2616                 output[0x16] = eeprom->cbus_function[4];
2617             break;
2618         case TYPE_2232H:
2619             output[0x00] = (eeprom->channel_a_type)?((1<<(eeprom->channel_a_type)) & 0x7):0;
2620             if ( eeprom->channel_a_driver == DRIVER_VCP)
2621                 output[0x00] |= DRIVER_VCP;
2622             else
2623                 output[0x00] &= ~DRIVER_VCP;
2624
2625             output[0x01] = (eeprom->channel_b_type)?((1<<(eeprom->channel_b_type)) & 0x7):0;
2626             if ( eeprom->channel_b_driver == DRIVER_VCP)
2627                 output[0x01] |= DRIVER_VCP;
2628             else
2629                 output[0x01] &= ~DRIVER_VCP;
2630             if (eeprom->suspend_dbus7 == SUSPEND_DBUS7_BIT)
2631                 output[0x01] |= SUSPEND_DBUS7_BIT;
2632             else
2633                 output[0x01] &= ~SUSPEND_DBUS7_BIT;
2634
2635             if (eeprom->suspend_pull_downs == 1)
2636                 output[0x0A] |= 0x4;
2637             else
2638                 output[0x0A] &= ~0x4;
2639
2640             if (eeprom->group0_drive > DRIVE_16MA)
2641                 output[0x0c] |= DRIVE_16MA;
2642             else
2643                 output[0x0c] |= eeprom->group0_drive;
2644             if (eeprom->group0_schmitt == IS_SCHMITT)
2645                 output[0x0c] |= IS_SCHMITT;
2646             if (eeprom->group0_slew == SLOW_SLEW)
2647                 output[0x0c] |= SLOW_SLEW;
2648
2649             if (eeprom->group1_drive > DRIVE_16MA)
2650                 output[0x0c] |= DRIVE_16MA<<4;
2651             else
2652                 output[0x0c] |= eeprom->group1_drive<<4;
2653             if (eeprom->group1_schmitt == IS_SCHMITT)
2654                 output[0x0c] |= IS_SCHMITT<<4;
2655             if (eeprom->group1_slew == SLOW_SLEW)
2656                 output[0x0c] |= SLOW_SLEW<<4;
2657
2658             if (eeprom->group2_drive > DRIVE_16MA)
2659                 output[0x0d] |= DRIVE_16MA;
2660             else
2661                 output[0x0d] |= eeprom->group2_drive;
2662             if (eeprom->group2_schmitt == IS_SCHMITT)
2663                 output[0x0d] |= IS_SCHMITT;
2664             if (eeprom->group2_slew == SLOW_SLEW)
2665                 output[0x0d] |= SLOW_SLEW;
2666
2667             if (eeprom->group3_drive > DRIVE_16MA)
2668                 output[0x0d] |= DRIVE_16MA<<4;
2669             else
2670                 output[0x0d] |= eeprom->group3_drive<<4;
2671             if (eeprom->group3_schmitt == IS_SCHMITT)
2672                 output[0x0d] |= IS_SCHMITT<<4;
2673             if (eeprom->group3_slew == SLOW_SLEW)
2674                 output[0x0d] |= SLOW_SLEW<<4;
2675
2676             output[0x18] = eeprom->chip;
2677
2678             break;
2679         case TYPE_4232H:
2680             output[0x18] = eeprom->chip;
2681             fprintf(stderr,"FIXME: Build FT4232H specific EEPROM settings\n");
2682             break;
2683         case TYPE_232H:
2684             output[0x00] = (eeprom->channel_a_type)?((1<<(eeprom->channel_a_type)) & 0xf):0;
2685             if ( eeprom->channel_a_driver == DRIVER_VCP)
2686                 output[0x00] |= DRIVER_VCPH;
2687             else
2688                 output[0x00] &= ~DRIVER_VCPH;
2689             if (eeprom->powersave)
2690                 output[0x01] |= POWER_SAVE_DISABLE_H;
2691             else
2692                 output[0x01] &= ~POWER_SAVE_DISABLE_H;
2693             if (eeprom->clock_polarity)
2694                 output[0x01] |= FT1284_CLK_IDLE_STATE;
2695             else
2696                 output[0x01] &= ~FT1284_CLK_IDLE_STATE;
2697             if (eeprom->data_order)
2698                 output[0x01] |= FT1284_DATA_LSB;
2699             else
2700                 output[0x01] &= ~FT1284_DATA_LSB;
2701             if (eeprom->flow_control)
2702                 output[0x01] |= FT1284_FLOW_CONTROL;
2703             else
2704                 output[0x01] &= ~FT1284_FLOW_CONTROL;
2705             if (eeprom->group0_drive > DRIVE_16MA)
2706                 output[0x0c] |= DRIVE_16MA;
2707             else
2708                 output[0x0c] |= eeprom->group0_drive;
2709             if (eeprom->group0_schmitt == IS_SCHMITT)
2710                 output[0x0c] |= IS_SCHMITT;
2711             if (eeprom->group0_slew == SLOW_SLEW)
2712                 output[0x0c] |= SLOW_SLEW;
2713
2714             if (eeprom->group1_drive > DRIVE_16MA)
2715                 output[0x0d] |= DRIVE_16MA;
2716             else
2717                 output[0x0d] |= eeprom->group1_drive;
2718             if (eeprom->group1_schmitt == IS_SCHMITT)
2719                 output[0x0d] |= IS_SCHMITT;
2720             if (eeprom->group1_slew == SLOW_SLEW)
2721                 output[0x0d] |= SLOW_SLEW;
2722
2723             set_ft232h_cbus(eeprom, output);
2724
2725             output[0x1e] = eeprom->chip;
2726             fprintf(stderr,"FIXME: Build FT232H specific EEPROM settings\n");
2727             break;
2728               
2729     }
2730
2731     // calculate checksum
2732     checksum = 0xAAAA;
2733
2734     for (i = 0; i < eeprom->size/2-1; i++)
2735     {
2736         value = output[i*2];
2737         value += output[(i*2)+1] << 8;
2738
2739         checksum = value^checksum;
2740         checksum = (checksum << 1) | (checksum >> 15);
2741     }
2742
2743     output[eeprom->size-2] = checksum;
2744     output[eeprom->size-1] = checksum >> 8;
2745
2746     return user_area_size;
2747 }
2748 /* FTD2XX doesn't allow to set multiple bits in the interface mode bitfield*/
2749 unsigned char bit2type(unsigned char bits)
2750 {
2751     switch (bits)
2752     {
2753     case 0: return 0;
2754     case 1: return 1;
2755     case 2: return 2;
2756     case 4: return 3;
2757     case 8: return 4;
2758     default:
2759         fprintf(stderr," Unexpected value %d for Hardware Interface type\n",
2760                 bits);
2761     }
2762     return 0;
2763 }
2764
2765 /**
2766    Decode binary EEPROM image into an ftdi_eeprom structure.
2767
2768    \param ftdi pointer to ftdi_context
2769    \param verbose Decode EEPROM on stdout
2770
2771    \retval 0: all fine
2772    \retval -1: something went wrong
2773
2774    FIXME: How to pass size? How to handle size field in ftdi_eeprom?
2775    FIXME: Strings are malloc'ed here and should be freed somewhere
2776 */
2777 int ftdi_eeprom_decode(struct ftdi_context *ftdi, int verbose)
2778 {
2779     unsigned char i, j;
2780     unsigned short checksum, eeprom_checksum, value;
2781     unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
2782     int eeprom_size;
2783     struct ftdi_eeprom *eeprom;
2784     unsigned char *buf = ftdi->eeprom->buf;
2785     int release;
2786
2787     if (ftdi == NULL)
2788         ftdi_error_return(-1,"No context");
2789     if (ftdi->eeprom == NULL)
2790         ftdi_error_return(-1,"No eeprom structure");
2791
2792     eeprom = ftdi->eeprom;
2793     eeprom_size = eeprom->size;
2794
2795     // Addr 02: Vendor ID
2796     eeprom->vendor_id = buf[0x02] + (buf[0x03] << 8);
2797
2798     // Addr 04: Product ID
2799     eeprom->product_id = buf[0x04] + (buf[0x05] << 8);
2800
2801     release = buf[0x06] + (buf[0x07]<<8);
2802
2803     // Addr 08: Config descriptor
2804     // Bit 7: always 1
2805     // Bit 6: 1 if this device is self powered, 0 if bus powered
2806     // Bit 5: 1 if this device uses remote wakeup
2807     eeprom->self_powered = buf[0x08] & 0x40;
2808     eeprom->remote_wakeup = buf[0x08] & 0x20;
2809
2810     // Addr 09: Max power consumption: max power = value * 2 mA
2811     eeprom->max_power = buf[0x09];
2812
2813     // Addr 0A: Chip configuration
2814     // Bit 7: 0 - reserved
2815     // Bit 6: 0 - reserved
2816     // Bit 5: 0 - reserved
2817     // Bit 4: 1 - Change USB version on BM and 2232C
2818     // Bit 3: 1 - Use the serial number string
2819     // Bit 2: 1 - Enable suspend pull downs for lower power
2820     // Bit 1: 1 - Out EndPoint is Isochronous
2821     // Bit 0: 1 - In EndPoint is Isochronous
2822     //
2823     eeprom->in_is_isochronous  = buf[0x0A]&0x01;
2824     eeprom->out_is_isochronous = buf[0x0A]&0x02;
2825     eeprom->suspend_pull_downs = buf[0x0A]&0x04;
2826     eeprom->use_serial         = buf[0x0A] & USE_SERIAL_NUM;
2827     eeprom->use_usb_version    = buf[0x0A] & USE_USB_VERSION_BIT;
2828
2829     // Addr 0C: USB version low byte when 0x0A
2830     // Addr 0D: USB version high byte when 0x0A
2831     eeprom->usb_version = buf[0x0C] + (buf[0x0D] << 8);
2832
2833     // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
2834     // Addr 0F: Length of manufacturer string
2835     manufacturer_size = buf[0x0F]/2;
2836     if (eeprom->manufacturer)
2837         free(eeprom->manufacturer);
2838     if (manufacturer_size > 0)
2839     {
2840         eeprom->manufacturer = malloc(manufacturer_size);
2841         if (eeprom->manufacturer)
2842         {
2843             // Decode manufacturer
2844             i = buf[0x0E] & (eeprom_size -1); // offset
2845             for (j=0;j<manufacturer_size-1;j++)
2846             {
2847                 eeprom->manufacturer[j] = buf[2*j+i+2];
2848             }
2849             eeprom->manufacturer[j] = '\0';
2850         }
2851     }
2852     else eeprom->manufacturer = NULL;
2853
2854     // Addr 10: Offset of the product string + 0x80, calculated later
2855     // Addr 11: Length of product string
2856     if (eeprom->product)
2857         free(eeprom->product);
2858     product_size = buf[0x11]/2;
2859     if (product_size > 0)
2860     {
2861         eeprom->product = malloc(product_size);
2862         if (eeprom->product)
2863         {
2864             // Decode product name
2865             i = buf[0x10] & (eeprom_size -1); // offset
2866             for (j=0;j<product_size-1;j++)
2867             {
2868                 eeprom->product[j] = buf[2*j+i+2];
2869             }
2870             eeprom->product[j] = '\0';
2871         }
2872     }
2873     else eeprom->product = NULL;
2874
2875     // Addr 12: Offset of the serial string + 0x80, calculated later
2876     // Addr 13: Length of serial string
2877     if (eeprom->serial)
2878         free(eeprom->serial);
2879     serial_size = buf[0x13]/2;
2880     if (serial_size > 0)
2881     {
2882         eeprom->serial = malloc(serial_size);
2883         if (eeprom->serial)
2884         {
2885             // Decode serial
2886             i = buf[0x12] & (eeprom_size -1); // offset
2887             for (j=0;j<serial_size-1;j++)
2888             {
2889                 eeprom->serial[j] = buf[2*j+i+2];
2890             }
2891             eeprom->serial[j] = '\0';
2892         }
2893     }
2894     else eeprom->serial = NULL;
2895
2896     // verify checksum
2897     checksum = 0xAAAA;
2898
2899     for (i = 0; i < eeprom_size/2-1; i++)
2900     {
2901         value = buf[i*2];
2902         value += buf[(i*2)+1] << 8;
2903
2904         checksum = value^checksum;
2905         checksum = (checksum << 1) | (checksum >> 15);
2906     }
2907
2908     eeprom_checksum = buf[eeprom_size-2] + (buf[eeprom_size-1] << 8);
2909
2910     if (eeprom_checksum != checksum)
2911     {
2912         fprintf(stderr, "Checksum Error: %04x %04x\n", checksum, eeprom_checksum);
2913         ftdi_error_return(-1,"EEPROM checksum error");
2914     }
2915
2916     eeprom->channel_a_type   = 0;
2917     if ((ftdi->type == TYPE_AM) || (ftdi->type == TYPE_BM))
2918     {
2919         eeprom->chip = -1;
2920     }
2921     else if (ftdi->type == TYPE_2232C)
2922     {
2923         eeprom->channel_a_type   = bit2type(buf[0x00] & 0x7);
2924         eeprom->channel_a_driver = buf[0x00] & DRIVER_VCP;
2925         eeprom->high_current_a   = buf[0x00] & HIGH_CURRENT_DRIVE;
2926         eeprom->channel_b_type   = buf[0x01] & 0x7;
2927         eeprom->channel_b_driver = buf[0x01] & DRIVER_VCP;
2928         eeprom->high_current_b   = buf[0x01] & HIGH_CURRENT_DRIVE;
2929         eeprom->chip = buf[0x14];
2930     }
2931     else if (ftdi->type == TYPE_R)
2932     {
2933         /* TYPE_R flags D2XX, not VCP as all others*/
2934         eeprom->channel_a_driver = (~buf[0x00]) & DRIVER_VCP;
2935         eeprom->high_current     = buf[0x00] & HIGH_CURRENT_DRIVE_R;
2936         if ( (buf[0x01]&0x40) != 0x40)
2937             fprintf(stderr,
2938                     "TYPE_R EEPROM byte[0x01] Bit 6 unexpected Endpoint size."
2939                     " If this happened with the\n"
2940                     " EEPROM programmed by FTDI tools, please report "
2941                     "to libftdi@developer.intra2net.com\n");
2942
2943         eeprom->chip = buf[0x16];
2944         // Addr 0B: Invert data lines
2945         // Works only on FT232R, not FT245R, but no way to distinguish
2946         eeprom->invert = buf[0x0B];
2947         // Addr 14: CBUS function: CBUS0, CBUS1
2948         // Addr 15: CBUS function: CBUS2, CBUS3
2949         // Addr 16: CBUS function: CBUS5
2950         eeprom->cbus_function[0] = buf[0x14] & 0x0f;
2951         eeprom->cbus_function[1] = (buf[0x14] >> 4) & 0x0f;
2952         eeprom->cbus_function[2] = buf[0x15] & 0x0f;
2953         eeprom->cbus_function[3] = (buf[0x15] >> 4) & 0x0f;
2954         eeprom->cbus_function[4] = buf[0x16] & 0x0f;
2955     }
2956     else if ((ftdi->type == TYPE_2232H) ||(ftdi->type == TYPE_4232H))
2957     {
2958         eeprom->channel_a_type   = bit2type(buf[0x00] & 0x7);
2959         eeprom->channel_a_driver = buf[0x00] & DRIVER_VCP;
2960         eeprom->channel_b_type   = buf[0x01] & 0x7;
2961         eeprom->channel_b_driver = buf[0x01] & DRIVER_VCP;
2962
2963         if (ftdi->type == TYPE_2232H)
2964             eeprom->suspend_dbus7    = buf[0x01] & SUSPEND_DBUS7_BIT;
2965
2966         eeprom->chip = buf[0x18];
2967         eeprom->group0_drive   =  buf[0x0c]       & DRIVE_16MA;
2968         eeprom->group0_schmitt =  buf[0x0c]       & IS_SCHMITT;
2969         eeprom->group0_slew    =  buf[0x0c]       & SLOW_SLEW;
2970         eeprom->group1_drive   = (buf[0x0c] >> 4) & 0x3;
2971         eeprom->group1_schmitt = (buf[0x0c] >> 4) & IS_SCHMITT;
2972         eeprom->group1_slew    = (buf[0x0c] >> 4) & SLOW_SLEW;
2973         eeprom->group2_drive   =  buf[0x0d]       & DRIVE_16MA;
2974         eeprom->group2_schmitt =  buf[0x0d]       & IS_SCHMITT;
2975         eeprom->group2_slew    =  buf[0x0d]       & SLOW_SLEW;
2976         eeprom->group3_drive   = (buf[0x0d] >> 4) & DRIVE_16MA;
2977         eeprom->group3_schmitt = (buf[0x0d] >> 4) & IS_SCHMITT;
2978         eeprom->group3_slew    = (buf[0x0d] >> 4) & SLOW_SLEW;
2979     }
2980     else if (ftdi->type == TYPE_232H)
2981     {
2982         int i;
2983
2984         eeprom->channel_a_type   = buf[0x00] & 0xf;
2985         eeprom->channel_a_driver = (buf[0x00] & DRIVER_VCPH)?DRIVER_VCP:0;
2986         eeprom->clock_polarity =  buf[0x01]       & FT1284_CLK_IDLE_STATE;
2987         eeprom->data_order     =  buf[0x01]       & FT1284_DATA_LSB;
2988         eeprom->flow_control   =  buf[0x01]       & FT1284_FLOW_CONTROL;
2989         eeprom->powersave      =  buf[0x01]       & POWER_SAVE_DISABLE_H;
2990         eeprom->group0_drive   =  buf[0x0c]       & DRIVE_16MA;
2991         eeprom->group0_schmitt =  buf[0x0c]       & IS_SCHMITT;
2992         eeprom->group0_slew    =  buf[0x0c]       & SLOW_SLEW;
2993         eeprom->group1_drive   =  buf[0x0d]       & DRIVE_16MA;
2994         eeprom->group1_schmitt =  buf[0x0d]       & IS_SCHMITT;
2995         eeprom->group1_slew    =  buf[0x0d]       & SLOW_SLEW;
2996
2997         for(i=0; i<5; i++)
2998         {
2999             eeprom->cbus_function[2*i  ] =  buf[0x18+i] & 0x0f;
3000             eeprom->cbus_function[2*i+1] = (buf[0x18+i] >> 4) & 0x0f;
3001         }
3002         eeprom->chip = buf[0x1e];
3003         /*FIXME: Decipher more values*/
3004     }
3005
3006     if (verbose)
3007     {
3008         char *channel_mode[] = {"UART","245","CPU", "OPTO", "FT1284"};
3009         fprintf(stdout, "VID:     0x%04x\n",eeprom->vendor_id);
3010         fprintf(stdout, "PID:     0x%04x\n",eeprom->product_id);
3011         fprintf(stdout, "Release: 0x%04x\n",release);
3012
3013         if (eeprom->self_powered)
3014             fprintf(stdout, "Self-Powered%s", (eeprom->remote_wakeup)?", USB Remote Wake Up\n":"\n");
3015         else
3016             fprintf(stdout, "Bus Powered: %3d mA%s", eeprom->max_power * 2,
3017                     (eeprom->remote_wakeup)?" USB Remote Wake Up\n":"\n");
3018         if (eeprom->manufacturer)
3019             fprintf(stdout, "Manufacturer: %s\n",eeprom->manufacturer);
3020         if (eeprom->product)
3021             fprintf(stdout, "Product:      %s\n",eeprom->product);
3022         if (eeprom->serial)
3023             fprintf(stdout, "Serial:       %s\n",eeprom->serial);
3024         fprintf(stdout,     "Checksum      : %04x\n", checksum);
3025         if (ftdi->type == TYPE_R)
3026             fprintf(stdout,     "Internal EEPROM\n");
3027         else if (eeprom->chip >= 0x46)
3028             fprintf(stdout,     "Attached EEPROM: 93x%02x\n", eeprom->chip);
3029         if (eeprom->suspend_dbus7)
3030             fprintf(stdout, "Suspend on DBUS7\n");
3031         if (eeprom->suspend_pull_downs)
3032             fprintf(stdout, "Pull IO pins low during suspend\n");
3033         if(eeprom->powersave)
3034         {
3035             if(ftdi->type >= TYPE_232H)
3036                 fprintf(stdout,"Enter low power state on ACBUS7\n");
3037         } 
3038         if (eeprom->remote_wakeup)
3039             fprintf(stdout, "Enable Remote Wake Up\n");
3040         fprintf(stdout, "PNP: %d\n",(eeprom->is_not_pnp)?0:1);
3041         if (ftdi->type >= TYPE_2232C)
3042             fprintf(stdout,"Channel A has Mode %s%s%s\n",
3043                     channel_mode[eeprom->channel_a_type],
3044                     (eeprom->channel_a_driver)?" VCP":"",
3045                     (eeprom->high_current_a)?" High Current IO":"");
3046         if (ftdi->type >= TYPE_232H)
3047         {
3048             fprintf(stdout,"FT1284 Mode Clock is idle %s, %s first, %sFlow Control\n",
3049                     (eeprom->clock_polarity)?"HIGH":"LOW",
3050                     (eeprom->data_order)?"LSB":"MSB",
3051                     (eeprom->flow_control)?"":"No ");
3052         }        
3053         if ((ftdi->type >= TYPE_2232C) && (ftdi->type != TYPE_R) && (ftdi->type != TYPE_232H))
3054             fprintf(stdout,"Channel B has Mode %s%s%s\n",
3055                     channel_mode[eeprom->channel_b_type],
3056                     (eeprom->channel_b_driver)?" VCP":"",
3057                     (eeprom->high_current_b)?" High Current IO":"");
3058         if (((ftdi->type == TYPE_BM) || (ftdi->type == TYPE_2232C)) &&
3059                 eeprom->use_usb_version == USE_USB_VERSION_BIT)
3060             fprintf(stdout,"Use explicit USB Version %04x\n",eeprom->usb_version);
3061
3062         if ((ftdi->type == TYPE_2232H) || (ftdi->type == TYPE_4232H))
3063         {
3064             fprintf(stdout,"%s has %d mA drive%s%s\n",
3065                     (ftdi->type == TYPE_2232H)?"AL":"A",
3066                     (eeprom->group0_drive+1) *4,
3067                     (eeprom->group0_schmitt)?" Schmitt Input":"",
3068                     (eeprom->group0_slew)?" Slow Slew":"");
3069             fprintf(stdout,"%s has %d mA drive%s%s\n",
3070                     (ftdi->type == TYPE_2232H)?"AH":"B",
3071                     (eeprom->group1_drive+1) *4,
3072                     (eeprom->group1_schmitt)?" Schmitt Input":"",
3073                     (eeprom->group1_slew)?" Slow Slew":"");
3074             fprintf(stdout,"%s has %d mA drive%s%s\n",
3075                     (ftdi->type == TYPE_2232H)?"BL":"C",
3076                     (eeprom->group2_drive+1) *4,
3077                     (eeprom->group2_schmitt)?" Schmitt Input":"",
3078                     (eeprom->group2_slew)?" Slow Slew":"");
3079             fprintf(stdout,"%s has %d mA drive%s%s\n",
3080                     (ftdi->type == TYPE_2232H)?"BH":"D",
3081                     (eeprom->group3_drive+1) *4,
3082                     (eeprom->group3_schmitt)?" Schmitt Input":"",
3083                     (eeprom->group3_slew)?" Slow Slew":"");
3084         }
3085         else if (ftdi->type == TYPE_232H)
3086         {
3087             int i;
3088             char *cbush_mux[] = {"TRISTATE","RXLED","TXLED", "TXRXLED","PWREN",
3089                                 "SLEEP","DRIVE_0","DRIVE_1","IOMODE","TXDEN",
3090                                 "CLK30","CLK15","CLK7_5"
3091                                };
3092             fprintf(stdout,"ACBUS has %d mA drive%s%s\n",
3093                     (eeprom->group0_drive+1) *4,
3094                     (eeprom->group0_schmitt)?" Schmitt Input":"",
3095                     (eeprom->group0_slew)?" Slow Slew":"");
3096             fprintf(stdout,"ADBUS has %d mA drive%s%s\n",
3097                     (eeprom->group1_drive+1) *4,
3098                     (eeprom->group1_schmitt)?" Schmitt Input":"",
3099                     (eeprom->group1_slew)?" Slow Slew":"");
3100             for (i=0; i<10; i++)
3101             {
3102                 if (eeprom->cbus_function[i]<= CBUSH_CLK7_5 )
3103                     fprintf(stdout,"C%d Function: %s\n", i,
3104                             cbush_mux[eeprom->cbus_function[i]]);
3105             }
3106
3107         }
3108
3109         if (ftdi->type == TYPE_R)
3110         {
3111             char *cbus_mux[] = {"TXDEN","PWREN","RXLED", "TXLED","TX+RXLED",
3112                                 "SLEEP","CLK48","CLK24","CLK12","CLK6",
3113                                 "IOMODE","BB_WR","BB_RD"
3114                                };
3115             char *cbus_BB[] = {"RXF","TXE","RD", "WR"};
3116
3117             if (eeprom->invert)
3118             {
3119                 char *r_bits[] = {"TXD","RXD","RTS", "CTS","DTR","DSR","DCD","RI"};
3120                 fprintf(stdout,"Inverted bits:");
3121                 for (i=0; i<8; i++)
3122                     if ((eeprom->invert & (1<<i)) == (1<<i))
3123                         fprintf(stdout," %s",r_bits[i]);
3124                 fprintf(stdout,"\n");
3125             }
3126             for (i=0; i<5; i++)
3127             {
3128                 if (eeprom->cbus_function[i]<CBUS_BB)
3129                     fprintf(stdout,"C%d Function: %s\n", i,
3130                             cbus_mux[eeprom->cbus_function[i]]);
3131                 else
3132                 {
3133                     if (i < 4)
3134                         /* Running MPROG show that C0..3 have fixed function Synchronous
3135                            Bit Bang mode */
3136                         fprintf(stdout,"C%d BB Function: %s\n", i,
3137                                 cbus_BB[i]);
3138                     else
3139                         fprintf(stdout, "Unknown CBUS mode. Might be special mode?\n");
3140                 }
3141             }
3142         }
3143     }
3144     return 0;
3145 }
3146
3147 /**
3148    Get a value from the decoded EEPROM structure
3149
3150    \param ftdi pointer to ftdi_context
3151    \param value_name Enum of the value to query
3152    \param value Pointer to store read value
3153
3154    \retval 0: all fine
3155    \retval -1: Value doesn't exist
3156 */
3157 int ftdi_get_eeprom_value(struct ftdi_context *ftdi, enum ftdi_eeprom_value value_name, int* value)
3158 {
3159     switch (value_name)
3160     {
3161         case VENDOR_ID:
3162             *value = ftdi->eeprom->vendor_id;
3163             break;
3164         case PRODUCT_ID:
3165             *value = ftdi->eeprom->product_id;
3166             break;
3167         case SELF_POWERED:
3168             *value = ftdi->eeprom->self_powered;
3169             break;
3170         case REMOTE_WAKEUP:
3171             *value = ftdi->eeprom->remote_wakeup;
3172             break;
3173         case IS_NOT_PNP:
3174             *value = ftdi->eeprom->is_not_pnp;
3175             break;
3176         case SUSPEND_DBUS7:
3177             *value = ftdi->eeprom->suspend_dbus7;
3178             break;
3179         case IN_IS_ISOCHRONOUS:
3180             *value = ftdi->eeprom->in_is_isochronous;
3181             break;
3182         case SUSPEND_PULL_DOWNS:
3183             *value = ftdi->eeprom->suspend_pull_downs;
3184             break;
3185         case USE_SERIAL:
3186             *value = ftdi->eeprom->use_serial;
3187             break;
3188         case USB_VERSION:
3189             *value = ftdi->eeprom->usb_version;
3190             break;
3191         case MAX_POWER:
3192             *value = ftdi->eeprom->max_power;
3193             break;
3194         case CHANNEL_A_TYPE:
3195             *value = ftdi->eeprom->channel_a_type;
3196             break;
3197         case CHANNEL_B_TYPE:
3198             *value = ftdi->eeprom->channel_b_type;
3199             break;
3200         case CHANNEL_A_DRIVER:
3201             *value = ftdi->eeprom->channel_a_driver;
3202             break;
3203         case CHANNEL_B_DRIVER:
3204             *value = ftdi->eeprom->channel_b_driver;
3205             break;
3206         case CBUS_FUNCTION_0:
3207             *value = ftdi->eeprom->cbus_function[0];
3208             break;
3209         case CBUS_FUNCTION_1:
3210             *value = ftdi->eeprom->cbus_function[1];
3211             break;
3212         case CBUS_FUNCTION_2:
3213             *value = ftdi->eeprom->cbus_function[2];
3214             break;
3215         case CBUS_FUNCTION_3:
3216             *value = ftdi->eeprom->cbus_function[3];
3217             break;
3218         case CBUS_FUNCTION_4:
3219             *value = ftdi->eeprom->cbus_function[4];
3220             break;
3221         case CBUS_FUNCTION_5:
3222             *value = ftdi->eeprom->cbus_function[5];
3223             break;
3224         case CBUS_FUNCTION_6:
3225             *value = ftdi->eeprom->cbus_function[6];
3226             break;
3227         case CBUS_FUNCTION_7:
3228             *value = ftdi->eeprom->cbus_function[7];
3229             break;
3230         case CBUS_FUNCTION_8:
3231             *value = ftdi->eeprom->cbus_function[8];
3232             break;
3233         case CBUS_FUNCTION_9:
3234             *value = ftdi->eeprom->cbus_function[8];
3235             break;
3236         case HIGH_CURRENT:
3237             *value = ftdi->eeprom->high_current;
3238             break;
3239         case HIGH_CURRENT_A:
3240             *value = ftdi->eeprom->high_current_a;
3241             break;
3242         case HIGH_CURRENT_B:
3243             *value = ftdi->eeprom->high_current_b;
3244             break;
3245         case INVERT:
3246             *value = ftdi->eeprom->invert;
3247             break;
3248         case GROUP0_DRIVE:
3249             *value = ftdi->eeprom->group0_drive;
3250             break;
3251         case GROUP0_SCHMITT:
3252             *value = ftdi->eeprom->group0_schmitt;
3253             break;
3254         case GROUP0_SLEW:
3255             *value = ftdi->eeprom->group0_slew;
3256             break;
3257         case GROUP1_DRIVE:
3258             *value = ftdi->eeprom->group1_drive;
3259             break;
3260         case GROUP1_SCHMITT:
3261             *value = ftdi->eeprom->group1_schmitt;
3262             break;
3263         case GROUP1_SLEW:
3264             *value = ftdi->eeprom->group1_slew;
3265             break;
3266         case GROUP2_DRIVE:
3267             *value = ftdi->eeprom->group2_drive;
3268             break;
3269         case GROUP2_SCHMITT:
3270             *value = ftdi->eeprom->group2_schmitt;
3271             break;
3272         case GROUP2_SLEW:
3273             *value = ftdi->eeprom->group2_slew;
3274             break;
3275         case GROUP3_DRIVE:
3276             *value = ftdi->eeprom->group3_drive;
3277             break;
3278         case GROUP3_SCHMITT:
3279             *value = ftdi->eeprom->group3_schmitt;
3280             break;
3281         case GROUP3_SLEW:
3282             *value = ftdi->eeprom->group3_slew;
3283             break;
3284          case POWER_SAVE:
3285             *value = ftdi->eeprom->powersave;
3286             break;
3287           case CLOCK_POLARITY:
3288             *value = ftdi->eeprom->clock_polarity;
3289             break;
3290          case DATA_ORDER:
3291             *value = ftdi->eeprom->data_order;
3292             break;
3293          case FLOW_CONTROL:
3294             *value = ftdi->eeprom->flow_control;
3295             break;
3296        case CHIP_TYPE:
3297             *value = ftdi->eeprom->chip;
3298             break;
3299         case CHIP_SIZE:
3300             *value = ftdi->eeprom->size;
3301             break;
3302         default:
3303             ftdi_error_return(-1, "Request for unknown EEPROM value");
3304     }
3305     return 0;
3306 }
3307
3308 /**
3309    Set a value in the decoded EEPROM Structure
3310    No parameter checking is performed
3311
3312    \param ftdi pointer to ftdi_context
3313    \param value_name Enum of the value to set
3314    \param value to set
3315
3316    \retval 0: all fine
3317    \retval -1: Value doesn't exist
3318    \retval -2: Value not user settable
3319 */
3320 int ftdi_set_eeprom_value(struct ftdi_context *ftdi, enum ftdi_eeprom_value value_name, int value)
3321 {
3322     switch (value_name)
3323     {
3324         case VENDOR_ID:
3325             ftdi->eeprom->vendor_id = value;
3326             break;
3327         case PRODUCT_ID:
3328             ftdi->eeprom->product_id = value;
3329             break;
3330         case SELF_POWERED:
3331             ftdi->eeprom->self_powered = value;
3332             break;
3333         case REMOTE_WAKEUP:
3334             ftdi->eeprom->remote_wakeup = value;
3335             break;
3336         case IS_NOT_PNP:
3337             ftdi->eeprom->is_not_pnp = value;
3338             break;
3339         case SUSPEND_DBUS7:
3340             ftdi->eeprom->suspend_dbus7 = value;
3341             break;
3342         case IN_IS_ISOCHRONOUS:
3343             ftdi->eeprom->in_is_isochronous = value;
3344             break;
3345         case SUSPEND_PULL_DOWNS:
3346             ftdi->eeprom->suspend_pull_downs = value;
3347             break;
3348         case USE_SERIAL:
3349             ftdi->eeprom->use_serial = value;
3350             break;
3351         case USB_VERSION:
3352             ftdi->eeprom->usb_version = value;
3353             break;
3354         case MAX_POWER:
3355             ftdi->eeprom->max_power = value;
3356             break;
3357         case CHANNEL_A_TYPE:
3358             ftdi->eeprom->channel_a_type = value;
3359             break;
3360         case CHANNEL_B_TYPE:
3361             ftdi->eeprom->channel_b_type = value;
3362             break;
3363         case CHANNEL_A_DRIVER:
3364             ftdi->eeprom->channel_a_driver = value;
3365             break;
3366         case CHANNEL_B_DRIVER:
3367             ftdi->eeprom->channel_b_driver = value;
3368             break;
3369         case CBUS_FUNCTION_0:
3370             ftdi->eeprom->cbus_function[0] = value;
3371             break;
3372         case CBUS_FUNCTION_1:
3373             ftdi->eeprom->cbus_function[1] = value;
3374             break;
3375         case CBUS_FUNCTION_2:
3376             ftdi->eeprom->cbus_function[2] = value;
3377             break;
3378         case CBUS_FUNCTION_3:
3379             ftdi->eeprom->cbus_function[3] = value;
3380             break;
3381         case CBUS_FUNCTION_4:
3382             ftdi->eeprom->cbus_function[4] = value;
3383             break;
3384         case CBUS_FUNCTION_5:
3385             ftdi->eeprom->cbus_function[5] = value;
3386             break;
3387         case CBUS_FUNCTION_6:
3388             ftdi->eeprom->cbus_function[6] = value;
3389             break;
3390         case CBUS_FUNCTION_7:
3391             ftdi->eeprom->cbus_function[7] = value;
3392             break;
3393         case CBUS_FUNCTION_8:
3394             ftdi->eeprom->cbus_function[8] = value;
3395             break;
3396         case CBUS_FUNCTION_9:
3397             ftdi->eeprom->cbus_function[9] = value;
3398             break;
3399         case HIGH_CURRENT:
3400             ftdi->eeprom->high_current = value;
3401             break;
3402         case HIGH_CURRENT_A:
3403             ftdi->eeprom->high_current_a = value;
3404             break;
3405         case HIGH_CURRENT_B:
3406             ftdi->eeprom->high_current_b = value;
3407             break;
3408         case INVERT:
3409             ftdi->eeprom->invert = value;
3410             break;
3411         case GROUP0_DRIVE:
3412             ftdi->eeprom->group0_drive = value;
3413             break;
3414         case GROUP0_SCHMITT:
3415             ftdi->eeprom->group0_schmitt = value;
3416             break;
3417         case GROUP0_SLEW:
3418             ftdi->eeprom->group0_slew = value;
3419             break;
3420         case GROUP1_DRIVE:
3421             ftdi->eeprom->group1_drive = value;
3422             break;
3423         case GROUP1_SCHMITT:
3424             ftdi->eeprom->group1_schmitt = value;
3425             break;
3426         case GROUP1_SLEW:
3427             ftdi->eeprom->group1_slew = value;
3428             break;
3429         case GROUP2_DRIVE:
3430             ftdi->eeprom->group2_drive = value;
3431             break;
3432         case GROUP2_SCHMITT:
3433             ftdi->eeprom->group2_schmitt = value;
3434             break;
3435         case GROUP2_SLEW:
3436             ftdi->eeprom->group2_slew = value;
3437             break;
3438         case GROUP3_DRIVE:
3439             ftdi->eeprom->group3_drive = value;
3440             break;
3441         case GROUP3_SCHMITT:
3442             ftdi->eeprom->group3_schmitt = value;
3443             break;
3444         case GROUP3_SLEW:
3445             ftdi->eeprom->group3_slew = value;
3446             break;
3447         case CHIP_TYPE:
3448             ftdi->eeprom->chip = value;
3449             break;
3450          case POWER_SAVE:
3451             ftdi->eeprom->powersave = value;
3452             break;
3453          case CLOCK_POLARITY:
3454             ftdi->eeprom->clock_polarity = value;
3455             break;
3456          case DATA_ORDER:
3457             ftdi->eeprom->data_order = value;
3458             break;
3459          case FLOW_CONTROL:
3460             ftdi->eeprom->flow_control = value;
3461             break;
3462         case CHIP_SIZE:
3463             ftdi_error_return(-2, "EEPROM Value can't be changed");
3464         default :
3465             ftdi_error_return(-1, "Request to unknown EEPROM value");
3466     }
3467     return 0;
3468 }
3469
3470 /** Get the read-only buffer to the binary EEPROM content
3471
3472     \param ftdi pointer to ftdi_context
3473     \param buf buffer to receive EEPROM content
3474     \param size Size of receiving buffer
3475
3476     \retval 0: All fine
3477     \retval -1: struct ftdi_contxt or ftdi_eeprom missing
3478     \retval -2: Not enough room to store eeprom
3479 */
3480 int ftdi_get_eeprom_buf(struct ftdi_context *ftdi, unsigned char * buf, int size)
3481 {
3482     if (!ftdi || !(ftdi->eeprom))
3483         ftdi_error_return(-1, "No appropriate structure");
3484
3485     if (!buf || size < ftdi->eeprom->size)
3486         ftdi_error_return(-1, "Not enough room to store eeprom");
3487
3488     // Only copy up to FTDI_MAX_EEPROM_SIZE bytes
3489     if (size > FTDI_MAX_EEPROM_SIZE)
3490         size = FTDI_MAX_EEPROM_SIZE;
3491
3492     memcpy(buf, ftdi->eeprom->buf, size);
3493
3494     return 0;
3495 }
3496
3497 /**
3498     Read eeprom location
3499
3500     \param ftdi pointer to ftdi_context
3501     \param eeprom_addr Address of eeprom location to be read
3502     \param eeprom_val Pointer to store read eeprom location
3503
3504     \retval  0: all fine
3505     \retval -1: read failed
3506     \retval -2: USB device unavailable
3507 */
3508 int ftdi_read_eeprom_location (struct ftdi_context *ftdi, int eeprom_addr, unsigned short *eeprom_val)
3509 {
3510     if (ftdi == NULL || ftdi->usb_dev == NULL)
3511         ftdi_error_return(-2, "USB device unavailable");
3512
3513     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_READ_EEPROM_REQUEST, 0, eeprom_addr, (unsigned char *)eeprom_val, 2, ftdi->usb_read_timeout) != 2)
3514         ftdi_error_return(-1, "reading eeprom failed");
3515
3516     return 0;
3517 }
3518
3519 /**
3520     Read eeprom
3521
3522     \param ftdi pointer to ftdi_context
3523
3524     \retval  0: all fine
3525     \retval -1: read failed
3526     \retval -2: USB device unavailable
3527 */
3528 int ftdi_read_eeprom(struct ftdi_context *ftdi)
3529 {
3530     int i;
3531     unsigned char *buf;
3532
3533     if (ftdi == NULL || ftdi->usb_dev == NULL)
3534         ftdi_error_return(-2, "USB device unavailable");
3535     buf = ftdi->eeprom->buf;
3536
3537     for (i = 0; i < FTDI_MAX_EEPROM_SIZE/2; i++)
3538     {
3539         if (libusb_control_transfer(
3540                     ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE,SIO_READ_EEPROM_REQUEST, 0, i,
3541                     buf+(i*2), 2, ftdi->usb_read_timeout) != 2)
3542             ftdi_error_return(-1, "reading eeprom failed");
3543     }
3544
3545     if (ftdi->type == TYPE_R)
3546         ftdi->eeprom->size = 0x80;
3547     /*    Guesses size of eeprom by comparing halves
3548           - will not work with blank eeprom */
3549     else if (strrchr((const char *)buf, 0xff) == ((const char *)buf +FTDI_MAX_EEPROM_SIZE -1))
3550         ftdi->eeprom->size = -1;
3551     else if (memcmp(buf,&buf[0x80],0x80) == 0)
3552         ftdi->eeprom->size = 0x80;
3553     else if (memcmp(buf,&buf[0x40],0x40) == 0)
3554         ftdi->eeprom->size = 0x40;
3555     else
3556         ftdi->eeprom->size = 0x100;
3557     return 0;
3558 }
3559
3560 /*
3561     ftdi_read_chipid_shift does the bitshift operation needed for the FTDIChip-ID
3562     Function is only used internally
3563     \internal
3564 */
3565 static unsigned char ftdi_read_chipid_shift(unsigned char value)
3566 {
3567     return ((value & 1) << 1) |
3568            ((value & 2) << 5) |
3569            ((value & 4) >> 2) |
3570            ((value & 8) << 4) |
3571            ((value & 16) >> 1) |
3572            ((value & 32) >> 1) |
3573            ((value & 64) >> 4) |
3574            ((value & 128) >> 2);
3575 }
3576
3577 /**
3578     Read the FTDIChip-ID from R-type devices
3579
3580     \param ftdi pointer to ftdi_context
3581     \param chipid Pointer to store FTDIChip-ID
3582
3583     \retval  0: all fine
3584     \retval -1: read failed
3585     \retval -2: USB device unavailable
3586 */
3587 int ftdi_read_chipid(struct ftdi_context *ftdi, unsigned int *chipid)
3588 {
3589     unsigned int a = 0, b = 0;
3590
3591     if (ftdi == NULL || ftdi->usb_dev == NULL)
3592         ftdi_error_return(-2, "USB device unavailable");
3593
3594     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_READ_EEPROM_REQUEST, 0, 0x43, (unsigned char *)&a, 2, ftdi->usb_read_timeout) == 2)
3595     {
3596         a = a << 8 | a >> 8;
3597         if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_READ_EEPROM_REQUEST, 0, 0x44, (unsigned char *)&b, 2, ftdi->usb_read_timeout) == 2)
3598         {
3599             b = b << 8 | b >> 8;
3600             a = (a << 16) | (b & 0xFFFF);
3601             a = ftdi_read_chipid_shift(a) | ftdi_read_chipid_shift(a>>8)<<8
3602                 | ftdi_read_chipid_shift(a>>16)<<16 | ftdi_read_chipid_shift(a>>24)<<24;
3603             *chipid = a ^ 0xa5f0f7d1;
3604             return 0;
3605         }
3606     }
3607
3608     ftdi_error_return(-1, "read of FTDIChip-ID failed");
3609 }
3610
3611 /**
3612     Write eeprom location
3613
3614     \param ftdi pointer to ftdi_context
3615     \param eeprom_addr Address of eeprom location to be written
3616     \param eeprom_val Value to be written
3617
3618     \retval  0: all fine
3619     \retval -1: write failed
3620     \retval -2: USB device unavailable
3621     \retval -3: Invalid access to checksum protected area below 0x80
3622     \retval -4: Device can't access unprotected area
3623     \retval -5: Reading chip type failed
3624 */
3625 int ftdi_write_eeprom_location(struct ftdi_context *ftdi, int eeprom_addr,
3626                                unsigned short eeprom_val)
3627 {
3628     int chip_type_location;
3629     unsigned short chip_type;
3630
3631     if (ftdi == NULL || ftdi->usb_dev == NULL)
3632         ftdi_error_return(-2, "USB device unavailable");
3633
3634     if (eeprom_addr <0x80)
3635         ftdi_error_return(-2, "Invalid access to checksum protected area  below 0x80");
3636
3637
3638     switch (ftdi->type)
3639     {
3640         case TYPE_BM:
3641         case  TYPE_2232C:
3642             chip_type_location = 0x14;
3643             break;
3644         case TYPE_2232H:
3645         case TYPE_4232H:
3646             chip_type_location = 0x18;
3647             break;
3648         case TYPE_232H:
3649             chip_type_location = 0x1e;
3650             break;
3651         default:
3652             ftdi_error_return(-4, "Device can't access unprotected area");
3653     }
3654
3655     if (ftdi_read_eeprom_location( ftdi, chip_type_location>>1, &chip_type))
3656         ftdi_error_return(-5, "Reading failed failed");
3657     fprintf(stderr," loc 0x%04x val 0x%04x\n", chip_type_location,chip_type);
3658     if ((chip_type & 0xff) != 0x66)
3659     {
3660         ftdi_error_return(-6, "EEPROM is not of 93x66");
3661     }
3662
3663     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
3664                                 SIO_WRITE_EEPROM_REQUEST, eeprom_val, eeprom_addr,
3665                                 NULL, 0, ftdi->usb_write_timeout) != 0)
3666         ftdi_error_return(-1, "unable to write eeprom");
3667
3668     return 0;
3669 }
3670
3671 /**
3672     Write eeprom
3673
3674     \param ftdi pointer to ftdi_context
3675
3676     \retval  0: all fine
3677     \retval -1: read failed
3678     \retval -2: USB device unavailable
3679 */
3680 int ftdi_write_eeprom(struct ftdi_context *ftdi)
3681 {
3682     unsigned short usb_val, status;
3683     int i, ret;
3684     unsigned char *eeprom;
3685
3686     if (ftdi == NULL || ftdi->usb_dev == NULL)
3687         ftdi_error_return(-2, "USB device unavailable");
3688     eeprom = ftdi->eeprom->buf;
3689
3690     /* These commands were traced while running MProg */
3691     if ((ret = ftdi_usb_reset(ftdi)) != 0)
3692         return ret;
3693     if ((ret = ftdi_poll_modem_status(ftdi, &status)) != 0)
3694         return ret;
3695     if ((ret = ftdi_set_latency_timer(ftdi, 0x77)) != 0)
3696         return ret;
3697
3698     for (i = 0; i < ftdi->eeprom->size/2; i++)
3699     {
3700         usb_val = eeprom[i*2];
3701         usb_val += eeprom[(i*2)+1] << 8;
3702         if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
3703                                     SIO_WRITE_EEPROM_REQUEST, usb_val, i,
3704                                     NULL, 0, ftdi->usb_write_timeout) < 0)
3705             ftdi_error_return(-1, "unable to write eeprom");
3706     }
3707
3708     return 0;
3709 }
3710
3711 /**
3712     Erase eeprom
3713
3714     This is not supported on FT232R/FT245R according to the MProg manual from FTDI.
3715
3716     \param ftdi pointer to ftdi_context
3717
3718     \retval  0: all fine
3719     \retval -1: erase failed
3720     \retval -2: USB device unavailable
3721     \retval -3: Writing magic failed
3722     \retval -4: Read EEPROM failed
3723     \retval -5: Unexpected EEPROM value
3724 */
3725 #define MAGIC 0x55aa
3726 int ftdi_erase_eeprom(struct ftdi_context *ftdi)
3727 {
3728     unsigned short eeprom_value;
3729     if (ftdi == NULL || ftdi->usb_dev == NULL)
3730         ftdi_error_return(-2, "USB device unavailable");
3731
3732     if (ftdi->type == TYPE_R)
3733     {
3734         ftdi->eeprom->chip = 0;
3735         return 0;
3736     }
3737
3738     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_ERASE_EEPROM_REQUEST,
3739                                 0, 0, NULL, 0, ftdi->usb_write_timeout) < 0)
3740         ftdi_error_return(-1, "unable to erase eeprom");
3741
3742
3743     /* detect chip type by writing 0x55AA as magic at word position 0xc0
3744        Chip is 93x46 if magic is read at word position 0x00, as wraparound happens around 0x40
3745        Chip is 93x56 if magic is read at word position 0x40, as wraparound happens around 0x80
3746        Chip is 93x66 if magic is only read at word position 0xc0*/
3747     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
3748                                 SIO_WRITE_EEPROM_REQUEST, MAGIC, 0xc0,
3749                                 NULL, 0, ftdi->usb_write_timeout) != 0)
3750         ftdi_error_return(-3, "Writing magic failed");
3751     if (ftdi_read_eeprom_location( ftdi, 0x00, &eeprom_value))
3752         ftdi_error_return(-4, "Reading failed failed");
3753     if (eeprom_value == MAGIC)
3754     {
3755         ftdi->eeprom->chip = 0x46;
3756     }
3757     else
3758     {
3759         if (ftdi_read_eeprom_location( ftdi, 0x40, &eeprom_value))
3760             ftdi_error_return(-4, "Reading failed failed");
3761         if (eeprom_value == MAGIC)
3762             ftdi->eeprom->chip = 0x56;
3763         else
3764         {
3765             if (ftdi_read_eeprom_location( ftdi, 0xc0, &eeprom_value))
3766                 ftdi_error_return(-4, "Reading failed failed");
3767             if (eeprom_value == MAGIC)
3768                 ftdi->eeprom->chip = 0x66;
3769             else
3770             {
3771                 ftdi->eeprom->chip = -1;
3772             }
3773         }
3774     }
3775     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_ERASE_EEPROM_REQUEST,
3776                                 0, 0, NULL, 0, ftdi->usb_write_timeout) < 0)
3777         ftdi_error_return(-1, "unable to erase eeprom");
3778     return 0;
3779 }
3780
3781 /**
3782     Get string representation for last error code
3783
3784     \param ftdi pointer to ftdi_context
3785
3786     \retval Pointer to error string
3787 */
3788 char *ftdi_get_error_string (struct ftdi_context *ftdi)
3789 {
3790     if (ftdi == NULL)
3791         return "";
3792
3793     return ftdi->error_str;
3794 }
3795
3796 /* @} end of doxygen libftdi group */