Implement tc[io]flush methods & deprecate broken purge_buffers methods.
[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             /*FIXME: Make DBUS & CBUS Control configurable*/
3415             output[0x0c] = 0;    /* DBUS drive 4mA, CBUS drive 4 mA like factory default */
3416             for (j = 0; j <= 6; j++)
3417             {
3418                 output[0x1a + j] = eeprom->cbus_function[j];
3419             }
3420             output[0x0b] = eeprom->invert;
3421             break;
3422     }
3423
3424     /* First address without use */
3425     free_start = 0;
3426     switch (ftdi->type)
3427     {
3428         case TYPE_230X:
3429             free_start += 2;
3430         case TYPE_232H:
3431             free_start += 6;
3432         case TYPE_2232H:
3433         case TYPE_4232H:
3434             free_start += 2;
3435         case TYPE_R:
3436             free_start += 2;
3437         case TYPE_2232C:
3438             free_start++;
3439         case TYPE_AM:
3440         case TYPE_BM:
3441             free_start += 0x14;
3442     }
3443
3444     /* Arbitrary user data */
3445     if (eeprom->user_data && eeprom->user_data_size >= 0)
3446     {
3447         if (eeprom->user_data_addr < free_start)
3448             fprintf(stderr,"Warning, user data starts inside the generated data!\n");
3449         if (eeprom->user_data_addr + eeprom->user_data_size >= free_end)
3450             fprintf(stderr,"Warning, user data overlaps the strings area!\n");
3451         if (eeprom->user_data_addr + eeprom->user_data_size > eeprom->size)
3452             ftdi_error_return(-1,"eeprom size exceeded");
3453         memcpy(output + eeprom->user_data_addr, eeprom->user_data, eeprom->user_data_size);
3454     }
3455
3456     // calculate checksum
3457     checksum = 0xAAAA;
3458
3459     for (i = 0; i < eeprom->size/2-1; i++)
3460     {
3461         if ((ftdi->type == TYPE_230X) && (i == 0x12))
3462         {
3463             /* FT230X has a user section in the MTP which is not part of the checksum */
3464             i = 0x40;
3465         }
3466         if ((ftdi->type == TYPE_230X) && (i >=  0x40) && (i < 0x50)) {
3467             uint16_t data;
3468             if (ftdi_read_eeprom_location(ftdi, i, &data)) {
3469                 fprintf(stderr, "Reading Factory Configuration Data failed\n");
3470                 i = 0x50;
3471             }
3472             value = data;
3473         }
3474         else {
3475             value = output[i*2];
3476             value += output[(i*2)+1] << 8;
3477         }
3478         checksum = value^checksum;
3479         checksum = (checksum << 1) | (checksum >> 15);
3480     }
3481
3482     output[eeprom->size-2] = checksum;
3483     output[eeprom->size-1] = checksum >> 8;
3484
3485     eeprom->initialized_for_connected_device = 1;
3486     return user_area_size;
3487 }
3488 /* Decode the encoded EEPROM field for the FTDI Mode into a value for the abstracted
3489  * EEPROM structure
3490  *
3491  * FTD2XX doesn't allow to set multiple bits in the interface mode bitfield, and so do we
3492  */
3493 static unsigned char bit2type(unsigned char bits)
3494 {
3495     switch (bits)
3496     {
3497         case   0: return CHANNEL_IS_UART;
3498         case   1: return CHANNEL_IS_FIFO;
3499         case   2: return CHANNEL_IS_OPTO;
3500         case   4: return CHANNEL_IS_CPU;
3501         case   8: return CHANNEL_IS_FT1284;
3502         default:
3503             fprintf(stderr," Unexpected value %d for Hardware Interface type\n",
3504                     bits);
3505     }
3506     return 0;
3507 }
3508 /* Decode 230X / 232R type chips invert bits
3509  * Prints directly to stdout.
3510 */
3511 static void print_inverted_bits(int invert)
3512 {
3513     const char *r_bits[] = {"TXD","RXD","RTS","CTS","DTR","DSR","DCD","RI"};
3514     int i;
3515
3516     fprintf(stdout,"Inverted bits:");
3517     for (i=0; i<8; i++)
3518         if ((invert & (1<<i)) == (1<<i))
3519             fprintf(stdout," %s",r_bits[i]);
3520
3521     fprintf(stdout,"\n");
3522 }
3523 /**
3524    Decode binary EEPROM image into an ftdi_eeprom structure.
3525
3526    For FT-X devices use AN_201 FT-X MTP memory Configuration to decode.
3527
3528    \param ftdi pointer to ftdi_context
3529    \param verbose Decode EEPROM on stdout
3530
3531    \retval 0: all fine
3532    \retval -1: something went wrong
3533
3534    FIXME: How to pass size? How to handle size field in ftdi_eeprom?
3535    FIXME: Strings are malloc'ed here and should be freed somewhere
3536 */
3537 int ftdi_eeprom_decode(struct ftdi_context *ftdi, int verbose)
3538 {
3539     int i, j;
3540     unsigned short checksum, eeprom_checksum, value;
3541     unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
3542     int eeprom_size;
3543     struct ftdi_eeprom *eeprom;
3544     unsigned char *buf = NULL;
3545
3546     if (ftdi == NULL)
3547         ftdi_error_return(-1,"No context");
3548     if (ftdi->eeprom == NULL)
3549         ftdi_error_return(-1,"No eeprom structure");
3550
3551     eeprom = ftdi->eeprom;
3552     eeprom_size = eeprom->size;
3553     buf = ftdi->eeprom->buf;
3554
3555     // Addr 02: Vendor ID
3556     eeprom->vendor_id = buf[0x02] + (buf[0x03] << 8);
3557
3558     // Addr 04: Product ID
3559     eeprom->product_id = buf[0x04] + (buf[0x05] << 8);
3560
3561     // Addr 06: Device release number
3562     eeprom->release_number = buf[0x06] + (buf[0x07]<<8);
3563
3564     // Addr 08: Config descriptor
3565     // Bit 7: always 1
3566     // Bit 6: 1 if this device is self powered, 0 if bus powered
3567     // Bit 5: 1 if this device uses remote wakeup
3568     eeprom->self_powered = buf[0x08] & 0x40;
3569     eeprom->remote_wakeup = buf[0x08] & 0x20;
3570
3571     // Addr 09: Max power consumption: max power = value * 2 mA
3572     eeprom->max_power = MAX_POWER_MILLIAMP_PER_UNIT * buf[0x09];
3573
3574     // Addr 0A: Chip configuration
3575     // Bit 7: 0 - reserved
3576     // Bit 6: 0 - reserved
3577     // Bit 5: 0 - reserved
3578     // Bit 4: 1 - Change USB version on BM and 2232C
3579     // Bit 3: 1 - Use the serial number string
3580     // Bit 2: 1 - Enable suspend pull downs for lower power
3581     // Bit 1: 1 - Out EndPoint is Isochronous
3582     // Bit 0: 1 - In EndPoint is Isochronous
3583     //
3584     eeprom->in_is_isochronous  = buf[0x0A]&0x01;
3585     eeprom->out_is_isochronous = buf[0x0A]&0x02;
3586     eeprom->suspend_pull_downs = buf[0x0A]&0x04;
3587     eeprom->use_serial         = !!(buf[0x0A] & USE_SERIAL_NUM);
3588     eeprom->use_usb_version    = !!(buf[0x0A] & USE_USB_VERSION_BIT);
3589
3590     // Addr 0C: USB version low byte when 0x0A
3591     // Addr 0D: USB version high byte when 0x0A
3592     eeprom->usb_version = buf[0x0C] + (buf[0x0D] << 8);
3593
3594     // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
3595     // Addr 0F: Length of manufacturer string
3596     manufacturer_size = buf[0x0F]/2;
3597     if (eeprom->manufacturer)
3598         free(eeprom->manufacturer);
3599     if (manufacturer_size > 0)
3600     {
3601         eeprom->manufacturer = (char *)malloc(manufacturer_size);
3602         if (eeprom->manufacturer)
3603         {
3604             // Decode manufacturer
3605             i = buf[0x0E] & (eeprom_size -1); // offset
3606             for (j=0; j<manufacturer_size-1; j++)
3607             {
3608                 eeprom->manufacturer[j] = buf[2*j+i+2];
3609             }
3610             eeprom->manufacturer[j] = '\0';
3611         }
3612     }
3613     else eeprom->manufacturer = NULL;
3614
3615     // Addr 10: Offset of the product string + 0x80, calculated later
3616     // Addr 11: Length of product string
3617     if (eeprom->product)
3618         free(eeprom->product);
3619     product_size = buf[0x11]/2;
3620     if (product_size > 0)
3621     {
3622         eeprom->product = (char *)malloc(product_size);
3623         if (eeprom->product)
3624         {
3625             // Decode product name
3626             i = buf[0x10] & (eeprom_size -1); // offset
3627             for (j=0; j<product_size-1; j++)
3628             {
3629                 eeprom->product[j] = buf[2*j+i+2];
3630             }
3631             eeprom->product[j] = '\0';
3632         }
3633     }
3634     else eeprom->product = NULL;
3635
3636     // Addr 12: Offset of the serial string + 0x80, calculated later
3637     // Addr 13: Length of serial string
3638     if (eeprom->serial)
3639         free(eeprom->serial);
3640     serial_size = buf[0x13]/2;
3641     if (serial_size > 0)
3642     {
3643         eeprom->serial = (char *)malloc(serial_size);
3644         if (eeprom->serial)
3645         {
3646             // Decode serial
3647             i = buf[0x12] & (eeprom_size -1); // offset
3648             for (j=0; j<serial_size-1; j++)
3649             {
3650                 eeprom->serial[j] = buf[2*j+i+2];
3651             }
3652             eeprom->serial[j] = '\0';
3653         }
3654     }
3655     else eeprom->serial = NULL;
3656
3657     // verify checksum
3658     checksum = 0xAAAA;
3659
3660     for (i = 0; i < eeprom_size/2-1; i++)
3661     {
3662         if ((ftdi->type == TYPE_230X) && (i == 0x12))
3663         {
3664             /* FT230X has a user section in the MTP which is not part of the checksum */
3665             i = 0x40;
3666         }
3667         value = buf[i*2];
3668         value += buf[(i*2)+1] << 8;
3669
3670         checksum = value^checksum;
3671         checksum = (checksum << 1) | (checksum >> 15);
3672     }
3673
3674     eeprom_checksum = buf[eeprom_size-2] + (buf[eeprom_size-1] << 8);
3675
3676     if (eeprom_checksum != checksum)
3677     {
3678         fprintf(stderr, "Checksum Error: %04x %04x\n", checksum, eeprom_checksum);
3679         ftdi_error_return(-1,"EEPROM checksum error");
3680     }
3681
3682     eeprom->channel_a_type   = 0;
3683     if ((ftdi->type == TYPE_AM) || (ftdi->type == TYPE_BM))
3684     {
3685         eeprom->chip = -1;
3686     }
3687     else if (ftdi->type == TYPE_2232C)
3688     {
3689         eeprom->channel_a_type   = bit2type(buf[0x00] & 0x7);
3690         eeprom->channel_a_driver = buf[0x00] & DRIVER_VCP;
3691         eeprom->high_current_a   = buf[0x00] & HIGH_CURRENT_DRIVE;
3692         eeprom->channel_b_type   = buf[0x01] & 0x7;
3693         eeprom->channel_b_driver = buf[0x01] & DRIVER_VCP;
3694         eeprom->high_current_b   = buf[0x01] & HIGH_CURRENT_DRIVE;
3695         eeprom->chip = buf[0x14];
3696     }
3697     else if (ftdi->type == TYPE_R)
3698     {
3699         /* TYPE_R flags D2XX, not VCP as all others*/
3700         eeprom->channel_a_driver = ~buf[0x00] & DRIVER_VCP;
3701         eeprom->high_current     = buf[0x00] & HIGH_CURRENT_DRIVE_R;
3702         eeprom->external_oscillator = buf[0x00] & 0x02;
3703         if ( (buf[0x01]&0x40) != 0x40)
3704             fprintf(stderr,
3705                     "TYPE_R EEPROM byte[0x01] Bit 6 unexpected Endpoint size."
3706                     " If this happened with the\n"
3707                     " EEPROM programmed by FTDI tools, please report "
3708                     "to libftdi@developer.intra2net.com\n");
3709
3710         eeprom->chip = buf[0x16];
3711         // Addr 0B: Invert data lines
3712         // Works only on FT232R, not FT245R, but no way to distinguish
3713         eeprom->invert = buf[0x0B];
3714         // Addr 14: CBUS function: CBUS0, CBUS1
3715         // Addr 15: CBUS function: CBUS2, CBUS3
3716         // Addr 16: CBUS function: CBUS5
3717         eeprom->cbus_function[0] = buf[0x14] & 0x0f;
3718         eeprom->cbus_function[1] = (buf[0x14] >> 4) & 0x0f;
3719         eeprom->cbus_function[2] = buf[0x15] & 0x0f;
3720         eeprom->cbus_function[3] = (buf[0x15] >> 4) & 0x0f;
3721         eeprom->cbus_function[4] = buf[0x16] & 0x0f;
3722     }
3723     else if ((ftdi->type == TYPE_2232H) || (ftdi->type == TYPE_4232H))
3724     {
3725         eeprom->channel_a_driver = buf[0x00] & DRIVER_VCP;
3726         eeprom->channel_b_driver = buf[0x01] & DRIVER_VCP;
3727
3728         if (ftdi->type == TYPE_2232H)
3729         {
3730             eeprom->channel_a_type   = bit2type(buf[0x00] & 0x7);
3731             eeprom->channel_b_type   = bit2type(buf[0x01] & 0x7);
3732             eeprom->suspend_dbus7    = buf[0x01] & SUSPEND_DBUS7_BIT;
3733         }
3734         else
3735         {
3736             eeprom->channel_c_driver = (buf[0x00] >> 4) & DRIVER_VCP;
3737             eeprom->channel_d_driver = (buf[0x01] >> 4) & DRIVER_VCP;
3738             eeprom->channel_a_rs485enable = buf[0x0b] & (CHANNEL_IS_RS485 << 0);
3739             eeprom->channel_b_rs485enable = buf[0x0b] & (CHANNEL_IS_RS485 << 1);
3740             eeprom->channel_c_rs485enable = buf[0x0b] & (CHANNEL_IS_RS485 << 2);
3741             eeprom->channel_d_rs485enable = buf[0x0b] & (CHANNEL_IS_RS485 << 3);
3742         }
3743
3744         eeprom->chip = buf[0x18];
3745         eeprom->group0_drive   =  buf[0x0c]       & DRIVE_16MA;
3746         eeprom->group0_schmitt =  buf[0x0c]       & IS_SCHMITT;
3747         eeprom->group0_slew    =  buf[0x0c]       & SLOW_SLEW;
3748         eeprom->group1_drive   = (buf[0x0c] >> 4) & 0x3;
3749         eeprom->group1_schmitt = (buf[0x0c] >> 4) & IS_SCHMITT;
3750         eeprom->group1_slew    = (buf[0x0c] >> 4) & SLOW_SLEW;
3751         eeprom->group2_drive   =  buf[0x0d]       & DRIVE_16MA;
3752         eeprom->group2_schmitt =  buf[0x0d]       & IS_SCHMITT;
3753         eeprom->group2_slew    =  buf[0x0d]       & SLOW_SLEW;
3754         eeprom->group3_drive   = (buf[0x0d] >> 4) & DRIVE_16MA;
3755         eeprom->group3_schmitt = (buf[0x0d] >> 4) & IS_SCHMITT;
3756         eeprom->group3_slew    = (buf[0x0d] >> 4) & SLOW_SLEW;
3757     }
3758     else if (ftdi->type == TYPE_232H)
3759     {
3760         eeprom->channel_a_type   = buf[0x00] & 0xf;
3761         eeprom->channel_a_driver = (buf[0x00] & DRIVER_VCPH)?DRIVER_VCP:0;
3762         eeprom->clock_polarity =  buf[0x01]       & FT1284_CLK_IDLE_STATE;
3763         eeprom->data_order     =  buf[0x01]       & FT1284_DATA_LSB;
3764         eeprom->flow_control   =  buf[0x01]       & FT1284_FLOW_CONTROL;
3765         eeprom->powersave      =  buf[0x01]       & POWER_SAVE_DISABLE_H;
3766         eeprom->group0_drive   =  buf[0x0c]       & DRIVE_16MA;
3767         eeprom->group0_schmitt =  buf[0x0c]       & IS_SCHMITT;
3768         eeprom->group0_slew    =  buf[0x0c]       & SLOW_SLEW;
3769         eeprom->group1_drive   =  buf[0x0d]       & DRIVE_16MA;
3770         eeprom->group1_schmitt =  buf[0x0d]       & IS_SCHMITT;
3771         eeprom->group1_slew    =  buf[0x0d]       & SLOW_SLEW;
3772
3773         for(i=0; i<5; i++)
3774         {
3775             eeprom->cbus_function[2*i  ] =  buf[0x18+i] & 0x0f;
3776             eeprom->cbus_function[2*i+1] = (buf[0x18+i] >> 4) & 0x0f;
3777         }
3778         eeprom->chip = buf[0x1e];
3779         /*FIXME: Decipher more values*/
3780     }
3781     else if (ftdi->type == TYPE_230X)
3782     {
3783         for(i=0; i<4; i++)
3784         {
3785             eeprom->cbus_function[i] =  buf[0x1a + i] & 0xFF;
3786         }
3787         eeprom->group0_drive   =  buf[0x0c]       & 0x03;
3788         eeprom->group0_schmitt =  buf[0x0c]       & IS_SCHMITT;
3789         eeprom->group0_slew    =  buf[0x0c]       & SLOW_SLEW;
3790         eeprom->group1_drive   = (buf[0x0c] >> 4) & 0x03;
3791         eeprom->group1_schmitt = (buf[0x0c] >> 4) & IS_SCHMITT;
3792         eeprom->group1_slew    = (buf[0x0c] >> 4) & SLOW_SLEW;
3793
3794         eeprom->invert = buf[0xb];
3795     }
3796
3797     if (verbose)
3798     {
3799         const char *channel_mode[] = {"UART", "FIFO", "CPU", "OPTO", "FT1284"};
3800         fprintf(stdout, "VID:     0x%04x\n",eeprom->vendor_id);
3801         fprintf(stdout, "PID:     0x%04x\n",eeprom->product_id);
3802         fprintf(stdout, "Release: 0x%04x\n",eeprom->release_number);
3803
3804         if (eeprom->self_powered)
3805             fprintf(stdout, "Self-Powered%s", (eeprom->remote_wakeup)?", USB Remote Wake Up\n":"\n");
3806         else
3807             fprintf(stdout, "Bus Powered: %3d mA%s", eeprom->max_power,
3808                     (eeprom->remote_wakeup)?" USB Remote Wake Up\n":"\n");
3809         if (eeprom->manufacturer)
3810             fprintf(stdout, "Manufacturer: %s\n",eeprom->manufacturer);
3811         if (eeprom->product)
3812             fprintf(stdout, "Product:      %s\n",eeprom->product);
3813         if (eeprom->serial)
3814             fprintf(stdout, "Serial:       %s\n",eeprom->serial);
3815         fprintf(stdout,     "Checksum      : %04x\n", checksum);
3816         if (ftdi->type == TYPE_R) {
3817             fprintf(stdout,     "Internal EEPROM\n");
3818             fprintf(stdout,"Oscillator: %s\n", eeprom->external_oscillator?"External":"Internal");
3819         }
3820         else if (eeprom->chip >= 0x46)
3821             fprintf(stdout,     "Attached EEPROM: 93x%02x\n", eeprom->chip);
3822         if (eeprom->suspend_dbus7)
3823             fprintf(stdout, "Suspend on DBUS7\n");
3824         if (eeprom->suspend_pull_downs)
3825             fprintf(stdout, "Pull IO pins low during suspend\n");
3826         if(eeprom->powersave)
3827         {
3828             if(ftdi->type >= TYPE_232H)
3829                 fprintf(stdout,"Enter low power state on ACBUS7\n");
3830         }
3831         if (eeprom->remote_wakeup)
3832             fprintf(stdout, "Enable Remote Wake Up\n");
3833         fprintf(stdout, "PNP: %d\n",(eeprom->is_not_pnp)?0:1);
3834         if (ftdi->type >= TYPE_2232C)
3835             fprintf(stdout,"Channel A has Mode %s%s%s\n",
3836                     channel_mode[eeprom->channel_a_type],
3837                     (eeprom->channel_a_driver)?" VCP":"",
3838                     (eeprom->high_current_a)?" High Current IO":"");
3839         if (ftdi->type == TYPE_232H)
3840         {
3841             fprintf(stdout,"FT1284 Mode Clock is idle %s, %s first, %sFlow Control\n",
3842                     (eeprom->clock_polarity)?"HIGH":"LOW",
3843                     (eeprom->data_order)?"LSB":"MSB",
3844                     (eeprom->flow_control)?"":"No ");
3845         }
3846         if ((ftdi->type == TYPE_2232H) || (ftdi->type == TYPE_4232H))
3847             fprintf(stdout,"Channel B has Mode %s%s%s\n",
3848                     channel_mode[eeprom->channel_b_type],
3849                     (eeprom->channel_b_driver)?" VCP":"",
3850                     (eeprom->high_current_b)?" High Current IO":"");
3851         if (((ftdi->type == TYPE_BM) || (ftdi->type == TYPE_2232C)) &&
3852                 eeprom->use_usb_version)
3853             fprintf(stdout,"Use explicit USB Version %04x\n",eeprom->usb_version);
3854
3855         if ((ftdi->type == TYPE_2232H) || (ftdi->type == TYPE_4232H))
3856         {
3857             fprintf(stdout,"%s has %d mA drive%s%s\n",
3858                     (ftdi->type == TYPE_2232H)?"AL":"A",
3859                     (eeprom->group0_drive+1) *4,
3860                     (eeprom->group0_schmitt)?" Schmitt Input":"",
3861                     (eeprom->group0_slew)?" Slow Slew":"");
3862             fprintf(stdout,"%s has %d mA drive%s%s\n",
3863                     (ftdi->type == TYPE_2232H)?"AH":"B",
3864                     (eeprom->group1_drive+1) *4,
3865                     (eeprom->group1_schmitt)?" Schmitt Input":"",
3866                     (eeprom->group1_slew)?" Slow Slew":"");
3867             fprintf(stdout,"%s has %d mA drive%s%s\n",
3868                     (ftdi->type == TYPE_2232H)?"BL":"C",
3869                     (eeprom->group2_drive+1) *4,
3870                     (eeprom->group2_schmitt)?" Schmitt Input":"",
3871                     (eeprom->group2_slew)?" Slow Slew":"");
3872             fprintf(stdout,"%s has %d mA drive%s%s\n",
3873                     (ftdi->type == TYPE_2232H)?"BH":"D",
3874                     (eeprom->group3_drive+1) *4,
3875                     (eeprom->group3_schmitt)?" Schmitt Input":"",
3876                     (eeprom->group3_slew)?" Slow Slew":"");
3877         }
3878         else if (ftdi->type == TYPE_232H)
3879         {
3880             const char *cbush_mux[] = {"TRISTATE","TXLED","RXLED", "TXRXLED","PWREN",
3881                                  "SLEEP","DRIVE_0","DRIVE_1","IOMODE","TXDEN",
3882                                  "CLK30","CLK15","CLK7_5"
3883                                 };
3884             fprintf(stdout,"ACBUS has %d mA drive%s%s\n",
3885                     (eeprom->group0_drive+1) *4,
3886                     (eeprom->group0_schmitt)?" Schmitt Input":"",
3887                     (eeprom->group0_slew)?" Slow Slew":"");
3888             fprintf(stdout,"ADBUS has %d mA drive%s%s\n",
3889                     (eeprom->group1_drive+1) *4,
3890                     (eeprom->group1_schmitt)?" Schmitt Input":"",
3891                     (eeprom->group1_slew)?" Slow Slew":"");
3892             for (i=0; i<10; i++)
3893             {
3894                 if (eeprom->cbus_function[i]<= CBUSH_CLK7_5 )
3895                     fprintf(stdout,"C%d Function: %s\n", i,
3896                             cbush_mux[eeprom->cbus_function[i]]);
3897             }
3898         }
3899         else if (ftdi->type == TYPE_230X)
3900         {
3901             const char *cbusx_mux[] = {"TRISTATE","TXLED","RXLED", "TXRXLED","PWREN",
3902                                  "SLEEP","DRIVE_0","DRIVE_1","IOMODE","TXDEN",
3903                                  "CLK24","CLK12","CLK6","BAT_DETECT","BAT_DETECT#",
3904                                  "I2C_TXE#", "I2C_RXF#", "VBUS_SENSE", "BB_WR#",
3905                                  "BBRD#", "TIME_STAMP", "AWAKE#",
3906                                 };
3907             fprintf(stdout,"DBUS has %d mA drive%s%s\n",
3908                     (eeprom->group0_drive+1) *4,
3909                     (eeprom->group0_schmitt)?" Schmitt Input":"",
3910                     (eeprom->group0_slew)?" Slow Slew":"");
3911             fprintf(stdout,"CBUS has %d mA drive%s%s\n",
3912                     (eeprom->group1_drive+1) *4,
3913                     (eeprom->group1_schmitt)?" Schmitt Input":"",
3914                     (eeprom->group1_slew)?" Slow Slew":"");
3915             for (i=0; i<4; i++)
3916             {
3917                 if (eeprom->cbus_function[i]<= CBUSX_AWAKE)
3918                     fprintf(stdout,"CBUS%d Function: %s\n", i, cbusx_mux[eeprom->cbus_function[i]]);
3919             }
3920
3921             if (eeprom->invert)
3922                 print_inverted_bits(eeprom->invert);
3923         }
3924
3925         if (ftdi->type == TYPE_R)
3926         {
3927             const char *cbus_mux[] = {"TXDEN","PWREN","RXLED", "TXLED","TX+RXLED",
3928                                 "SLEEP","CLK48","CLK24","CLK12","CLK6",
3929                                 "IOMODE","BB_WR","BB_RD"
3930                                };
3931             const char *cbus_BB[] = {"RXF","TXE","RD", "WR"};
3932
3933             if (eeprom->invert)
3934                 print_inverted_bits(eeprom->invert);
3935
3936             for (i=0; i<5; i++)
3937             {
3938                 if (eeprom->cbus_function[i]<=CBUS_BB_RD)
3939                     fprintf(stdout,"C%d Function: %s\n", i,
3940                             cbus_mux[eeprom->cbus_function[i]]);
3941                 else
3942                 {
3943                     if (i < 4)
3944                         /* Running MPROG show that C0..3 have fixed function Synchronous
3945                            Bit Bang mode */
3946                         fprintf(stdout,"C%d BB Function: %s\n", i,
3947                                 cbus_BB[i]);
3948                     else
3949                         fprintf(stdout, "Unknown CBUS mode. Might be special mode?\n");
3950                 }
3951             }
3952         }
3953     }
3954     return 0;
3955 }
3956
3957 /**
3958    Get a value from the decoded EEPROM structure
3959
3960    \param ftdi pointer to ftdi_context
3961    \param value_name Enum of the value to query
3962    \param value Pointer to store read value
3963
3964    \retval 0: all fine
3965    \retval -1: Value doesn't exist
3966 */
3967 int ftdi_get_eeprom_value(struct ftdi_context *ftdi, enum ftdi_eeprom_value value_name, int* value)
3968 {
3969     switch (value_name)
3970     {
3971         case VENDOR_ID:
3972             *value = ftdi->eeprom->vendor_id;
3973             break;
3974         case PRODUCT_ID:
3975             *value = ftdi->eeprom->product_id;
3976             break;
3977         case RELEASE_NUMBER:
3978             *value = ftdi->eeprom->release_number;
3979             break;
3980         case SELF_POWERED:
3981             *value = ftdi->eeprom->self_powered;
3982             break;
3983         case REMOTE_WAKEUP:
3984             *value = ftdi->eeprom->remote_wakeup;
3985             break;
3986         case IS_NOT_PNP:
3987             *value = ftdi->eeprom->is_not_pnp;
3988             break;
3989         case SUSPEND_DBUS7:
3990             *value = ftdi->eeprom->suspend_dbus7;
3991             break;
3992         case IN_IS_ISOCHRONOUS:
3993             *value = ftdi->eeprom->in_is_isochronous;
3994             break;
3995         case OUT_IS_ISOCHRONOUS:
3996             *value = ftdi->eeprom->out_is_isochronous;
3997             break;
3998         case SUSPEND_PULL_DOWNS:
3999             *value = ftdi->eeprom->suspend_pull_downs;
4000             break;
4001         case USE_SERIAL:
4002             *value = ftdi->eeprom->use_serial;
4003             break;
4004         case USB_VERSION:
4005             *value = ftdi->eeprom->usb_version;
4006             break;
4007         case USE_USB_VERSION:
4008             *value = ftdi->eeprom->use_usb_version;
4009             break;
4010         case MAX_POWER:
4011             *value = ftdi->eeprom->max_power;
4012             break;
4013         case CHANNEL_A_TYPE:
4014             *value = ftdi->eeprom->channel_a_type;
4015             break;
4016         case CHANNEL_B_TYPE:
4017             *value = ftdi->eeprom->channel_b_type;
4018             break;
4019         case CHANNEL_A_DRIVER:
4020             *value = ftdi->eeprom->channel_a_driver;
4021             break;
4022         case CHANNEL_B_DRIVER:
4023             *value = ftdi->eeprom->channel_b_driver;
4024             break;
4025         case CHANNEL_C_DRIVER:
4026             *value = ftdi->eeprom->channel_c_driver;
4027             break;
4028         case CHANNEL_D_DRIVER:
4029             *value = ftdi->eeprom->channel_d_driver;
4030             break;
4031         case CHANNEL_A_RS485:
4032             *value = ftdi->eeprom->channel_a_rs485enable;
4033             break;
4034         case CHANNEL_B_RS485:
4035             *value = ftdi->eeprom->channel_b_rs485enable;
4036             break;
4037         case CHANNEL_C_RS485:
4038             *value = ftdi->eeprom->channel_c_rs485enable;
4039             break;
4040         case CHANNEL_D_RS485:
4041             *value = ftdi->eeprom->channel_d_rs485enable;
4042             break;
4043         case CBUS_FUNCTION_0:
4044             *value = ftdi->eeprom->cbus_function[0];
4045             break;
4046         case CBUS_FUNCTION_1:
4047             *value = ftdi->eeprom->cbus_function[1];
4048             break;
4049         case CBUS_FUNCTION_2:
4050             *value = ftdi->eeprom->cbus_function[2];
4051             break;
4052         case CBUS_FUNCTION_3:
4053             *value = ftdi->eeprom->cbus_function[3];
4054             break;
4055         case CBUS_FUNCTION_4:
4056             *value = ftdi->eeprom->cbus_function[4];
4057             break;
4058         case CBUS_FUNCTION_5:
4059             *value = ftdi->eeprom->cbus_function[5];
4060             break;
4061         case CBUS_FUNCTION_6:
4062             *value = ftdi->eeprom->cbus_function[6];
4063             break;
4064         case CBUS_FUNCTION_7:
4065             *value = ftdi->eeprom->cbus_function[7];
4066             break;
4067         case CBUS_FUNCTION_8:
4068             *value = ftdi->eeprom->cbus_function[8];
4069             break;
4070         case CBUS_FUNCTION_9:
4071             *value = ftdi->eeprom->cbus_function[9];
4072             break;
4073         case HIGH_CURRENT:
4074             *value = ftdi->eeprom->high_current;
4075             break;
4076         case HIGH_CURRENT_A:
4077             *value = ftdi->eeprom->high_current_a;
4078             break;
4079         case HIGH_CURRENT_B:
4080             *value = ftdi->eeprom->high_current_b;
4081             break;
4082         case INVERT:
4083             *value = ftdi->eeprom->invert;
4084             break;
4085         case GROUP0_DRIVE:
4086             *value = ftdi->eeprom->group0_drive;
4087             break;
4088         case GROUP0_SCHMITT:
4089             *value = ftdi->eeprom->group0_schmitt;
4090             break;
4091         case GROUP0_SLEW:
4092             *value = ftdi->eeprom->group0_slew;
4093             break;
4094         case GROUP1_DRIVE:
4095             *value = ftdi->eeprom->group1_drive;
4096             break;
4097         case GROUP1_SCHMITT:
4098             *value = ftdi->eeprom->group1_schmitt;
4099             break;
4100         case GROUP1_SLEW:
4101             *value = ftdi->eeprom->group1_slew;
4102             break;
4103         case GROUP2_DRIVE:
4104             *value = ftdi->eeprom->group2_drive;
4105             break;
4106         case GROUP2_SCHMITT:
4107             *value = ftdi->eeprom->group2_schmitt;
4108             break;
4109         case GROUP2_SLEW:
4110             *value = ftdi->eeprom->group2_slew;
4111             break;
4112         case GROUP3_DRIVE:
4113             *value = ftdi->eeprom->group3_drive;
4114             break;
4115         case GROUP3_SCHMITT:
4116             *value = ftdi->eeprom->group3_schmitt;
4117             break;
4118         case GROUP3_SLEW:
4119             *value = ftdi->eeprom->group3_slew;
4120             break;
4121         case POWER_SAVE:
4122             *value = ftdi->eeprom->powersave;
4123             break;
4124         case CLOCK_POLARITY:
4125             *value = ftdi->eeprom->clock_polarity;
4126             break;
4127         case DATA_ORDER:
4128             *value = ftdi->eeprom->data_order;
4129             break;
4130         case FLOW_CONTROL:
4131             *value = ftdi->eeprom->flow_control;
4132             break;
4133         case CHIP_TYPE:
4134             *value = ftdi->eeprom->chip;
4135             break;
4136         case CHIP_SIZE:
4137             *value = ftdi->eeprom->size;
4138             break;
4139         case EXTERNAL_OSCILLATOR:
4140             *value = ftdi->eeprom->external_oscillator;
4141             break;
4142         default:
4143             ftdi_error_return(-1, "Request for unknown EEPROM value");
4144     }
4145     return 0;
4146 }
4147
4148 /**
4149    Set a value in the decoded EEPROM Structure
4150    No parameter checking is performed
4151
4152    \param ftdi pointer to ftdi_context
4153    \param value_name Enum of the value to set
4154    \param value to set
4155
4156    \retval 0: all fine
4157    \retval -1: Value doesn't exist
4158    \retval -2: Value not user settable
4159 */
4160 int ftdi_set_eeprom_value(struct ftdi_context *ftdi, enum ftdi_eeprom_value value_name, int value)
4161 {
4162     switch (value_name)
4163     {
4164         case VENDOR_ID:
4165             ftdi->eeprom->vendor_id = value;
4166             break;
4167         case PRODUCT_ID:
4168             ftdi->eeprom->product_id = value;
4169             break;
4170         case RELEASE_NUMBER:
4171             ftdi->eeprom->release_number = value;
4172             break;
4173         case SELF_POWERED:
4174             ftdi->eeprom->self_powered = value;
4175             break;
4176         case REMOTE_WAKEUP:
4177             ftdi->eeprom->remote_wakeup = value;
4178             break;
4179         case IS_NOT_PNP:
4180             ftdi->eeprom->is_not_pnp = value;
4181             break;
4182         case SUSPEND_DBUS7:
4183             ftdi->eeprom->suspend_dbus7 = value;
4184             break;
4185         case IN_IS_ISOCHRONOUS:
4186             ftdi->eeprom->in_is_isochronous = value;
4187             break;
4188         case OUT_IS_ISOCHRONOUS:
4189             ftdi->eeprom->out_is_isochronous = value;
4190             break;
4191         case SUSPEND_PULL_DOWNS:
4192             ftdi->eeprom->suspend_pull_downs = value;
4193             break;
4194         case USE_SERIAL:
4195             ftdi->eeprom->use_serial = value;
4196             break;
4197         case USB_VERSION:
4198             ftdi->eeprom->usb_version = value;
4199             break;
4200         case USE_USB_VERSION:
4201             ftdi->eeprom->use_usb_version = value;
4202             break;
4203         case MAX_POWER:
4204             ftdi->eeprom->max_power = value;
4205             break;
4206         case CHANNEL_A_TYPE:
4207             ftdi->eeprom->channel_a_type = value;
4208             break;
4209         case CHANNEL_B_TYPE:
4210             ftdi->eeprom->channel_b_type = value;
4211             break;
4212         case CHANNEL_A_DRIVER:
4213             ftdi->eeprom->channel_a_driver = value;
4214             break;
4215         case CHANNEL_B_DRIVER:
4216             ftdi->eeprom->channel_b_driver = value;
4217             break;
4218         case CHANNEL_C_DRIVER:
4219             ftdi->eeprom->channel_c_driver = value;
4220             break;
4221         case CHANNEL_D_DRIVER:
4222             ftdi->eeprom->channel_d_driver = value;
4223             break;
4224         case CHANNEL_A_RS485:
4225             ftdi->eeprom->channel_a_rs485enable = value;
4226             break;
4227         case CHANNEL_B_RS485:
4228             ftdi->eeprom->channel_b_rs485enable = value;
4229             break;
4230         case CHANNEL_C_RS485:
4231             ftdi->eeprom->channel_c_rs485enable = value;
4232             break;
4233         case CHANNEL_D_RS485:
4234             ftdi->eeprom->channel_d_rs485enable = value;
4235             break;
4236         case CBUS_FUNCTION_0:
4237             ftdi->eeprom->cbus_function[0] = value;
4238             break;
4239         case CBUS_FUNCTION_1:
4240             ftdi->eeprom->cbus_function[1] = value;
4241             break;
4242         case CBUS_FUNCTION_2:
4243             ftdi->eeprom->cbus_function[2] = value;
4244             break;
4245         case CBUS_FUNCTION_3:
4246             ftdi->eeprom->cbus_function[3] = value;
4247             break;
4248         case CBUS_FUNCTION_4:
4249             ftdi->eeprom->cbus_function[4] = value;
4250             break;
4251         case CBUS_FUNCTION_5:
4252             ftdi->eeprom->cbus_function[5] = value;
4253             break;
4254         case CBUS_FUNCTION_6:
4255             ftdi->eeprom->cbus_function[6] = value;
4256             break;
4257         case CBUS_FUNCTION_7:
4258             ftdi->eeprom->cbus_function[7] = value;
4259             break;
4260         case CBUS_FUNCTION_8:
4261             ftdi->eeprom->cbus_function[8] = value;
4262             break;
4263         case CBUS_FUNCTION_9:
4264             ftdi->eeprom->cbus_function[9] = value;
4265             break;
4266         case HIGH_CURRENT:
4267             ftdi->eeprom->high_current = value;
4268             break;
4269         case HIGH_CURRENT_A:
4270             ftdi->eeprom->high_current_a = value;
4271             break;
4272         case HIGH_CURRENT_B:
4273             ftdi->eeprom->high_current_b = value;
4274             break;
4275         case INVERT:
4276             ftdi->eeprom->invert = value;
4277             break;
4278         case GROUP0_DRIVE:
4279             ftdi->eeprom->group0_drive = value;
4280             break;
4281         case GROUP0_SCHMITT:
4282             ftdi->eeprom->group0_schmitt = value;
4283             break;
4284         case GROUP0_SLEW:
4285             ftdi->eeprom->group0_slew = value;
4286             break;
4287         case GROUP1_DRIVE:
4288             ftdi->eeprom->group1_drive = value;
4289             break;
4290         case GROUP1_SCHMITT:
4291             ftdi->eeprom->group1_schmitt = value;
4292             break;
4293         case GROUP1_SLEW:
4294             ftdi->eeprom->group1_slew = value;
4295             break;
4296         case GROUP2_DRIVE:
4297             ftdi->eeprom->group2_drive = value;
4298             break;
4299         case GROUP2_SCHMITT:
4300             ftdi->eeprom->group2_schmitt = value;
4301             break;
4302         case GROUP2_SLEW:
4303             ftdi->eeprom->group2_slew = value;
4304             break;
4305         case GROUP3_DRIVE:
4306             ftdi->eeprom->group3_drive = value;
4307             break;
4308         case GROUP3_SCHMITT:
4309             ftdi->eeprom->group3_schmitt = value;
4310             break;
4311         case GROUP3_SLEW:
4312             ftdi->eeprom->group3_slew = value;
4313             break;
4314         case CHIP_TYPE:
4315             ftdi->eeprom->chip = value;
4316             break;
4317         case POWER_SAVE:
4318             ftdi->eeprom->powersave = value;
4319             break;
4320         case CLOCK_POLARITY:
4321             ftdi->eeprom->clock_polarity = value;
4322             break;
4323         case DATA_ORDER:
4324             ftdi->eeprom->data_order = value;
4325             break;
4326         case FLOW_CONTROL:
4327             ftdi->eeprom->flow_control = value;
4328             break;
4329         case CHIP_SIZE:
4330             ftdi_error_return(-2, "EEPROM Value can't be changed");
4331             break;
4332         case EXTERNAL_OSCILLATOR:
4333             ftdi->eeprom->external_oscillator = value;
4334             break;
4335         case USER_DATA_ADDR:
4336             ftdi->eeprom->user_data_addr = value;
4337             break;
4338
4339         default :
4340             ftdi_error_return(-1, "Request to unknown EEPROM value");
4341     }
4342     ftdi->eeprom->initialized_for_connected_device = 0;
4343     return 0;
4344 }
4345
4346 /** Get the read-only buffer to the binary EEPROM content
4347
4348     \param ftdi pointer to ftdi_context
4349     \param buf buffer to receive EEPROM content
4350     \param size Size of receiving buffer
4351
4352     \retval 0: All fine
4353     \retval -1: struct ftdi_contxt or ftdi_eeprom missing
4354     \retval -2: Not enough room to store eeprom
4355 */
4356 int ftdi_get_eeprom_buf(struct ftdi_context *ftdi, unsigned char * buf, int size)
4357 {
4358     if (!ftdi || !(ftdi->eeprom))
4359         ftdi_error_return(-1, "No appropriate structure");
4360
4361     if (!buf || size < ftdi->eeprom->size)
4362         ftdi_error_return(-1, "Not enough room to store eeprom");
4363
4364     // Only copy up to FTDI_MAX_EEPROM_SIZE bytes
4365     if (size > FTDI_MAX_EEPROM_SIZE)
4366         size = FTDI_MAX_EEPROM_SIZE;
4367
4368     memcpy(buf, ftdi->eeprom->buf, size);
4369
4370     return 0;
4371 }
4372
4373 /** Set the EEPROM content from the user-supplied prefilled buffer
4374
4375     \param ftdi pointer to ftdi_context
4376     \param buf buffer to read EEPROM content
4377     \param size Size of buffer
4378
4379     \retval 0: All fine
4380     \retval -1: struct ftdi_context or ftdi_eeprom or buf missing
4381 */
4382 int ftdi_set_eeprom_buf(struct ftdi_context *ftdi, const unsigned char * buf, int size)
4383 {
4384     if (!ftdi || !(ftdi->eeprom) || !buf)
4385         ftdi_error_return(-1, "No appropriate structure");
4386
4387     // Only copy up to FTDI_MAX_EEPROM_SIZE bytes
4388     if (size > FTDI_MAX_EEPROM_SIZE)
4389         size = FTDI_MAX_EEPROM_SIZE;
4390
4391     memcpy(ftdi->eeprom->buf, buf, size);
4392
4393     return 0;
4394 }
4395
4396 /** Set the EEPROM user data content from the user-supplied prefilled buffer
4397
4398     \param ftdi pointer to ftdi_context
4399     \param buf buffer to read EEPROM user data content
4400     \param size Size of buffer
4401
4402     \retval 0: All fine
4403     \retval -1: struct ftdi_context or ftdi_eeprom or buf missing
4404 */
4405 int ftdi_set_eeprom_user_data(struct ftdi_context *ftdi, const char * buf, int size)
4406 {
4407     if (!ftdi || !(ftdi->eeprom) || !buf)
4408         ftdi_error_return(-1, "No appropriate structure");
4409
4410     ftdi->eeprom->user_data_size = size;
4411     ftdi->eeprom->user_data = buf;
4412     return 0;
4413 }
4414
4415 /**
4416     Read eeprom location
4417
4418     \param ftdi pointer to ftdi_context
4419     \param eeprom_addr Address of eeprom location to be read
4420     \param eeprom_val Pointer to store read eeprom location
4421
4422     \retval  0: all fine
4423     \retval -1: read failed
4424     \retval -2: USB device unavailable
4425 */
4426 int ftdi_read_eeprom_location (struct ftdi_context *ftdi, int eeprom_addr, unsigned short *eeprom_val)
4427 {
4428     unsigned char buf[2];
4429
4430     if (ftdi == NULL || ftdi->usb_dev == NULL)
4431         ftdi_error_return(-2, "USB device unavailable");
4432
4433     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)
4434         ftdi_error_return(-1, "reading eeprom failed");
4435
4436     *eeprom_val = (0xff & buf[0]) | (buf[1] << 8);
4437
4438     return 0;
4439 }
4440
4441 /**
4442     Read eeprom
4443
4444     \param ftdi pointer to ftdi_context
4445
4446     \retval  0: all fine
4447     \retval -1: read failed
4448     \retval -2: USB device unavailable
4449 */
4450 int ftdi_read_eeprom(struct ftdi_context *ftdi)
4451 {
4452     int i;
4453     unsigned char *buf;
4454
4455     if (ftdi == NULL || ftdi->usb_dev == NULL)
4456         ftdi_error_return(-2, "USB device unavailable");
4457     buf = ftdi->eeprom->buf;
4458
4459     for (i = 0; i < FTDI_MAX_EEPROM_SIZE/2; i++)
4460     {
4461         if (libusb_control_transfer(
4462                     ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE,SIO_READ_EEPROM_REQUEST, 0, i,
4463                     buf+(i*2), 2, ftdi->usb_read_timeout) != 2)
4464             ftdi_error_return(-1, "reading eeprom failed");
4465     }
4466
4467     if (ftdi->type == TYPE_R)
4468         ftdi->eeprom->size = 0x80;
4469     /*    Guesses size of eeprom by comparing halves
4470           - will not work with blank eeprom */
4471     else if (strrchr((const char *)buf, 0xff) == ((const char *)buf +FTDI_MAX_EEPROM_SIZE -1))
4472         ftdi->eeprom->size = -1;
4473     else if (memcmp(buf,&buf[0x80],0x80) == 0)
4474         ftdi->eeprom->size = 0x80;
4475     else if (memcmp(buf,&buf[0x40],0x40) == 0)
4476         ftdi->eeprom->size = 0x40;
4477     else
4478         ftdi->eeprom->size = 0x100;
4479     return 0;
4480 }
4481
4482 /*
4483     ftdi_read_chipid_shift does the bitshift operation needed for the FTDIChip-ID
4484     Function is only used internally
4485     \internal
4486 */
4487 static unsigned char ftdi_read_chipid_shift(unsigned char value)
4488 {
4489     return ((value & 1) << 1) |
4490            ((value & 2) << 5) |
4491            ((value & 4) >> 2) |
4492            ((value & 8) << 4) |
4493            ((value & 16) >> 1) |
4494            ((value & 32) >> 1) |
4495            ((value & 64) >> 4) |
4496            ((value & 128) >> 2);
4497 }
4498
4499 /**
4500     Read the FTDIChip-ID from R-type devices
4501
4502     \param ftdi pointer to ftdi_context
4503     \param chipid Pointer to store FTDIChip-ID
4504
4505     \retval  0: all fine
4506     \retval -1: read failed
4507     \retval -2: USB device unavailable
4508 */
4509 int ftdi_read_chipid(struct ftdi_context *ftdi, unsigned int *chipid)
4510 {
4511     unsigned int a = 0, b = 0;
4512
4513     if (ftdi == NULL || ftdi->usb_dev == NULL)
4514         ftdi_error_return(-2, "USB device unavailable");
4515
4516     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)
4517     {
4518         a = a << 8 | a >> 8;
4519         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)
4520         {
4521             b = b << 8 | b >> 8;
4522             a = (a << 16) | (b & 0xFFFF);
4523             a = ftdi_read_chipid_shift(a) | ftdi_read_chipid_shift(a>>8)<<8
4524                 | ftdi_read_chipid_shift(a>>16)<<16 | ftdi_read_chipid_shift(a>>24)<<24;
4525             *chipid = a ^ 0xa5f0f7d1;
4526             return 0;
4527         }
4528     }
4529
4530     ftdi_error_return(-1, "read of FTDIChip-ID failed");
4531 }
4532
4533 /**
4534     Write eeprom location
4535
4536     \param ftdi pointer to ftdi_context
4537     \param eeprom_addr Address of eeprom location to be written
4538     \param eeprom_val Value to be written
4539
4540     \retval  0: all fine
4541     \retval -1: write failed
4542     \retval -2: USB device unavailable
4543     \retval -3: Invalid access to checksum protected area below 0x80
4544     \retval -4: Device can't access unprotected area
4545     \retval -5: Reading chip type failed
4546 */
4547 int ftdi_write_eeprom_location(struct ftdi_context *ftdi, int eeprom_addr,
4548                                unsigned short eeprom_val)
4549 {
4550     int chip_type_location;
4551     unsigned short chip_type;
4552
4553     if (ftdi == NULL || ftdi->usb_dev == NULL)
4554         ftdi_error_return(-2, "USB device unavailable");
4555
4556     if (eeprom_addr <0x80)
4557         ftdi_error_return(-2, "Invalid access to checksum protected area  below 0x80");
4558
4559
4560     switch (ftdi->type)
4561     {
4562         case TYPE_BM:
4563         case  TYPE_2232C:
4564             chip_type_location = 0x14;
4565             break;
4566         case TYPE_2232H:
4567         case TYPE_4232H:
4568             chip_type_location = 0x18;
4569             break;
4570         case TYPE_232H:
4571             chip_type_location = 0x1e;
4572             break;
4573         default:
4574             ftdi_error_return(-4, "Device can't access unprotected area");
4575     }
4576
4577     if (ftdi_read_eeprom_location( ftdi, chip_type_location>>1, &chip_type))
4578         ftdi_error_return(-5, "Reading failed");
4579     fprintf(stderr," loc 0x%04x val 0x%04x\n", chip_type_location,chip_type);
4580     if ((chip_type & 0xff) != 0x66)
4581     {
4582         ftdi_error_return(-6, "EEPROM is not of 93x66");
4583     }
4584
4585     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
4586                                 SIO_WRITE_EEPROM_REQUEST, eeprom_val, eeprom_addr,
4587                                 NULL, 0, ftdi->usb_write_timeout) != 0)
4588         ftdi_error_return(-1, "unable to write eeprom");
4589
4590     return 0;
4591 }
4592
4593 /**
4594     Write eeprom
4595
4596     \param ftdi pointer to ftdi_context
4597
4598     \retval  0: all fine
4599     \retval -1: read failed
4600     \retval -2: USB device unavailable
4601     \retval -3: EEPROM not initialized for the connected device;
4602 */
4603 int ftdi_write_eeprom(struct ftdi_context *ftdi)
4604 {
4605     unsigned short usb_val, status;
4606     int i, ret;
4607     unsigned char *eeprom;
4608
4609     if (ftdi == NULL || ftdi->usb_dev == NULL)
4610         ftdi_error_return(-2, "USB device unavailable");
4611
4612     if(ftdi->eeprom->initialized_for_connected_device == 0)
4613         ftdi_error_return(-3, "EEPROM not initialized for the connected device");
4614
4615     eeprom = ftdi->eeprom->buf;
4616
4617     /* These commands were traced while running MProg */
4618     if ((ret = ftdi_usb_reset(ftdi)) != 0)
4619         return ret;
4620     if ((ret = ftdi_poll_modem_status(ftdi, &status)) != 0)
4621         return ret;
4622     if ((ret = ftdi_set_latency_timer(ftdi, 0x77)) != 0)
4623         return ret;
4624
4625     for (i = 0; i < ftdi->eeprom->size/2; i++)
4626     {
4627         /* Do not try to write to reserved area */
4628         if ((ftdi->type == TYPE_230X) && (i == 0x40))
4629         {
4630             i = 0x50;
4631         }
4632         usb_val = eeprom[i*2];
4633         usb_val += eeprom[(i*2)+1] << 8;
4634         if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
4635                                     SIO_WRITE_EEPROM_REQUEST, usb_val, i,
4636                                     NULL, 0, ftdi->usb_write_timeout) < 0)
4637             ftdi_error_return(-1, "unable to write eeprom");
4638     }
4639
4640     return 0;
4641 }
4642
4643 /**
4644     Erase eeprom
4645
4646     This is not supported on FT232R/FT245R according to the MProg manual from FTDI.
4647
4648     \param ftdi pointer to ftdi_context
4649
4650     \retval  0: all fine
4651     \retval -1: erase failed
4652     \retval -2: USB device unavailable
4653     \retval -3: Writing magic failed
4654     \retval -4: Read EEPROM failed
4655     \retval -5: Unexpected EEPROM value
4656 */
4657 #define MAGIC 0x55aa
4658 int ftdi_erase_eeprom(struct ftdi_context *ftdi)
4659 {
4660     unsigned short eeprom_value;
4661     if (ftdi == NULL || ftdi->usb_dev == NULL)
4662         ftdi_error_return(-2, "USB device unavailable");
4663
4664     if ((ftdi->type == TYPE_R) || (ftdi->type == TYPE_230X))
4665     {
4666         ftdi->eeprom->chip = 0;
4667         return 0;
4668     }
4669
4670     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_ERASE_EEPROM_REQUEST,
4671                                 0, 0, NULL, 0, ftdi->usb_write_timeout) < 0)
4672         ftdi_error_return(-1, "unable to erase eeprom");
4673
4674
4675     /* detect chip type by writing 0x55AA as magic at word position 0xc0
4676        Chip is 93x46 if magic is read at word position 0x00, as wraparound happens around 0x40
4677        Chip is 93x56 if magic is read at word position 0x40, as wraparound happens around 0x80
4678        Chip is 93x66 if magic is only read at word position 0xc0*/
4679     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
4680                                 SIO_WRITE_EEPROM_REQUEST, MAGIC, 0xc0,
4681                                 NULL, 0, ftdi->usb_write_timeout) != 0)
4682         ftdi_error_return(-3, "Writing magic failed");
4683     if (ftdi_read_eeprom_location( ftdi, 0x00, &eeprom_value))
4684         ftdi_error_return(-4, "Reading failed");
4685     if (eeprom_value == MAGIC)
4686     {
4687         ftdi->eeprom->chip = 0x46;
4688     }
4689     else
4690     {
4691         if (ftdi_read_eeprom_location( ftdi, 0x40, &eeprom_value))
4692             ftdi_error_return(-4, "Reading failed");
4693         if (eeprom_value == MAGIC)
4694             ftdi->eeprom->chip = 0x56;
4695         else
4696         {
4697             if (ftdi_read_eeprom_location( ftdi, 0xc0, &eeprom_value))
4698                 ftdi_error_return(-4, "Reading failed");
4699             if (eeprom_value == MAGIC)
4700                 ftdi->eeprom->chip = 0x66;
4701             else
4702             {
4703                 ftdi->eeprom->chip = -1;
4704             }
4705         }
4706     }
4707     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_ERASE_EEPROM_REQUEST,
4708                                 0, 0, NULL, 0, ftdi->usb_write_timeout) < 0)
4709         ftdi_error_return(-1, "unable to erase eeprom");
4710     return 0;
4711 }
4712
4713 /**
4714     Get string representation for last error code
4715
4716     \param ftdi pointer to ftdi_context
4717
4718     \retval Pointer to error string
4719 */
4720 const char *ftdi_get_error_string (struct ftdi_context *ftdi)
4721 {
4722     if (ftdi == NULL)
4723         return "";
4724
4725     return ftdi->error_str;
4726 }
4727
4728 /* @} end of doxygen libftdi group */