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