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