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