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