Free the device list in ftdi_usb_find_all
[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_free_device_list(-6, "libusb_get_device_descriptor() failed", devs);
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_free_device_list(-3, "out of memory", devs);
299
300             (*curdev)->next = NULL;
301             (*curdev)->dev = dev;
302
303             curdev = &(*curdev)->next;
304             count++;
305         }
306     }
307     libusb_free_device_list(devs,1);
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     if(product)
2230     {
2231         eeprom->product = malloc(strlen(product)+1);
2232         if (eeprom->product)
2233             strcpy(eeprom->product, product);
2234     }
2235
2236     if (eeprom->serial)
2237         free (eeprom->serial);
2238     eeprom->serial = NULL;
2239     if (serial)
2240     {
2241         eeprom->serial = malloc(strlen(serial)+1);
2242         if (eeprom->serial)
2243             strcpy(eeprom->serial, serial);
2244     }
2245
2246
2247     if (ftdi->type == TYPE_R)
2248     {
2249         eeprom->max_power = 90;
2250         eeprom->size = 0x80;
2251         eeprom->cbus_function[0] = CBUS_TXLED;
2252         eeprom->cbus_function[1] = CBUS_RXLED;
2253         eeprom->cbus_function[2] = CBUS_TXDEN;
2254         eeprom->cbus_function[3] = CBUS_PWREN;
2255         eeprom->cbus_function[4] = CBUS_SLEEP;
2256     }
2257     else
2258         eeprom->size = -1;
2259     return 0;
2260 }
2261
2262 /**
2263     Build binary buffer from ftdi_eeprom structure.
2264     Output is suitable for ftdi_write_eeprom().
2265
2266     \param ftdi pointer to ftdi_context
2267
2268     \retval >=0: size of eeprom user area in bytes
2269     \retval -1: eeprom size (128 bytes) exceeded by custom strings
2270     \retval -2: Invalid eeprom or ftdi pointer
2271     \retval -3: Invalid cbus function setting     (FIXME: Not in the code?)
2272     \retval -4: Chip doesn't support invert       (FIXME: Not in the code?)
2273     \retval -5: Chip doesn't support high current drive         (FIXME: Not in the code?)
2274     \retval -6: No connected EEPROM or EEPROM Type unknown
2275 */
2276 int ftdi_eeprom_build(struct ftdi_context *ftdi)
2277 {
2278     unsigned char i, j, eeprom_size_mask;
2279     unsigned short checksum, value;
2280     unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
2281     int user_area_size;
2282     struct ftdi_eeprom *eeprom;
2283     unsigned char * output;
2284
2285     if (ftdi == NULL)
2286         ftdi_error_return(-2,"No context");
2287     if (ftdi->eeprom == NULL)
2288         ftdi_error_return(-2,"No eeprom structure");
2289
2290     eeprom= ftdi->eeprom;
2291     output = eeprom->buf;
2292
2293     if (eeprom->chip == -1)
2294         ftdi_error_return(-6,"No connected EEPROM or EEPROM type unknown");
2295
2296     if ((eeprom->chip == 0x56) || (eeprom->chip == 0x66))
2297         eeprom->size = 0x100;
2298     else
2299         eeprom->size = 0x80;
2300
2301     if (eeprom->manufacturer != NULL)
2302         manufacturer_size = strlen(eeprom->manufacturer);
2303     if (eeprom->product != NULL)
2304         product_size = strlen(eeprom->product);
2305     if (eeprom->serial != NULL)
2306         serial_size = strlen(eeprom->serial);
2307
2308     // eeprom size check
2309     switch (ftdi->type)
2310     {
2311         case TYPE_AM:
2312         case TYPE_BM:
2313             user_area_size = 96;    // base size for strings (total of 48 characters)
2314             break;
2315         case TYPE_2232C:
2316             user_area_size = 90;     // two extra config bytes and 4 bytes PnP stuff
2317             break;
2318         case TYPE_R:
2319             user_area_size = 88;     // four extra config bytes + 4 bytes PnP stuff
2320             break;
2321         case TYPE_2232H:            // six extra config bytes + 4 bytes PnP stuff
2322         case TYPE_4232H:
2323             user_area_size = 86;
2324             break;
2325         default:
2326             user_area_size = 0;
2327             break;
2328     }
2329     user_area_size  -= (manufacturer_size + product_size + serial_size) * 2;
2330
2331     if (user_area_size < 0)
2332         ftdi_error_return(-1,"eeprom size exceeded");
2333
2334     // empty eeprom
2335     memset (ftdi->eeprom->buf, 0, FTDI_MAX_EEPROM_SIZE);
2336
2337     // Bytes and Bits set for all Types
2338
2339     // Addr 02: Vendor ID
2340     output[0x02] = eeprom->vendor_id;
2341     output[0x03] = eeprom->vendor_id >> 8;
2342
2343     // Addr 04: Product ID
2344     output[0x04] = eeprom->product_id;
2345     output[0x05] = eeprom->product_id >> 8;
2346
2347     // Addr 06: Device release number (0400h for BM features)
2348     output[0x06] = 0x00;
2349     switch (ftdi->type)
2350     {
2351         case TYPE_AM:
2352             output[0x07] = 0x02;
2353             break;
2354         case TYPE_BM:
2355             output[0x07] = 0x04;
2356             break;
2357         case TYPE_2232C:
2358             output[0x07] = 0x05;
2359             break;
2360         case TYPE_R:
2361             output[0x07] = 0x06;
2362             break;
2363         case TYPE_2232H:
2364             output[0x07] = 0x07;
2365             break;
2366         case TYPE_4232H:
2367             output[0x07] = 0x08;
2368             break;
2369         default:
2370             output[0x07] = 0x00;
2371     }
2372
2373     // Addr 08: Config descriptor
2374     // Bit 7: always 1
2375     // Bit 6: 1 if this device is self powered, 0 if bus powered
2376     // Bit 5: 1 if this device uses remote wakeup
2377     // Bit 4-0: reserved - 0
2378     j = 0x80;
2379     if (eeprom->self_powered == 1)
2380         j |= 0x40;
2381     if (eeprom->remote_wakeup == 1)
2382         j |= 0x20;
2383     output[0x08] = j;
2384
2385     // Addr 09: Max power consumption: max power = value * 2 mA
2386     output[0x09] = eeprom->max_power>>1;
2387
2388     if (ftdi->type != TYPE_AM)
2389     {
2390         // Addr 0A: Chip configuration
2391         // Bit 7: 0 - reserved
2392         // Bit 6: 0 - reserved
2393         // Bit 5: 0 - reserved
2394         // Bit 4: 1 - Change USB version
2395         // Bit 3: 1 - Use the serial number string
2396         // Bit 2: 1 - Enable suspend pull downs for lower power
2397         // Bit 1: 1 - Out EndPoint is Isochronous
2398         // Bit 0: 1 - In EndPoint is Isochronous
2399         //
2400         j = 0;
2401         if (eeprom->in_is_isochronous == 1)
2402             j = j | 1;
2403         if (eeprom->out_is_isochronous == 1)
2404             j = j | 2;
2405         output[0x0A] = j;
2406     }
2407
2408     // Dynamic content
2409     // Strings start at 0x94 (TYPE_AM, TYPE_BM)
2410     // 0x96 (TYPE_2232C), 0x98 (TYPE_R) and 0x9a (TYPE_x232H)
2411     i = 0;
2412     switch (ftdi->type)
2413     {
2414         case TYPE_2232H:
2415         case TYPE_4232H:
2416             i += 2;
2417         case TYPE_R:
2418             i += 2;
2419         case TYPE_2232C:
2420             i += 2;
2421         case TYPE_AM:
2422         case TYPE_BM:
2423             i += 0x94;
2424     }
2425     /* Wrap around 0x80 for 128 byte EEPROMS (Internale and 93x46) */
2426     eeprom_size_mask = eeprom->size -1;
2427
2428     // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
2429     // Addr 0F: Length of manufacturer string
2430     // Output manufacturer
2431     output[0x0E] = i;  // calculate offset
2432     output[i & eeprom_size_mask] = manufacturer_size*2 + 2, i++;
2433     output[i & eeprom_size_mask] = 0x03, i++; // type: string
2434     for (j = 0; j < manufacturer_size; j++)
2435     {
2436         output[i & eeprom_size_mask] = eeprom->manufacturer[j], i++;
2437         output[i & eeprom_size_mask] = 0x00, i++;
2438     }
2439     output[0x0F] = manufacturer_size*2 + 2;
2440
2441     // Addr 10: Offset of the product string + 0x80, calculated later
2442     // Addr 11: Length of product string
2443     output[0x10] = i | 0x80;  // calculate offset
2444     output[i & eeprom_size_mask] = product_size*2 + 2, i++;
2445     output[i & eeprom_size_mask] = 0x03, i++;
2446     for (j = 0; j < product_size; j++)
2447     {
2448         output[i & eeprom_size_mask] = eeprom->product[j], i++;
2449         output[i & eeprom_size_mask] = 0x00, i++;
2450     }
2451     output[0x11] = product_size*2 + 2;
2452
2453     // Addr 12: Offset of the serial string + 0x80, calculated later
2454     // Addr 13: Length of serial string
2455     output[0x12] = i | 0x80; // calculate offset
2456     output[i & eeprom_size_mask] = serial_size*2 + 2, i++;
2457     output[i & eeprom_size_mask] = 0x03, i++;
2458     for (j = 0; j < serial_size; j++)
2459     {
2460         output[i & eeprom_size_mask] = eeprom->serial[j], i++;
2461         output[i & eeprom_size_mask] = 0x00, i++;
2462     }
2463
2464     // Legacy port name and PnP fields for FT2232 and newer chips
2465     if (ftdi->type > TYPE_BM)
2466     {
2467         output[i & eeprom_size_mask] = 0x02; /* as seen when written with FTD2XX */
2468         i++;
2469         output[i & eeprom_size_mask] = 0x03; /* as seen when written with FTD2XX */
2470         i++;
2471         output[i & eeprom_size_mask] = eeprom->is_not_pnp; /* as seen when written with FTD2XX */
2472         i++;
2473     }
2474
2475     output[0x13] = serial_size*2 + 2;
2476
2477     if (ftdi->type > TYPE_AM) /* use_serial not used in AM devices */
2478     {
2479         if (eeprom->use_serial == USE_SERIAL_NUM )
2480             output[0x0A] |= USE_SERIAL_NUM;
2481         else
2482             output[0x0A] &= ~USE_SERIAL_NUM;
2483     }
2484
2485     /* Bytes and Bits specific to (some) types
2486        Write linear, as this allows easier fixing*/
2487     switch (ftdi->type)
2488     {
2489         case TYPE_AM:
2490             break;
2491         case TYPE_BM:
2492             output[0x0C] = eeprom->usb_version & 0xff;
2493             output[0x0D] = (eeprom->usb_version>>8) & 0xff;
2494             if (eeprom->use_usb_version == USE_USB_VERSION_BIT)
2495                 output[0x0A] |= USE_USB_VERSION_BIT;
2496             else
2497                 output[0x0A] &= ~USE_USB_VERSION_BIT;
2498
2499             break;
2500         case TYPE_2232C:
2501
2502             output[0x00] = (eeprom->channel_a_type);
2503             if ( eeprom->channel_a_driver == DRIVER_VCP)
2504                 output[0x00] |= DRIVER_VCP;
2505             else
2506                 output[0x00] &= ~DRIVER_VCP;
2507
2508             if ( eeprom->high_current_a == HIGH_CURRENT_DRIVE)
2509                 output[0x00] |= HIGH_CURRENT_DRIVE;
2510             else
2511                 output[0x00] &= ~HIGH_CURRENT_DRIVE;
2512
2513             output[0x01] = (eeprom->channel_b_type);
2514             if ( eeprom->channel_b_driver == DRIVER_VCP)
2515                 output[0x01] |= DRIVER_VCP;
2516             else
2517                 output[0x01] &= ~DRIVER_VCP;
2518
2519             if ( eeprom->high_current_b == HIGH_CURRENT_DRIVE)
2520                 output[0x01] |= HIGH_CURRENT_DRIVE;
2521             else
2522                 output[0x01] &= ~HIGH_CURRENT_DRIVE;
2523
2524             if (eeprom->in_is_isochronous == 1)
2525                 output[0x0A] |= 0x1;
2526             else
2527                 output[0x0A] &= ~0x1;
2528             if (eeprom->out_is_isochronous == 1)
2529                 output[0x0A] |= 0x2;
2530             else
2531                 output[0x0A] &= ~0x2;
2532             if (eeprom->suspend_pull_downs == 1)
2533                 output[0x0A] |= 0x4;
2534             else
2535                 output[0x0A] &= ~0x4;
2536             if (eeprom->use_usb_version == USE_USB_VERSION_BIT)
2537                 output[0x0A] |= USE_USB_VERSION_BIT;
2538             else
2539                 output[0x0A] &= ~USE_USB_VERSION_BIT;
2540
2541             output[0x0C] = eeprom->usb_version & 0xff;
2542             output[0x0D] = (eeprom->usb_version>>8) & 0xff;
2543             output[0x14] = eeprom->chip;
2544             break;
2545         case TYPE_R:
2546             if (eeprom->high_current == HIGH_CURRENT_DRIVE_R)
2547                 output[0x00] |= HIGH_CURRENT_DRIVE_R;
2548             output[0x01] = 0x40; /* Hard coded Endpoint Size*/
2549
2550             if (eeprom->suspend_pull_downs == 1)
2551                 output[0x0A] |= 0x4;
2552             else
2553                 output[0x0A] &= ~0x4;
2554             output[0x0B] = eeprom->invert;
2555             output[0x0C] = eeprom->usb_version & 0xff;
2556             output[0x0D] = (eeprom->usb_version>>8) & 0xff;
2557
2558             if (eeprom->cbus_function[0] > CBUS_BB)
2559                 output[0x14] = CBUS_TXLED;
2560             else
2561                 output[0x14] = eeprom->cbus_function[0];
2562
2563             if (eeprom->cbus_function[1] > CBUS_BB)
2564                 output[0x14] |= CBUS_RXLED<<4;
2565             else
2566                 output[0x14] |= eeprom->cbus_function[1]<<4;
2567
2568             if (eeprom->cbus_function[2] > CBUS_BB)
2569                 output[0x15] = CBUS_TXDEN;
2570             else
2571                 output[0x15] = eeprom->cbus_function[2];
2572
2573             if (eeprom->cbus_function[3] > CBUS_BB)
2574                 output[0x15] |= CBUS_PWREN<<4;
2575             else
2576                 output[0x15] |= eeprom->cbus_function[3]<<4;
2577
2578             if (eeprom->cbus_function[4] > CBUS_CLK6)
2579                 output[0x16] = CBUS_SLEEP;
2580             else
2581                 output[0x16] = eeprom->cbus_function[4];
2582             break;
2583         case TYPE_2232H:
2584             output[0x00] = (eeprom->channel_a_type);
2585             if ( eeprom->channel_a_driver == DRIVER_VCP)
2586                 output[0x00] |= DRIVER_VCP;
2587             else
2588                 output[0x00] &= ~DRIVER_VCP;
2589
2590             output[0x01] = (eeprom->channel_b_type);
2591             if ( eeprom->channel_b_driver == DRIVER_VCP)
2592                 output[0x01] |= DRIVER_VCP;
2593             else
2594                 output[0x01] &= ~DRIVER_VCP;
2595             if (eeprom->suspend_dbus7 == SUSPEND_DBUS7_BIT)
2596                 output[0x01] |= SUSPEND_DBUS7_BIT;
2597             else
2598                 output[0x01] &= ~SUSPEND_DBUS7_BIT;
2599
2600             if (eeprom->suspend_pull_downs == 1)
2601                 output[0x0A] |= 0x4;
2602             else
2603                 output[0x0A] &= ~0x4;
2604
2605             if (eeprom->group0_drive > DRIVE_16MA)
2606                 output[0x0c] |= DRIVE_16MA;
2607             else
2608                 output[0x0c] |= eeprom->group0_drive;
2609             if (eeprom->group0_schmitt == IS_SCHMITT)
2610                 output[0x0c] |= IS_SCHMITT;
2611             if (eeprom->group0_slew == SLOW_SLEW)
2612                 output[0x0c] |= SLOW_SLEW;
2613
2614             if (eeprom->group1_drive > DRIVE_16MA)
2615                 output[0x0c] |= DRIVE_16MA<<4;
2616             else
2617                 output[0x0c] |= eeprom->group1_drive<<4;
2618             if (eeprom->group1_schmitt == IS_SCHMITT)
2619                 output[0x0c] |= IS_SCHMITT<<4;
2620             if (eeprom->group1_slew == SLOW_SLEW)
2621                 output[0x0c] |= SLOW_SLEW<<4;
2622
2623             if (eeprom->group2_drive > DRIVE_16MA)
2624                 output[0x0d] |= DRIVE_16MA;
2625             else
2626                 output[0x0d] |= eeprom->group2_drive;
2627             if (eeprom->group2_schmitt == IS_SCHMITT)
2628                 output[0x0d] |= IS_SCHMITT;
2629             if (eeprom->group2_slew == SLOW_SLEW)
2630                 output[0x0d] |= SLOW_SLEW;
2631
2632             if (eeprom->group3_drive > DRIVE_16MA)
2633                 output[0x0d] |= DRIVE_16MA<<4;
2634             else
2635                 output[0x0d] |= eeprom->group3_drive<<4;
2636             if (eeprom->group3_schmitt == IS_SCHMITT)
2637                 output[0x0d] |= IS_SCHMITT<<4;
2638             if (eeprom->group3_slew == SLOW_SLEW)
2639                 output[0x0d] |= SLOW_SLEW<<4;
2640
2641             output[0x18] = eeprom->chip;
2642
2643             break;
2644         case TYPE_4232H:
2645             fprintf(stderr,"FIXME: Build FT4232H specific EEPROM settings\n");
2646     }
2647
2648     // calculate checksum
2649     checksum = 0xAAAA;
2650
2651     for (i = 0; i < eeprom->size/2-1; i++)
2652     {
2653         value = output[i*2];
2654         value += output[(i*2)+1] << 8;
2655
2656         checksum = value^checksum;
2657         checksum = (checksum << 1) | (checksum >> 15);
2658     }
2659
2660     output[eeprom->size-2] = checksum;
2661     output[eeprom->size-1] = checksum >> 8;
2662
2663     return user_area_size;
2664 }
2665
2666 /**
2667    Decode binary EEPROM image into an ftdi_eeprom structure.
2668
2669    \param ftdi pointer to ftdi_context
2670    \param verbose Decode EEPROM on stdout
2671
2672    \retval 0: all fine
2673    \retval -1: something went wrong
2674
2675    FIXME: How to pass size? How to handle size field in ftdi_eeprom?
2676    FIXME: Strings are malloc'ed here and should be freed somewhere
2677 */
2678 int ftdi_eeprom_decode(struct ftdi_context *ftdi, int verbose)
2679 {
2680     unsigned char i, j;
2681     unsigned short checksum, eeprom_checksum, value;
2682     unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
2683     int eeprom_size;
2684     struct ftdi_eeprom *eeprom;
2685     unsigned char *buf = ftdi->eeprom->buf;
2686     int release;
2687
2688     if (ftdi == NULL)
2689         ftdi_error_return(-1,"No context");
2690     if (ftdi->eeprom == NULL)
2691         ftdi_error_return(-1,"No eeprom structure");
2692
2693     eeprom = ftdi->eeprom;
2694     eeprom_size = eeprom->size;
2695
2696     // Addr 02: Vendor ID
2697     eeprom->vendor_id = buf[0x02] + (buf[0x03] << 8);
2698
2699     // Addr 04: Product ID
2700     eeprom->product_id = buf[0x04] + (buf[0x05] << 8);
2701
2702     release = buf[0x06] + (buf[0x07]<<8);
2703
2704     // Addr 08: Config descriptor
2705     // Bit 7: always 1
2706     // Bit 6: 1 if this device is self powered, 0 if bus powered
2707     // Bit 5: 1 if this device uses remote wakeup
2708     eeprom->self_powered = buf[0x08] & 0x40;
2709     eeprom->remote_wakeup = buf[0x08] & 0x20;
2710
2711     // Addr 09: Max power consumption: max power = value * 2 mA
2712     eeprom->max_power = buf[0x09];
2713
2714     // Addr 0A: Chip configuration
2715     // Bit 7: 0 - reserved
2716     // Bit 6: 0 - reserved
2717     // Bit 5: 0 - reserved
2718     // Bit 4: 1 - Change USB version on BM and 2232C
2719     // Bit 3: 1 - Use the serial number string
2720     // Bit 2: 1 - Enable suspend pull downs for lower power
2721     // Bit 1: 1 - Out EndPoint is Isochronous
2722     // Bit 0: 1 - In EndPoint is Isochronous
2723     //
2724     eeprom->in_is_isochronous  = buf[0x0A]&0x01;
2725     eeprom->out_is_isochronous = buf[0x0A]&0x02;
2726     eeprom->suspend_pull_downs = buf[0x0A]&0x04;
2727     eeprom->use_serial         = buf[0x0A] & USE_SERIAL_NUM;
2728     eeprom->use_usb_version    = buf[0x0A] & USE_USB_VERSION_BIT;
2729
2730     // Addr 0C: USB version low byte when 0x0A
2731     // Addr 0D: USB version high byte when 0x0A
2732     eeprom->usb_version = buf[0x0C] + (buf[0x0D] << 8);
2733
2734     // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
2735     // Addr 0F: Length of manufacturer string
2736     manufacturer_size = buf[0x0F]/2;
2737     if (eeprom->manufacturer)
2738         free(eeprom->manufacturer);
2739     if (manufacturer_size > 0)
2740     {
2741         eeprom->manufacturer = malloc(manufacturer_size);
2742         if (eeprom->manufacturer)
2743         {
2744             // Decode manufacturer
2745             i = buf[0x0E] & (eeprom_size -1); // offset
2746             for (j=0;j<manufacturer_size-1;j++)
2747             {
2748                 eeprom->manufacturer[j] = buf[2*j+i+2];
2749             }
2750             eeprom->manufacturer[j] = '\0';
2751         }
2752     }
2753     else eeprom->manufacturer = NULL;
2754
2755     // Addr 10: Offset of the product string + 0x80, calculated later
2756     // Addr 11: Length of product string
2757     if (eeprom->product)
2758         free(eeprom->product);
2759     product_size = buf[0x11]/2;
2760     if (product_size > 0)
2761     {
2762         eeprom->product = malloc(product_size);
2763         if (eeprom->product)
2764         {
2765             // Decode product name
2766             i = buf[0x10] & (eeprom_size -1); // offset
2767             for (j=0;j<product_size-1;j++)
2768             {
2769                 eeprom->product[j] = buf[2*j+i+2];
2770             }
2771             eeprom->product[j] = '\0';
2772         }
2773     }
2774     else eeprom->product = NULL;
2775
2776     // Addr 12: Offset of the serial string + 0x80, calculated later
2777     // Addr 13: Length of serial string
2778     if (eeprom->serial)
2779         free(eeprom->serial);
2780     serial_size = buf[0x13]/2;
2781     if (serial_size > 0)
2782     {
2783         eeprom->serial = malloc(serial_size);
2784         if (eeprom->serial)
2785         {
2786             // Decode serial
2787             i = buf[0x12] & (eeprom_size -1); // offset
2788             for (j=0;j<serial_size-1;j++)
2789             {
2790                 eeprom->serial[j] = buf[2*j+i+2];
2791             }
2792             eeprom->serial[j] = '\0';
2793         }
2794     }
2795     else eeprom->serial = NULL;
2796
2797     // verify checksum
2798     checksum = 0xAAAA;
2799
2800     for (i = 0; i < eeprom_size/2-1; i++)
2801     {
2802         value = buf[i*2];
2803         value += buf[(i*2)+1] << 8;
2804
2805         checksum = value^checksum;
2806         checksum = (checksum << 1) | (checksum >> 15);
2807     }
2808
2809     eeprom_checksum = buf[eeprom_size-2] + (buf[eeprom_size-1] << 8);
2810
2811     if (eeprom_checksum != checksum)
2812     {
2813         fprintf(stderr, "Checksum Error: %04x %04x\n", checksum, eeprom_checksum);
2814         ftdi_error_return(-1,"EEPROM checksum error");
2815     }
2816
2817     eeprom->channel_a_type   = 0;
2818     if ((ftdi->type == TYPE_AM) || (ftdi->type == TYPE_BM))
2819     {
2820         eeprom->chip = -1;
2821     }
2822     else if (ftdi->type == TYPE_2232C)
2823     {
2824         eeprom->channel_a_type   = buf[0x00] & 0x7;
2825         eeprom->channel_a_driver = buf[0x00] & DRIVER_VCP;
2826         eeprom->high_current_a   = buf[0x00] & HIGH_CURRENT_DRIVE;
2827         eeprom->channel_b_type   = buf[0x01] & 0x7;
2828         eeprom->channel_b_driver = buf[0x01] & DRIVER_VCP;
2829         eeprom->high_current_b   = buf[0x01] & HIGH_CURRENT_DRIVE;
2830         eeprom->chip = buf[0x14];
2831     }
2832     else if (ftdi->type == TYPE_R)
2833     {
2834         /* TYPE_R flags D2XX, not VCP as all others*/
2835         eeprom->channel_a_driver = (~buf[0x00]) & DRIVER_VCP;
2836         eeprom->high_current     = buf[0x00] & HIGH_CURRENT_DRIVE_R;
2837         if ( (buf[0x01]&0x40) != 0x40)
2838             fprintf(stderr,
2839                     "TYPE_R EEPROM byte[0x01] Bit 6 unexpected Endpoint size."
2840                     " If this happened with the\n"
2841                     " EEPROM programmed by FTDI tools, please report "
2842                     "to libftdi@developer.intra2net.com\n");
2843
2844         eeprom->chip = buf[0x16];
2845         // Addr 0B: Invert data lines
2846         // Works only on FT232R, not FT245R, but no way to distinguish
2847         eeprom->invert = buf[0x0B];
2848         // Addr 14: CBUS function: CBUS0, CBUS1
2849         // Addr 15: CBUS function: CBUS2, CBUS3
2850         // Addr 16: CBUS function: CBUS5
2851         eeprom->cbus_function[0] = buf[0x14] & 0x0f;
2852         eeprom->cbus_function[1] = (buf[0x14] >> 4) & 0x0f;
2853         eeprom->cbus_function[2] = buf[0x15] & 0x0f;
2854         eeprom->cbus_function[3] = (buf[0x15] >> 4) & 0x0f;
2855         eeprom->cbus_function[4] = buf[0x16] & 0x0f;
2856     }
2857     else if ((ftdi->type == TYPE_2232H) ||(ftdi->type == TYPE_4232H))
2858     {
2859         eeprom->channel_a_type   = buf[0x00] & 0x7;
2860         eeprom->channel_a_driver = buf[0x00] & DRIVER_VCP;
2861         eeprom->channel_b_type   = buf[0x01] & 0x7;
2862         eeprom->channel_b_driver = buf[0x01] & DRIVER_VCP;
2863
2864         if (ftdi->type == TYPE_2232H)
2865             eeprom->suspend_dbus7    = buf[0x01] & SUSPEND_DBUS7_BIT;
2866
2867         eeprom->chip = buf[0x18];
2868         eeprom->group0_drive   =  buf[0x0c]       & DRIVE_16MA;
2869         eeprom->group0_schmitt =  buf[0x0c]       & IS_SCHMITT;
2870         eeprom->group0_slew    =  buf[0x0c]       & SLOW_SLEW;
2871         eeprom->group1_drive   = (buf[0x0c] >> 4) & 0x3;
2872         eeprom->group1_schmitt = (buf[0x0c] >> 4) & IS_SCHMITT;
2873         eeprom->group1_slew    = (buf[0x0c] >> 4) & SLOW_SLEW;
2874         eeprom->group2_drive   =  buf[0x0d]       & DRIVE_16MA;
2875         eeprom->group2_schmitt =  buf[0x0d]       & IS_SCHMITT;
2876         eeprom->group2_slew    =  buf[0x0d]       & SLOW_SLEW;
2877         eeprom->group3_drive   = (buf[0x0d] >> 4) & DRIVE_16MA;
2878         eeprom->group3_schmitt = (buf[0x0d] >> 4) & IS_SCHMITT;
2879         eeprom->group3_slew    = (buf[0x0d] >> 4) & SLOW_SLEW;
2880     }
2881
2882     if (verbose)
2883     {
2884         char *channel_mode[] = {"UART","245","CPU", "unknown", "OPTO"};
2885         fprintf(stdout, "VID:     0x%04x\n",eeprom->vendor_id);
2886         fprintf(stdout, "PID:     0x%04x\n",eeprom->product_id);
2887         fprintf(stdout, "Release: 0x%04x\n",release);
2888
2889         if (eeprom->self_powered)
2890             fprintf(stdout, "Self-Powered%s", (eeprom->remote_wakeup)?", USB Remote Wake Up\n":"\n");
2891         else
2892             fprintf(stdout, "Bus Powered: %3d mA%s", eeprom->max_power * 2,
2893                     (eeprom->remote_wakeup)?" USB Remote Wake Up\n":"\n");
2894         if (eeprom->manufacturer)
2895             fprintf(stdout, "Manufacturer: %s\n",eeprom->manufacturer);
2896         if (eeprom->product)
2897             fprintf(stdout, "Product:      %s\n",eeprom->product);
2898         if (eeprom->serial)
2899             fprintf(stdout, "Serial:       %s\n",eeprom->serial);
2900         fprintf(stdout,     "Checksum      : %04x\n", checksum);
2901         if (ftdi->type == TYPE_R)
2902             fprintf(stdout,     "Internal EEPROM\n");
2903         else if (eeprom->chip >= 0x46)
2904             fprintf(stdout,     "Attached EEPROM: 93x%02x\n", eeprom->chip);
2905         if (eeprom->suspend_dbus7)
2906             fprintf(stdout, "Suspend on DBUS7\n");
2907         if (eeprom->suspend_pull_downs)
2908             fprintf(stdout, "Pull IO pins low during suspend\n");
2909         if (eeprom->remote_wakeup)
2910             fprintf(stdout, "Enable Remote Wake Up\n");
2911         fprintf(stdout, "PNP: %d\n",(eeprom->is_not_pnp)?0:1);
2912         if (ftdi->type >= TYPE_2232C)
2913             fprintf(stdout,"Channel A has Mode %s%s%s\n",
2914                     channel_mode[eeprom->channel_a_type],
2915                     (eeprom->channel_a_driver)?" VCP":"",
2916                     (eeprom->high_current_a)?" High Current IO":"");
2917         if ((ftdi->type >= TYPE_2232C) && (ftdi->type != TYPE_R))
2918             fprintf(stdout,"Channel B has Mode %s%s%s\n",
2919                     channel_mode[eeprom->channel_b_type],
2920                     (eeprom->channel_b_driver)?" VCP":"",
2921                     (eeprom->high_current_b)?" High Current IO":"");
2922         if (((ftdi->type == TYPE_BM) || (ftdi->type == TYPE_2232C)) &&
2923                 eeprom->use_usb_version == USE_USB_VERSION_BIT)
2924             fprintf(stdout,"Use explicit USB Version %04x\n",eeprom->usb_version);
2925
2926         if ((ftdi->type == TYPE_2232H) || (ftdi->type == TYPE_4232H))
2927         {
2928             fprintf(stdout,"%s has %d mA drive%s%s\n",
2929                     (ftdi->type == TYPE_2232H)?"AL":"A",
2930                     (eeprom->group0_drive+1) *4,
2931                     (eeprom->group0_schmitt)?" Schmitt Input":"",
2932                     (eeprom->group0_slew)?" Slow Slew":"");
2933             fprintf(stdout,"%s has %d mA drive%s%s\n",
2934                     (ftdi->type == TYPE_2232H)?"AH":"B",
2935                     (eeprom->group1_drive+1) *4,
2936                     (eeprom->group1_schmitt)?" Schmitt Input":"",
2937                     (eeprom->group1_slew)?" Slow Slew":"");
2938             fprintf(stdout,"%s has %d mA drive%s%s\n",
2939                     (ftdi->type == TYPE_2232H)?"BL":"C",
2940                     (eeprom->group2_drive+1) *4,
2941                     (eeprom->group2_schmitt)?" Schmitt Input":"",
2942                     (eeprom->group2_slew)?" Slow Slew":"");
2943             fprintf(stdout,"%s has %d mA drive%s%s\n",
2944                     (ftdi->type == TYPE_2232H)?"BH":"D",
2945                     (eeprom->group3_drive+1) *4,
2946                     (eeprom->group3_schmitt)?" Schmitt Input":"",
2947                     (eeprom->group3_slew)?" Slow Slew":"");
2948         }
2949         if (ftdi->type == TYPE_R)
2950         {
2951             char *cbus_mux[] = {"TXDEN","PWREN","RXLED", "TXLED","TX+RXLED",
2952                                 "SLEEP","CLK48","CLK24","CLK12","CLK6",
2953                                 "IOMODE","BB_WR","BB_RD"
2954                                };
2955             char *cbus_BB[] = {"RXF","TXE","RD", "WR"};
2956
2957             if (eeprom->invert)
2958             {
2959                 char *r_bits[] = {"TXD","RXD","RTS", "CTS","DTR","DSR","DCD","RI"};
2960                 fprintf(stdout,"Inverted bits:");
2961                 for (i=0; i<8; i++)
2962                     if ((eeprom->invert & (1<<i)) == (1<<i))
2963                         fprintf(stdout," %s",r_bits[i]);
2964                 fprintf(stdout,"\n");
2965             }
2966             for (i=0; i<5; i++)
2967             {
2968                 if (eeprom->cbus_function[i]<CBUS_BB)
2969                     fprintf(stdout,"C%d Function: %s\n", i,
2970                             cbus_mux[eeprom->cbus_function[i]]);
2971                 else
2972                 {
2973                     if (i < 4)
2974                         /* Running MPROG show that C0..3 have fixed function Synchronous
2975                            Bit Bang mode */
2976                         fprintf(stdout,"C%d BB Function: %s\n", i,
2977                                 cbus_BB[i]);
2978                     else
2979                         fprintf(stdout, "Unknown CBUS mode. Might be special mode?\n");
2980                 }
2981             }
2982         }
2983     }
2984     return 0;
2985 }
2986
2987 /**
2988    Get a value from the decoded EEPROM structure
2989
2990    \param ftdi pointer to ftdi_context
2991    \param value_name Enum of the value to query
2992    \param value Pointer to store read value
2993
2994    \retval 0: all fine
2995    \retval -1: Value doesn't exist
2996 */
2997 int ftdi_get_eeprom_value(struct ftdi_context *ftdi, enum ftdi_eeprom_value value_name, int* value)
2998 {
2999     switch (value_name)
3000     {
3001         case VENDOR_ID:
3002             *value = ftdi->eeprom->vendor_id;
3003             break;
3004         case PRODUCT_ID:
3005             *value = ftdi->eeprom->product_id;
3006             break;
3007         case SELF_POWERED:
3008             *value = ftdi->eeprom->self_powered;
3009             break;
3010         case REMOTE_WAKEUP:
3011             *value = ftdi->eeprom->remote_wakeup;
3012             break;
3013         case IS_NOT_PNP:
3014             *value = ftdi->eeprom->is_not_pnp;
3015             break;
3016         case SUSPEND_DBUS7:
3017             *value = ftdi->eeprom->suspend_dbus7;
3018             break;
3019         case IN_IS_ISOCHRONOUS:
3020             *value = ftdi->eeprom->in_is_isochronous;
3021             break;
3022         case SUSPEND_PULL_DOWNS:
3023             *value = ftdi->eeprom->suspend_pull_downs;
3024             break;
3025         case USE_SERIAL:
3026             *value = ftdi->eeprom->use_serial;
3027             break;
3028         case USB_VERSION:
3029             *value = ftdi->eeprom->usb_version;
3030             break;
3031         case MAX_POWER:
3032             *value = ftdi->eeprom->max_power;
3033             break;
3034         case CHANNEL_A_TYPE:
3035             *value = ftdi->eeprom->channel_a_type;
3036             break;
3037         case CHANNEL_B_TYPE:
3038             *value = ftdi->eeprom->channel_b_type;
3039             break;
3040         case CHANNEL_A_DRIVER:
3041             *value = ftdi->eeprom->channel_a_driver;
3042             break;
3043         case CHANNEL_B_DRIVER:
3044             *value = ftdi->eeprom->channel_b_driver;
3045             break;
3046         case CBUS_FUNCTION_0:
3047             *value = ftdi->eeprom->cbus_function[0];
3048             break;
3049         case CBUS_FUNCTION_1:
3050             *value = ftdi->eeprom->cbus_function[1];
3051             break;
3052         case CBUS_FUNCTION_2:
3053             *value = ftdi->eeprom->cbus_function[2];
3054             break;
3055         case CBUS_FUNCTION_3:
3056             *value = ftdi->eeprom->cbus_function[3];
3057             break;
3058         case CBUS_FUNCTION_4:
3059             *value = ftdi->eeprom->cbus_function[4];
3060             break;
3061         case HIGH_CURRENT:
3062             *value = ftdi->eeprom->high_current;
3063             break;
3064         case HIGH_CURRENT_A:
3065             *value = ftdi->eeprom->high_current_a;
3066             break;
3067         case HIGH_CURRENT_B:
3068             *value = ftdi->eeprom->high_current_b;
3069             break;
3070         case INVERT:
3071             *value = ftdi->eeprom->invert;
3072             break;
3073         case GROUP0_DRIVE:
3074             *value = ftdi->eeprom->group0_drive;
3075             break;
3076         case GROUP0_SCHMITT:
3077             *value = ftdi->eeprom->group0_schmitt;
3078             break;
3079         case GROUP0_SLEW:
3080             *value = ftdi->eeprom->group0_slew;
3081             break;
3082         case GROUP1_DRIVE:
3083             *value = ftdi->eeprom->group1_drive;
3084             break;
3085         case GROUP1_SCHMITT:
3086             *value = ftdi->eeprom->group1_schmitt;
3087             break;
3088         case GROUP1_SLEW:
3089             *value = ftdi->eeprom->group1_slew;
3090             break;
3091         case GROUP2_DRIVE:
3092             *value = ftdi->eeprom->group2_drive;
3093             break;
3094         case GROUP2_SCHMITT:
3095             *value = ftdi->eeprom->group2_schmitt;
3096             break;
3097         case GROUP2_SLEW:
3098             *value = ftdi->eeprom->group2_slew;
3099             break;
3100         case GROUP3_DRIVE:
3101             *value = ftdi->eeprom->group3_drive;
3102             break;
3103         case GROUP3_SCHMITT:
3104             *value = ftdi->eeprom->group3_schmitt;
3105             break;
3106         case GROUP3_SLEW:
3107             *value = ftdi->eeprom->group3_slew;
3108             break;
3109         case CHIP_TYPE:
3110             *value = ftdi->eeprom->chip;
3111             break;
3112         case CHIP_SIZE:
3113             *value = ftdi->eeprom->size;
3114             break;
3115         default:
3116             ftdi_error_return(-1, "Request for unknown EEPROM value");
3117     }
3118     return 0;
3119 }
3120
3121 /**
3122    Set a value in the decoded EEPROM Structure
3123    No parameter checking is performed
3124
3125    \param ftdi pointer to ftdi_context
3126    \param value_name Enum of the value to set
3127    \param value to set
3128
3129    \retval 0: all fine
3130    \retval -1: Value doesn't exist
3131    \retval -2: Value not user settable
3132 */
3133 int ftdi_set_eeprom_value(struct ftdi_context *ftdi, enum ftdi_eeprom_value value_name, int value)
3134 {
3135     switch (value_name)
3136     {
3137         case VENDOR_ID:
3138             ftdi->eeprom->vendor_id = value;
3139             break;
3140         case PRODUCT_ID:
3141             ftdi->eeprom->product_id = value;
3142             break;
3143         case SELF_POWERED:
3144             ftdi->eeprom->self_powered = value;
3145             break;
3146         case REMOTE_WAKEUP:
3147             ftdi->eeprom->remote_wakeup = value;
3148             break;
3149         case IS_NOT_PNP:
3150             ftdi->eeprom->is_not_pnp = value;
3151             break;
3152         case SUSPEND_DBUS7:
3153             ftdi->eeprom->suspend_dbus7 = value;
3154             break;
3155         case IN_IS_ISOCHRONOUS:
3156             ftdi->eeprom->in_is_isochronous = value;
3157             break;
3158         case SUSPEND_PULL_DOWNS:
3159             ftdi->eeprom->suspend_pull_downs = value;
3160             break;
3161         case USE_SERIAL:
3162             ftdi->eeprom->use_serial = value;
3163             break;
3164         case USB_VERSION:
3165             ftdi->eeprom->usb_version = value;
3166             break;
3167         case MAX_POWER:
3168             ftdi->eeprom->max_power = value;
3169             break;
3170         case CHANNEL_A_TYPE:
3171             ftdi->eeprom->channel_a_type = value;
3172             break;
3173         case CHANNEL_B_TYPE:
3174             ftdi->eeprom->channel_b_type = value;
3175             break;
3176         case CHANNEL_A_DRIVER:
3177             ftdi->eeprom->channel_a_driver = value;
3178             break;
3179         case CHANNEL_B_DRIVER:
3180             ftdi->eeprom->channel_b_driver = value;
3181             break;
3182         case CBUS_FUNCTION_0:
3183             ftdi->eeprom->cbus_function[0] = value;
3184             break;
3185         case CBUS_FUNCTION_1:
3186             ftdi->eeprom->cbus_function[1] = value;
3187             break;
3188         case CBUS_FUNCTION_2:
3189             ftdi->eeprom->cbus_function[2] = value;
3190             break;
3191         case CBUS_FUNCTION_3:
3192             ftdi->eeprom->cbus_function[3] = value;
3193             break;
3194         case CBUS_FUNCTION_4:
3195             ftdi->eeprom->cbus_function[4] = value;
3196             break;
3197         case HIGH_CURRENT:
3198             ftdi->eeprom->high_current = value;
3199             break;
3200         case HIGH_CURRENT_A:
3201             ftdi->eeprom->high_current_a = value;
3202             break;
3203         case HIGH_CURRENT_B:
3204             ftdi->eeprom->high_current_b = value;
3205             break;
3206         case INVERT:
3207             ftdi->eeprom->invert = value;
3208             break;
3209         case GROUP0_DRIVE:
3210             ftdi->eeprom->group0_drive = value;
3211             break;
3212         case GROUP0_SCHMITT:
3213             ftdi->eeprom->group0_schmitt = value;
3214             break;
3215         case GROUP0_SLEW:
3216             ftdi->eeprom->group0_slew = value;
3217             break;
3218         case GROUP1_DRIVE:
3219             ftdi->eeprom->group1_drive = value;
3220             break;
3221         case GROUP1_SCHMITT:
3222             ftdi->eeprom->group1_schmitt = value;
3223             break;
3224         case GROUP1_SLEW:
3225             ftdi->eeprom->group1_slew = value;
3226             break;
3227         case GROUP2_DRIVE:
3228             ftdi->eeprom->group2_drive = value;
3229             break;
3230         case GROUP2_SCHMITT:
3231             ftdi->eeprom->group2_schmitt = value;
3232             break;
3233         case GROUP2_SLEW:
3234             ftdi->eeprom->group2_slew = value;
3235             break;
3236         case GROUP3_DRIVE:
3237             ftdi->eeprom->group3_drive = value;
3238             break;
3239         case GROUP3_SCHMITT:
3240             ftdi->eeprom->group3_schmitt = value;
3241             break;
3242         case GROUP3_SLEW:
3243             ftdi->eeprom->group3_slew = value;
3244             break;
3245         case CHIP_TYPE:
3246             ftdi->eeprom->chip = value;
3247             break;
3248         case CHIP_SIZE:
3249             ftdi_error_return(-2, "EEPROM Value can't be changed");
3250         default :
3251             ftdi_error_return(-1, "Request to unknown EEPROM value");
3252     }
3253     return 0;
3254 }
3255
3256 /** Get the read-only buffer to the binary EEPROM content
3257
3258     \param ftdi pointer to ftdi_context
3259     \param buf buffer to receive EEPROM content
3260     \param size Size of receiving buffer
3261
3262     \retval 0: All fine
3263     \retval -1: struct ftdi_contxt or ftdi_eeprom missing
3264     \retval -2: Not enough room to store eeprom
3265 */
3266 int ftdi_get_eeprom_buf(struct ftdi_context *ftdi, unsigned char * buf, int size)
3267 {
3268     if (!ftdi || !(ftdi->eeprom))
3269         ftdi_error_return(-1, "No appropriate structure");
3270
3271     if (!buf || size < ftdi->eeprom->size)
3272         ftdi_error_return(-1, "Not enough room to store eeprom");
3273
3274     // Only copy up to FTDI_MAX_EEPROM_SIZE bytes
3275     if (size > FTDI_MAX_EEPROM_SIZE)
3276         size = FTDI_MAX_EEPROM_SIZE;
3277
3278     memcpy(buf, ftdi->eeprom->buf, size);
3279
3280     return 0;
3281 }
3282
3283 /**
3284     Read eeprom location
3285
3286     \param ftdi pointer to ftdi_context
3287     \param eeprom_addr Address of eeprom location to be read
3288     \param eeprom_val Pointer to store read eeprom location
3289
3290     \retval  0: all fine
3291     \retval -1: read failed
3292     \retval -2: USB device unavailable
3293 */
3294 int ftdi_read_eeprom_location (struct ftdi_context *ftdi, int eeprom_addr, unsigned short *eeprom_val)
3295 {
3296     if (ftdi == NULL || ftdi->usb_dev == NULL)
3297         ftdi_error_return(-2, "USB device unavailable");
3298
3299     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)
3300         ftdi_error_return(-1, "reading eeprom failed");
3301
3302     return 0;
3303 }
3304
3305 /**
3306     Read eeprom
3307
3308     \param ftdi pointer to ftdi_context
3309
3310     \retval  0: all fine
3311     \retval -1: read failed
3312     \retval -2: USB device unavailable
3313 */
3314 int ftdi_read_eeprom(struct ftdi_context *ftdi)
3315 {
3316     int i;
3317     unsigned char *buf;
3318
3319     if (ftdi == NULL || ftdi->usb_dev == NULL)
3320         ftdi_error_return(-2, "USB device unavailable");
3321     buf = ftdi->eeprom->buf;
3322
3323     for (i = 0; i < FTDI_MAX_EEPROM_SIZE/2; i++)
3324     {
3325         if (libusb_control_transfer(
3326                     ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE,SIO_READ_EEPROM_REQUEST, 0, i,
3327                     buf+(i*2), 2, ftdi->usb_read_timeout) != 2)
3328             ftdi_error_return(-1, "reading eeprom failed");
3329     }
3330
3331     if (ftdi->type == TYPE_R)
3332         ftdi->eeprom->size = 0x80;
3333     /*    Guesses size of eeprom by comparing halves
3334           - will not work with blank eeprom */
3335     else if (strrchr((const char *)buf, 0xff) == ((const char *)buf +FTDI_MAX_EEPROM_SIZE -1))
3336         ftdi->eeprom->size = -1;
3337     else if (memcmp(buf,&buf[0x80],0x80) == 0)
3338         ftdi->eeprom->size = 0x80;
3339     else if (memcmp(buf,&buf[0x40],0x40) == 0)
3340         ftdi->eeprom->size = 0x40;
3341     else
3342         ftdi->eeprom->size = 0x100;
3343     return 0;
3344 }
3345
3346 /*
3347     ftdi_read_chipid_shift does the bitshift operation needed for the FTDIChip-ID
3348     Function is only used internally
3349     \internal
3350 */
3351 static unsigned char ftdi_read_chipid_shift(unsigned char value)
3352 {
3353     return ((value & 1) << 1) |
3354            ((value & 2) << 5) |
3355            ((value & 4) >> 2) |
3356            ((value & 8) << 4) |
3357            ((value & 16) >> 1) |
3358            ((value & 32) >> 1) |
3359            ((value & 64) >> 4) |
3360            ((value & 128) >> 2);
3361 }
3362
3363 /**
3364     Read the FTDIChip-ID from R-type devices
3365
3366     \param ftdi pointer to ftdi_context
3367     \param chipid Pointer to store FTDIChip-ID
3368
3369     \retval  0: all fine
3370     \retval -1: read failed
3371     \retval -2: USB device unavailable
3372 */
3373 int ftdi_read_chipid(struct ftdi_context *ftdi, unsigned int *chipid)
3374 {
3375     unsigned int a = 0, b = 0;
3376
3377     if (ftdi == NULL || ftdi->usb_dev == NULL)
3378         ftdi_error_return(-2, "USB device unavailable");
3379
3380     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)
3381     {
3382         a = a << 8 | a >> 8;
3383         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)
3384         {
3385             b = b << 8 | b >> 8;
3386             a = (a << 16) | (b & 0xFFFF);
3387             a = ftdi_read_chipid_shift(a) | ftdi_read_chipid_shift(a>>8)<<8
3388                 | ftdi_read_chipid_shift(a>>16)<<16 | ftdi_read_chipid_shift(a>>24)<<24;
3389             *chipid = a ^ 0xa5f0f7d1;
3390             return 0;
3391         }
3392     }
3393
3394     ftdi_error_return(-1, "read of FTDIChip-ID failed");
3395 }
3396
3397 /**
3398     Write eeprom location
3399
3400     \param ftdi pointer to ftdi_context
3401     \param eeprom_addr Address of eeprom location to be written
3402     \param eeprom_val Value to be written
3403
3404     \retval  0: all fine
3405     \retval -1: write failed
3406     \retval -2: USB device unavailable
3407     \retval -3: Invalid access to checksum protected area below 0x80
3408     \retval -4: Device can't access unprotected area
3409     \retval -5: Reading chip type failed
3410 */
3411 int ftdi_write_eeprom_location(struct ftdi_context *ftdi, int eeprom_addr,
3412                                unsigned short eeprom_val)
3413 {
3414     int chip_type_location;
3415     unsigned short chip_type;
3416
3417     if (ftdi == NULL || ftdi->usb_dev == NULL)
3418         ftdi_error_return(-2, "USB device unavailable");
3419
3420     if (eeprom_addr <0x80)
3421         ftdi_error_return(-2, "Invalid access to checksum protected area  below 0x80");
3422
3423
3424     switch (ftdi->type)
3425     {
3426         case TYPE_BM:
3427         case  TYPE_2232C:
3428             chip_type_location = 0x14;
3429             break;
3430         case TYPE_2232H:
3431         case TYPE_4232H:
3432             chip_type_location = 0x18;
3433             break;
3434         default:
3435             ftdi_error_return(-4, "Device can't access unprotected area");
3436     }
3437
3438     if (ftdi_read_eeprom_location( ftdi, chip_type_location>>1, &chip_type))
3439         ftdi_error_return(-5, "Reading failed failed");
3440     fprintf(stderr," loc 0x%04x val 0x%04x\n", chip_type_location,chip_type);
3441     if ((chip_type & 0xff) != 0x66)
3442     {
3443         ftdi_error_return(-6, "EEPROM is not of 93x66");
3444     }
3445
3446     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
3447                                 SIO_WRITE_EEPROM_REQUEST, eeprom_val, eeprom_addr,
3448                                 NULL, 0, ftdi->usb_write_timeout) != 0)
3449         ftdi_error_return(-1, "unable to write eeprom");
3450
3451     return 0;
3452 }
3453
3454 /**
3455     Write eeprom
3456
3457     \param ftdi pointer to ftdi_context
3458
3459     \retval  0: all fine
3460     \retval -1: read failed
3461     \retval -2: USB device unavailable
3462 */
3463 int ftdi_write_eeprom(struct ftdi_context *ftdi)
3464 {
3465     unsigned short usb_val, status;
3466     int i, ret;
3467     unsigned char *eeprom;
3468
3469     if (ftdi == NULL || ftdi->usb_dev == NULL)
3470         ftdi_error_return(-2, "USB device unavailable");
3471     eeprom = ftdi->eeprom->buf;
3472
3473     /* These commands were traced while running MProg */
3474     if ((ret = ftdi_usb_reset(ftdi)) != 0)
3475         return ret;
3476     if ((ret = ftdi_poll_modem_status(ftdi, &status)) != 0)
3477         return ret;
3478     if ((ret = ftdi_set_latency_timer(ftdi, 0x77)) != 0)
3479         return ret;
3480
3481     for (i = 0; i < ftdi->eeprom->size/2; i++)
3482     {
3483         usb_val = eeprom[i*2];
3484         usb_val += eeprom[(i*2)+1] << 8;
3485         if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
3486                                     SIO_WRITE_EEPROM_REQUEST, usb_val, i,
3487                                     NULL, 0, ftdi->usb_write_timeout) < 0)
3488             ftdi_error_return(-1, "unable to write eeprom");
3489     }
3490
3491     return 0;
3492 }
3493
3494 /**
3495     Erase eeprom
3496
3497     This is not supported on FT232R/FT245R according to the MProg manual from FTDI.
3498
3499     \param ftdi pointer to ftdi_context
3500
3501     \retval  0: all fine
3502     \retval -1: erase failed
3503     \retval -2: USB device unavailable
3504     \retval -3: Writing magic failed
3505     \retval -4: Read EEPROM failed
3506     \retval -5: Unexpected EEPROM value
3507 */
3508 #define MAGIC 0x55aa
3509 int ftdi_erase_eeprom(struct ftdi_context *ftdi)
3510 {
3511     unsigned short eeprom_value;
3512     if (ftdi == NULL || ftdi->usb_dev == NULL)
3513         ftdi_error_return(-2, "USB device unavailable");
3514
3515     if (ftdi->type == TYPE_R)
3516     {
3517         ftdi->eeprom->chip = 0;
3518         return 0;
3519     }
3520
3521     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_ERASE_EEPROM_REQUEST,
3522                                 0, 0, NULL, 0, ftdi->usb_write_timeout) < 0)
3523         ftdi_error_return(-1, "unable to erase eeprom");
3524
3525
3526     /* detect chip type by writing 0x55AA as magic at word position 0xc0
3527        Chip is 93x46 if magic is read at word position 0x00, as wraparound happens around 0x40
3528        Chip is 93x56 if magic is read at word position 0x40, as wraparound happens around 0x80
3529        Chip is 93x66 if magic is only read at word position 0xc0*/
3530     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
3531                                 SIO_WRITE_EEPROM_REQUEST, MAGIC, 0xc0,
3532                                 NULL, 0, ftdi->usb_write_timeout) != 0)
3533         ftdi_error_return(-3, "Writing magic failed");
3534     if (ftdi_read_eeprom_location( ftdi, 0x00, &eeprom_value))
3535         ftdi_error_return(-4, "Reading failed failed");
3536     if (eeprom_value == MAGIC)
3537     {
3538         ftdi->eeprom->chip = 0x46;
3539     }
3540     else
3541     {
3542         if (ftdi_read_eeprom_location( ftdi, 0x40, &eeprom_value))
3543             ftdi_error_return(-4, "Reading failed failed");
3544         if (eeprom_value == MAGIC)
3545             ftdi->eeprom->chip = 0x56;
3546         else
3547         {
3548             if (ftdi_read_eeprom_location( ftdi, 0xc0, &eeprom_value))
3549                 ftdi_error_return(-4, "Reading failed failed");
3550             if (eeprom_value == MAGIC)
3551                 ftdi->eeprom->chip = 0x66;
3552             else
3553             {
3554                 ftdi->eeprom->chip = -1;
3555             }
3556         }
3557     }
3558     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_ERASE_EEPROM_REQUEST,
3559                                 0, 0, NULL, 0, ftdi->usb_write_timeout) < 0)
3560         ftdi_error_return(-1, "unable to erase eeprom");
3561     return 0;
3562 }
3563
3564 /**
3565     Get string representation for last error code
3566
3567     \param ftdi pointer to ftdi_context
3568
3569     \retval Pointer to error string
3570 */
3571 char *ftdi_get_error_string (struct ftdi_context *ftdi)
3572 {
3573     if (ftdi == NULL)
3574         return "";
3575
3576     return ftdi->error_str;
3577 }
3578
3579 /* @} end of doxygen libftdi group */