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