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