Forward port flexible module unload behavior
[libftdi] / src / ftdi.c
1 /***************************************************************************
2                           ftdi.c  -  description
3                              -------------------
4     begin                : Fri Apr 4 2003
5     copyright            : (C) 2003-2011 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.h"
38
39 #define ftdi_error_return(code, str) do {  \
40         ftdi->error_str = str;             \
41         return code;                       \
42    } while(0);
43
44 #define ftdi_error_return_free_device_list(code, str, devs) do {    \
45         libusb_free_device_list(devs,1);   \
46         ftdi->error_str = str;             \
47         return code;                       \
48    } while(0);
49
50
51 /**
52     Internal function to close usb device pointer.
53     Sets ftdi->usb_dev to NULL.
54     \internal
55
56     \param ftdi pointer to ftdi_context
57
58     \retval none
59 */
60 static void ftdi_usb_close_internal (struct ftdi_context *ftdi)
61 {
62     if (ftdi && ftdi->usb_dev)
63     {
64         libusb_close (ftdi->usb_dev);
65         ftdi->usb_dev = NULL;
66     }
67 }
68
69 /**
70     Initializes a ftdi_context.
71
72     \param ftdi pointer to ftdi_context
73
74     \retval  0: all fine
75     \retval -1: couldn't allocate read buffer
76     \retval -2: couldn't allocate struct  buffer
77
78     \remark This should be called before all functions
79 */
80 int ftdi_init(struct ftdi_context *ftdi)
81 {
82     struct ftdi_eeprom* eeprom = (struct ftdi_eeprom *)malloc(sizeof(struct ftdi_eeprom));
83     ftdi->usb_ctx = NULL;
84     ftdi->usb_dev = NULL;
85     ftdi->usb_read_timeout = 5000;
86     ftdi->usb_write_timeout = 5000;
87
88     ftdi->type = TYPE_BM;    /* chip type */
89     ftdi->baudrate = -1;
90     ftdi->bitbang_enabled = 0;  /* 0: normal mode 1: any of the bitbang modes enabled */
91
92     ftdi->readbuffer = NULL;
93     ftdi->readbuffer_offset = 0;
94     ftdi->readbuffer_remaining = 0;
95     ftdi->writebuffer_chunksize = 4096;
96     ftdi->max_packet_size = 0;
97
98     ftdi_set_interface(ftdi, INTERFACE_ANY);
99     ftdi->bitbang_mode = 1; /* when bitbang is enabled this holds the number of the mode  */
100
101     ftdi->error_str = NULL;
102
103     if (eeprom == 0)
104         ftdi_error_return(-2, "Can't malloc struct ftdi_eeprom");
105     memset(eeprom, 0, sizeof(struct ftdi_eeprom));
106     ftdi->eeprom = eeprom;
107
108     ftdi->module_detach_mode = AUTO_DETACH_SIO_MODULE;
109
110     /* All fine. Now allocate the readbuffer */
111     return ftdi_read_data_set_chunksize(ftdi, 4096);
112 }
113
114 /**
115     Allocate and initialize a new ftdi_context
116
117     \return a pointer to a new ftdi_context, or NULL on failure
118 */
119 struct ftdi_context *ftdi_new(void)
120 {
121     struct ftdi_context * ftdi = (struct ftdi_context *)malloc(sizeof(struct ftdi_context));
122
123     if (ftdi == NULL)
124     {
125         return NULL;
126     }
127
128     if (ftdi_init(ftdi) != 0)
129     {
130         free(ftdi);
131         return NULL;
132     }
133
134     return ftdi;
135 }
136
137 /**
138     Open selected channels on a chip, otherwise use first channel.
139
140     \param ftdi pointer to ftdi_context
141     \param interface Interface to use for FT2232C/2232H/4232H chips.
142
143     \retval  0: all fine
144     \retval -1: unknown interface
145     \retval -2: USB device unavailable
146 */
147 int ftdi_set_interface(struct ftdi_context *ftdi, enum ftdi_interface interface)
148 {
149     if (ftdi == NULL)
150         ftdi_error_return(-2, "USB device unavailable");
151
152     switch (interface)
153     {
154         case INTERFACE_ANY:
155         case INTERFACE_A:
156             ftdi->interface = 0;
157             ftdi->index     = INTERFACE_A;
158             ftdi->in_ep     = 0x02;
159             ftdi->out_ep    = 0x81;
160             break;
161         case INTERFACE_B:
162             ftdi->interface = 1;
163             ftdi->index     = INTERFACE_B;
164             ftdi->in_ep     = 0x04;
165             ftdi->out_ep    = 0x83;
166             break;
167         case INTERFACE_C:
168             ftdi->interface = 2;
169             ftdi->index     = INTERFACE_C;
170             ftdi->in_ep     = 0x06;
171             ftdi->out_ep    = 0x85;
172             break;
173         case INTERFACE_D:
174             ftdi->interface = 3;
175             ftdi->index     = INTERFACE_D;
176             ftdi->in_ep     = 0x08;
177             ftdi->out_ep    = 0x87;
178             break;
179         default:
180             ftdi_error_return(-1, "Unknown interface");
181     }
182     return 0;
183 }
184
185 /**
186     Deinitializes a ftdi_context.
187
188     \param ftdi pointer to ftdi_context
189 */
190 void ftdi_deinit(struct ftdi_context *ftdi)
191 {
192     if (ftdi == NULL)
193         return;
194
195     ftdi_usb_close_internal (ftdi);
196
197     if (ftdi->readbuffer != NULL)
198     {
199         free(ftdi->readbuffer);
200         ftdi->readbuffer = NULL;
201     }
202
203     if (ftdi->eeprom != NULL)
204     {
205         if (ftdi->eeprom->manufacturer != 0)
206         {
207             free(ftdi->eeprom->manufacturer);
208             ftdi->eeprom->manufacturer = 0;
209         }
210         if (ftdi->eeprom->product != 0)
211         {
212             free(ftdi->eeprom->product);
213             ftdi->eeprom->product = 0;
214         }
215         if (ftdi->eeprom->serial != 0)
216         {
217             free(ftdi->eeprom->serial);
218             ftdi->eeprom->serial = 0;
219         }
220         free(ftdi->eeprom);
221         ftdi->eeprom = NULL;
222     }
223     libusb_exit(ftdi->usb_ctx);
224 }
225
226 /**
227     Deinitialize and free an ftdi_context.
228
229     \param ftdi pointer to ftdi_context
230 */
231 void ftdi_free(struct ftdi_context *ftdi)
232 {
233     ftdi_deinit(ftdi);
234     free(ftdi);
235 }
236
237 /**
238     Use an already open libusb device.
239
240     \param ftdi pointer to ftdi_context
241     \param usb libusb libusb_device_handle to use
242 */
243 void ftdi_set_usbdev (struct ftdi_context *ftdi, libusb_device_handle *usb)
244 {
245     if (ftdi == NULL)
246         return;
247
248     ftdi->usb_dev = usb;
249 }
250
251
252 /**
253     Finds all ftdi devices on the usb bus. Creates a new ftdi_device_list which
254     needs to be deallocated by ftdi_list_free() after use.
255
256     \param ftdi pointer to ftdi_context
257     \param devlist Pointer where to store list of found devices
258     \param vendor Vendor ID to search for
259     \param product Product ID to search for
260
261     \retval >0: number of devices found
262     \retval -3: out of memory
263     \retval -4: libusb_init() failed
264     \retval -5: libusb_get_device_list() failed
265     \retval -6: libusb_get_device_descriptor() failed
266 */
267 int ftdi_usb_find_all(struct ftdi_context *ftdi, struct ftdi_device_list **devlist, int vendor, int product)
268 {
269     struct ftdi_device_list **curdev;
270     libusb_device *dev;
271     libusb_device **devs;
272     int count = 0;
273     int i = 0;
274
275     if (libusb_init(&ftdi->usb_ctx) < 0)
276         ftdi_error_return(-4, "libusb_init() failed");
277
278     if (libusb_get_device_list(ftdi->usb_ctx, &devs) < 0)
279         ftdi_error_return(-5, "libusb_get_device_list() failed");
280
281     curdev = devlist;
282     *curdev = NULL;
283
284     while ((dev = devs[i++]) != NULL)
285     {
286         struct libusb_device_descriptor desc;
287
288         if (libusb_get_device_descriptor(dev, &desc) < 0)
289             ftdi_error_return(-6, "libusb_get_device_descriptor() failed");
290
291         if (desc.idVendor == vendor && desc.idProduct == product)
292         {
293             *curdev = (struct ftdi_device_list*)malloc(sizeof(struct ftdi_device_list));
294             if (!*curdev)
295                 ftdi_error_return(-3, "out of memory");
296
297             (*curdev)->next = NULL;
298             (*curdev)->dev = dev;
299
300             curdev = &(*curdev)->next;
301             count++;
302         }
303     }
304
305     return count;
306 }
307
308 /**
309     Frees a usb device list.
310
311     \param devlist USB device list created by ftdi_usb_find_all()
312 */
313 void ftdi_list_free(struct ftdi_device_list **devlist)
314 {
315     struct ftdi_device_list *curdev, *next;
316
317     for (curdev = *devlist; curdev != NULL;)
318     {
319         next = curdev->next;
320         free(curdev);
321         curdev = next;
322     }
323
324     *devlist = NULL;
325 }
326
327 /**
328     Frees a usb device list.
329
330     \param devlist USB device list created by ftdi_usb_find_all()
331 */
332 void ftdi_list_free2(struct ftdi_device_list *devlist)
333 {
334     ftdi_list_free(&devlist);
335 }
336
337 /**
338     Return device ID strings from the usb device.
339
340     The parameters manufacturer, description and serial may be NULL
341     or pointer to buffers to store the fetched strings.
342
343     \note Use this function only in combination with ftdi_usb_find_all()
344           as it closes the internal "usb_dev" after use.
345
346     \param ftdi pointer to ftdi_context
347     \param dev libusb usb_dev to use
348     \param manufacturer Store manufacturer string here if not NULL
349     \param mnf_len Buffer size of manufacturer string
350     \param description Store product description string here if not NULL
351     \param desc_len Buffer size of product description string
352     \param serial Store serial string here if not NULL
353     \param serial_len Buffer size of serial string
354
355     \retval   0: all fine
356     \retval  -1: wrong arguments
357     \retval  -4: unable to open device
358     \retval  -7: get product manufacturer failed
359     \retval  -8: get product description failed
360     \retval  -9: get serial number failed
361     \retval -11: libusb_get_device_descriptor() failed
362 */
363 int ftdi_usb_get_strings(struct ftdi_context * ftdi, struct libusb_device * dev,
364                          char * manufacturer, int mnf_len, char * description, int desc_len, char * serial, int serial_len)
365 {
366     struct libusb_device_descriptor desc;
367
368     if ((ftdi==NULL) || (dev==NULL))
369         return -1;
370
371     if (libusb_open(dev, &ftdi->usb_dev) < 0)
372         ftdi_error_return(-4, "libusb_open() failed");
373
374     if (libusb_get_device_descriptor(dev, &desc) < 0)
375         ftdi_error_return(-11, "libusb_get_device_descriptor() failed");
376
377     if (manufacturer != NULL)
378     {
379         if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iManufacturer, (unsigned char *)manufacturer, mnf_len) < 0)
380         {
381             ftdi_usb_close_internal (ftdi);
382             ftdi_error_return(-7, "libusb_get_string_descriptor_ascii() failed");
383         }
384     }
385
386     if (description != NULL)
387     {
388         if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iProduct, (unsigned char *)description, desc_len) < 0)
389         {
390             ftdi_usb_close_internal (ftdi);
391             ftdi_error_return(-8, "libusb_get_string_descriptor_ascii() failed");
392         }
393     }
394
395     if (serial != NULL)
396     {
397         if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iSerialNumber, (unsigned char *)serial, serial_len) < 0)
398         {
399             ftdi_usb_close_internal (ftdi);
400             ftdi_error_return(-9, "libusb_get_string_descriptor_ascii() failed");
401         }
402     }
403
404     ftdi_usb_close_internal (ftdi);
405
406     return 0;
407 }
408
409 /**
410  * Internal function to determine the maximum packet size.
411  * \param ftdi pointer to ftdi_context
412  * \param dev libusb usb_dev to use
413  * \retval Maximum packet size for this device
414  */
415 static unsigned int _ftdi_determine_max_packet_size(struct ftdi_context *ftdi, libusb_device *dev)
416 {
417     struct libusb_device_descriptor desc;
418     struct libusb_config_descriptor *config0;
419     unsigned int packet_size;
420
421     // Sanity check
422     if (ftdi == NULL || dev == NULL)
423         return 64;
424
425     // Determine maximum packet size. Init with default value.
426     // New hi-speed devices from FTDI use a packet size of 512 bytes
427     // but could be connected to a normal speed USB hub -> 64 bytes packet size.
428     if (ftdi->type == TYPE_2232H || ftdi->type == TYPE_4232H)
429         packet_size = 512;
430     else
431         packet_size = 64;
432
433     if (libusb_get_device_descriptor(dev, &desc) < 0)
434         return packet_size;
435
436     if (libusb_get_config_descriptor(dev, 0, &config0) < 0)
437         return packet_size;
438
439     if (desc.bNumConfigurations > 0)
440     {
441         if (ftdi->interface < config0->bNumInterfaces)
442         {
443             struct libusb_interface interface = config0->interface[ftdi->interface];
444             if (interface.num_altsetting > 0)
445             {
446                 struct libusb_interface_descriptor descriptor = interface.altsetting[0];
447                 if (descriptor.bNumEndpoints > 0)
448                 {
449                     packet_size = descriptor.endpoint[0].wMaxPacketSize;
450                 }
451             }
452         }
453     }
454
455     libusb_free_config_descriptor (config0);
456     return packet_size;
457 }
458
459 /**
460     Opens a ftdi device given by an usb_device.
461
462     \param ftdi pointer to ftdi_context
463     \param dev libusb usb_dev to use
464
465     \retval  0: all fine
466     \retval -3: unable to config device
467     \retval -4: unable to open device
468     \retval -5: unable to claim device
469     \retval -6: reset failed
470     \retval -7: set baudrate failed
471     \retval -8: ftdi context invalid
472     \retval -9: libusb_get_device_descriptor() failed
473     \retval -10: libusb_get_config_descriptor() failed
474     \retval -11: libusb_detach_kernel_driver() failed
475     \retval -12: libusb_get_configuration() failed
476 */
477 int ftdi_usb_open_dev(struct ftdi_context *ftdi, libusb_device *dev)
478 {
479     struct libusb_device_descriptor desc;
480     struct libusb_config_descriptor *config0;
481     int cfg, cfg0, detach_errno = 0;
482
483     if (ftdi == NULL)
484         ftdi_error_return(-8, "ftdi context invalid");
485
486     if (libusb_open(dev, &ftdi->usb_dev) < 0)
487         ftdi_error_return(-4, "libusb_open() failed");
488
489     if (libusb_get_device_descriptor(dev, &desc) < 0)
490         ftdi_error_return(-9, "libusb_get_device_descriptor() failed");
491
492     if (libusb_get_config_descriptor(dev, 0, &config0) < 0)
493         ftdi_error_return(-10, "libusb_get_config_descriptor() failed");
494     cfg0 = config0->bConfigurationValue;
495     libusb_free_config_descriptor (config0);
496
497     // Try to detach ftdi_sio kernel module.
498     //
499     // The return code is kept in a separate variable and only parsed
500     // if usb_set_configuration() or usb_claim_interface() fails as the
501     // detach operation might be denied and everything still works fine.
502     // Likely scenario is a static ftdi_sio kernel module.
503     if (ftdi->module_detach_mode == AUTO_DETACH_SIO_MODULE)
504     {
505         if (libusb_detach_kernel_driver(ftdi->usb_dev, ftdi->interface) !=0)
506             detach_errno = errno;
507     }
508
509     if (libusb_get_configuration (ftdi->usb_dev, &cfg) < 0)
510         ftdi_error_return(-12, "libusb_get_configuration () failed");
511     // set configuration (needed especially for windows)
512     // tolerate EBUSY: one device with one configuration, but two interfaces
513     //    and libftdi sessions to both interfaces (e.g. FT2232)
514     if (desc.bNumConfigurations > 0 && cfg != cfg0)
515     {
516         if (libusb_set_configuration(ftdi->usb_dev, cfg0) < 0)
517         {
518             ftdi_usb_close_internal (ftdi);
519             if (detach_errno == EPERM)
520             {
521                 ftdi_error_return(-8, "inappropriate permissions on device!");
522             }
523             else
524             {
525                 ftdi_error_return(-3, "unable to set usb configuration. Make sure the default FTDI driver is not in use");
526             }
527         }
528     }
529
530     if (libusb_claim_interface(ftdi->usb_dev, ftdi->interface) < 0)
531     {
532         ftdi_usb_close_internal (ftdi);
533         if (detach_errno == EPERM)
534         {
535             ftdi_error_return(-8, "inappropriate permissions on device!");
536         }
537         else
538         {
539             ftdi_error_return(-5, "unable to claim usb device. Make sure the default FTDI driver is not in use");
540         }
541     }
542
543     if (ftdi_usb_reset (ftdi) != 0)
544     {
545         ftdi_usb_close_internal (ftdi);
546         ftdi_error_return(-6, "ftdi_usb_reset failed");
547     }
548
549     // Try to guess chip type
550     // Bug in the BM type chips: bcdDevice is 0x200 for serial == 0
551     if (desc.bcdDevice == 0x400 || (desc.bcdDevice == 0x200
552                                     && desc.iSerialNumber == 0))
553         ftdi->type = TYPE_BM;
554     else if (desc.bcdDevice == 0x200)
555         ftdi->type = TYPE_AM;
556     else if (desc.bcdDevice == 0x500)
557         ftdi->type = TYPE_2232C;
558     else if (desc.bcdDevice == 0x600)
559         ftdi->type = TYPE_R;
560     else if (desc.bcdDevice == 0x700)
561         ftdi->type = TYPE_2232H;
562     else if (desc.bcdDevice == 0x800)
563         ftdi->type = TYPE_4232H;
564
565     // Determine maximum packet size
566     ftdi->max_packet_size = _ftdi_determine_max_packet_size(ftdi, dev);
567
568     if (ftdi_set_baudrate (ftdi, 9600) != 0)
569     {
570         ftdi_usb_close_internal (ftdi);
571         ftdi_error_return(-7, "set baudrate failed");
572     }
573
574     ftdi_error_return(0, "all fine");
575 }
576
577 /**
578     Opens the first device with a given vendor and product ids.
579
580     \param ftdi pointer to ftdi_context
581     \param vendor Vendor ID
582     \param product Product ID
583
584     \retval same as ftdi_usb_open_desc()
585 */
586 int ftdi_usb_open(struct ftdi_context *ftdi, int vendor, int product)
587 {
588     return ftdi_usb_open_desc(ftdi, vendor, product, NULL, NULL);
589 }
590
591 /**
592     Opens the first device with a given, vendor id, product id,
593     description and serial.
594
595     \param ftdi pointer to ftdi_context
596     \param vendor Vendor ID
597     \param product Product ID
598     \param description Description to search for. Use NULL if not needed.
599     \param serial Serial to search for. Use NULL if not needed.
600
601     \retval  0: all fine
602     \retval -3: usb device not found
603     \retval -4: unable to open device
604     \retval -5: unable to claim device
605     \retval -6: reset failed
606     \retval -7: set baudrate failed
607     \retval -8: get product description failed
608     \retval -9: get serial number failed
609     \retval -11: libusb_init() failed
610     \retval -12: libusb_get_device_list() failed
611     \retval -13: libusb_get_device_descriptor() failed
612 */
613 int ftdi_usb_open_desc(struct ftdi_context *ftdi, int vendor, int product,
614                        const char* description, const char* serial)
615 {
616     return ftdi_usb_open_desc_index(ftdi,vendor,product,description,serial,0);
617 }
618
619 /**
620     Opens the index-th device with a given, vendor id, product id,
621     description and serial.
622
623     \param ftdi pointer to ftdi_context
624     \param vendor Vendor ID
625     \param product Product ID
626     \param description Description to search for. Use NULL if not needed.
627     \param serial Serial to search for. Use NULL if not needed.
628     \param index Number of matching device to open if there are more than one, starts with 0.
629
630     \retval  0: all fine
631     \retval -1: usb_find_busses() failed
632     \retval -2: usb_find_devices() failed
633     \retval -3: usb device not found
634     \retval -4: unable to open device
635     \retval -5: unable to claim device
636     \retval -6: reset failed
637     \retval -7: set baudrate failed
638     \retval -8: get product description failed
639     \retval -9: get serial number failed
640     \retval -10: unable to close device
641     \retval -11: ftdi context invalid
642 */
643 int ftdi_usb_open_desc_index(struct ftdi_context *ftdi, int vendor, int product,
644                              const char* description, const char* serial, unsigned int index)
645 {
646     libusb_device *dev;
647     libusb_device **devs;
648     char string[256];
649     int i = 0;
650
651     if (ftdi == NULL)
652         ftdi_error_return(-11, "ftdi context invalid");
653
654     if (libusb_init(&ftdi->usb_ctx) < 0)
655         ftdi_error_return(-11, "libusb_init() failed");
656
657     if (libusb_get_device_list(ftdi->usb_ctx, &devs) < 0)
658         ftdi_error_return(-12, "libusb_get_device_list() failed");
659
660     while ((dev = devs[i++]) != NULL)
661     {
662         struct libusb_device_descriptor desc;
663         int res;
664
665         if (libusb_get_device_descriptor(dev, &desc) < 0)
666             ftdi_error_return_free_device_list(-13, "libusb_get_device_descriptor() failed", devs);
667
668         if (desc.idVendor == vendor && desc.idProduct == product)
669         {
670             if (libusb_open(dev, &ftdi->usb_dev) < 0)
671                 ftdi_error_return_free_device_list(-4, "usb_open() failed", devs);
672
673             if (description != NULL)
674             {
675                 if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iProduct, (unsigned char *)string, sizeof(string)) < 0)
676                 {
677                     ftdi_usb_close_internal (ftdi);
678                     ftdi_error_return_free_device_list(-8, "unable to fetch product description", devs);
679                 }
680                 if (strncmp(string, description, sizeof(string)) != 0)
681                 {
682                     ftdi_usb_close_internal (ftdi);
683                     continue;
684                 }
685             }
686             if (serial != NULL)
687             {
688                 if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iSerialNumber, (unsigned char *)string, sizeof(string)) < 0)
689                 {
690                     ftdi_usb_close_internal (ftdi);
691                     ftdi_error_return_free_device_list(-9, "unable to fetch serial number", devs);
692                 }
693                 if (strncmp(string, serial, sizeof(string)) != 0)
694                 {
695                     ftdi_usb_close_internal (ftdi);
696                     continue;
697                 }
698             }
699
700             ftdi_usb_close_internal (ftdi);
701
702             if (index > 0)
703             {
704                 index--;
705                 continue;
706             }
707
708             res = ftdi_usb_open_dev(ftdi, dev);
709             libusb_free_device_list(devs,1);
710             return res;
711         }
712     }
713
714     // device not found
715     ftdi_error_return_free_device_list(-3, "device not found", devs);
716 }
717
718 /**
719     Opens the ftdi-device described by a description-string.
720     Intended to be used for parsing a device-description given as commandline argument.
721
722     \param ftdi pointer to ftdi_context
723     \param description NULL-terminated description-string, using this format:
724         \li <tt>d:\<devicenode></tt> path of bus and device-node (e.g. "003/001") within usb device tree (usually at /proc/bus/usb/)
725         \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")
726         \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
727         \li <tt>s:\<vendor>:\<product>:\<serial></tt> first device with given vendor id, product id and serial string
728
729     \note The description format may be extended in later versions.
730
731     \retval  0: all fine
732     \retval -1: libusb_init() failed
733     \retval -2: libusb_get_device_list() failed
734     \retval -3: usb device not found
735     \retval -4: unable to open device
736     \retval -5: unable to claim device
737     \retval -6: reset failed
738     \retval -7: set baudrate failed
739     \retval -8: get product description failed
740     \retval -9: get serial number failed
741     \retval -10: unable to close device
742     \retval -11: illegal description format
743     \retval -12: ftdi context invalid
744 */
745 int ftdi_usb_open_string(struct ftdi_context *ftdi, const char* description)
746 {
747     if (ftdi == NULL)
748         ftdi_error_return(-12, "ftdi context invalid");
749
750     if (description[0] == 0 || description[1] != ':')
751         ftdi_error_return(-11, "illegal description format");
752
753     if (description[0] == 'd')
754     {
755         libusb_device *dev;
756         libusb_device **devs;
757         unsigned int bus_number, device_address;
758         int i = 0;
759
760         if (libusb_init (&ftdi->usb_ctx) < 0)
761             ftdi_error_return(-1, "libusb_init() failed");
762
763         if (libusb_get_device_list(ftdi->usb_ctx, &devs) < 0)
764             ftdi_error_return(-2, "libusb_get_device_list() failed");
765
766         /* XXX: This doesn't handle symlinks/odd paths/etc... */
767         if (sscanf (description + 2, "%u/%u", &bus_number, &device_address) != 2)
768             ftdi_error_return_free_device_list(-11, "illegal description format", devs);
769
770         while ((dev = devs[i++]) != NULL)
771         {
772             int ret;
773             if (bus_number == libusb_get_bus_number (dev)
774                     && device_address == libusb_get_device_address (dev))
775             {
776                 ret = ftdi_usb_open_dev(ftdi, dev);
777                 libusb_free_device_list(devs,1);
778                 return ret;
779             }
780         }
781
782         // device not found
783         ftdi_error_return_free_device_list(-3, "device not found", devs);
784     }
785     else if (description[0] == 'i' || description[0] == 's')
786     {
787         unsigned int vendor;
788         unsigned int product;
789         unsigned int index=0;
790         const char *serial=NULL;
791         const char *startp, *endp;
792
793         errno=0;
794         startp=description+2;
795         vendor=strtoul((char*)startp,(char**)&endp,0);
796         if (*endp != ':' || endp == startp || errno != 0)
797             ftdi_error_return(-11, "illegal description format");
798
799         startp=endp+1;
800         product=strtoul((char*)startp,(char**)&endp,0);
801         if (endp == startp || errno != 0)
802             ftdi_error_return(-11, "illegal description format");
803
804         if (description[0] == 'i' && *endp != 0)
805         {
806             /* optional index field in i-mode */
807             if (*endp != ':')
808                 ftdi_error_return(-11, "illegal description format");
809
810             startp=endp+1;
811             index=strtoul((char*)startp,(char**)&endp,0);
812             if (*endp != 0 || endp == startp || errno != 0)
813                 ftdi_error_return(-11, "illegal description format");
814         }
815         if (description[0] == 's')
816         {
817             if (*endp != ':')
818                 ftdi_error_return(-11, "illegal description format");
819
820             /* rest of the description is the serial */
821             serial=endp+1;
822         }
823
824         return ftdi_usb_open_desc_index(ftdi, vendor, product, NULL, serial, index);
825     }
826     else
827     {
828         ftdi_error_return(-11, "illegal description format");
829     }
830 }
831
832 /**
833     Resets the ftdi device.
834
835     \param ftdi pointer to ftdi_context
836
837     \retval  0: all fine
838     \retval -1: FTDI reset failed
839     \retval -2: USB device unavailable
840 */
841 int ftdi_usb_reset(struct ftdi_context *ftdi)
842 {
843     if (ftdi == NULL || ftdi->usb_dev == NULL)
844         ftdi_error_return(-2, "USB device unavailable");
845
846     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
847                                 SIO_RESET_REQUEST, SIO_RESET_SIO,
848                                 ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
849         ftdi_error_return(-1,"FTDI reset failed");
850
851     // Invalidate data in the readbuffer
852     ftdi->readbuffer_offset = 0;
853     ftdi->readbuffer_remaining = 0;
854
855     return 0;
856 }
857
858 /**
859     Clears the read buffer on the chip and the internal read buffer.
860
861     \param ftdi pointer to ftdi_context
862
863     \retval  0: all fine
864     \retval -1: read buffer purge failed
865     \retval -2: USB device unavailable
866 */
867 int ftdi_usb_purge_rx_buffer(struct ftdi_context *ftdi)
868 {
869     if (ftdi == NULL || ftdi->usb_dev == NULL)
870         ftdi_error_return(-2, "USB device unavailable");
871
872     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
873                                 SIO_RESET_REQUEST, SIO_RESET_PURGE_RX,
874                                 ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
875         ftdi_error_return(-1, "FTDI purge of RX buffer failed");
876
877     // Invalidate data in the readbuffer
878     ftdi->readbuffer_offset = 0;
879     ftdi->readbuffer_remaining = 0;
880
881     return 0;
882 }
883
884 /**
885     Clears the write buffer on the chip.
886
887     \param ftdi pointer to ftdi_context
888
889     \retval  0: all fine
890     \retval -1: write buffer purge failed
891     \retval -2: USB device unavailable
892 */
893 int ftdi_usb_purge_tx_buffer(struct ftdi_context *ftdi)
894 {
895     if (ftdi == NULL || ftdi->usb_dev == NULL)
896         ftdi_error_return(-2, "USB device unavailable");
897
898     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
899                                 SIO_RESET_REQUEST, SIO_RESET_PURGE_TX,
900                                 ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
901         ftdi_error_return(-1, "FTDI purge of TX buffer failed");
902
903     return 0;
904 }
905
906 /**
907     Clears the buffers on the chip and the internal read buffer.
908
909     \param ftdi pointer to ftdi_context
910
911     \retval  0: all fine
912     \retval -1: read buffer purge failed
913     \retval -2: write buffer purge failed
914     \retval -3: USB device unavailable
915 */
916 int ftdi_usb_purge_buffers(struct ftdi_context *ftdi)
917 {
918     int result;
919
920     if (ftdi == NULL || ftdi->usb_dev == NULL)
921         ftdi_error_return(-3, "USB device unavailable");
922
923     result = ftdi_usb_purge_rx_buffer(ftdi);
924     if (result < 0)
925         return -1;
926
927     result = ftdi_usb_purge_tx_buffer(ftdi);
928     if (result < 0)
929         return -2;
930
931     return 0;
932 }
933
934
935
936 /**
937     Closes the ftdi device. Call ftdi_deinit() if you're cleaning up.
938
939     \param ftdi pointer to ftdi_context
940
941     \retval  0: all fine
942     \retval -1: usb_release failed
943     \retval -3: ftdi context invalid
944 */
945 int ftdi_usb_close(struct ftdi_context *ftdi)
946 {
947     int rtn = 0;
948
949     if (ftdi == NULL)
950         ftdi_error_return(-3, "ftdi context invalid");
951
952     if (ftdi->usb_dev != NULL)
953         if (libusb_release_interface(ftdi->usb_dev, ftdi->interface) < 0)
954             rtn = -1;
955
956     ftdi_usb_close_internal (ftdi);
957
958     return rtn;
959 }
960
961 /**
962     ftdi_convert_baudrate returns nearest supported baud rate to that requested.
963     Function is only used internally
964     \internal
965 */
966 static int ftdi_convert_baudrate(int baudrate, struct ftdi_context *ftdi,
967                                  unsigned short *value, unsigned short *index)
968 {
969     static const char am_adjust_up[8] = {0, 0, 0, 1, 0, 3, 2, 1};
970     static const char am_adjust_dn[8] = {0, 0, 0, 1, 0, 1, 2, 3};
971     static const char frac_code[8] = {0, 3, 2, 4, 1, 5, 6, 7};
972     int divisor, best_divisor, best_baud, best_baud_diff;
973     unsigned long encoded_divisor;
974     int i;
975
976     if (baudrate <= 0)
977     {
978         // Return error
979         return -1;
980     }
981
982     divisor = 24000000 / baudrate;
983
984     if (ftdi->type == TYPE_AM)
985     {
986         // Round down to supported fraction (AM only)
987         divisor -= am_adjust_dn[divisor & 7];
988     }
989
990     // Try this divisor and the one above it (because division rounds down)
991     best_divisor = 0;
992     best_baud = 0;
993     best_baud_diff = 0;
994     for (i = 0; i < 2; i++)
995     {
996         int try_divisor = divisor + i;
997         int baud_estimate;
998         int baud_diff;
999
1000         // Round up to supported divisor value
1001         if (try_divisor <= 8)
1002         {
1003             // Round up to minimum supported divisor
1004             try_divisor = 8;
1005         }
1006         else if (ftdi->type != TYPE_AM && try_divisor < 12)
1007         {
1008             // BM doesn't support divisors 9 through 11 inclusive
1009             try_divisor = 12;
1010         }
1011         else if (divisor < 16)
1012         {
1013             // AM doesn't support divisors 9 through 15 inclusive
1014             try_divisor = 16;
1015         }
1016         else
1017         {
1018             if (ftdi->type == TYPE_AM)
1019             {
1020                 // Round up to supported fraction (AM only)
1021                 try_divisor += am_adjust_up[try_divisor & 7];
1022                 if (try_divisor > 0x1FFF8)
1023                 {
1024                     // Round down to maximum supported divisor value (for AM)
1025                     try_divisor = 0x1FFF8;
1026                 }
1027             }
1028             else
1029             {
1030                 if (try_divisor > 0x1FFFF)
1031                 {
1032                     // Round down to maximum supported divisor value (for BM)
1033                     try_divisor = 0x1FFFF;
1034                 }
1035             }
1036         }
1037         // Get estimated baud rate (to nearest integer)
1038         baud_estimate = (24000000 + (try_divisor / 2)) / try_divisor;
1039         // Get absolute difference from requested baud rate
1040         if (baud_estimate < baudrate)
1041         {
1042             baud_diff = baudrate - baud_estimate;
1043         }
1044         else
1045         {
1046             baud_diff = baud_estimate - baudrate;
1047         }
1048         if (i == 0 || baud_diff < best_baud_diff)
1049         {
1050             // Closest to requested baud rate so far
1051             best_divisor = try_divisor;
1052             best_baud = baud_estimate;
1053             best_baud_diff = baud_diff;
1054             if (baud_diff == 0)
1055             {
1056                 // Spot on! No point trying
1057                 break;
1058             }
1059         }
1060     }
1061     // Encode the best divisor value
1062     encoded_divisor = (best_divisor >> 3) | (frac_code[best_divisor & 7] << 14);
1063     // Deal with special cases for encoded value
1064     if (encoded_divisor == 1)
1065     {
1066         encoded_divisor = 0;    // 3000000 baud
1067     }
1068     else if (encoded_divisor == 0x4001)
1069     {
1070         encoded_divisor = 1;    // 2000000 baud (BM only)
1071     }
1072     // Split into "value" and "index" values
1073     *value = (unsigned short)(encoded_divisor & 0xFFFF);
1074     if (ftdi->type == TYPE_2232C || ftdi->type == TYPE_2232H || ftdi->type == TYPE_4232H)
1075     {
1076         *index = (unsigned short)(encoded_divisor >> 8);
1077         *index &= 0xFF00;
1078         *index |= ftdi->index;
1079     }
1080     else
1081         *index = (unsigned short)(encoded_divisor >> 16);
1082
1083     // Return the nearest baud rate
1084     return best_baud;
1085 }
1086
1087 /**
1088     Sets the chip baud rate
1089
1090     \param ftdi pointer to ftdi_context
1091     \param baudrate baud rate to set
1092
1093     \retval  0: all fine
1094     \retval -1: invalid baudrate
1095     \retval -2: setting baudrate failed
1096     \retval -3: USB device unavailable
1097 */
1098 int ftdi_set_baudrate(struct ftdi_context *ftdi, int baudrate)
1099 {
1100     unsigned short value, index;
1101     int actual_baudrate;
1102
1103     if (ftdi == NULL || ftdi->usb_dev == NULL)
1104         ftdi_error_return(-3, "USB device unavailable");
1105
1106     if (ftdi->bitbang_enabled)
1107     {
1108         baudrate = baudrate*4;
1109     }
1110
1111     actual_baudrate = ftdi_convert_baudrate(baudrate, ftdi, &value, &index);
1112     if (actual_baudrate <= 0)
1113         ftdi_error_return (-1, "Silly baudrate <= 0.");
1114
1115     // Check within tolerance (about 5%)
1116     if ((actual_baudrate * 2 < baudrate /* Catch overflows */ )
1117             || ((actual_baudrate < baudrate)
1118                 ? (actual_baudrate * 21 < baudrate * 20)
1119                 : (baudrate * 21 < actual_baudrate * 20)))
1120         ftdi_error_return (-1, "Unsupported baudrate. Note: bitbang baudrates are automatically multiplied by 4");
1121
1122     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1123                                 SIO_SET_BAUDRATE_REQUEST, value,
1124                                 index, NULL, 0, ftdi->usb_write_timeout) < 0)
1125         ftdi_error_return (-2, "Setting new baudrate failed");
1126
1127     ftdi->baudrate = baudrate;
1128     return 0;
1129 }
1130
1131 /**
1132     Set (RS232) line characteristics.
1133     The break type can only be set via ftdi_set_line_property2()
1134     and defaults to "off".
1135
1136     \param ftdi pointer to ftdi_context
1137     \param bits Number of bits
1138     \param sbit Number of stop bits
1139     \param parity Parity mode
1140
1141     \retval  0: all fine
1142     \retval -1: Setting line property failed
1143 */
1144 int ftdi_set_line_property(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
1145                            enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity)
1146 {
1147     return ftdi_set_line_property2(ftdi, bits, sbit, parity, BREAK_OFF);
1148 }
1149
1150 /**
1151     Set (RS232) line characteristics
1152
1153     \param ftdi pointer to ftdi_context
1154     \param bits Number of bits
1155     \param sbit Number of stop bits
1156     \param parity Parity mode
1157     \param break_type Break type
1158
1159     \retval  0: all fine
1160     \retval -1: Setting line property failed
1161     \retval -2: USB device unavailable
1162 */
1163 int ftdi_set_line_property2(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
1164                             enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity,
1165                             enum ftdi_break_type break_type)
1166 {
1167     unsigned short value = bits;
1168
1169     if (ftdi == NULL || ftdi->usb_dev == NULL)
1170         ftdi_error_return(-2, "USB device unavailable");
1171
1172     switch (parity)
1173     {
1174         case NONE:
1175             value |= (0x00 << 8);
1176             break;
1177         case ODD:
1178             value |= (0x01 << 8);
1179             break;
1180         case EVEN:
1181             value |= (0x02 << 8);
1182             break;
1183         case MARK:
1184             value |= (0x03 << 8);
1185             break;
1186         case SPACE:
1187             value |= (0x04 << 8);
1188             break;
1189     }
1190
1191     switch (sbit)
1192     {
1193         case STOP_BIT_1:
1194             value |= (0x00 << 11);
1195             break;
1196         case STOP_BIT_15:
1197             value |= (0x01 << 11);
1198             break;
1199         case STOP_BIT_2:
1200             value |= (0x02 << 11);
1201             break;
1202     }
1203
1204     switch (break_type)
1205     {
1206         case BREAK_OFF:
1207             value |= (0x00 << 14);
1208             break;
1209         case BREAK_ON:
1210             value |= (0x01 << 14);
1211             break;
1212     }
1213
1214     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1215                                 SIO_SET_DATA_REQUEST, value,
1216                                 ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
1217         ftdi_error_return (-1, "Setting new line property failed");
1218
1219     return 0;
1220 }
1221
1222 /**
1223     Writes data in chunks (see ftdi_write_data_set_chunksize()) to the chip
1224
1225     \param ftdi pointer to ftdi_context
1226     \param buf Buffer with the data
1227     \param size Size of the buffer
1228
1229     \retval -666: USB device unavailable
1230     \retval <0: error code from usb_bulk_write()
1231     \retval >0: number of bytes written
1232 */
1233 int ftdi_write_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
1234 {
1235     int offset = 0;
1236     int actual_length;
1237
1238     if (ftdi == NULL || ftdi->usb_dev == NULL)
1239         ftdi_error_return(-666, "USB device unavailable");
1240
1241     while (offset < size)
1242     {
1243         int write_size = ftdi->writebuffer_chunksize;
1244
1245         if (offset+write_size > size)
1246             write_size = size-offset;
1247
1248         if (libusb_bulk_transfer(ftdi->usb_dev, ftdi->in_ep, buf+offset, write_size, &actual_length, ftdi->usb_write_timeout) < 0)
1249             ftdi_error_return(-1, "usb bulk write failed");
1250
1251         offset += actual_length;
1252     }
1253
1254     return offset;
1255 }
1256
1257 static void ftdi_read_data_cb(struct libusb_transfer *transfer)
1258 {
1259     struct ftdi_transfer_control *tc = (struct ftdi_transfer_control *) transfer->user_data;
1260     struct ftdi_context *ftdi = tc->ftdi;
1261     int packet_size, actual_length, num_of_chunks, chunk_remains, i, ret;
1262
1263     packet_size = ftdi->max_packet_size;
1264
1265     actual_length = transfer->actual_length;
1266
1267     if (actual_length > 2)
1268     {
1269         // skip FTDI status bytes.
1270         // Maybe stored in the future to enable modem use
1271         num_of_chunks = actual_length / packet_size;
1272         chunk_remains = actual_length % packet_size;
1273         //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);
1274
1275         ftdi->readbuffer_offset += 2;
1276         actual_length -= 2;
1277
1278         if (actual_length > packet_size - 2)
1279         {
1280             for (i = 1; i < num_of_chunks; i++)
1281                 memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1282                          ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1283                          packet_size - 2);
1284             if (chunk_remains > 2)
1285             {
1286                 memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1287                          ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1288                          chunk_remains-2);
1289                 actual_length -= 2*num_of_chunks;
1290             }
1291             else
1292                 actual_length -= 2*(num_of_chunks-1)+chunk_remains;
1293         }
1294
1295         if (actual_length > 0)
1296         {
1297             // data still fits in buf?
1298             if (tc->offset + actual_length <= tc->size)
1299             {
1300                 memcpy (tc->buf + tc->offset, ftdi->readbuffer + ftdi->readbuffer_offset, actual_length);
1301                 //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
1302                 tc->offset += actual_length;
1303
1304                 ftdi->readbuffer_offset = 0;
1305                 ftdi->readbuffer_remaining = 0;
1306
1307                 /* Did we read exactly the right amount of bytes? */
1308                 if (tc->offset == tc->size)
1309                 {
1310                     //printf("read_data exact rem %d offset %d\n",
1311                     //ftdi->readbuffer_remaining, offset);
1312                     tc->completed = 1;
1313                     return;
1314                 }
1315             }
1316             else
1317             {
1318                 // only copy part of the data or size <= readbuffer_chunksize
1319                 int part_size = tc->size - tc->offset;
1320                 memcpy (tc->buf + tc->offset, ftdi->readbuffer + ftdi->readbuffer_offset, part_size);
1321                 tc->offset += part_size;
1322
1323                 ftdi->readbuffer_offset += part_size;
1324                 ftdi->readbuffer_remaining = actual_length - part_size;
1325
1326                 /* printf("Returning part: %d - size: %d - offset: %d - actual_length: %d - remaining: %d\n",
1327                 part_size, size, offset, actual_length, ftdi->readbuffer_remaining); */
1328                 tc->completed = 1;
1329                 return;
1330             }
1331         }
1332     }
1333     ret = libusb_submit_transfer (transfer);
1334     if (ret < 0)
1335         tc->completed = 1;
1336 }
1337
1338
1339 static void ftdi_write_data_cb(struct libusb_transfer *transfer)
1340 {
1341     struct ftdi_transfer_control *tc = (struct ftdi_transfer_control *) transfer->user_data;
1342     struct ftdi_context *ftdi = tc->ftdi;
1343
1344     tc->offset += transfer->actual_length;
1345
1346     if (tc->offset == tc->size)
1347     {
1348         tc->completed = 1;
1349     }
1350     else
1351     {
1352         int write_size = ftdi->writebuffer_chunksize;
1353         int ret;
1354
1355         if (tc->offset + write_size > tc->size)
1356             write_size = tc->size - tc->offset;
1357
1358         transfer->length = write_size;
1359         transfer->buffer = tc->buf + tc->offset;
1360         ret = libusb_submit_transfer (transfer);
1361         if (ret < 0)
1362             tc->completed = 1;
1363     }
1364 }
1365
1366
1367 /**
1368     Writes data to the chip. Does not wait for completion of the transfer
1369     nor does it make sure that the transfer was successful.
1370
1371     Use libusb 1.0 asynchronous API.
1372
1373     \param ftdi pointer to ftdi_context
1374     \param buf Buffer with the data
1375     \param size Size of the buffer
1376
1377     \retval NULL: Some error happens when submit transfer
1378     \retval !NULL: Pointer to a ftdi_transfer_control
1379 */
1380
1381 struct ftdi_transfer_control *ftdi_write_data_submit(struct ftdi_context *ftdi, unsigned char *buf, int size)
1382 {
1383     struct ftdi_transfer_control *tc;
1384     struct libusb_transfer *transfer;
1385     int write_size, ret;
1386
1387     if (ftdi == NULL || ftdi->usb_dev == NULL)
1388         return NULL;
1389
1390     tc = (struct ftdi_transfer_control *) malloc (sizeof (*tc));
1391     if (!tc)
1392         return NULL;
1393
1394     transfer = libusb_alloc_transfer(0);
1395     if (!transfer)
1396     {
1397         free(tc);
1398         return NULL;
1399     }
1400
1401     tc->ftdi = ftdi;
1402     tc->completed = 0;
1403     tc->buf = buf;
1404     tc->size = size;
1405     tc->offset = 0;
1406
1407     if (size < ftdi->writebuffer_chunksize)
1408         write_size = size;
1409     else
1410         write_size = ftdi->writebuffer_chunksize;
1411
1412     libusb_fill_bulk_transfer(transfer, ftdi->usb_dev, ftdi->in_ep, buf,
1413                               write_size, ftdi_write_data_cb, tc,
1414                               ftdi->usb_write_timeout);
1415     transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
1416
1417     ret = libusb_submit_transfer(transfer);
1418     if (ret < 0)
1419     {
1420         libusb_free_transfer(transfer);
1421         free(tc);
1422         return NULL;
1423     }
1424     tc->transfer = transfer;
1425
1426     return tc;
1427 }
1428
1429 /**
1430     Reads data from the chip. Does not wait for completion of the transfer
1431     nor does it make sure that the transfer was successful.
1432
1433     Use libusb 1.0 asynchronous API.
1434
1435     \param ftdi pointer to ftdi_context
1436     \param buf Buffer with the data
1437     \param size Size of the buffer
1438
1439     \retval NULL: Some error happens when submit transfer
1440     \retval !NULL: Pointer to a ftdi_transfer_control
1441 */
1442
1443 struct ftdi_transfer_control *ftdi_read_data_submit(struct ftdi_context *ftdi, unsigned char *buf, int size)
1444 {
1445     struct ftdi_transfer_control *tc;
1446     struct libusb_transfer *transfer;
1447     int ret;
1448
1449     if (ftdi == NULL || ftdi->usb_dev == NULL)
1450         return NULL;
1451
1452     tc = (struct ftdi_transfer_control *) malloc (sizeof (*tc));
1453     if (!tc)
1454         return NULL;
1455
1456     tc->ftdi = ftdi;
1457     tc->buf = buf;
1458     tc->size = size;
1459
1460     if (size <= ftdi->readbuffer_remaining)
1461     {
1462         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);
1463
1464         // Fix offsets
1465         ftdi->readbuffer_remaining -= size;
1466         ftdi->readbuffer_offset += size;
1467
1468         /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */
1469
1470         tc->completed = 1;
1471         tc->offset = size;
1472         tc->transfer = NULL;
1473         return tc;
1474     }
1475
1476     tc->completed = 0;
1477     if (ftdi->readbuffer_remaining != 0)
1478     {
1479         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);
1480
1481         tc->offset = ftdi->readbuffer_remaining;
1482     }
1483     else
1484         tc->offset = 0;
1485
1486     transfer = libusb_alloc_transfer(0);
1487     if (!transfer)
1488     {
1489         free (tc);
1490         return NULL;
1491     }
1492
1493     ftdi->readbuffer_remaining = 0;
1494     ftdi->readbuffer_offset = 0;
1495
1496     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);
1497     transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
1498
1499     ret = libusb_submit_transfer(transfer);
1500     if (ret < 0)
1501     {
1502         libusb_free_transfer(transfer);
1503         free (tc);
1504         return NULL;
1505     }
1506     tc->transfer = transfer;
1507
1508     return tc;
1509 }
1510
1511 /**
1512     Wait for completion of the transfer.
1513
1514     Use libusb 1.0 asynchronous API.
1515
1516     \param tc pointer to ftdi_transfer_control
1517
1518     \retval < 0: Some error happens
1519     \retval >= 0: Data size transferred
1520 */
1521
1522 int ftdi_transfer_data_done(struct ftdi_transfer_control *tc)
1523 {
1524     int ret;
1525
1526     while (!tc->completed)
1527     {
1528         ret = libusb_handle_events(tc->ftdi->usb_ctx);
1529         if (ret < 0)
1530         {
1531             if (ret == LIBUSB_ERROR_INTERRUPTED)
1532                 continue;
1533             libusb_cancel_transfer(tc->transfer);
1534             while (!tc->completed)
1535                 if (libusb_handle_events(tc->ftdi->usb_ctx) < 0)
1536                     break;
1537             libusb_free_transfer(tc->transfer);
1538             free (tc);
1539             return ret;
1540         }
1541     }
1542
1543     ret = tc->offset;
1544     /**
1545      * tc->transfer could be NULL if "(size <= ftdi->readbuffer_remaining)"
1546      * at ftdi_read_data_submit(). Therefore, we need to check it here.
1547      **/
1548     if (tc->transfer)
1549     {
1550         if (tc->transfer->status != LIBUSB_TRANSFER_COMPLETED)
1551             ret = -1;
1552         libusb_free_transfer(tc->transfer);
1553     }
1554     free(tc);
1555     return ret;
1556 }
1557
1558 /**
1559     Configure write buffer chunk size.
1560     Default is 4096.
1561
1562     \param ftdi pointer to ftdi_context
1563     \param chunksize Chunk size
1564
1565     \retval 0: all fine
1566     \retval -1: ftdi context invalid
1567 */
1568 int ftdi_write_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
1569 {
1570     if (ftdi == NULL)
1571         ftdi_error_return(-1, "ftdi context invalid");
1572
1573     ftdi->writebuffer_chunksize = chunksize;
1574     return 0;
1575 }
1576
1577 /**
1578     Get write buffer chunk size.
1579
1580     \param ftdi pointer to ftdi_context
1581     \param chunksize Pointer to store chunk size in
1582
1583     \retval 0: all fine
1584     \retval -1: ftdi context invalid
1585 */
1586 int ftdi_write_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
1587 {
1588     if (ftdi == NULL)
1589         ftdi_error_return(-1, "ftdi context invalid");
1590
1591     *chunksize = ftdi->writebuffer_chunksize;
1592     return 0;
1593 }
1594
1595 /**
1596     Reads data in chunks (see ftdi_read_data_set_chunksize()) from the chip.
1597
1598     Automatically strips the two modem status bytes transfered during every read.
1599
1600     \param ftdi pointer to ftdi_context
1601     \param buf Buffer to store data in
1602     \param size Size of the buffer
1603
1604     \retval -666: USB device unavailable
1605     \retval <0: error code from libusb_bulk_transfer()
1606     \retval  0: no data was available
1607     \retval >0: number of bytes read
1608
1609 */
1610 int ftdi_read_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
1611 {
1612     int offset = 0, ret, i, num_of_chunks, chunk_remains;
1613     int packet_size = ftdi->max_packet_size;
1614     int actual_length = 1;
1615
1616     if (ftdi == NULL || ftdi->usb_dev == NULL)
1617         ftdi_error_return(-666, "USB device unavailable");
1618
1619     // Packet size sanity check (avoid division by zero)
1620     if (packet_size == 0)
1621         ftdi_error_return(-1, "max_packet_size is bogus (zero)");
1622
1623     // everything we want is still in the readbuffer?
1624     if (size <= ftdi->readbuffer_remaining)
1625     {
1626         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);
1627
1628         // Fix offsets
1629         ftdi->readbuffer_remaining -= size;
1630         ftdi->readbuffer_offset += size;
1631
1632         /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */
1633
1634         return size;
1635     }
1636     // something still in the readbuffer, but not enough to satisfy 'size'?
1637     if (ftdi->readbuffer_remaining != 0)
1638     {
1639         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);
1640
1641         // Fix offset
1642         offset += ftdi->readbuffer_remaining;
1643     }
1644     // do the actual USB read
1645     while (offset < size && actual_length > 0)
1646     {
1647         ftdi->readbuffer_remaining = 0;
1648         ftdi->readbuffer_offset = 0;
1649         /* returns how much received */
1650         ret = libusb_bulk_transfer (ftdi->usb_dev, ftdi->out_ep, ftdi->readbuffer, ftdi->readbuffer_chunksize, &actual_length, ftdi->usb_read_timeout);
1651         if (ret < 0)
1652             ftdi_error_return(ret, "usb bulk read failed");
1653
1654         if (actual_length > 2)
1655         {
1656             // skip FTDI status bytes.
1657             // Maybe stored in the future to enable modem use
1658             num_of_chunks = actual_length / packet_size;
1659             chunk_remains = actual_length % packet_size;
1660             //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);
1661
1662             ftdi->readbuffer_offset += 2;
1663             actual_length -= 2;
1664
1665             if (actual_length > packet_size - 2)
1666             {
1667                 for (i = 1; i < num_of_chunks; i++)
1668                     memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1669                              ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1670                              packet_size - 2);
1671                 if (chunk_remains > 2)
1672                 {
1673                     memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1674                              ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1675                              chunk_remains-2);
1676                     actual_length -= 2*num_of_chunks;
1677                 }
1678                 else
1679                     actual_length -= 2*(num_of_chunks-1)+chunk_remains;
1680             }
1681         }
1682         else if (actual_length <= 2)
1683         {
1684             // no more data to read?
1685             return offset;
1686         }
1687         if (actual_length > 0)
1688         {
1689             // data still fits in buf?
1690             if (offset+actual_length <= size)
1691             {
1692                 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, actual_length);
1693                 //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
1694                 offset += actual_length;
1695
1696                 /* Did we read exactly the right amount of bytes? */
1697                 if (offset == size)
1698                     //printf("read_data exact rem %d offset %d\n",
1699                     //ftdi->readbuffer_remaining, offset);
1700                     return offset;
1701             }
1702             else
1703             {
1704                 // only copy part of the data or size <= readbuffer_chunksize
1705                 int part_size = size-offset;
1706                 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, part_size);
1707
1708                 ftdi->readbuffer_offset += part_size;
1709                 ftdi->readbuffer_remaining = actual_length-part_size;
1710                 offset += part_size;
1711
1712                 /* printf("Returning part: %d - size: %d - offset: %d - actual_length: %d - remaining: %d\n",
1713                 part_size, size, offset, actual_length, ftdi->readbuffer_remaining); */
1714
1715                 return offset;
1716             }
1717         }
1718     }
1719     // never reached
1720     return -127;
1721 }
1722
1723 /**
1724     Configure read buffer chunk size.
1725     Default is 4096.
1726
1727     Automatically reallocates the buffer.
1728
1729     \param ftdi pointer to ftdi_context
1730     \param chunksize Chunk size
1731
1732     \retval 0: all fine
1733     \retval -1: ftdi context invalid
1734 */
1735 int ftdi_read_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
1736 {
1737     unsigned char *new_buf;
1738
1739     if (ftdi == NULL)
1740         ftdi_error_return(-1, "ftdi context invalid");
1741
1742     // Invalidate all remaining data
1743     ftdi->readbuffer_offset = 0;
1744     ftdi->readbuffer_remaining = 0;
1745 #ifdef __linux__
1746     /* We can't set readbuffer_chunksize larger than MAX_BULK_BUFFER_LENGTH,
1747        which is defined in libusb-1.0.  Otherwise, each USB read request will
1748        be divided into multiple URBs.  This will cause issues on Linux kernel
1749        older than 2.6.32.  */
1750     if (chunksize > 16384)
1751         chunksize = 16384;
1752 #endif
1753
1754     if ((new_buf = (unsigned char *)realloc(ftdi->readbuffer, chunksize)) == NULL)
1755         ftdi_error_return(-1, "out of memory for readbuffer");
1756
1757     ftdi->readbuffer = new_buf;
1758     ftdi->readbuffer_chunksize = chunksize;
1759
1760     return 0;
1761 }
1762
1763 /**
1764     Get read buffer chunk size.
1765
1766     \param ftdi pointer to ftdi_context
1767     \param chunksize Pointer to store chunk size in
1768
1769     \retval 0: all fine
1770     \retval -1: FTDI context invalid
1771 */
1772 int ftdi_read_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
1773 {
1774     if (ftdi == NULL)
1775         ftdi_error_return(-1, "FTDI context invalid");
1776
1777     *chunksize = ftdi->readbuffer_chunksize;
1778     return 0;
1779 }
1780
1781
1782 /**
1783     Enable bitbang mode.
1784
1785     \deprecated use \ref ftdi_set_bitmode with mode BITMODE_BITBANG instead
1786
1787     \param ftdi pointer to ftdi_context
1788     \param bitmask Bitmask to configure lines.
1789            HIGH/ON value configures a line as output.
1790
1791     \retval  0: all fine
1792     \retval -1: can't enable bitbang mode
1793     \retval -2: USB device unavailable
1794 */
1795 int ftdi_enable_bitbang(struct ftdi_context *ftdi, unsigned char bitmask)
1796 {
1797     unsigned short usb_val;
1798
1799     if (ftdi == NULL || ftdi->usb_dev == NULL)
1800         ftdi_error_return(-2, "USB device unavailable");
1801
1802     usb_val = bitmask; // low byte: bitmask
1803     /* FT2232C: Set bitbang_mode to 2 to enable SPI */
1804     usb_val |= (ftdi->bitbang_mode << 8);
1805
1806     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1807                                 SIO_SET_BITMODE_REQUEST, usb_val, ftdi->index,
1808                                 NULL, 0, ftdi->usb_write_timeout) < 0)
1809         ftdi_error_return(-1, "unable to enter bitbang mode. Perhaps not a BM type chip?");
1810
1811     ftdi->bitbang_enabled = 1;
1812     return 0;
1813 }
1814
1815 /**
1816     Disable bitbang mode.
1817
1818     \param ftdi pointer to ftdi_context
1819
1820     \retval  0: all fine
1821     \retval -1: can't disable bitbang mode
1822     \retval -2: USB device unavailable
1823 */
1824 int ftdi_disable_bitbang(struct ftdi_context *ftdi)
1825 {
1826     if (ftdi == NULL || ftdi->usb_dev == NULL)
1827         ftdi_error_return(-2, "USB device unavailable");
1828
1829     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)
1830         ftdi_error_return(-1, "unable to leave bitbang mode. Perhaps not a BM type chip?");
1831
1832     ftdi->bitbang_enabled = 0;
1833     return 0;
1834 }
1835
1836 /**
1837     Enable/disable bitbang modes.
1838
1839     \param ftdi pointer to ftdi_context
1840     \param bitmask Bitmask to configure lines.
1841            HIGH/ON value configures a line as output.
1842     \param mode Bitbang mode: use the values defined in \ref ftdi_mpsse_mode
1843
1844     \retval  0: all fine
1845     \retval -1: can't enable bitbang mode
1846     \retval -2: USB device unavailable
1847 */
1848 int ftdi_set_bitmode(struct ftdi_context *ftdi, unsigned char bitmask, unsigned char mode)
1849 {
1850     unsigned short usb_val;
1851
1852     if (ftdi == NULL || ftdi->usb_dev == NULL)
1853         ftdi_error_return(-2, "USB device unavailable");
1854
1855     usb_val = bitmask; // low byte: bitmask
1856     usb_val |= (mode << 8);
1857     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)
1858         ftdi_error_return(-1, "unable to configure bitbang mode. Perhaps not a 2232C type chip?");
1859
1860     ftdi->bitbang_mode = mode;
1861     ftdi->bitbang_enabled = (mode == BITMODE_RESET) ? 0 : 1;
1862     return 0;
1863 }
1864
1865 /**
1866     Directly read pin state, circumventing the read buffer. Useful for bitbang mode.
1867
1868     \param ftdi pointer to ftdi_context
1869     \param pins Pointer to store pins into
1870
1871     \retval  0: all fine
1872     \retval -1: read pins failed
1873     \retval -2: USB device unavailable
1874 */
1875 int ftdi_read_pins(struct ftdi_context *ftdi, unsigned char *pins)
1876 {
1877     if (ftdi == NULL || ftdi->usb_dev == NULL)
1878         ftdi_error_return(-2, "USB device unavailable");
1879
1880     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)
1881         ftdi_error_return(-1, "read pins failed");
1882
1883     return 0;
1884 }
1885
1886 /**
1887     Set latency timer
1888
1889     The FTDI chip keeps data in the internal buffer for a specific
1890     amount of time if the buffer is not full yet to decrease
1891     load on the usb bus.
1892
1893     \param ftdi pointer to ftdi_context
1894     \param latency Value between 1 and 255
1895
1896     \retval  0: all fine
1897     \retval -1: latency out of range
1898     \retval -2: unable to set latency timer
1899     \retval -3: USB device unavailable
1900 */
1901 int ftdi_set_latency_timer(struct ftdi_context *ftdi, unsigned char latency)
1902 {
1903     unsigned short usb_val;
1904
1905     if (latency < 1)
1906         ftdi_error_return(-1, "latency out of range. Only valid for 1-255");
1907
1908     if (ftdi == NULL || ftdi->usb_dev == NULL)
1909         ftdi_error_return(-3, "USB device unavailable");
1910
1911     usb_val = latency;
1912     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)
1913         ftdi_error_return(-2, "unable to set latency timer");
1914
1915     return 0;
1916 }
1917
1918 /**
1919     Get latency timer
1920
1921     \param ftdi pointer to ftdi_context
1922     \param latency Pointer to store latency value in
1923
1924     \retval  0: all fine
1925     \retval -1: unable to get latency timer
1926     \retval -2: USB device unavailable
1927 */
1928 int ftdi_get_latency_timer(struct ftdi_context *ftdi, unsigned char *latency)
1929 {
1930     unsigned short usb_val;
1931
1932     if (ftdi == NULL || ftdi->usb_dev == NULL)
1933         ftdi_error_return(-2, "USB device unavailable");
1934
1935     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)
1936         ftdi_error_return(-1, "reading latency timer failed");
1937
1938     *latency = (unsigned char)usb_val;
1939     return 0;
1940 }
1941
1942 /**
1943     Poll modem status information
1944
1945     This function allows the retrieve the two status bytes of the device.
1946     The device sends these bytes also as a header for each read access
1947     where they are discarded by ftdi_read_data(). The chip generates
1948     the two stripped status bytes in the absence of data every 40 ms.
1949
1950     Layout of the first byte:
1951     - B0..B3 - must be 0
1952     - B4       Clear to send (CTS)
1953                  0 = inactive
1954                  1 = active
1955     - B5       Data set ready (DTS)
1956                  0 = inactive
1957                  1 = active
1958     - B6       Ring indicator (RI)
1959                  0 = inactive
1960                  1 = active
1961     - B7       Receive line signal detect (RLSD)
1962                  0 = inactive
1963                  1 = active
1964
1965     Layout of the second byte:
1966     - B0       Data ready (DR)
1967     - B1       Overrun error (OE)
1968     - B2       Parity error (PE)
1969     - B3       Framing error (FE)
1970     - B4       Break interrupt (BI)
1971     - B5       Transmitter holding register (THRE)
1972     - B6       Transmitter empty (TEMT)
1973     - B7       Error in RCVR FIFO
1974
1975     \param ftdi pointer to ftdi_context
1976     \param status Pointer to store status information in. Must be two bytes.
1977
1978     \retval  0: all fine
1979     \retval -1: unable to retrieve status information
1980     \retval -2: USB device unavailable
1981 */
1982 int ftdi_poll_modem_status(struct ftdi_context *ftdi, unsigned short *status)
1983 {
1984     char usb_val[2];
1985
1986     if (ftdi == NULL || ftdi->usb_dev == NULL)
1987         ftdi_error_return(-2, "USB device unavailable");
1988
1989     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)
1990         ftdi_error_return(-1, "getting modem status failed");
1991
1992     *status = (usb_val[1] << 8) | (usb_val[0] & 0xFF);
1993
1994     return 0;
1995 }
1996
1997 /**
1998     Set flowcontrol for ftdi chip
1999
2000     \param ftdi pointer to ftdi_context
2001     \param flowctrl flow control to use. should be
2002            SIO_DISABLE_FLOW_CTRL, SIO_RTS_CTS_HS, SIO_DTR_DSR_HS or SIO_XON_XOFF_HS
2003
2004     \retval  0: all fine
2005     \retval -1: set flow control failed
2006     \retval -2: USB device unavailable
2007 */
2008 int ftdi_setflowctrl(struct ftdi_context *ftdi, int flowctrl)
2009 {
2010     if (ftdi == NULL || ftdi->usb_dev == NULL)
2011         ftdi_error_return(-2, "USB device unavailable");
2012
2013     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
2014                                 SIO_SET_FLOW_CTRL_REQUEST, 0, (flowctrl | ftdi->index),
2015                                 NULL, 0, ftdi->usb_write_timeout) < 0)
2016         ftdi_error_return(-1, "set flow control failed");
2017
2018     return 0;
2019 }
2020
2021 /**
2022     Set dtr line
2023
2024     \param ftdi pointer to ftdi_context
2025     \param state state to set line to (1 or 0)
2026
2027     \retval  0: all fine
2028     \retval -1: set dtr failed
2029     \retval -2: USB device unavailable
2030 */
2031 int ftdi_setdtr(struct ftdi_context *ftdi, int state)
2032 {
2033     unsigned short usb_val;
2034
2035     if (ftdi == NULL || ftdi->usb_dev == NULL)
2036         ftdi_error_return(-2, "USB device unavailable");
2037
2038     if (state)
2039         usb_val = SIO_SET_DTR_HIGH;
2040     else
2041         usb_val = SIO_SET_DTR_LOW;
2042
2043     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
2044                                 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
2045                                 NULL, 0, ftdi->usb_write_timeout) < 0)
2046         ftdi_error_return(-1, "set dtr failed");
2047
2048     return 0;
2049 }
2050
2051 /**
2052     Set rts line
2053
2054     \param ftdi pointer to ftdi_context
2055     \param state state to set line to (1 or 0)
2056
2057     \retval  0: all fine
2058     \retval -1: set rts failed
2059     \retval -2: USB device unavailable
2060 */
2061 int ftdi_setrts(struct ftdi_context *ftdi, int state)
2062 {
2063     unsigned short usb_val;
2064
2065     if (ftdi == NULL || ftdi->usb_dev == NULL)
2066         ftdi_error_return(-2, "USB device unavailable");
2067
2068     if (state)
2069         usb_val = SIO_SET_RTS_HIGH;
2070     else
2071         usb_val = SIO_SET_RTS_LOW;
2072
2073     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
2074                                 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
2075                                 NULL, 0, ftdi->usb_write_timeout) < 0)
2076         ftdi_error_return(-1, "set of rts failed");
2077
2078     return 0;
2079 }
2080
2081 /**
2082     Set dtr and rts line in one pass
2083
2084     \param ftdi pointer to ftdi_context
2085     \param dtr  DTR state to set line to (1 or 0)
2086     \param rts  RTS state to set line to (1 or 0)
2087
2088     \retval  0: all fine
2089     \retval -1: set dtr/rts failed
2090     \retval -2: USB device unavailable
2091  */
2092 int ftdi_setdtr_rts(struct ftdi_context *ftdi, int dtr, int rts)
2093 {
2094     unsigned short usb_val;
2095
2096     if (ftdi == NULL || ftdi->usb_dev == NULL)
2097         ftdi_error_return(-2, "USB device unavailable");
2098
2099     if (dtr)
2100         usb_val = SIO_SET_DTR_HIGH;
2101     else
2102         usb_val = SIO_SET_DTR_LOW;
2103
2104     if (rts)
2105         usb_val |= SIO_SET_RTS_HIGH;
2106     else
2107         usb_val |= SIO_SET_RTS_LOW;
2108
2109     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
2110                                 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
2111                                 NULL, 0, ftdi->usb_write_timeout) < 0)
2112         ftdi_error_return(-1, "set of rts/dtr failed");
2113
2114     return 0;
2115 }
2116
2117 /**
2118     Set the special event character
2119
2120     \param ftdi pointer to ftdi_context
2121     \param eventch Event character
2122     \param enable 0 to disable the event character, non-zero otherwise
2123
2124     \retval  0: all fine
2125     \retval -1: unable to set event character
2126     \retval -2: USB device unavailable
2127 */
2128 int ftdi_set_event_char(struct ftdi_context *ftdi,
2129                         unsigned char eventch, unsigned char enable)
2130 {
2131     unsigned short usb_val;
2132
2133     if (ftdi == NULL || ftdi->usb_dev == NULL)
2134         ftdi_error_return(-2, "USB device unavailable");
2135
2136     usb_val = eventch;
2137     if (enable)
2138         usb_val |= 1 << 8;
2139
2140     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)
2141         ftdi_error_return(-1, "setting event character failed");
2142
2143     return 0;
2144 }
2145
2146 /**
2147     Set error character
2148
2149     \param ftdi pointer to ftdi_context
2150     \param errorch Error character
2151     \param enable 0 to disable the error character, non-zero otherwise
2152
2153     \retval  0: all fine
2154     \retval -1: unable to set error character
2155     \retval -2: USB device unavailable
2156 */
2157 int ftdi_set_error_char(struct ftdi_context *ftdi,
2158                         unsigned char errorch, unsigned char enable)
2159 {
2160     unsigned short usb_val;
2161
2162     if (ftdi == NULL || ftdi->usb_dev == NULL)
2163         ftdi_error_return(-2, "USB device unavailable");
2164
2165     usb_val = errorch;
2166     if (enable)
2167         usb_val |= 1 << 8;
2168
2169     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)
2170         ftdi_error_return(-1, "setting error character failed");
2171
2172     return 0;
2173 }
2174
2175 /**
2176     Init eeprom with default values.
2177     \param ftdi pointer to ftdi_context
2178     \param manufacturer String to use as Manufacturer
2179     \param product String to use as Product description
2180     \param serial String to use as Serial number description
2181
2182     \retval  0: all fine
2183     \retval -1: No struct ftdi_context
2184     \retval -2: No struct ftdi_eeprom
2185 */
2186 int ftdi_eeprom_initdefaults(struct ftdi_context *ftdi, char * manufacturer,
2187                              char * product, char * serial)
2188 {
2189     struct ftdi_eeprom *eeprom;
2190
2191     if (ftdi == NULL)
2192         ftdi_error_return(-1, "No struct ftdi_context");
2193
2194     if (ftdi->eeprom == NULL)
2195         ftdi_error_return(-2,"No struct ftdi_eeprom");
2196
2197     eeprom = ftdi->eeprom;
2198     memset(eeprom, 0, sizeof(struct ftdi_eeprom));
2199
2200     eeprom->vendor_id = 0x0403;
2201     eeprom->use_serial = USE_SERIAL_NUM;
2202     if ((ftdi->type == TYPE_AM) || (ftdi->type == TYPE_BM) ||
2203             (ftdi->type == TYPE_R))
2204         eeprom->product_id = 0x6001;
2205     else
2206         eeprom->product_id = 0x6010;
2207     if (ftdi->type == TYPE_AM)
2208         eeprom->usb_version = 0x0101;
2209     else
2210         eeprom->usb_version = 0x0200;
2211     eeprom->max_power = 100;
2212
2213     if (eeprom->manufacturer)
2214         free (eeprom->manufacturer);
2215     eeprom->manufacturer = NULL;
2216     if (manufacturer)
2217     {
2218         eeprom->manufacturer = malloc(strlen(manufacturer)+1);
2219         if (eeprom->manufacturer)
2220             strcpy(eeprom->manufacturer, manufacturer);
2221     }
2222
2223     if (eeprom->product)
2224         free (eeprom->product);
2225     eeprom->product = NULL;
2226     {
2227         eeprom->product = malloc(strlen(product)+1);
2228         if (eeprom->product)
2229             strcpy(eeprom->product, product);
2230     }
2231
2232     if (eeprom->serial)
2233         free (eeprom->serial);
2234     eeprom->serial = NULL;
2235     if (serial)
2236     {
2237         eeprom->serial = malloc(strlen(serial)+1);
2238         if (eeprom->serial)
2239             strcpy(eeprom->serial, serial);
2240     }
2241
2242
2243     if (ftdi->type == TYPE_R)
2244     {
2245         eeprom->max_power = 90;
2246         eeprom->size = 0x80;
2247         eeprom->cbus_function[0] = CBUS_TXLED;
2248         eeprom->cbus_function[1] = CBUS_RXLED;
2249         eeprom->cbus_function[2] = CBUS_TXDEN;
2250         eeprom->cbus_function[3] = CBUS_PWREN;
2251         eeprom->cbus_function[4] = CBUS_SLEEP;
2252     }
2253     else
2254         eeprom->size = -1;
2255     return 0;
2256 }
2257
2258 /**
2259     Build binary buffer from ftdi_eeprom structure.
2260     Output is suitable for ftdi_write_eeprom().
2261
2262     \param ftdi pointer to ftdi_context
2263
2264     \retval >=0: size of eeprom user area in bytes
2265     \retval -1: eeprom size (128 bytes) exceeded by custom strings
2266     \retval -2: Invalid eeprom or ftdi pointer
2267     \retval -3: Invalid cbus function setting     (FIXME: Not in the code?)
2268     \retval -4: Chip doesn't support invert       (FIXME: Not in the code?)
2269     \retval -5: Chip doesn't support high current drive         (FIXME: Not in the code?)
2270     \retval -6: No connected EEPROM or EEPROM Type unknown
2271 */
2272 int ftdi_eeprom_build(struct ftdi_context *ftdi)
2273 {
2274     unsigned char i, j, eeprom_size_mask;
2275     unsigned short checksum, value;
2276     unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
2277     int user_area_size;
2278     struct ftdi_eeprom *eeprom;
2279     unsigned char * output;
2280
2281     if (ftdi == NULL)
2282         ftdi_error_return(-2,"No context");
2283     if (ftdi->eeprom == NULL)
2284         ftdi_error_return(-2,"No eeprom structure");
2285
2286     eeprom= ftdi->eeprom;
2287     output = eeprom->buf;
2288
2289     if (eeprom->chip == -1)
2290         ftdi_error_return(-6,"No connected EEPROM or EEPROM type unknown");
2291
2292     if ((eeprom->chip == 0x56) || (eeprom->chip == 0x66))
2293         eeprom->size = 0x100;
2294     else
2295         eeprom->size = 0x80;
2296
2297     if (eeprom->manufacturer != NULL)
2298         manufacturer_size = strlen(eeprom->manufacturer);
2299     if (eeprom->product != NULL)
2300         product_size = strlen(eeprom->product);
2301     if (eeprom->serial != NULL)
2302         serial_size = strlen(eeprom->serial);
2303
2304     // eeprom size check
2305     switch (ftdi->type)
2306     {
2307         case TYPE_AM:
2308         case TYPE_BM:
2309             user_area_size = 96;    // base size for strings (total of 48 characters)
2310             break;
2311         case TYPE_2232C:
2312             user_area_size = 90;     // two extra config bytes and 4 bytes PnP stuff
2313             break;
2314         case TYPE_R:
2315             user_area_size = 88;     // four extra config bytes + 4 bytes PnP stuff
2316             break;
2317         case TYPE_2232H:            // six extra config bytes + 4 bytes PnP stuff
2318         case TYPE_4232H:
2319             user_area_size = 86;
2320             break;
2321         default:
2322             user_area_size = 0;
2323             break;
2324     }
2325     user_area_size  -= (manufacturer_size + product_size + serial_size) * 2;
2326
2327     if (user_area_size < 0)
2328         ftdi_error_return(-1,"eeprom size exceeded");
2329
2330     // empty eeprom
2331     memset (ftdi->eeprom->buf, 0, FTDI_MAX_EEPROM_SIZE);
2332
2333     // Bytes and Bits set for all Types
2334
2335     // Addr 02: Vendor ID
2336     output[0x02] = eeprom->vendor_id;
2337     output[0x03] = eeprom->vendor_id >> 8;
2338
2339     // Addr 04: Product ID
2340     output[0x04] = eeprom->product_id;
2341     output[0x05] = eeprom->product_id >> 8;
2342
2343     // Addr 06: Device release number (0400h for BM features)
2344     output[0x06] = 0x00;
2345     switch (ftdi->type)
2346     {
2347         case TYPE_AM:
2348             output[0x07] = 0x02;
2349             break;
2350         case TYPE_BM:
2351             output[0x07] = 0x04;
2352             break;
2353         case TYPE_2232C:
2354             output[0x07] = 0x05;
2355             break;
2356         case TYPE_R:
2357             output[0x07] = 0x06;
2358             break;
2359         case TYPE_2232H:
2360             output[0x07] = 0x07;
2361             break;
2362         case TYPE_4232H:
2363             output[0x07] = 0x08;
2364             break;
2365         default:
2366             output[0x07] = 0x00;
2367     }
2368
2369     // Addr 08: Config descriptor
2370     // Bit 7: always 1
2371     // Bit 6: 1 if this device is self powered, 0 if bus powered
2372     // Bit 5: 1 if this device uses remote wakeup
2373     // Bit 4-0: reserved - 0
2374     j = 0x80;
2375     if (eeprom->self_powered == 1)
2376         j |= 0x40;
2377     if (eeprom->remote_wakeup == 1)
2378         j |= 0x20;
2379     output[0x08] = j;
2380
2381     // Addr 09: Max power consumption: max power = value * 2 mA
2382     output[0x09] = eeprom->max_power>>1;
2383
2384     if (ftdi->type != TYPE_AM)
2385     {
2386         // Addr 0A: Chip configuration
2387         // Bit 7: 0 - reserved
2388         // Bit 6: 0 - reserved
2389         // Bit 5: 0 - reserved
2390         // Bit 4: 1 - Change USB version
2391         // Bit 3: 1 - Use the serial number string
2392         // Bit 2: 1 - Enable suspend pull downs for lower power
2393         // Bit 1: 1 - Out EndPoint is Isochronous
2394         // Bit 0: 1 - In EndPoint is Isochronous
2395         //
2396         j = 0;
2397         if (eeprom->in_is_isochronous == 1)
2398             j = j | 1;
2399         if (eeprom->out_is_isochronous == 1)
2400             j = j | 2;
2401         output[0x0A] = j;
2402     }
2403
2404     // Dynamic content
2405     // Strings start at 0x94 (TYPE_AM, TYPE_BM)
2406     // 0x96 (TYPE_2232C), 0x98 (TYPE_R) and 0x9a (TYPE_x232H)
2407     i = 0;
2408     switch (ftdi->type)
2409     {
2410         case TYPE_2232H:
2411         case TYPE_4232H:
2412             i += 2;
2413         case TYPE_R:
2414             i += 2;
2415         case TYPE_2232C:
2416             i += 2;
2417         case TYPE_AM:
2418         case TYPE_BM:
2419             i += 0x94;
2420     }
2421     /* Wrap around 0x80 for 128 byte EEPROMS (Internale and 93x46) */
2422     eeprom_size_mask = eeprom->size -1;
2423
2424     // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
2425     // Addr 0F: Length of manufacturer string
2426     // Output manufacturer
2427     output[0x0E] = i;  // calculate offset
2428     output[i & eeprom_size_mask] = manufacturer_size*2 + 2, i++;
2429     output[i & eeprom_size_mask] = 0x03, i++; // type: string
2430     for (j = 0; j < manufacturer_size; j++)
2431     {
2432         output[i & eeprom_size_mask] = eeprom->manufacturer[j], i++;
2433         output[i & eeprom_size_mask] = 0x00, i++;
2434     }
2435     output[0x0F] = manufacturer_size*2 + 2;
2436
2437     // Addr 10: Offset of the product string + 0x80, calculated later
2438     // Addr 11: Length of product string
2439     output[0x10] = i | 0x80;  // calculate offset
2440     output[i & eeprom_size_mask] = product_size*2 + 2, i++;
2441     output[i & eeprom_size_mask] = 0x03, i++;
2442     for (j = 0; j < product_size; j++)
2443     {
2444         output[i & eeprom_size_mask] = eeprom->product[j], i++;
2445         output[i & eeprom_size_mask] = 0x00, i++;
2446     }
2447     output[0x11] = product_size*2 + 2;
2448
2449     // Addr 12: Offset of the serial string + 0x80, calculated later
2450     // Addr 13: Length of serial string
2451     output[0x12] = i | 0x80; // calculate offset
2452     output[i & eeprom_size_mask] = serial_size*2 + 2, i++;
2453     output[i & eeprom_size_mask] = 0x03, i++;
2454     for (j = 0; j < serial_size; j++)
2455     {
2456         output[i & eeprom_size_mask] = eeprom->serial[j], i++;
2457         output[i & eeprom_size_mask] = 0x00, i++;
2458     }
2459
2460     // Legacy port name and PnP fields for FT2232 and newer chips
2461     if (ftdi->type > TYPE_BM)
2462     {
2463         output[i & eeprom_size_mask] = 0x02; /* as seen when written with FTD2XX */
2464         i++;
2465         output[i & eeprom_size_mask] = 0x03; /* as seen when written with FTD2XX */
2466         i++;
2467         output[i & eeprom_size_mask] = eeprom->is_not_pnp; /* as seen when written with FTD2XX */
2468         i++;
2469     }
2470
2471     output[0x13] = serial_size*2 + 2;
2472
2473     if (ftdi->type > TYPE_AM) /* use_serial not used in AM devices */
2474     {
2475         if (eeprom->use_serial == USE_SERIAL_NUM )
2476             output[0x0A] |= USE_SERIAL_NUM;
2477         else
2478             output[0x0A] &= ~USE_SERIAL_NUM;
2479     }
2480
2481     /* Bytes and Bits specific to (some) types
2482        Write linear, as this allows easier fixing*/
2483     switch (ftdi->type)
2484     {
2485         case TYPE_AM:
2486             break;
2487         case TYPE_BM:
2488             output[0x0C] = eeprom->usb_version & 0xff;
2489             output[0x0D] = (eeprom->usb_version>>8) & 0xff;
2490             if (eeprom->use_usb_version == USE_USB_VERSION_BIT)
2491                 output[0x0A] |= USE_USB_VERSION_BIT;
2492             else
2493                 output[0x0A] &= ~USE_USB_VERSION_BIT;
2494
2495             break;
2496         case TYPE_2232C:
2497
2498             output[0x00] = (eeprom->channel_a_type);
2499             if ( eeprom->channel_a_driver == DRIVER_VCP)
2500                 output[0x00] |= DRIVER_VCP;
2501             else
2502                 output[0x00] &= ~DRIVER_VCP;
2503
2504             if ( eeprom->high_current_a == HIGH_CURRENT_DRIVE)
2505                 output[0x00] |= HIGH_CURRENT_DRIVE;
2506             else
2507                 output[0x00] &= ~HIGH_CURRENT_DRIVE;
2508
2509             output[0x01] = (eeprom->channel_b_type);
2510             if ( eeprom->channel_b_driver == DRIVER_VCP)
2511                 output[0x01] |= DRIVER_VCP;
2512             else
2513                 output[0x01] &= ~DRIVER_VCP;
2514
2515             if ( eeprom->high_current_b == HIGH_CURRENT_DRIVE)
2516                 output[0x01] |= HIGH_CURRENT_DRIVE;
2517             else
2518                 output[0x01] &= ~HIGH_CURRENT_DRIVE;
2519
2520             if (eeprom->in_is_isochronous == 1)
2521                 output[0x0A] |= 0x1;
2522             else
2523                 output[0x0A] &= ~0x1;
2524             if (eeprom->out_is_isochronous == 1)
2525                 output[0x0A] |= 0x2;
2526             else
2527                 output[0x0A] &= ~0x2;
2528             if (eeprom->suspend_pull_downs == 1)
2529                 output[0x0A] |= 0x4;
2530             else
2531                 output[0x0A] &= ~0x4;
2532             if (eeprom->use_usb_version == USE_USB_VERSION_BIT)
2533                 output[0x0A] |= USE_USB_VERSION_BIT;
2534             else
2535                 output[0x0A] &= ~USE_USB_VERSION_BIT;
2536
2537             output[0x0C] = eeprom->usb_version & 0xff;
2538             output[0x0D] = (eeprom->usb_version>>8) & 0xff;
2539             output[0x14] = eeprom->chip;
2540             break;
2541         case TYPE_R:
2542             if (eeprom->high_current == HIGH_CURRENT_DRIVE_R)
2543                 output[0x00] |= HIGH_CURRENT_DRIVE_R;
2544             output[0x01] = 0x40; /* Hard coded Endpoint Size*/
2545
2546             if (eeprom->suspend_pull_downs == 1)
2547                 output[0x0A] |= 0x4;
2548             else
2549                 output[0x0A] &= ~0x4;
2550             output[0x0B] = eeprom->invert;
2551             output[0x0C] = eeprom->usb_version & 0xff;
2552             output[0x0D] = (eeprom->usb_version>>8) & 0xff;
2553
2554             if (eeprom->cbus_function[0] > CBUS_BB)
2555                 output[0x14] = CBUS_TXLED;
2556             else
2557                 output[0x14] = eeprom->cbus_function[0];
2558
2559             if (eeprom->cbus_function[1] > CBUS_BB)
2560                 output[0x14] |= CBUS_RXLED<<4;
2561             else
2562                 output[0x14] |= eeprom->cbus_function[1]<<4;
2563
2564             if (eeprom->cbus_function[2] > CBUS_BB)
2565                 output[0x15] = CBUS_TXDEN;
2566             else
2567                 output[0x15] = eeprom->cbus_function[2];
2568
2569             if (eeprom->cbus_function[3] > CBUS_BB)
2570                 output[0x15] |= CBUS_PWREN<<4;
2571             else
2572                 output[0x15] |= eeprom->cbus_function[3]<<4;
2573
2574             if (eeprom->cbus_function[4] > CBUS_CLK6)
2575                 output[0x16] = CBUS_SLEEP;
2576             else
2577                 output[0x16] = eeprom->cbus_function[4];
2578             break;
2579         case TYPE_2232H:
2580             output[0x00] = (eeprom->channel_a_type);
2581             if ( eeprom->channel_a_driver == DRIVER_VCP)
2582                 output[0x00] |= DRIVER_VCP;
2583             else
2584                 output[0x00] &= ~DRIVER_VCP;
2585
2586             output[0x01] = (eeprom->channel_b_type);
2587             if ( eeprom->channel_b_driver == DRIVER_VCP)
2588                 output[0x01] |= DRIVER_VCP;
2589             else
2590                 output[0x01] &= ~DRIVER_VCP;
2591             if (eeprom->suspend_dbus7 == SUSPEND_DBUS7_BIT)
2592                 output[0x01] |= SUSPEND_DBUS7_BIT;
2593             else
2594                 output[0x01] &= ~SUSPEND_DBUS7_BIT;
2595
2596             if (eeprom->suspend_pull_downs == 1)
2597                 output[0x0A] |= 0x4;
2598             else
2599                 output[0x0A] &= ~0x4;
2600
2601             if (eeprom->group0_drive > DRIVE_16MA)
2602                 output[0x0c] |= DRIVE_16MA;
2603             else
2604                 output[0x0c] |= eeprom->group0_drive;
2605             if (eeprom->group0_schmitt == IS_SCHMITT)
2606                 output[0x0c] |= IS_SCHMITT;
2607             if (eeprom->group0_slew == SLOW_SLEW)
2608                 output[0x0c] |= SLOW_SLEW;
2609
2610             if (eeprom->group1_drive > DRIVE_16MA)
2611                 output[0x0c] |= DRIVE_16MA<<4;
2612             else
2613                 output[0x0c] |= eeprom->group1_drive<<4;
2614             if (eeprom->group1_schmitt == IS_SCHMITT)
2615                 output[0x0c] |= IS_SCHMITT<<4;
2616             if (eeprom->group1_slew == SLOW_SLEW)
2617                 output[0x0c] |= SLOW_SLEW<<4;
2618
2619             if (eeprom->group2_drive > DRIVE_16MA)
2620                 output[0x0d] |= DRIVE_16MA;
2621             else
2622                 output[0x0d] |= eeprom->group2_drive;
2623             if (eeprom->group2_schmitt == IS_SCHMITT)
2624                 output[0x0d] |= IS_SCHMITT;
2625             if (eeprom->group2_slew == SLOW_SLEW)
2626                 output[0x0d] |= SLOW_SLEW;
2627
2628             if (eeprom->group3_drive > DRIVE_16MA)
2629                 output[0x0d] |= DRIVE_16MA<<4;
2630             else
2631                 output[0x0d] |= eeprom->group3_drive<<4;
2632             if (eeprom->group3_schmitt == IS_SCHMITT)
2633                 output[0x0d] |= IS_SCHMITT<<4;
2634             if (eeprom->group3_slew == SLOW_SLEW)
2635                 output[0x0d] |= SLOW_SLEW<<4;
2636
2637             output[0x18] = eeprom->chip;
2638
2639             break;
2640         case TYPE_4232H:
2641             fprintf(stderr,"FIXME: Build FT4232H specific EEPROM settings\n");
2642     }
2643
2644     // calculate checksum
2645     checksum = 0xAAAA;
2646
2647     for (i = 0; i < eeprom->size/2-1; i++)
2648     {
2649         value = output[i*2];
2650         value += output[(i*2)+1] << 8;
2651
2652         checksum = value^checksum;
2653         checksum = (checksum << 1) | (checksum >> 15);
2654     }
2655
2656     output[eeprom->size-2] = checksum;
2657     output[eeprom->size-1] = checksum >> 8;
2658
2659     return user_area_size;
2660 }
2661
2662 /**
2663    Decode binary EEPROM image into an ftdi_eeprom structure.
2664
2665    \param ftdi pointer to ftdi_context
2666    \param verbose Decode EEPROM on stdout
2667
2668    \retval 0: all fine
2669    \retval -1: something went wrong
2670
2671    FIXME: How to pass size? How to handle size field in ftdi_eeprom?
2672    FIXME: Strings are malloc'ed here and should be freed somewhere
2673 */
2674 int ftdi_eeprom_decode(struct ftdi_context *ftdi, int verbose)
2675 {
2676     unsigned char i, j;
2677     unsigned short checksum, eeprom_checksum, value;
2678     unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
2679     int eeprom_size;
2680     struct ftdi_eeprom *eeprom;
2681     unsigned char *buf = ftdi->eeprom->buf;
2682     int release;
2683
2684     if (ftdi == NULL)
2685         ftdi_error_return(-1,"No context");
2686     if (ftdi->eeprom == NULL)
2687         ftdi_error_return(-1,"No eeprom structure");
2688
2689     eeprom = ftdi->eeprom;
2690     eeprom_size = eeprom->size;
2691
2692     // Addr 02: Vendor ID
2693     eeprom->vendor_id = buf[0x02] + (buf[0x03] << 8);
2694
2695     // Addr 04: Product ID
2696     eeprom->product_id = buf[0x04] + (buf[0x05] << 8);
2697
2698     release = buf[0x06] + (buf[0x07]<<8);
2699
2700     // Addr 08: Config descriptor
2701     // Bit 7: always 1
2702     // Bit 6: 1 if this device is self powered, 0 if bus powered
2703     // Bit 5: 1 if this device uses remote wakeup
2704     eeprom->self_powered = buf[0x08] & 0x40;
2705     eeprom->remote_wakeup = buf[0x08] & 0x20;
2706
2707     // Addr 09: Max power consumption: max power = value * 2 mA
2708     eeprom->max_power = buf[0x09];
2709
2710     // Addr 0A: Chip configuration
2711     // Bit 7: 0 - reserved
2712     // Bit 6: 0 - reserved
2713     // Bit 5: 0 - reserved
2714     // Bit 4: 1 - Change USB version on BM and 2232C
2715     // Bit 3: 1 - Use the serial number string
2716     // Bit 2: 1 - Enable suspend pull downs for lower power
2717     // Bit 1: 1 - Out EndPoint is Isochronous
2718     // Bit 0: 1 - In EndPoint is Isochronous
2719     //
2720     eeprom->in_is_isochronous  = buf[0x0A]&0x01;
2721     eeprom->out_is_isochronous = buf[0x0A]&0x02;
2722     eeprom->suspend_pull_downs = buf[0x0A]&0x04;
2723     eeprom->use_serial         = buf[0x0A] & USE_SERIAL_NUM;
2724     eeprom->use_usb_version    = buf[0x0A] & USE_USB_VERSION_BIT;
2725
2726     // Addr 0C: USB version low byte when 0x0A
2727     // Addr 0D: USB version high byte when 0x0A
2728     eeprom->usb_version = buf[0x0C] + (buf[0x0D] << 8);
2729
2730     // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
2731     // Addr 0F: Length of manufacturer string
2732     manufacturer_size = buf[0x0F]/2;
2733     if (eeprom->manufacturer)
2734         free(eeprom->manufacturer);
2735     if (manufacturer_size > 0)
2736     {
2737         eeprom->manufacturer = malloc(manufacturer_size);
2738         if (eeprom->manufacturer)
2739         {
2740             // Decode manufacturer
2741             i = buf[0x0E] & (eeprom_size -1); // offset
2742             for (j=0;j<manufacturer_size-1;j++)
2743             {
2744                 eeprom->manufacturer[j] = buf[2*j+i+2];
2745             }
2746             eeprom->manufacturer[j] = '\0';
2747         }
2748     }
2749     else eeprom->manufacturer = NULL;
2750
2751     // Addr 10: Offset of the product string + 0x80, calculated later
2752     // Addr 11: Length of product string
2753     if (eeprom->product)
2754         free(eeprom->product);
2755     product_size = buf[0x11]/2;
2756     if (product_size > 0)
2757     {
2758         eeprom->product = malloc(product_size);
2759         if (eeprom->product)
2760         {
2761             // Decode product name
2762             i = buf[0x10] & (eeprom_size -1); // offset
2763             for (j=0;j<product_size-1;j++)
2764             {
2765                 eeprom->product[j] = buf[2*j+i+2];
2766             }
2767             eeprom->product[j] = '\0';
2768         }
2769     }
2770     else eeprom->product = NULL;
2771
2772     // Addr 12: Offset of the serial string + 0x80, calculated later
2773     // Addr 13: Length of serial string
2774     if (eeprom->serial)
2775         free(eeprom->serial);
2776     serial_size = buf[0x13]/2;
2777     if (serial_size > 0)
2778     {
2779         eeprom->serial = malloc(serial_size);
2780         if (eeprom->serial)
2781         {
2782             // Decode serial
2783             i = buf[0x12] & (eeprom_size -1); // offset
2784             for (j=0;j<serial_size-1;j++)
2785             {
2786                 eeprom->serial[j] = buf[2*j+i+2];
2787             }
2788             eeprom->serial[j] = '\0';
2789         }
2790     }
2791     else eeprom->serial = NULL;
2792
2793     // verify checksum
2794     checksum = 0xAAAA;
2795
2796     for (i = 0; i < eeprom_size/2-1; i++)
2797     {
2798         value = buf[i*2];
2799         value += buf[(i*2)+1] << 8;
2800
2801         checksum = value^checksum;
2802         checksum = (checksum << 1) | (checksum >> 15);
2803     }
2804
2805     eeprom_checksum = buf[eeprom_size-2] + (buf[eeprom_size-1] << 8);
2806
2807     if (eeprom_checksum != checksum)
2808     {
2809         fprintf(stderr, "Checksum Error: %04x %04x\n", checksum, eeprom_checksum);
2810         ftdi_error_return(-1,"EEPROM checksum error");
2811     }
2812
2813     eeprom->channel_a_type   = 0;
2814     if ((ftdi->type == TYPE_AM) || (ftdi->type == TYPE_BM))
2815     {
2816         eeprom->chip = -1;
2817     }
2818     else if (ftdi->type == TYPE_2232C)
2819     {
2820         eeprom->channel_a_type   = buf[0x00] & 0x7;
2821         eeprom->channel_a_driver = buf[0x00] & DRIVER_VCP;
2822         eeprom->high_current_a   = buf[0x00] & HIGH_CURRENT_DRIVE;
2823         eeprom->channel_b_type   = buf[0x01] & 0x7;
2824         eeprom->channel_b_driver = buf[0x01] & DRIVER_VCP;
2825         eeprom->high_current_b   = buf[0x01] & HIGH_CURRENT_DRIVE;
2826         eeprom->chip = buf[0x14];
2827     }
2828     else if (ftdi->type == TYPE_R)
2829     {
2830         /* TYPE_R flags D2XX, not VCP as all others*/
2831         eeprom->channel_a_driver = (~buf[0x00]) & DRIVER_VCP;
2832         eeprom->high_current     = buf[0x00] & HIGH_CURRENT_DRIVE_R;
2833         if ( (buf[0x01]&0x40) != 0x40)
2834             fprintf(stderr,
2835                     "TYPE_R EEPROM byte[0x01] Bit 6 unexpected Endpoint size."
2836                     " If this happened with the\n"
2837                     " EEPROM programmed by FTDI tools, please report "
2838                     "to libftdi@developer.intra2net.com\n");
2839
2840         eeprom->chip = buf[0x16];
2841         // Addr 0B: Invert data lines
2842         // Works only on FT232R, not FT245R, but no way to distinguish
2843         eeprom->invert = buf[0x0B];
2844         // Addr 14: CBUS function: CBUS0, CBUS1
2845         // Addr 15: CBUS function: CBUS2, CBUS3
2846         // Addr 16: CBUS function: CBUS5
2847         eeprom->cbus_function[0] = buf[0x14] & 0x0f;
2848         eeprom->cbus_function[1] = (buf[0x14] >> 4) & 0x0f;
2849         eeprom->cbus_function[2] = buf[0x15] & 0x0f;
2850         eeprom->cbus_function[3] = (buf[0x15] >> 4) & 0x0f;
2851         eeprom->cbus_function[4] = buf[0x16] & 0x0f;
2852     }
2853     else if ((ftdi->type == TYPE_2232H) ||(ftdi->type == TYPE_4232H))
2854     {
2855         eeprom->channel_a_type   = buf[0x00] & 0x7;
2856         eeprom->channel_a_driver = buf[0x00] & DRIVER_VCP;
2857         eeprom->channel_b_type   = buf[0x01] & 0x7;
2858         eeprom->channel_b_driver = buf[0x01] & DRIVER_VCP;
2859
2860         if (ftdi->type == TYPE_2232H)
2861             eeprom->suspend_dbus7    = buf[0x01] & SUSPEND_DBUS7_BIT;
2862
2863         eeprom->chip = buf[0x18];
2864         eeprom->group0_drive   =  buf[0x0c]       & DRIVE_16MA;
2865         eeprom->group0_schmitt =  buf[0x0c]       & IS_SCHMITT;
2866         eeprom->group0_slew    =  buf[0x0c]       & SLOW_SLEW;
2867         eeprom->group1_drive   = (buf[0x0c] >> 4) & 0x3;
2868         eeprom->group1_schmitt = (buf[0x0c] >> 4) & IS_SCHMITT;
2869         eeprom->group1_slew    = (buf[0x0c] >> 4) & SLOW_SLEW;
2870         eeprom->group2_drive   =  buf[0x0d]       & DRIVE_16MA;
2871         eeprom->group2_schmitt =  buf[0x0d]       & IS_SCHMITT;
2872         eeprom->group2_slew    =  buf[0x0d]       & SLOW_SLEW;
2873         eeprom->group3_drive   = (buf[0x0d] >> 4) & DRIVE_16MA;
2874         eeprom->group3_schmitt = (buf[0x0d] >> 4) & IS_SCHMITT;
2875         eeprom->group3_slew    = (buf[0x0d] >> 4) & SLOW_SLEW;
2876     }
2877
2878     if (verbose)
2879     {
2880         char *channel_mode[] = {"UART","245","CPU", "unknown", "OPTO"};
2881         fprintf(stdout, "VID:     0x%04x\n",eeprom->vendor_id);
2882         fprintf(stdout, "PID:     0x%04x\n",eeprom->product_id);
2883         fprintf(stdout, "Release: 0x%04x\n",release);
2884
2885         if (eeprom->self_powered)
2886             fprintf(stdout, "Self-Powered%s", (eeprom->remote_wakeup)?", USB Remote Wake Up\n":"\n");
2887         else
2888             fprintf(stdout, "Bus Powered: %3d mA%s", eeprom->max_power * 2,
2889                     (eeprom->remote_wakeup)?" USB Remote Wake Up\n":"\n");
2890         if (eeprom->manufacturer)
2891             fprintf(stdout, "Manufacturer: %s\n",eeprom->manufacturer);
2892         if (eeprom->product)
2893             fprintf(stdout, "Product:      %s\n",eeprom->product);
2894         if (eeprom->serial)
2895             fprintf(stdout, "Serial:       %s\n",eeprom->serial);
2896         fprintf(stdout,     "Checksum      : %04x\n", checksum);
2897         if (ftdi->type == TYPE_R)
2898             fprintf(stdout,     "Internal EEPROM\n");
2899         else if (eeprom->chip >= 0x46)
2900             fprintf(stdout,     "Attached EEPROM: 93x%02x\n", eeprom->chip);
2901         if (eeprom->suspend_dbus7)
2902             fprintf(stdout, "Suspend on DBUS7\n");
2903         if (eeprom->suspend_pull_downs)
2904             fprintf(stdout, "Pull IO pins low during suspend\n");
2905         if (eeprom->remote_wakeup)
2906             fprintf(stdout, "Enable Remote Wake Up\n");
2907         fprintf(stdout, "PNP: %d\n",(eeprom->is_not_pnp)?0:1);
2908         if (ftdi->type >= TYPE_2232C)
2909             fprintf(stdout,"Channel A has Mode %s%s%s\n",
2910                     channel_mode[eeprom->channel_a_type],
2911                     (eeprom->channel_a_driver)?" VCP":"",
2912                     (eeprom->high_current_a)?" High Current IO":"");
2913         if ((ftdi->type >= TYPE_2232C) && (ftdi->type != TYPE_R))
2914             fprintf(stdout,"Channel B has Mode %s%s%s\n",
2915                     channel_mode[eeprom->channel_b_type],
2916                     (eeprom->channel_b_driver)?" VCP":"",
2917                     (eeprom->high_current_b)?" High Current IO":"");
2918         if (((ftdi->type == TYPE_BM) || (ftdi->type == TYPE_2232C)) &&
2919                 eeprom->use_usb_version == USE_USB_VERSION_BIT)
2920             fprintf(stdout,"Use explicit USB Version %04x\n",eeprom->usb_version);
2921
2922         if ((ftdi->type == TYPE_2232H) || (ftdi->type == TYPE_4232H))
2923         {
2924             fprintf(stdout,"%s has %d mA drive%s%s\n",
2925                     (ftdi->type == TYPE_2232H)?"AL":"A",
2926                     (eeprom->group0_drive+1) *4,
2927                     (eeprom->group0_schmitt)?" Schmitt Input":"",
2928                     (eeprom->group0_slew)?" Slow Slew":"");
2929             fprintf(stdout,"%s has %d mA drive%s%s\n",
2930                     (ftdi->type == TYPE_2232H)?"AH":"B",
2931                     (eeprom->group1_drive+1) *4,
2932                     (eeprom->group1_schmitt)?" Schmitt Input":"",
2933                     (eeprom->group1_slew)?" Slow Slew":"");
2934             fprintf(stdout,"%s has %d mA drive%s%s\n",
2935                     (ftdi->type == TYPE_2232H)?"BL":"C",
2936                     (eeprom->group2_drive+1) *4,
2937                     (eeprom->group2_schmitt)?" Schmitt Input":"",
2938                     (eeprom->group2_slew)?" Slow Slew":"");
2939             fprintf(stdout,"%s has %d mA drive%s%s\n",
2940                     (ftdi->type == TYPE_2232H)?"BH":"D",
2941                     (eeprom->group3_drive+1) *4,
2942                     (eeprom->group3_schmitt)?" Schmitt Input":"",
2943                     (eeprom->group3_slew)?" Slow Slew":"");
2944         }
2945         if (ftdi->type == TYPE_R)
2946         {
2947             char *cbus_mux[] = {"TXDEN","PWREN","RXLED", "TXLED","TX+RXLED",
2948                                 "SLEEP","CLK48","CLK24","CLK12","CLK6",
2949                                 "IOMODE","BB_WR","BB_RD"
2950                                };
2951             char *cbus_BB[] = {"RXF","TXE","RD", "WR"};
2952
2953             if (eeprom->invert)
2954             {
2955                 char *r_bits[] = {"TXD","RXD","RTS", "CTS","DTR","DSR","DCD","RI"};
2956                 fprintf(stdout,"Inverted bits:");
2957                 for (i=0; i<8; i++)
2958                     if ((eeprom->invert & (1<<i)) == (1<<i))
2959                         fprintf(stdout," %s",r_bits[i]);
2960                 fprintf(stdout,"\n");
2961             }
2962             for (i=0; i<5; i++)
2963             {
2964                 if (eeprom->cbus_function[i]<CBUS_BB)
2965                     fprintf(stdout,"C%d Function: %s\n", i,
2966                             cbus_mux[eeprom->cbus_function[i]]);
2967                 else
2968                 {
2969                     if (i < 4)
2970                         /* Running MPROG show that C0..3 have fixed function Synchronous
2971                            Bit Bang mode */
2972                         fprintf(stdout,"C%d BB Function: %s\n", i,
2973                                 cbus_BB[i]);
2974                     else
2975                         fprintf(stdout, "Unknown CBUS mode. Might be special mode?\n");
2976                 }
2977             }
2978         }
2979     }
2980     return 0;
2981 }
2982
2983 /**
2984    Get a value from the decoded EEPROM structure
2985
2986    \param ftdi pointer to ftdi_context
2987    \param value_name Enum of the value to query
2988    \param value Pointer to store read value
2989
2990    \retval 0: all fine
2991    \retval -1: Value doesn't exist
2992 */
2993 int ftdi_get_eeprom_value(struct ftdi_context *ftdi, enum ftdi_eeprom_value value_name, int* value)
2994 {
2995     switch (value_name)
2996     {
2997         case VENDOR_ID:
2998             *value = ftdi->eeprom->vendor_id;
2999             break;
3000         case PRODUCT_ID:
3001             *value = ftdi->eeprom->product_id;
3002             break;
3003         case SELF_POWERED:
3004             *value = ftdi->eeprom->self_powered;
3005             break;
3006         case REMOTE_WAKEUP:
3007             *value = ftdi->eeprom->remote_wakeup;
3008             break;
3009         case IS_NOT_PNP:
3010             *value = ftdi->eeprom->is_not_pnp;
3011             break;
3012         case SUSPEND_DBUS7:
3013             *value = ftdi->eeprom->suspend_dbus7;
3014             break;
3015         case IN_IS_ISOCHRONOUS:
3016             *value = ftdi->eeprom->in_is_isochronous;
3017             break;
3018         case SUSPEND_PULL_DOWNS:
3019             *value = ftdi->eeprom->suspend_pull_downs;
3020             break;
3021         case USE_SERIAL:
3022             *value = ftdi->eeprom->use_serial;
3023             break;
3024         case USB_VERSION:
3025             *value = ftdi->eeprom->usb_version;
3026             break;
3027         case MAX_POWER:
3028             *value = ftdi->eeprom->max_power;
3029             break;
3030         case CHANNEL_A_TYPE:
3031             *value = ftdi->eeprom->channel_a_type;
3032             break;
3033         case CHANNEL_B_TYPE:
3034             *value = ftdi->eeprom->channel_b_type;
3035             break;
3036         case CHANNEL_A_DRIVER:
3037             *value = ftdi->eeprom->channel_a_driver;
3038             break;
3039         case CHANNEL_B_DRIVER:
3040             *value = ftdi->eeprom->channel_b_driver;
3041             break;
3042         case CBUS_FUNCTION_0:
3043             *value = ftdi->eeprom->cbus_function[0];
3044             break;
3045         case CBUS_FUNCTION_1:
3046             *value = ftdi->eeprom->cbus_function[1];
3047             break;
3048         case CBUS_FUNCTION_2:
3049             *value = ftdi->eeprom->cbus_function[2];
3050             break;
3051         case CBUS_FUNCTION_3:
3052             *value = ftdi->eeprom->cbus_function[3];
3053             break;
3054         case CBUS_FUNCTION_4:
3055             *value = ftdi->eeprom->cbus_function[4];
3056             break;
3057         case HIGH_CURRENT:
3058             *value = ftdi->eeprom->high_current;
3059             break;
3060         case HIGH_CURRENT_A:
3061             *value = ftdi->eeprom->high_current_a;
3062             break;
3063         case HIGH_CURRENT_B:
3064             *value = ftdi->eeprom->high_current_b;
3065             break;
3066         case INVERT:
3067             *value = ftdi->eeprom->invert;
3068             break;
3069         case GROUP0_DRIVE:
3070             *value = ftdi->eeprom->group0_drive;
3071             break;
3072         case GROUP0_SCHMITT:
3073             *value = ftdi->eeprom->group0_schmitt;
3074             break;
3075         case GROUP0_SLEW:
3076             *value = ftdi->eeprom->group0_slew;
3077             break;
3078         case GROUP1_DRIVE:
3079             *value = ftdi->eeprom->group1_drive;
3080             break;
3081         case GROUP1_SCHMITT:
3082             *value = ftdi->eeprom->group1_schmitt;
3083             break;
3084         case GROUP1_SLEW:
3085             *value = ftdi->eeprom->group1_slew;
3086             break;
3087         case GROUP2_DRIVE:
3088             *value = ftdi->eeprom->group2_drive;
3089             break;
3090         case GROUP2_SCHMITT:
3091             *value = ftdi->eeprom->group2_schmitt;
3092             break;
3093         case GROUP2_SLEW:
3094             *value = ftdi->eeprom->group2_slew;
3095             break;
3096         case GROUP3_DRIVE:
3097             *value = ftdi->eeprom->group3_drive;
3098             break;
3099         case GROUP3_SCHMITT:
3100             *value = ftdi->eeprom->group3_schmitt;
3101             break;
3102         case GROUP3_SLEW:
3103             *value = ftdi->eeprom->group3_slew;
3104             break;
3105         case CHIP_TYPE:
3106             *value = ftdi->eeprom->chip;
3107             break;
3108         case CHIP_SIZE:
3109             *value = ftdi->eeprom->size;
3110             break;
3111         default:
3112             ftdi_error_return(-1, "Request for unknown EEPROM value");
3113     }
3114     return 0;
3115 }
3116
3117 /**
3118    Set a value in the decoded EEPROM Structure
3119    No parameter checking is performed
3120
3121    \param ftdi pointer to ftdi_context
3122    \param value_name Enum of the value to set
3123    \param value to set
3124
3125    \retval 0: all fine
3126    \retval -1: Value doesn't exist
3127    \retval -2: Value not user settable
3128 */
3129 int ftdi_set_eeprom_value(struct ftdi_context *ftdi, enum ftdi_eeprom_value value_name, int value)
3130 {
3131     switch (value_name)
3132     {
3133         case VENDOR_ID:
3134             ftdi->eeprom->vendor_id = value;
3135             break;
3136         case PRODUCT_ID:
3137             ftdi->eeprom->product_id = value;
3138             break;
3139         case SELF_POWERED:
3140             ftdi->eeprom->self_powered = value;
3141             break;
3142         case REMOTE_WAKEUP:
3143             ftdi->eeprom->remote_wakeup = value;
3144             break;
3145         case IS_NOT_PNP:
3146             ftdi->eeprom->is_not_pnp = value;
3147             break;
3148         case SUSPEND_DBUS7:
3149             ftdi->eeprom->suspend_dbus7 = value;
3150             break;
3151         case IN_IS_ISOCHRONOUS:
3152             ftdi->eeprom->in_is_isochronous = value;
3153             break;
3154         case SUSPEND_PULL_DOWNS:
3155             ftdi->eeprom->suspend_pull_downs = value;
3156             break;
3157         case USE_SERIAL:
3158             ftdi->eeprom->use_serial = value;
3159             break;
3160         case USB_VERSION:
3161             ftdi->eeprom->usb_version = value;
3162             break;
3163         case MAX_POWER:
3164             ftdi->eeprom->max_power = value;
3165             break;
3166         case CHANNEL_A_TYPE:
3167             ftdi->eeprom->channel_a_type = value;
3168             break;
3169         case CHANNEL_B_TYPE:
3170             ftdi->eeprom->channel_b_type = value;
3171             break;
3172         case CHANNEL_A_DRIVER:
3173             ftdi->eeprom->channel_a_driver = value;
3174             break;
3175         case CHANNEL_B_DRIVER:
3176             ftdi->eeprom->channel_b_driver = value;
3177             break;
3178         case CBUS_FUNCTION_0:
3179             ftdi->eeprom->cbus_function[0] = value;
3180             break;
3181         case CBUS_FUNCTION_1:
3182             ftdi->eeprom->cbus_function[1] = value;
3183             break;
3184         case CBUS_FUNCTION_2:
3185             ftdi->eeprom->cbus_function[2] = value;
3186             break;
3187         case CBUS_FUNCTION_3:
3188             ftdi->eeprom->cbus_function[3] = value;
3189             break;
3190         case CBUS_FUNCTION_4:
3191             ftdi->eeprom->cbus_function[4] = value;
3192             break;
3193         case HIGH_CURRENT:
3194             ftdi->eeprom->high_current = value;
3195             break;
3196         case HIGH_CURRENT_A:
3197             ftdi->eeprom->high_current_a = value;
3198             break;
3199         case HIGH_CURRENT_B:
3200             ftdi->eeprom->high_current_b = value;
3201             break;
3202         case INVERT:
3203             ftdi->eeprom->invert = value;
3204             break;
3205         case GROUP0_DRIVE:
3206             ftdi->eeprom->group0_drive = value;
3207             break;
3208         case GROUP0_SCHMITT:
3209             ftdi->eeprom->group0_schmitt = value;
3210             break;
3211         case GROUP0_SLEW:
3212             ftdi->eeprom->group0_slew = value;
3213             break;
3214         case GROUP1_DRIVE:
3215             ftdi->eeprom->group1_drive = value;
3216             break;
3217         case GROUP1_SCHMITT:
3218             ftdi->eeprom->group1_schmitt = value;
3219             break;
3220         case GROUP1_SLEW:
3221             ftdi->eeprom->group1_slew = value;
3222             break;
3223         case GROUP2_DRIVE:
3224             ftdi->eeprom->group2_drive = value;
3225             break;
3226         case GROUP2_SCHMITT:
3227             ftdi->eeprom->group2_schmitt = value;
3228             break;
3229         case GROUP2_SLEW:
3230             ftdi->eeprom->group2_slew = value;
3231             break;
3232         case GROUP3_DRIVE:
3233             ftdi->eeprom->group3_drive = value;
3234             break;
3235         case GROUP3_SCHMITT:
3236             ftdi->eeprom->group3_schmitt = value;
3237             break;
3238         case GROUP3_SLEW:
3239             ftdi->eeprom->group3_slew = value;
3240             break;
3241         case CHIP_TYPE:
3242             ftdi->eeprom->chip = value;
3243             break;
3244         case CHIP_SIZE:
3245             ftdi_error_return(-2, "EEPROM Value can't be changed");
3246         default :
3247             ftdi_error_return(-1, "Request to unknown EEPROM value");
3248     }
3249     return 0;
3250 }
3251
3252 /** Get the read-only buffer to the binary EEPROM content
3253
3254     \param ftdi pointer to ftdi_context
3255     \param buf buffer to receive EEPROM content
3256     \param size Size of receiving buffer
3257
3258     \retval 0: All fine
3259     \retval -1: struct ftdi_contxt or ftdi_eeprom missing
3260     \retval -2: Not enough room to store eeprom
3261 */
3262 int ftdi_get_eeprom_buf(struct ftdi_context *ftdi, unsigned char * buf, int size)
3263 {
3264     if (!ftdi || !(ftdi->eeprom))
3265         ftdi_error_return(-1, "No appropriate structure");
3266
3267     if (!buf || size < ftdi->eeprom->size)
3268         ftdi_error_return(-1, "Not enough room to store eeprom");
3269
3270     // Only copy up to FTDI_MAX_EEPROM_SIZE bytes
3271     if (size > FTDI_MAX_EEPROM_SIZE)
3272         size = FTDI_MAX_EEPROM_SIZE;
3273
3274     memcpy(buf, ftdi->eeprom->buf, size);
3275
3276     return 0;
3277 }
3278
3279 /**
3280     Read eeprom location
3281
3282     \param ftdi pointer to ftdi_context
3283     \param eeprom_addr Address of eeprom location to be read
3284     \param eeprom_val Pointer to store read eeprom location
3285
3286     \retval  0: all fine
3287     \retval -1: read failed
3288     \retval -2: USB device unavailable
3289 */
3290 int ftdi_read_eeprom_location (struct ftdi_context *ftdi, int eeprom_addr, unsigned short *eeprom_val)
3291 {
3292     if (ftdi == NULL || ftdi->usb_dev == NULL)
3293         ftdi_error_return(-2, "USB device unavailable");
3294
3295     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)
3296         ftdi_error_return(-1, "reading eeprom failed");
3297
3298     return 0;
3299 }
3300
3301 /**
3302     Read eeprom
3303
3304     \param ftdi pointer to ftdi_context
3305
3306     \retval  0: all fine
3307     \retval -1: read failed
3308     \retval -2: USB device unavailable
3309 */
3310 int ftdi_read_eeprom(struct ftdi_context *ftdi)
3311 {
3312     int i;
3313     unsigned char *buf;
3314
3315     if (ftdi == NULL || ftdi->usb_dev == NULL)
3316         ftdi_error_return(-2, "USB device unavailable");
3317     buf = ftdi->eeprom->buf;
3318
3319     for (i = 0; i < FTDI_MAX_EEPROM_SIZE/2; i++)
3320     {
3321         if (libusb_control_transfer(
3322                     ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE,SIO_READ_EEPROM_REQUEST, 0, i,
3323                     buf+(i*2), 2, ftdi->usb_read_timeout) != 2)
3324             ftdi_error_return(-1, "reading eeprom failed");
3325     }
3326
3327     if (ftdi->type == TYPE_R)
3328         ftdi->eeprom->size = 0x80;
3329     /*    Guesses size of eeprom by comparing halves
3330           - will not work with blank eeprom */
3331     else if (strrchr((const char *)buf, 0xff) == ((const char *)buf +FTDI_MAX_EEPROM_SIZE -1))
3332         ftdi->eeprom->size = -1;
3333     else if (memcmp(buf,&buf[0x80],0x80) == 0)
3334         ftdi->eeprom->size = 0x80;
3335     else if (memcmp(buf,&buf[0x40],0x40) == 0)
3336         ftdi->eeprom->size = 0x40;
3337     else
3338         ftdi->eeprom->size = 0x100;
3339     return 0;
3340 }
3341
3342 /*
3343     ftdi_read_chipid_shift does the bitshift operation needed for the FTDIChip-ID
3344     Function is only used internally
3345     \internal
3346 */
3347 static unsigned char ftdi_read_chipid_shift(unsigned char value)
3348 {
3349     return ((value & 1) << 1) |
3350            ((value & 2) << 5) |
3351            ((value & 4) >> 2) |
3352            ((value & 8) << 4) |
3353            ((value & 16) >> 1) |
3354            ((value & 32) >> 1) |
3355            ((value & 64) >> 4) |
3356            ((value & 128) >> 2);
3357 }
3358
3359 /**
3360     Read the FTDIChip-ID from R-type devices
3361
3362     \param ftdi pointer to ftdi_context
3363     \param chipid Pointer to store FTDIChip-ID
3364
3365     \retval  0: all fine
3366     \retval -1: read failed
3367     \retval -2: USB device unavailable
3368 */
3369 int ftdi_read_chipid(struct ftdi_context *ftdi, unsigned int *chipid)
3370 {
3371     unsigned int a = 0, b = 0;
3372
3373     if (ftdi == NULL || ftdi->usb_dev == NULL)
3374         ftdi_error_return(-2, "USB device unavailable");
3375
3376     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)
3377     {
3378         a = a << 8 | a >> 8;
3379         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)
3380         {
3381             b = b << 8 | b >> 8;
3382             a = (a << 16) | (b & 0xFFFF);
3383             a = ftdi_read_chipid_shift(a) | ftdi_read_chipid_shift(a>>8)<<8
3384                 | ftdi_read_chipid_shift(a>>16)<<16 | ftdi_read_chipid_shift(a>>24)<<24;
3385             *chipid = a ^ 0xa5f0f7d1;
3386             return 0;
3387         }
3388     }
3389
3390     ftdi_error_return(-1, "read of FTDIChip-ID failed");
3391 }
3392
3393 /**
3394     Write eeprom location
3395
3396     \param ftdi pointer to ftdi_context
3397     \param eeprom_addr Address of eeprom location to be written
3398     \param eeprom_val Value to be written
3399
3400     \retval  0: all fine
3401     \retval -1: write failed
3402     \retval -2: USB device unavailable
3403     \retval -3: Invalid access to checksum protected area below 0x80
3404     \retval -4: Device can't access unprotected area
3405     \retval -5: Reading chip type failed
3406 */
3407 int ftdi_write_eeprom_location(struct ftdi_context *ftdi, int eeprom_addr,
3408                                unsigned short eeprom_val)
3409 {
3410     int chip_type_location;
3411     unsigned short chip_type;
3412
3413     if (ftdi == NULL || ftdi->usb_dev == NULL)
3414         ftdi_error_return(-2, "USB device unavailable");
3415
3416     if (eeprom_addr <0x80)
3417         ftdi_error_return(-2, "Invalid access to checksum protected area  below 0x80");
3418
3419
3420     switch (ftdi->type)
3421     {
3422         case TYPE_BM:
3423         case  TYPE_2232C:
3424             chip_type_location = 0x14;
3425             break;
3426         case TYPE_2232H:
3427         case TYPE_4232H:
3428             chip_type_location = 0x18;
3429             break;
3430         default:
3431             ftdi_error_return(-4, "Device can't access unprotected area");
3432     }
3433
3434     if (ftdi_read_eeprom_location( ftdi, chip_type_location>>1, &chip_type))
3435         ftdi_error_return(-5, "Reading failed failed");
3436     fprintf(stderr," loc 0x%04x val 0x%04x\n", chip_type_location,chip_type);
3437     if ((chip_type & 0xff) != 0x66)
3438     {
3439         ftdi_error_return(-6, "EEPROM is not of 93x66");
3440     }
3441
3442     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
3443                                 SIO_WRITE_EEPROM_REQUEST, eeprom_val, eeprom_addr,
3444                                 NULL, 0, ftdi->usb_write_timeout) != 0)
3445         ftdi_error_return(-1, "unable to write eeprom");
3446
3447     return 0;
3448 }
3449
3450 /**
3451     Write eeprom
3452
3453     \param ftdi pointer to ftdi_context
3454
3455     \retval  0: all fine
3456     \retval -1: read failed
3457     \retval -2: USB device unavailable
3458 */
3459 int ftdi_write_eeprom(struct ftdi_context *ftdi)
3460 {
3461     unsigned short usb_val, status;
3462     int i, ret;
3463     unsigned char *eeprom;
3464
3465     if (ftdi == NULL || ftdi->usb_dev == NULL)
3466         ftdi_error_return(-2, "USB device unavailable");
3467     eeprom = ftdi->eeprom->buf;
3468
3469     /* These commands were traced while running MProg */
3470     if ((ret = ftdi_usb_reset(ftdi)) != 0)
3471         return ret;
3472     if ((ret = ftdi_poll_modem_status(ftdi, &status)) != 0)
3473         return ret;
3474     if ((ret = ftdi_set_latency_timer(ftdi, 0x77)) != 0)
3475         return ret;
3476
3477     for (i = 0; i < ftdi->eeprom->size/2; i++)
3478     {
3479         usb_val = eeprom[i*2];
3480         usb_val += eeprom[(i*2)+1] << 8;
3481         if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
3482                                     SIO_WRITE_EEPROM_REQUEST, usb_val, i,
3483                                     NULL, 0, ftdi->usb_write_timeout) < 0)
3484             ftdi_error_return(-1, "unable to write eeprom");
3485     }
3486
3487     return 0;
3488 }
3489
3490 /**
3491     Erase eeprom
3492
3493     This is not supported on FT232R/FT245R according to the MProg manual from FTDI.
3494
3495     \param ftdi pointer to ftdi_context
3496
3497     \retval  0: all fine
3498     \retval -1: erase failed
3499     \retval -2: USB device unavailable
3500     \retval -3: Writing magic failed
3501     \retval -4: Read EEPROM failed
3502     \retval -5: Unexpected EEPROM value
3503 */
3504 #define MAGIC 0x55aa
3505 int ftdi_erase_eeprom(struct ftdi_context *ftdi)
3506 {
3507     unsigned short eeprom_value;
3508     if (ftdi == NULL || ftdi->usb_dev == NULL)
3509         ftdi_error_return(-2, "USB device unavailable");
3510
3511     if (ftdi->type == TYPE_R)
3512     {
3513         ftdi->eeprom->chip = 0;
3514         return 0;
3515     }
3516
3517     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_ERASE_EEPROM_REQUEST,
3518                                 0, 0, NULL, 0, ftdi->usb_write_timeout) < 0)
3519         ftdi_error_return(-1, "unable to erase eeprom");
3520
3521
3522     /* detect chip type by writing 0x55AA as magic at word position 0xc0
3523        Chip is 93x46 if magic is read at word position 0x00, as wraparound happens around 0x40
3524        Chip is 93x56 if magic is read at word position 0x40, as wraparound happens around 0x80
3525        Chip is 93x66 if magic is only read at word position 0xc0*/
3526     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
3527                                 SIO_WRITE_EEPROM_REQUEST, MAGIC, 0xc0,
3528                                 NULL, 0, ftdi->usb_write_timeout) != 0)
3529         ftdi_error_return(-3, "Writing magic failed");
3530     if (ftdi_read_eeprom_location( ftdi, 0x00, &eeprom_value))
3531         ftdi_error_return(-4, "Reading failed failed");
3532     if (eeprom_value == MAGIC)
3533     {
3534         ftdi->eeprom->chip = 0x46;
3535     }
3536     else
3537     {
3538         if (ftdi_read_eeprom_location( ftdi, 0x40, &eeprom_value))
3539             ftdi_error_return(-4, "Reading failed failed");
3540         if (eeprom_value == MAGIC)
3541             ftdi->eeprom->chip = 0x56;
3542         else
3543         {
3544             if (ftdi_read_eeprom_location( ftdi, 0xc0, &eeprom_value))
3545                 ftdi_error_return(-4, "Reading failed failed");
3546             if (eeprom_value == MAGIC)
3547                 ftdi->eeprom->chip = 0x66;
3548             else
3549             {
3550                 ftdi->eeprom->chip = -1;
3551             }
3552         }
3553     }
3554     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_ERASE_EEPROM_REQUEST,
3555                                 0, 0, NULL, 0, ftdi->usb_write_timeout) < 0)
3556         ftdi_error_return(-1, "unable to erase eeprom");
3557     return 0;
3558 }
3559
3560 /**
3561     Get string representation for last error code
3562
3563     \param ftdi pointer to ftdi_context
3564
3565     \retval Pointer to error string
3566 */
3567 char *ftdi_get_error_string (struct ftdi_context *ftdi)
3568 {
3569     if (ftdi == NULL)
3570         return "";
3571
3572     return ftdi->error_str;
3573 }
3574
3575 /* @} end of doxygen libftdi group */