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