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