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