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