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