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