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