Use max_packet_size
[libftdi] / src / ftdi.c
1 /***************************************************************************
2                           ftdi.c  -  description
3                              -------------------
4     begin                : Fri Apr 4 2003
5     copyright            : (C) 2003-2008 by Intra2net AG
6     email                : opensource@intra2net.com
7  ***************************************************************************/
8
9 /***************************************************************************
10  *                                                                         *
11  *   This program is free software; you can redistribute it and/or modify  *
12  *   it under the terms of the GNU Lesser General Public License           *
13  *   version 2.1 as published by the Free Software Foundation;             *
14  *                                                                         *
15  ***************************************************************************/
16
17 /**
18     \mainpage libftdi API documentation
19
20     Library to talk to FTDI chips. You find the latest versions of libftdi at
21     http://www.intra2net.com/en/developer/libftdi/
22
23     The library is easy to use. Have a look at this short example:
24     \include simple.c
25
26     More examples can be found in the "examples" directory.
27 */
28 /** \addtogroup libftdi */
29 /* @{ */
30
31 #include <libusb.h>
32 #include <string.h>
33 #include <errno.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36
37 #include "ftdi.h"
38
39 #define ftdi_error_return(code, str) do {  \
40         ftdi->error_str = str;             \
41         return code;                       \
42    } while(0);
43
44
45 /**
46     Internal function to close usb device pointer.
47     Sets ftdi->usb_dev to NULL.
48     \internal
49
50     \param ftdi pointer to ftdi_context
51
52     \retval none
53 */
54 static void ftdi_usb_close_internal (struct ftdi_context *ftdi)
55 {
56     if (ftdi->usb_dev)
57     {
58        libusb_close (ftdi->usb_dev);
59        ftdi->usb_dev = NULL;
60     }
61 }
62
63 /**
64     Initializes a ftdi_context.
65
66     \param ftdi pointer to ftdi_context
67
68     \retval  0: all fine
69     \retval -1: couldn't allocate read buffer
70
71     \remark This should be called before all functions
72 */
73 int ftdi_init(struct ftdi_context *ftdi)
74 {
75     ftdi->usb_dev = NULL;
76     ftdi->usb_read_timeout = 5000;
77     ftdi->usb_write_timeout = 5000;
78
79     ftdi->type = TYPE_BM;    /* chip type */
80     ftdi->baudrate = -1;
81     ftdi->bitbang_enabled = 0;  /* 0: normal mode 1: any of the bitbang modes enabled */
82
83     ftdi->readbuffer = NULL;
84     ftdi->readbuffer_offset = 0;
85     ftdi->readbuffer_remaining = 0;
86     ftdi->writebuffer_chunksize = 4096;
87     ftdi->max_packet_size = 0;
88
89     ftdi->interface = 0;
90     ftdi->index = 0;
91     ftdi->in_ep = 0x02;
92     ftdi->out_ep = 0x81;
93     ftdi->bitbang_mode = 1; /* when bitbang is enabled this holds the number of the mode  */
94
95     ftdi->error_str = NULL;
96
97     ftdi->eeprom_size = FTDI_DEFAULT_EEPROM_SIZE;
98
99     /* All fine. Now allocate the readbuffer */
100     return ftdi_read_data_set_chunksize(ftdi, 4096);
101 }
102
103 /**
104     Allocate and initialize a new ftdi_context
105
106     \return a pointer to a new ftdi_context, or NULL on failure
107 */
108 struct ftdi_context *ftdi_new(void)
109 {
110     struct ftdi_context * ftdi = (struct ftdi_context *)malloc(sizeof(struct ftdi_context));
111
112     if (ftdi == NULL)
113     {
114         return NULL;
115     }
116
117     if (ftdi_init(ftdi) != 0)
118     {
119         free(ftdi);
120         return NULL;
121     }
122
123     return ftdi;
124 }
125
126 /**
127     Open selected channels on a chip, otherwise use first channel.
128
129     \param ftdi pointer to ftdi_context
130     \param interface Interface to use for FT2232C/2232H/4232H chips.
131
132     \retval  0: all fine
133     \retval -1: unknown interface
134 */
135 int ftdi_set_interface(struct ftdi_context *ftdi, enum ftdi_interface interface)
136 {
137     switch (interface)
138     {
139         case INTERFACE_ANY:
140         case INTERFACE_A:
141             /* ftdi_usb_open_desc cares to set the right index, depending on the found chip */
142             break;
143         case INTERFACE_B:
144             ftdi->interface = 1;
145             ftdi->index     = INTERFACE_B;
146             ftdi->in_ep     = 0x04;
147             ftdi->out_ep    = 0x83;
148             break;
149         case INTERFACE_C:
150             ftdi->interface = 2;
151             ftdi->index     = INTERFACE_C;
152             ftdi->in_ep     = 0x06;
153             ftdi->out_ep    = 0x85;
154             break;
155         case INTERFACE_D:
156             ftdi->interface = 3;
157             ftdi->index     = INTERFACE_D;
158             ftdi->in_ep     = 0x08;
159             ftdi->out_ep    = 0x87;
160             break;
161         default:
162             ftdi_error_return(-1, "Unknown interface");
163     }
164     return 0;
165 }
166
167 /**
168     Deinitializes a ftdi_context.
169
170     \param ftdi pointer to ftdi_context
171 */
172 void ftdi_deinit(struct ftdi_context *ftdi)
173 {
174     ftdi_usb_close_internal (ftdi);
175
176     if (ftdi->readbuffer != NULL)
177     {
178         free(ftdi->readbuffer);
179         ftdi->readbuffer = NULL;
180     }
181 }
182
183 /**
184     Deinitialize and free an ftdi_context.
185
186     \param ftdi pointer to ftdi_context
187 */
188 void ftdi_free(struct ftdi_context *ftdi)
189 {
190     ftdi_deinit(ftdi);
191     free(ftdi);
192 }
193
194 /**
195     Use an already open libusb device.
196
197     \param ftdi pointer to ftdi_context
198     \param usb libusb libusb_device_handle to use
199 */
200 void ftdi_set_usbdev (struct ftdi_context *ftdi, libusb_device_handle *usb)
201 {
202     ftdi->usb_dev = usb;
203 }
204
205
206 /**
207     Finds all ftdi devices on the usb bus. Creates a new ftdi_device_list which
208     needs to be deallocated by ftdi_list_free() after use.
209
210     \param ftdi pointer to ftdi_context
211     \param devlist Pointer where to store list of found devices
212     \param vendor Vendor ID to search for
213     \param product Product ID to search for
214
215     \retval >0: number of devices found
216     \retval -3: out of memory
217     \retval -4: libusb_init() failed
218     \retval -5: libusb_get_device_list() failed
219     \retval -6: libusb_get_device_descriptor() failed
220 */
221 int ftdi_usb_find_all(struct ftdi_context *ftdi, struct ftdi_device_list **devlist, int vendor, int product)
222 {
223     struct ftdi_device_list **curdev;
224     libusb_device *dev;
225     libusb_device **devs;
226     int count = 0;
227     int i = 0;
228
229     if (libusb_init(NULL) < 0)
230         ftdi_error_return(-4, "libusb_init() failed");
231
232     if (libusb_get_device_list(NULL, &devs) < 0)
233         ftdi_error_return(-5, "libusb_get_device_list() failed");
234
235     curdev = devlist;
236     *curdev = NULL;
237
238     while ((dev = devs[i++]) != NULL)
239     {
240         struct libusb_device_descriptor desc;
241
242         if (libusb_get_device_descriptor(dev, &desc) < 0)
243             ftdi_error_return(-6, "libusb_get_device_descriptor() failed");
244
245         if (desc.idVendor == vendor && desc.idProduct == product)
246         {
247             *curdev = (struct ftdi_device_list*)malloc(sizeof(struct ftdi_device_list));
248             if (!*curdev)
249                 ftdi_error_return(-3, "out of memory");
250               
251             (*curdev)->next = NULL;
252             (*curdev)->dev = dev;
253
254             curdev = &(*curdev)->next;
255             count++;
256         }
257     }
258
259     return count;
260 }
261
262 /**
263     Frees a usb device list.
264
265     \param devlist USB device list created by ftdi_usb_find_all()
266 */
267 void ftdi_list_free(struct ftdi_device_list **devlist)
268 {
269     struct ftdi_device_list *curdev, *next;
270
271     for (curdev = *devlist; curdev != NULL;)
272     {
273         next = curdev->next;
274         free(curdev);
275         curdev = next;
276     }
277
278     *devlist = NULL;
279 }
280
281 /**
282     Frees a usb device list.
283
284     \param devlist USB device list created by ftdi_usb_find_all()
285 */
286 void ftdi_list_free2(struct ftdi_device_list *devlist)
287 {
288     ftdi_list_free(&devlist);
289 }
290
291 /**
292     Return device ID strings from the usb device.
293
294     The parameters manufacturer, description and serial may be NULL
295     or pointer to buffers to store the fetched strings.
296
297     \note Use this function only in combination with ftdi_usb_find_all()
298           as it closes the internal "usb_dev" after use.
299
300     \param ftdi pointer to ftdi_context
301     \param dev libusb usb_dev to use
302     \param manufacturer Store manufacturer string here if not NULL
303     \param mnf_len Buffer size of manufacturer string
304     \param description Store product description string here if not NULL
305     \param desc_len Buffer size of product description string
306     \param serial Store serial string here if not NULL
307     \param serial_len Buffer size of serial string
308
309     \retval   0: all fine
310     \retval  -1: wrong arguments
311     \retval  -4: unable to open device
312     \retval  -7: get product manufacturer failed
313     \retval  -8: get product description failed
314     \retval  -9: get serial number failed
315     \retval -11: libusb_get_device_descriptor() failed
316 */
317 int ftdi_usb_get_strings(struct ftdi_context * ftdi, struct libusb_device * dev,
318                          char * manufacturer, int mnf_len, char * description, int desc_len, char * serial, int serial_len)
319 {
320     struct libusb_device_descriptor desc;
321
322     if ((ftdi==NULL) || (dev==NULL))
323         return -1;
324
325     if (libusb_open(dev, &ftdi->usb_dev) < 0)
326         ftdi_error_return(-4, "libusb_open() failed");
327
328     if (libusb_get_device_descriptor(dev, &desc) < 0)
329         ftdi_error_return(-11, "libusb_get_device_descriptor() failed");
330
331     if (manufacturer != NULL)
332     {
333         if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iManufacturer, (unsigned char *)manufacturer, mnf_len) < 0)
334         {
335             ftdi_usb_close_internal (ftdi);
336             ftdi_error_return(-7, "libusb_get_string_descriptor_ascii() failed");
337         }
338     }
339
340     if (description != NULL)
341     {
342         if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iProduct, (unsigned char *)description, desc_len) < 0)
343         {
344             ftdi_usb_close_internal (ftdi);
345             ftdi_error_return(-8, "libusb_get_string_descriptor_ascii() failed");
346         }
347     }
348
349     if (serial != NULL)
350     {
351         if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iSerialNumber, (unsigned char *)serial, serial_len) < 0)
352         {
353             ftdi_usb_close_internal (ftdi);
354             ftdi_error_return(-9, "libusb_get_string_descriptor_ascii() failed");
355         }
356     }
357
358     ftdi_usb_close_internal (ftdi);
359
360     return 0;
361 }
362
363 /**
364  * Internal function to determine the maximum packet size.
365  * \param ftdi pointer to ftdi_context
366  * \param dev libusb usb_dev to use
367  * \retval Maximum packet size for this device
368  */
369 static unsigned int _ftdi_determine_max_packet_size(struct ftdi_context *ftdi, libusb_device *dev)
370 {
371     struct libusb_device_descriptor desc;
372     struct libusb_config_descriptor *config0;
373     unsigned int packet_size;
374
375     // Determine maximum packet size. Init with default value.
376     // New hi-speed devices from FTDI use a packet size of 512 bytes
377     // but could be connected to a normal speed USB hub -> 64 bytes packet size.
378     if (ftdi->type == TYPE_2232H || ftdi->type == TYPE_4232H)
379         packet_size = 512;
380     else
381         packet_size = 64;
382
383     if (libusb_get_device_descriptor(dev, &desc) < 0)
384         return packet_size;
385
386     if (libusb_get_config_descriptor(dev, 0, &config0) < 0)
387         return packet_size;
388
389     if (desc.bNumConfigurations > 0)
390     {
391         if (ftdi->interface < config0->bNumInterfaces)
392         {
393             struct libusb_interface interface = config0->interface[ftdi->interface];
394             if (interface.num_altsetting > 0)
395             {
396                 struct libusb_interface_descriptor descriptor = interface.altsetting[0];
397                 if (descriptor.bNumEndpoints > 0)
398                 {
399                     packet_size = descriptor.endpoint[0].wMaxPacketSize;
400                 }
401             }
402         }
403     }
404
405     libusb_free_config_descriptor (config0);
406     return packet_size;
407 }
408
409 /**
410     Opens a ftdi device given by an usb_device.
411
412     \param ftdi pointer to ftdi_context
413     \param dev libusb usb_dev to use
414
415     \retval  0: all fine
416     \retval -3: unable to config device
417     \retval -4: unable to open device
418     \retval -5: unable to claim device
419     \retval -6: reset failed
420     \retval -7: set baudrate failed
421     \retval -9: libusb_get_device_descriptor() failed
422     \retval -10: libusb_get_config_descriptor() failed
423     \retval -11: libusb_etach_kernel_driver() failed
424     \retval -12: libusb_get_configuration() failed
425 */
426 int ftdi_usb_open_dev(struct ftdi_context *ftdi, libusb_device *dev)
427 {
428     struct libusb_device_descriptor desc;
429     struct libusb_config_descriptor *config0;
430     int cfg, cfg0;
431
432     if (libusb_open(dev, &ftdi->usb_dev) < 0)
433         ftdi_error_return(-4, "libusb_open() failed");
434
435     if (libusb_get_device_descriptor(dev, &desc) < 0)
436         ftdi_error_return(-9, "libusb_get_device_descriptor() failed");
437
438     if (libusb_get_config_descriptor(dev, 0, &config0) < 0)
439         ftdi_error_return(-10, "libusb_get_config_descriptor() failed");
440     cfg0 = config0->bConfigurationValue;
441     libusb_free_config_descriptor (config0);
442
443 #ifdef LIBUSB_HAS_GET_DRIVER_NP
444     // Try to detach ftdi_sio kernel module.
445     // Returns ENODATA if driver is not loaded.
446     //
447     // The return code is kept in a separate variable and only parsed
448     // if usb_set_configuration() or usb_claim_interface() fails as the
449     // detach operation might be denied and everything still works fine.
450     // Likely scenario is a static ftdi_sio kernel module.
451     ret = libusb_detach_kernel_driver(ftdi->usb_dev, ftdi->interface);
452     if (ret < 0 && ret != LIBUSB_ERROR_NOT_FOUND)
453         ftdi_error_return(-11, "libusb_detach_kernel_driver () failed");
454 #endif
455
456     if (libusb_get_configuration (ftdi->usb_dev, &cfg) < 0)
457         ftdi_error_return(-12, "libusb_get_configuration () failed");
458
459     // set configuration (needed especially for windows)
460     // tolerate EBUSY: one device with one configuration, but two interfaces
461     //    and libftdi sessions to both interfaces (e.g. FT2232)
462     if (desc.bNumConfigurations > 0 && cfg != cfg0)
463     {
464         if (libusb_set_configuration(ftdi->usb_dev, cfg0) < 0)
465         {
466             ftdi_usb_close_internal (ftdi);
467             ftdi_error_return(-3, "unable to set usb configuration. Make sure ftdi_sio is unloaded!");
468         }
469     }
470
471     if (libusb_claim_interface(ftdi->usb_dev, ftdi->interface) < 0)
472     {
473         ftdi_usb_close_internal (ftdi);
474         ftdi_error_return(-5, "unable to claim usb device. Make sure ftdi_sio is unloaded!");
475     }
476
477     if (ftdi_usb_reset (ftdi) != 0)
478     {
479         ftdi_usb_close_internal (ftdi);
480         ftdi_error_return(-6, "ftdi_usb_reset failed");
481     }
482
483     // Try to guess chip type
484     // Bug in the BM type chips: bcdDevice is 0x200 for serial == 0
485     if (desc.bcdDevice == 0x400 || (desc.bcdDevice == 0x200
486             && desc.iSerialNumber == 0))
487         ftdi->type = TYPE_BM;
488     else if (desc.bcdDevice == 0x200)
489         ftdi->type = TYPE_AM;
490     else if (desc.bcdDevice == 0x500)
491         ftdi->type = TYPE_2232C;
492     else if (desc.bcdDevice == 0x600)
493         ftdi->type = TYPE_R;
494     else if (desc.bcdDevice == 0x700)
495         ftdi->type = TYPE_2232H;
496     else if (desc.bcdDevice == 0x800)
497         ftdi->type = TYPE_4232H;
498
499     // Set default interface on dual/quad type chips
500     switch(ftdi->type)
501     {
502         case TYPE_2232C:
503         case TYPE_2232H:
504         case TYPE_4232H:
505             if (!ftdi->index)
506                 ftdi->index = INTERFACE_A;
507             break;
508         default:
509             break;
510     }
511
512     // Determine maximum packet size
513     ftdi->max_packet_size = _ftdi_determine_max_packet_size(ftdi, dev);
514
515     if (ftdi_set_baudrate (ftdi, 9600) != 0)
516     {
517         ftdi_usb_close_internal (ftdi);
518         ftdi_error_return(-7, "set baudrate failed");
519     }
520
521     ftdi_error_return(0, "all fine");
522 }
523
524 /**
525     Opens the first device with a given vendor and product ids.
526
527     \param ftdi pointer to ftdi_context
528     \param vendor Vendor ID
529     \param product Product ID
530
531     \retval same as ftdi_usb_open_desc()
532 */
533 int ftdi_usb_open(struct ftdi_context *ftdi, int vendor, int product)
534 {
535     return ftdi_usb_open_desc(ftdi, vendor, product, NULL, NULL);
536 }
537
538 /**
539     Opens the first device with a given, vendor id, product id,
540     description and serial.
541
542     \param ftdi pointer to ftdi_context
543     \param vendor Vendor ID
544     \param product Product ID
545     \param description Description to search for. Use NULL if not needed.
546     \param serial Serial to search for. Use NULL if not needed.
547
548     \retval  0: all fine
549     \retval -3: usb device not found
550     \retval -4: unable to open device
551     \retval -5: unable to claim device
552     \retval -6: reset failed
553     \retval -7: set baudrate failed
554     \retval -8: get product description failed
555     \retval -9: get serial number failed
556     \retval -11: libusb_init() failed
557     \retval -12: libusb_get_device_list() failed
558     \retval -13: libusb_get_device_descriptor() failed
559 */
560 int ftdi_usb_open_desc(struct ftdi_context *ftdi, int vendor, int product,
561                        const char* description, const char* serial)
562 {
563     return ftdi_usb_open_desc_index(ftdi,vendor,product,description,serial,0);
564 }
565
566 /**
567     Opens the index-th device with a given, vendor id, product id,
568     description and serial.
569
570     \param ftdi pointer to ftdi_context
571     \param vendor Vendor ID
572     \param product Product ID
573     \param description Description to search for. Use NULL if not needed.
574     \param serial Serial to search for. Use NULL if not needed.
575     \param index Number of matching device to open if there are more than one, starts with 0.
576
577     \retval  0: all fine
578     \retval -1: usb_find_busses() failed
579     \retval -2: usb_find_devices() failed
580     \retval -3: usb device not found
581     \retval -4: unable to open device
582     \retval -5: unable to claim device
583     \retval -6: reset failed
584     \retval -7: set baudrate failed
585     \retval -8: get product description failed
586     \retval -9: get serial number failed
587     \retval -10: unable to close device
588 */
589 int ftdi_usb_open_desc_index(struct ftdi_context *ftdi, int vendor, int product,
590                        const char* description, const char* serial, unsigned int index)
591 {
592     libusb_device *dev;
593     libusb_device **devs;
594     char string[256];
595     int i = 0;
596
597     if (libusb_init(NULL) < 0)
598         ftdi_error_return(-11, "libusb_init() failed");
599
600     if (libusb_get_device_list(NULL, &devs) < 0)
601         ftdi_error_return(-12, "libusb_get_device_list() failed");
602
603     while ((dev = devs[i++]) != NULL)
604     {
605         struct libusb_device_descriptor desc;
606
607         if (libusb_get_device_descriptor(dev, &desc) < 0)
608             ftdi_error_return(-13, "libusb_get_device_descriptor() failed");
609
610         if (desc.idVendor == vendor && desc.idProduct == product)
611         {
612             if (libusb_open(dev, &ftdi->usb_dev) < 0)
613                 ftdi_error_return(-4, "usb_open() failed");
614
615             if (description != NULL)
616             {
617                 if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iProduct, (unsigned char *)string, sizeof(string)) < 0)
618                 {
619                     libusb_close (ftdi->usb_dev);
620                     ftdi_error_return(-8, "unable to fetch product description");
621                 }
622                 if (strncmp(string, description, sizeof(string)) != 0)
623                 {
624                     libusb_close (ftdi->usb_dev);
625                     continue;
626                 }
627             }
628             if (serial != NULL)
629             {
630                 if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iSerialNumber, (unsigned char *)string, sizeof(string)) < 0)
631                 {
632                     ftdi_usb_close_internal (ftdi);
633                     ftdi_error_return(-9, "unable to fetch serial number");
634                 }
635                 if (strncmp(string, serial, sizeof(string)) != 0)
636                 {
637                     ftdi_usb_close_internal (ftdi);
638                     continue;
639                 }
640             }
641
642             ftdi_usb_close_internal (ftdi);
643
644                 if (index > 0)
645                 {
646                     index--;
647                     continue;
648                 }
649
650             return ftdi_usb_open_dev(ftdi, dev);
651         }
652     }
653
654     // device not found
655     ftdi_error_return(-3, "device not found");
656 }
657
658 /**
659     Opens the ftdi-device described by a description-string.
660     Intended to be used for parsing a device-description given as commandline argument.
661
662     \param ftdi pointer to ftdi_context
663     \param description NULL-terminated description-string, using this format:
664         \li <tt>d:\<devicenode></tt> path of bus and device-node (e.g. "003/001") within usb device tree (usually at /proc/bus/usb/)
665         \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")
666         \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
667         \li <tt>s:\<vendor>:\<product>:\<serial></tt> first device with given vendor id, product id and serial string
668
669     \note The description format may be extended in later versions.
670
671     \retval  0: all fine
672     \retval -1: libusb_init() failed
673     \retval -2: libusb_get_device_list() failed
674     \retval -3: usb device not found
675     \retval -4: unable to open device
676     \retval -5: unable to claim device
677     \retval -6: reset failed
678     \retval -7: set baudrate failed
679     \retval -8: get product description failed
680     \retval -9: get serial number failed
681     \retval -10: unable to close device
682     \retval -11: illegal description format
683 */
684 int ftdi_usb_open_string(struct ftdi_context *ftdi, const char* description)
685 {
686     if (description[0] == 0 || description[1] != ':')
687         ftdi_error_return(-11, "illegal description format");
688
689     if (description[0] == 'd')
690     {
691         libusb_device *dev;
692         libusb_device **devs;
693         unsigned int bus_number, device_address;
694         int i = 0;
695
696         if (libusb_init (NULL) < 0)
697             ftdi_error_return(-1, "libusb_init() failed");
698
699         if (libusb_get_device_list(NULL, &devs) < 0)
700             ftdi_error_return(-2, "libusb_get_device_list() failed");
701
702         /* XXX: This doesn't handle symlinks/odd paths/etc... */
703         if (sscanf (description + 2, "%u/%u", &bus_number, &device_address) != 2)
704             ftdi_error_return(-11, "illegal description format");
705
706         while ((dev = devs[i++]) != NULL)
707         {
708             if (bus_number == libusb_get_bus_number (dev)
709                 && device_address == libusb_get_device_address (dev))
710                 return ftdi_usb_open_dev(ftdi, dev);
711         }
712
713         // device not found
714         ftdi_error_return(-3, "device not found");
715     }
716     else if (description[0] == 'i' || description[0] == 's')
717     {
718         unsigned int vendor;
719         unsigned int product;
720         unsigned int index=0;
721         const char *serial=NULL;
722         const char *startp, *endp;
723
724         errno=0;
725         startp=description+2;
726         vendor=strtoul((char*)startp,(char**)&endp,0);
727         if (*endp != ':' || endp == startp || errno != 0)
728             ftdi_error_return(-11, "illegal description format");
729
730         startp=endp+1;
731         product=strtoul((char*)startp,(char**)&endp,0);
732         if (endp == startp || errno != 0)
733             ftdi_error_return(-11, "illegal description format");
734
735         if (description[0] == 'i' && *endp != 0)
736         {
737             /* optional index field in i-mode */
738             if (*endp != ':')
739                 ftdi_error_return(-11, "illegal description format");
740
741             startp=endp+1;
742             index=strtoul((char*)startp,(char**)&endp,0);
743             if (*endp != 0 || endp == startp || errno != 0)
744                 ftdi_error_return(-11, "illegal description format");
745         }
746         if (description[0] == 's')
747         {
748             if (*endp != ':')
749                 ftdi_error_return(-11, "illegal description format");
750
751             /* rest of the description is the serial */
752             serial=endp+1;
753         }
754
755         return ftdi_usb_open_desc_index(ftdi, vendor, product, NULL, serial, index);
756     }
757     else
758     {
759         ftdi_error_return(-11, "illegal description format");
760     }
761 }
762
763 /**
764     Resets the ftdi device.
765
766     \param ftdi pointer to ftdi_context
767
768     \retval  0: all fine
769     \retval -1: FTDI reset failed
770 */
771 int ftdi_usb_reset(struct ftdi_context *ftdi)
772 {
773     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
774                                 SIO_RESET_REQUEST, SIO_RESET_SIO,
775                                 ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
776         ftdi_error_return(-1,"FTDI reset failed");
777
778     // Invalidate data in the readbuffer
779     ftdi->readbuffer_offset = 0;
780     ftdi->readbuffer_remaining = 0;
781
782     return 0;
783 }
784
785 /**
786     Clears the read buffer on the chip and the internal read buffer.
787
788     \param ftdi pointer to ftdi_context
789
790     \retval  0: all fine
791     \retval -1: read buffer purge failed
792 */
793 int ftdi_usb_purge_rx_buffer(struct ftdi_context *ftdi)
794 {
795     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
796                                 SIO_RESET_REQUEST, SIO_RESET_PURGE_RX,
797                                 ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
798         ftdi_error_return(-1, "FTDI purge of RX buffer failed");
799
800     // Invalidate data in the readbuffer
801     ftdi->readbuffer_offset = 0;
802     ftdi->readbuffer_remaining = 0;
803
804     return 0;
805 }
806
807 /**
808     Clears the write buffer on the chip.
809
810     \param ftdi pointer to ftdi_context
811
812     \retval  0: all fine
813     \retval -1: write buffer purge failed
814 */
815 int ftdi_usb_purge_tx_buffer(struct ftdi_context *ftdi)
816 {
817     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
818                                 SIO_RESET_REQUEST, SIO_RESET_PURGE_TX,
819                                 ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
820         ftdi_error_return(-1, "FTDI purge of TX buffer failed");
821
822     return 0;
823 }
824
825 /**
826     Clears the buffers on the chip and the internal read buffer.
827
828     \param ftdi pointer to ftdi_context
829
830     \retval  0: all fine
831     \retval -1: read buffer purge failed
832     \retval -2: write buffer purge failed
833 */
834 int ftdi_usb_purge_buffers(struct ftdi_context *ftdi)
835 {
836     int result;
837
838     result = ftdi_usb_purge_rx_buffer(ftdi);
839     if (result < 0)
840         return -1;
841
842     result = ftdi_usb_purge_tx_buffer(ftdi);
843     if (result < 0)
844         return -2;
845
846     return 0;
847 }
848
849
850
851 /**
852     Closes the ftdi device. Call ftdi_deinit() if you're cleaning up.
853
854     \param ftdi pointer to ftdi_context
855
856     \retval  0: all fine
857     \retval -1: usb_release failed
858 */
859 int ftdi_usb_close(struct ftdi_context *ftdi)
860 {
861     int rtn = 0;
862
863     if (ftdi->usb_dev != NULL)
864         if (libusb_release_interface(ftdi->usb_dev, ftdi->interface) < 0)
865             rtn = -1;
866
867     ftdi_usb_close_internal (ftdi);
868
869     return rtn;
870 }
871
872 /**
873     ftdi_convert_baudrate returns nearest supported baud rate to that requested.
874     Function is only used internally
875     \internal
876 */
877 static int ftdi_convert_baudrate(int baudrate, struct ftdi_context *ftdi,
878                                  unsigned short *value, unsigned short *index)
879 {
880     static const char am_adjust_up[8] = {0, 0, 0, 1, 0, 3, 2, 1};
881     static const char am_adjust_dn[8] = {0, 0, 0, 1, 0, 1, 2, 3};
882     static const char frac_code[8] = {0, 3, 2, 4, 1, 5, 6, 7};
883     int divisor, best_divisor, best_baud, best_baud_diff;
884     unsigned long encoded_divisor;
885     int i;
886
887     if (baudrate <= 0)
888     {
889         // Return error
890         return -1;
891     }
892
893     divisor = 24000000 / baudrate;
894
895     if (ftdi->type == TYPE_AM)
896     {
897         // Round down to supported fraction (AM only)
898         divisor -= am_adjust_dn[divisor & 7];
899     }
900
901     // Try this divisor and the one above it (because division rounds down)
902     best_divisor = 0;
903     best_baud = 0;
904     best_baud_diff = 0;
905     for (i = 0; i < 2; i++)
906     {
907         int try_divisor = divisor + i;
908         int baud_estimate;
909         int baud_diff;
910
911         // Round up to supported divisor value
912         if (try_divisor <= 8)
913         {
914             // Round up to minimum supported divisor
915             try_divisor = 8;
916         }
917         else if (ftdi->type != TYPE_AM && try_divisor < 12)
918         {
919             // BM doesn't support divisors 9 through 11 inclusive
920             try_divisor = 12;
921         }
922         else if (divisor < 16)
923         {
924             // AM doesn't support divisors 9 through 15 inclusive
925             try_divisor = 16;
926         }
927         else
928         {
929             if (ftdi->type == TYPE_AM)
930             {
931                 // Round up to supported fraction (AM only)
932                 try_divisor += am_adjust_up[try_divisor & 7];
933                 if (try_divisor > 0x1FFF8)
934                 {
935                     // Round down to maximum supported divisor value (for AM)
936                     try_divisor = 0x1FFF8;
937                 }
938             }
939             else
940             {
941                 if (try_divisor > 0x1FFFF)
942                 {
943                     // Round down to maximum supported divisor value (for BM)
944                     try_divisor = 0x1FFFF;
945                 }
946             }
947         }
948         // Get estimated baud rate (to nearest integer)
949         baud_estimate = (24000000 + (try_divisor / 2)) / try_divisor;
950         // Get absolute difference from requested baud rate
951         if (baud_estimate < baudrate)
952         {
953             baud_diff = baudrate - baud_estimate;
954         }
955         else
956         {
957             baud_diff = baud_estimate - baudrate;
958         }
959         if (i == 0 || baud_diff < best_baud_diff)
960         {
961             // Closest to requested baud rate so far
962             best_divisor = try_divisor;
963             best_baud = baud_estimate;
964             best_baud_diff = baud_diff;
965             if (baud_diff == 0)
966             {
967                 // Spot on! No point trying
968                 break;
969             }
970         }
971     }
972     // Encode the best divisor value
973     encoded_divisor = (best_divisor >> 3) | (frac_code[best_divisor & 7] << 14);
974     // Deal with special cases for encoded value
975     if (encoded_divisor == 1)
976     {
977         encoded_divisor = 0;    // 3000000 baud
978     }
979     else if (encoded_divisor == 0x4001)
980     {
981         encoded_divisor = 1;    // 2000000 baud (BM only)
982     }
983     // Split into "value" and "index" values
984     *value = (unsigned short)(encoded_divisor & 0xFFFF);
985     if (ftdi->type == TYPE_2232C || ftdi->type == TYPE_2232H || ftdi->type == TYPE_4232H)
986     {
987         *index = (unsigned short)(encoded_divisor >> 8);
988         *index &= 0xFF00;
989         *index |= ftdi->index;
990     }
991     else
992         *index = (unsigned short)(encoded_divisor >> 16);
993
994     // Return the nearest baud rate
995     return best_baud;
996 }
997
998 /**
999     Sets the chip baud rate
1000
1001     \param ftdi pointer to ftdi_context
1002     \param baudrate baud rate to set
1003
1004     \retval  0: all fine
1005     \retval -1: invalid baudrate
1006     \retval -2: setting baudrate failed
1007 */
1008 int ftdi_set_baudrate(struct ftdi_context *ftdi, int baudrate)
1009 {
1010     unsigned short value, index;
1011     int actual_baudrate;
1012
1013     if (ftdi->bitbang_enabled)
1014     {
1015         baudrate = baudrate*4;
1016     }
1017
1018     actual_baudrate = ftdi_convert_baudrate(baudrate, ftdi, &value, &index);
1019     if (actual_baudrate <= 0)
1020         ftdi_error_return (-1, "Silly baudrate <= 0.");
1021
1022     // Check within tolerance (about 5%)
1023     if ((actual_baudrate * 2 < baudrate /* Catch overflows */ )
1024             || ((actual_baudrate < baudrate)
1025                 ? (actual_baudrate * 21 < baudrate * 20)
1026                 : (baudrate * 21 < actual_baudrate * 20)))
1027         ftdi_error_return (-1, "Unsupported baudrate. Note: bitbang baudrates are automatically multiplied by 4");
1028
1029     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1030                                 SIO_SET_BAUDRATE_REQUEST, value,
1031                                 index, NULL, 0, ftdi->usb_write_timeout) < 0)
1032         ftdi_error_return (-2, "Setting new baudrate failed");
1033
1034     ftdi->baudrate = baudrate;
1035     return 0;
1036 }
1037
1038 /**
1039     Set (RS232) line characteristics.
1040     The break type can only be set via ftdi_set_line_property2()
1041     and defaults to "off".
1042
1043     \param ftdi pointer to ftdi_context
1044     \param bits Number of bits
1045     \param sbit Number of stop bits
1046     \param parity Parity mode
1047
1048     \retval  0: all fine
1049     \retval -1: Setting line property failed
1050 */
1051 int ftdi_set_line_property(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
1052                            enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity)
1053 {
1054     return ftdi_set_line_property2(ftdi, bits, sbit, parity, BREAK_OFF);
1055 }
1056
1057 /**
1058     Set (RS232) line characteristics
1059
1060     \param ftdi pointer to ftdi_context
1061     \param bits Number of bits
1062     \param sbit Number of stop bits
1063     \param parity Parity mode
1064     \param break_type Break type
1065
1066     \retval  0: all fine
1067     \retval -1: Setting line property failed
1068 */
1069 int ftdi_set_line_property2(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
1070                             enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity,
1071                             enum ftdi_break_type break_type)
1072 {
1073     unsigned short value = bits;
1074
1075     switch (parity)
1076     {
1077         case NONE:
1078             value |= (0x00 << 8);
1079             break;
1080         case ODD:
1081             value |= (0x01 << 8);
1082             break;
1083         case EVEN:
1084             value |= (0x02 << 8);
1085             break;
1086         case MARK:
1087             value |= (0x03 << 8);
1088             break;
1089         case SPACE:
1090             value |= (0x04 << 8);
1091             break;
1092     }
1093
1094     switch (sbit)
1095     {
1096         case STOP_BIT_1:
1097             value |= (0x00 << 11);
1098             break;
1099         case STOP_BIT_15:
1100             value |= (0x01 << 11);
1101             break;
1102         case STOP_BIT_2:
1103             value |= (0x02 << 11);
1104             break;
1105     }
1106
1107     switch (break_type)
1108     {
1109         case BREAK_OFF:
1110             value |= (0x00 << 14);
1111             break;
1112         case BREAK_ON:
1113             value |= (0x01 << 14);
1114             break;
1115     }
1116
1117     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1118                                 SIO_SET_DATA_REQUEST, value,
1119                                 ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
1120         ftdi_error_return (-1, "Setting new line property failed");
1121
1122     return 0;
1123 }
1124
1125 /**
1126     Writes data in chunks (see ftdi_write_data_set_chunksize()) to the chip
1127
1128     \param ftdi pointer to ftdi_context
1129     \param buf Buffer with the data
1130     \param size Size of the buffer
1131
1132     \retval <0: error code from usb_bulk_write()
1133     \retval >0: number of bytes written
1134 */
1135 int ftdi_write_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
1136 {
1137     int offset = 0;
1138     int actual_length;
1139
1140     while (offset < size)
1141     {
1142         int write_size = ftdi->writebuffer_chunksize;
1143
1144         if (offset+write_size > size)
1145             write_size = size-offset;
1146
1147         if (libusb_bulk_transfer(ftdi->usb_dev, ftdi->in_ep, buf+offset, write_size, &actual_length, ftdi->usb_write_timeout) < 0)
1148             ftdi_error_return(-1, "usb bulk write failed");
1149
1150         offset += actual_length;
1151     }
1152
1153     return offset;
1154 }
1155
1156 #ifdef LIBFTDI_LINUX_ASYNC_MODE
1157 #ifdef USB_CLASS_PTP
1158 #error LIBFTDI_LINUX_ASYNC_MODE is not compatible with libusb-compat-0.1!
1159 #endif
1160 static void ftdi_read_data_cb(struct libusb_transfer *transfer)
1161 {
1162     struct ftdi_transfer_control *tc = (struct ftdi_transfer_control *) transfer->user_data;
1163     struct ftdi_context *ftdi = tc->ftdi;
1164     int packet_size, actual_length, num_of_chunks, chunk_remains, i, ret;
1165
1166     packet_size = ftdi->max_packet_size;
1167
1168     actual_length = transfer->actual_length;
1169
1170     if (actual_length > 2)
1171     {
1172         // skip FTDI status bytes.
1173         // Maybe stored in the future to enable modem use
1174         num_of_chunks = actual_length / packet_size;
1175         chunk_remains = actual_length % packet_size;
1176         //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);
1177
1178         ftdi->readbuffer_offset += 2;
1179         actual_length -= 2;
1180
1181         if (actual_length > packet_size - 2)
1182         {
1183             for (i = 1; i < num_of_chunks; i++)
1184               memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1185                        ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1186                        packet_size - 2);
1187             if (chunk_remains > 2)
1188             {
1189                 memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1190                          ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1191                          chunk_remains-2);
1192                 actual_length -= 2*num_of_chunks;
1193             }
1194             else
1195               actual_length -= 2*(num_of_chunks-1)+chunk_remains;
1196         }
1197
1198         if (actual_length > 0)
1199         {
1200             // data still fits in buf?
1201             if (tc->offset + actual_length <= tc->size)
1202             {
1203                 memcpy (tc->buf + tc->offset, ftdi->readbuffer + ftdi->readbuffer_offset, actual_length);
1204                 //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
1205                 tc->offset += actual_length;
1206
1207                 ftdi->readbuffer_offset = 0;
1208                 ftdi->readbuffer_remaining = 0;
1209
1210                 /* Did we read exactly the right amount of bytes? */
1211                 if (tc->offset == tc->size)
1212                 {
1213                     //printf("read_data exact rem %d offset %d\n",
1214                     //ftdi->readbuffer_remaining, offset);
1215                     tc->completed = 1;
1216                     return;
1217                 }
1218             }
1219             else
1220             {
1221                 // only copy part of the data or size <= readbuffer_chunksize
1222                 int part_size = tc->size - tc->offset;
1223                 memcpy (tc->buf + tc->offset, ftdi->readbuffer + ftdi->readbuffer_offset, part_size);
1224                 tc->offset += part_size;
1225
1226                 ftdi->readbuffer_offset += part_size;
1227                 ftdi->readbuffer_remaining = actual_length - part_size;
1228
1229                 /* printf("Returning part: %d - size: %d - offset: %d - actual_length: %d - remaining: %d\n",
1230                 part_size, size, offset, actual_length, ftdi->readbuffer_remaining); */
1231                 tc->completed = 1;
1232                 return;
1233             }
1234         }
1235     }
1236     ret = libusb_submit_transfer (transfer);
1237     if (ret < 0)
1238         tc->completed = 1;
1239 }
1240
1241
1242 static void ftdi_write_data_cb(struct libusb_transfer *transfer)
1243 {
1244     struct ftdi_transfer_control *tc = (struct ftdi_transfer_control *) transfer->user_data;
1245     struct ftdi_context *ftdi = tc->ftdi;
1246
1247     tc->offset = transfer->actual_length;
1248
1249     if (tc->offset == tc->size)
1250     {
1251         tc->completed = 1;
1252     }
1253     else
1254     {
1255         int write_size = ftdi->writebuffer_chunksize;
1256         int ret;
1257
1258         if (tc->offset + write_size > tc->size)
1259             write_size = tc->size - tc->offset;
1260
1261         transfer->length = write_size;
1262         transfer->buffer = tc->buf + tc->offset;
1263         ret = libusb_submit_transfer (transfer);
1264         if (ret < 0)
1265             tc->completed = 1;
1266     }
1267 }
1268
1269
1270 /**
1271     Writes data to the chip. Does not wait for completion of the transfer
1272     nor does it make sure that the transfer was successful.
1273
1274     Use libusb 1.0 Asynchronous API.
1275     Only available if compiled with --with-async-mode.
1276
1277     \param ftdi pointer to ftdi_context
1278     \param buf Buffer with the data
1279     \param size Size of the buffer
1280
1281     \retval NULL: Some error happens when submit transfer
1282     \retval !NULL: Pointer to a ftdi_transfer_control
1283 */
1284
1285 struct ftdi_transfer_control *ftdi_write_data_submit(struct ftdi_context *ftdi, unsigned char *buf, int size)
1286 {
1287     struct ftdi_transfer_control *tc;
1288     struct libusb_transfer *transfer = libusb_alloc_transfer(0);
1289     int write_size, ret;
1290
1291     tc = (struct ftdi_transfer_control *) malloc (sizeof (*tc));
1292
1293     if (!tc || !transfer)
1294         return NULL;
1295
1296     tc->ftdi = ftdi;
1297     tc->completed = 0;
1298     tc->buf = buf;
1299     tc->size = size;
1300     tc->offset = 0;
1301
1302     if (size < ftdi->writebuffer_chunksize)
1303       write_size = size;
1304     else
1305       write_size = ftdi->writebuffer_chunksize;
1306
1307     libusb_fill_bulk_transfer(transfer, ftdi->usb_dev, ftdi->in_ep, buf, write_size, ftdi_write_data_cb, tc, ftdi->usb_write_timeout);
1308     transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
1309
1310     ret = libusb_submit_transfer(transfer);
1311     if (ret < 0)
1312     {
1313         libusb_free_transfer(transfer);
1314         tc->completed = 1;
1315         tc->transfer = NULL;
1316         return NULL;
1317     }
1318     tc->transfer = transfer;
1319
1320     return tc;
1321 }
1322
1323 /**
1324     Reads data from the chip. Does not wait for completion of the transfer
1325     nor does it make sure that the transfer was successful.
1326
1327     Use libusb 1.0 Asynchronous API.
1328     Only available if compiled with --with-async-mode.
1329
1330     \param ftdi pointer to ftdi_context
1331     \param buf Buffer with the data
1332     \param size Size of the buffer
1333
1334     \retval NULL: Some error happens when submit transfer
1335     \retval !NULL: Pointer to a ftdi_transfer_control
1336 */
1337
1338 struct ftdi_transfer_control *ftdi_read_data_submit(struct ftdi_context *ftdi, unsigned char *buf, int size)
1339 {
1340     struct ftdi_transfer_control *tc;
1341     struct libusb_transfer *transfer;
1342     int ret;
1343
1344     tc = (struct ftdi_transfer_control *) malloc (sizeof (*tc));
1345     if (!tc)
1346         return NULL;
1347
1348     tc->ftdi = ftdi;
1349     tc->buf = buf;
1350     tc->size = size;
1351
1352     if (size <= ftdi->readbuffer_remaining)
1353     {
1354         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);
1355
1356         // Fix offsets
1357         ftdi->readbuffer_remaining -= size;
1358         ftdi->readbuffer_offset += size;
1359
1360         /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */
1361
1362         tc->completed = 1;
1363         tc->offset = size;
1364         tc->transfer = NULL;
1365         return tc;
1366     }
1367
1368     tc->completed = 0;
1369     if (ftdi->readbuffer_remaining != 0)
1370     {
1371         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);
1372
1373         tc->offset = ftdi->readbuffer_remaining;
1374     }
1375     else
1376         tc->offset = 0;
1377
1378     transfer = libusb_alloc_transfer(0);
1379     if (!transfer)
1380     {
1381         free (tc);
1382         return NULL;
1383     }
1384
1385     ftdi->readbuffer_remaining = 0;
1386     ftdi->readbuffer_offset = 0;
1387
1388     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);
1389     transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
1390
1391     ret = libusb_submit_transfer(transfer);
1392     if (ret < 0)
1393     {
1394         libusb_free_transfer(transfer);
1395         free (tc);
1396         return NULL;
1397     }
1398     tc->transfer = transfer;
1399
1400     return tc;
1401 }
1402
1403 /**
1404     Wait for completion of the transfer.
1405
1406     Use libusb 1.0 Asynchronous API.
1407     Only available if compiled with --with-async-mode.
1408
1409     \param tc pointer to ftdi_transfer_control
1410
1411     \retval < 0: Some error happens
1412     \retval >= 0: Data size transferred
1413 */
1414
1415 int ftdi_transfer_data_done(struct ftdi_transfer_control *tc)
1416 {
1417     int ret;
1418
1419     while (!tc->completed)
1420     {
1421         ret = libusb_handle_events(NULL);
1422         if (ret < 0)
1423         {
1424             if (ret == LIBUSB_ERROR_INTERRUPTED)
1425                 continue;
1426             libusb_cancel_transfer(tc->transfer);
1427             while (!tc->completed)
1428                 if (libusb_handle_events(NULL) < 0)
1429                     break;
1430             libusb_free_transfer(tc->transfer);
1431             free (tc);
1432             tc = NULL;
1433             return ret;
1434         }
1435     }
1436
1437     if (tc->transfer->status == LIBUSB_TRANSFER_COMPLETED)
1438         ret = tc->offset;
1439     else
1440         ret = -1;
1441
1442     libusb_free_transfer(tc->transfer);
1443     free(tc);
1444     return ret;
1445 }
1446
1447 #endif // LIBFTDI_LINUX_ASYNC_MODE
1448
1449 /**
1450     Configure write buffer chunk size.
1451     Default is 4096.
1452
1453     \param ftdi pointer to ftdi_context
1454     \param chunksize Chunk size
1455
1456     \retval 0: all fine
1457 */
1458 int ftdi_write_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
1459 {
1460     ftdi->writebuffer_chunksize = chunksize;
1461     return 0;
1462 }
1463
1464 /**
1465     Get write buffer chunk size.
1466
1467     \param ftdi pointer to ftdi_context
1468     \param chunksize Pointer to store chunk size in
1469
1470     \retval 0: all fine
1471 */
1472 int ftdi_write_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
1473 {
1474     *chunksize = ftdi->writebuffer_chunksize;
1475     return 0;
1476 }
1477
1478 /**
1479     Reads data in chunks (see ftdi_read_data_set_chunksize()) from the chip.
1480
1481     Automatically strips the two modem status bytes transfered during every read.
1482
1483     \param ftdi pointer to ftdi_context
1484     \param buf Buffer to store data in
1485     \param size Size of the buffer
1486
1487     \retval <0: error code from libusb_bulk_transfer()
1488     \retval  0: no data was available
1489     \retval >0: number of bytes read
1490
1491 */
1492 int ftdi_read_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
1493 {
1494     int offset = 0, ret, i, num_of_chunks, chunk_remains;
1495     int packet_size = ftdi->max_packet_size;
1496     int actual_length = 1;
1497
1498     // Packet size sanity check (avoid division by zero)
1499     if (packet_size == 0)
1500         ftdi_error_return(-1, "max_packet_size is bogus (zero)");
1501
1502     // everything we want is still in the readbuffer?
1503     if (size <= ftdi->readbuffer_remaining)
1504     {
1505         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);
1506
1507         // Fix offsets
1508         ftdi->readbuffer_remaining -= size;
1509         ftdi->readbuffer_offset += size;
1510
1511         /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */
1512
1513         return size;
1514     }
1515     // something still in the readbuffer, but not enough to satisfy 'size'?
1516     if (ftdi->readbuffer_remaining != 0)
1517     {
1518         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);
1519
1520         // Fix offset
1521         offset += ftdi->readbuffer_remaining;
1522     }
1523     // do the actual USB read
1524     while (offset < size && actual_length > 0)
1525     {
1526         ftdi->readbuffer_remaining = 0;
1527         ftdi->readbuffer_offset = 0;
1528         /* returns how much received */
1529         ret = libusb_bulk_transfer (ftdi->usb_dev, ftdi->out_ep, ftdi->readbuffer, ftdi->readbuffer_chunksize, &actual_length, ftdi->usb_read_timeout);
1530         if (ret < 0)
1531             ftdi_error_return(ret, "usb bulk read failed");
1532
1533         if (actual_length > 2)
1534         {
1535             // skip FTDI status bytes.
1536             // Maybe stored in the future to enable modem use
1537             num_of_chunks = actual_length / packet_size;
1538             chunk_remains = actual_length % packet_size;
1539             //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);
1540
1541             ftdi->readbuffer_offset += 2;
1542             actual_length -= 2;
1543
1544             if (actual_length > packet_size - 2)
1545             {
1546                 for (i = 1; i < num_of_chunks; i++)
1547                     memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1548                              ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1549                              packet_size - 2);
1550                 if (chunk_remains > 2)
1551                 {
1552                     memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1553                              ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1554                              chunk_remains-2);
1555                     actual_length -= 2*num_of_chunks;
1556                 }
1557                 else
1558                     actual_length -= 2*(num_of_chunks-1)+chunk_remains;
1559             }
1560         }
1561         else if (actual_length <= 2)
1562         {
1563             // no more data to read?
1564             return offset;
1565         }
1566         if (actual_length > 0)
1567         {
1568             // data still fits in buf?
1569             if (offset+actual_length <= size)
1570             {
1571                 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, actual_length);
1572                 //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
1573                 offset += actual_length;
1574
1575                 /* Did we read exactly the right amount of bytes? */
1576                 if (offset == size)
1577                     //printf("read_data exact rem %d offset %d\n",
1578                     //ftdi->readbuffer_remaining, offset);
1579                     return offset;
1580             }
1581             else
1582             {
1583                 // only copy part of the data or size <= readbuffer_chunksize
1584                 int part_size = size-offset;
1585                 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, part_size);
1586
1587                 ftdi->readbuffer_offset += part_size;
1588                 ftdi->readbuffer_remaining = actual_length-part_size;
1589                 offset += part_size;
1590
1591                 /* printf("Returning part: %d - size: %d - offset: %d - actual_length: %d - remaining: %d\n",
1592                 part_size, size, offset, actual_length, ftdi->readbuffer_remaining); */
1593
1594                 return offset;
1595             }
1596         }
1597     }
1598     // never reached
1599     return -127;
1600 }
1601
1602 /**
1603     Configure read buffer chunk size.
1604     Default is 4096.
1605
1606     Automatically reallocates the buffer.
1607
1608     \param ftdi pointer to ftdi_context
1609     \param chunksize Chunk size
1610
1611     \retval 0: all fine
1612 */
1613 int ftdi_read_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
1614 {
1615     unsigned char *new_buf;
1616
1617     // Invalidate all remaining data
1618     ftdi->readbuffer_offset = 0;
1619     ftdi->readbuffer_remaining = 0;
1620 #ifdef __linux__
1621     /* We can't set readbuffer_chunksize larger than MAX_BULK_BUFFER_LENGTH,
1622        which is defined in libusb-1.0.  Otherwise, each USB read request will
1623        be divided into multiple URBs.  This will cause issues on Linux kernel
1624        older than 2.6.32.  */
1625     if (chunksize > 16384)
1626         chunksize = 16384;
1627 #endif
1628
1629     if ((new_buf = (unsigned char *)realloc(ftdi->readbuffer, chunksize)) == NULL)
1630         ftdi_error_return(-1, "out of memory for readbuffer");
1631
1632     ftdi->readbuffer = new_buf;
1633     ftdi->readbuffer_chunksize = chunksize;
1634
1635     return 0;
1636 }
1637
1638 /**
1639     Get read buffer chunk size.
1640
1641     \param ftdi pointer to ftdi_context
1642     \param chunksize Pointer to store chunk size in
1643
1644     \retval 0: all fine
1645 */
1646 int ftdi_read_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
1647 {
1648     *chunksize = ftdi->readbuffer_chunksize;
1649     return 0;
1650 }
1651
1652
1653 /**
1654     Enable bitbang mode.
1655
1656     \deprecated use \ref ftdi_set_bitmode with mode BITMODE_BITBANG instead
1657
1658     \param ftdi pointer to ftdi_context
1659     \param bitmask Bitmask to configure lines.
1660            HIGH/ON value configures a line as output.
1661
1662     \retval  0: all fine
1663     \retval -1: can't enable bitbang mode
1664 */
1665 int ftdi_enable_bitbang(struct ftdi_context *ftdi, unsigned char bitmask)
1666 {
1667     unsigned short usb_val;
1668
1669     usb_val = bitmask; // low byte: bitmask
1670     /* FT2232C: Set bitbang_mode to 2 to enable SPI */
1671     usb_val |= (ftdi->bitbang_mode << 8);
1672
1673     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1674                                 SIO_SET_BITMODE_REQUEST, usb_val, ftdi->index,
1675                                 NULL, 0, ftdi->usb_write_timeout) < 0)
1676         ftdi_error_return(-1, "unable to enter bitbang mode. Perhaps not a BM type chip?");
1677
1678     ftdi->bitbang_enabled = 1;
1679     return 0;
1680 }
1681
1682 /**
1683     Disable bitbang mode.
1684
1685     \param ftdi pointer to ftdi_context
1686
1687     \retval  0: all fine
1688     \retval -1: can't disable bitbang mode
1689 */
1690 int ftdi_disable_bitbang(struct ftdi_context *ftdi)
1691 {
1692     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)
1693         ftdi_error_return(-1, "unable to leave bitbang mode. Perhaps not a BM type chip?");
1694
1695     ftdi->bitbang_enabled = 0;
1696     return 0;
1697 }
1698
1699 /**
1700     Enable/disable bitbang modes.
1701
1702     \param ftdi pointer to ftdi_context
1703     \param bitmask Bitmask to configure lines.
1704            HIGH/ON value configures a line as output.
1705     \param mode Bitbang mode: use the values defined in \ref ftdi_mpsse_mode
1706
1707     \retval  0: all fine
1708     \retval -1: can't enable bitbang mode
1709 */
1710 int ftdi_set_bitmode(struct ftdi_context *ftdi, unsigned char bitmask, unsigned char mode)
1711 {
1712     unsigned short usb_val;
1713
1714     usb_val = bitmask; // low byte: bitmask
1715     usb_val |= (mode << 8);
1716     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)
1717         ftdi_error_return(-1, "unable to configure bitbang mode. Perhaps not a 2232C type chip?");
1718
1719     ftdi->bitbang_mode = mode;
1720     ftdi->bitbang_enabled = (mode == BITMODE_RESET) ? 0 : 1;
1721     return 0;
1722 }
1723
1724 /**
1725     Directly read pin state, circumventing the read buffer. Useful for bitbang mode.
1726
1727     \param ftdi pointer to ftdi_context
1728     \param pins Pointer to store pins into
1729
1730     \retval  0: all fine
1731     \retval -1: read pins failed
1732 */
1733 int ftdi_read_pins(struct ftdi_context *ftdi, unsigned char *pins)
1734 {
1735     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)
1736         ftdi_error_return(-1, "read pins failed");
1737
1738     return 0;
1739 }
1740
1741 /**
1742     Set latency timer
1743
1744     The FTDI chip keeps data in the internal buffer for a specific
1745     amount of time if the buffer is not full yet to decrease
1746     load on the usb bus.
1747
1748     \param ftdi pointer to ftdi_context
1749     \param latency Value between 1 and 255
1750
1751     \retval  0: all fine
1752     \retval -1: latency out of range
1753     \retval -2: unable to set latency timer
1754 */
1755 int ftdi_set_latency_timer(struct ftdi_context *ftdi, unsigned char latency)
1756 {
1757     unsigned short usb_val;
1758
1759     if (latency < 1)
1760         ftdi_error_return(-1, "latency out of range. Only valid for 1-255");
1761
1762     usb_val = latency;
1763     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)
1764         ftdi_error_return(-2, "unable to set latency timer");
1765
1766     return 0;
1767 }
1768
1769 /**
1770     Get latency timer
1771
1772     \param ftdi pointer to ftdi_context
1773     \param latency Pointer to store latency value in
1774
1775     \retval  0: all fine
1776     \retval -1: unable to get latency timer
1777 */
1778 int ftdi_get_latency_timer(struct ftdi_context *ftdi, unsigned char *latency)
1779 {
1780     unsigned short usb_val;
1781     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)
1782         ftdi_error_return(-1, "reading latency timer failed");
1783
1784     *latency = (unsigned char)usb_val;
1785     return 0;
1786 }
1787
1788 /**
1789     Poll modem status information
1790
1791     This function allows the retrieve the two status bytes of the device.
1792     The device sends these bytes also as a header for each read access
1793     where they are discarded by ftdi_read_data(). The chip generates
1794     the two stripped status bytes in the absence of data every 40 ms.
1795
1796     Layout of the first byte:
1797     - B0..B3 - must be 0
1798     - B4       Clear to send (CTS)
1799                  0 = inactive
1800                  1 = active
1801     - B5       Data set ready (DTS)
1802                  0 = inactive
1803                  1 = active
1804     - B6       Ring indicator (RI)
1805                  0 = inactive
1806                  1 = active
1807     - B7       Receive line signal detect (RLSD)
1808                  0 = inactive
1809                  1 = active
1810
1811     Layout of the second byte:
1812     - B0       Data ready (DR)
1813     - B1       Overrun error (OE)
1814     - B2       Parity error (PE)
1815     - B3       Framing error (FE)
1816     - B4       Break interrupt (BI)
1817     - B5       Transmitter holding register (THRE)
1818     - B6       Transmitter empty (TEMT)
1819     - B7       Error in RCVR FIFO
1820
1821     \param ftdi pointer to ftdi_context
1822     \param status Pointer to store status information in. Must be two bytes.
1823
1824     \retval  0: all fine
1825     \retval -1: unable to retrieve status information
1826 */
1827 int ftdi_poll_modem_status(struct ftdi_context *ftdi, unsigned short *status)
1828 {
1829     char usb_val[2];
1830
1831     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)
1832         ftdi_error_return(-1, "getting modem status failed");
1833
1834     *status = (usb_val[1] << 8) | usb_val[0];
1835
1836     return 0;
1837 }
1838
1839 /**
1840     Set flowcontrol for ftdi chip
1841
1842     \param ftdi pointer to ftdi_context
1843     \param flowctrl flow control to use. should be
1844            SIO_DISABLE_FLOW_CTRL, SIO_RTS_CTS_HS, SIO_DTR_DSR_HS or SIO_XON_XOFF_HS
1845
1846     \retval  0: all fine
1847     \retval -1: set flow control failed
1848 */
1849 int ftdi_setflowctrl(struct ftdi_context *ftdi, int flowctrl)
1850 {
1851     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1852                                 SIO_SET_FLOW_CTRL_REQUEST, 0, (flowctrl | ftdi->index),
1853                                 NULL, 0, ftdi->usb_write_timeout) < 0)
1854         ftdi_error_return(-1, "set flow control failed");
1855
1856     return 0;
1857 }
1858
1859 /**
1860     Set dtr line
1861
1862     \param ftdi pointer to ftdi_context
1863     \param state state to set line to (1 or 0)
1864
1865     \retval  0: all fine
1866     \retval -1: set dtr failed
1867 */
1868 int ftdi_setdtr(struct ftdi_context *ftdi, int state)
1869 {
1870     unsigned short usb_val;
1871
1872     if (state)
1873         usb_val = SIO_SET_DTR_HIGH;
1874     else
1875         usb_val = SIO_SET_DTR_LOW;
1876
1877     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1878                                 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
1879                                 NULL, 0, ftdi->usb_write_timeout) < 0)
1880         ftdi_error_return(-1, "set dtr failed");
1881
1882     return 0;
1883 }
1884
1885 /**
1886     Set rts line
1887
1888     \param ftdi pointer to ftdi_context
1889     \param state state to set line to (1 or 0)
1890
1891     \retval  0: all fine
1892     \retval -1 set rts failed
1893 */
1894 int ftdi_setrts(struct ftdi_context *ftdi, int state)
1895 {
1896     unsigned short usb_val;
1897
1898     if (state)
1899         usb_val = SIO_SET_RTS_HIGH;
1900     else
1901         usb_val = SIO_SET_RTS_LOW;
1902
1903     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1904                                 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
1905                                 NULL, 0, ftdi->usb_write_timeout) < 0)
1906         ftdi_error_return(-1, "set of rts failed");
1907
1908     return 0;
1909 }
1910
1911 /**
1912  Set dtr and rts line in one pass
1913
1914  \param ftdi pointer to ftdi_context
1915  \param dtr  DTR state to set line to (1 or 0)
1916  \param rts  RTS state to set line to (1 or 0)
1917
1918  \retval  0: all fine
1919  \retval -1 set dtr/rts failed
1920  */
1921 int ftdi_setdtr_rts(struct ftdi_context *ftdi, int dtr, int rts)
1922 {
1923     unsigned short usb_val;
1924
1925     if (dtr)
1926         usb_val = SIO_SET_DTR_HIGH;
1927     else
1928         usb_val = SIO_SET_DTR_LOW;
1929
1930     if (rts)
1931         usb_val |= SIO_SET_RTS_HIGH;
1932     else
1933         usb_val |= SIO_SET_RTS_LOW;
1934
1935     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1936                                 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
1937                                 NULL, 0, ftdi->usb_write_timeout) < 0)
1938         ftdi_error_return(-1, "set of rts/dtr failed");
1939
1940     return 0;
1941 }
1942
1943 /**
1944     Set the special event character
1945
1946     \param ftdi pointer to ftdi_context
1947     \param eventch Event character
1948     \param enable 0 to disable the event character, non-zero otherwise
1949
1950     \retval  0: all fine
1951     \retval -1: unable to set event character
1952 */
1953 int ftdi_set_event_char(struct ftdi_context *ftdi,
1954                         unsigned char eventch, unsigned char enable)
1955 {
1956     unsigned short usb_val;
1957
1958     usb_val = eventch;
1959     if (enable)
1960         usb_val |= 1 << 8;
1961
1962     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)
1963         ftdi_error_return(-1, "setting event character failed");
1964
1965     return 0;
1966 }
1967
1968 /**
1969     Set error character
1970
1971     \param ftdi pointer to ftdi_context
1972     \param errorch Error character
1973     \param enable 0 to disable the error character, non-zero otherwise
1974
1975     \retval  0: all fine
1976     \retval -1: unable to set error character
1977 */
1978 int ftdi_set_error_char(struct ftdi_context *ftdi,
1979                         unsigned char errorch, unsigned char enable)
1980 {
1981     unsigned short usb_val;
1982
1983     usb_val = errorch;
1984     if (enable)
1985         usb_val |= 1 << 8;
1986
1987     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)
1988         ftdi_error_return(-1, "setting error character failed");
1989
1990     return 0;
1991 }
1992
1993 /**
1994    Set the eeprom size
1995
1996    \param ftdi pointer to ftdi_context
1997    \param eeprom Pointer to ftdi_eeprom
1998    \param size
1999
2000 */
2001 void ftdi_eeprom_setsize(struct ftdi_context *ftdi, struct ftdi_eeprom *eeprom, int size)
2002 {
2003     ftdi->eeprom_size=size;
2004     eeprom->size=size;
2005 }
2006
2007 /**
2008     Init eeprom with default values.
2009
2010     \param eeprom Pointer to ftdi_eeprom
2011 */
2012 void ftdi_eeprom_initdefaults(struct ftdi_eeprom *eeprom)
2013 {
2014     eeprom->vendor_id = 0x0403;
2015     eeprom->product_id = 0x6001;
2016
2017     eeprom->self_powered = 1;
2018     eeprom->remote_wakeup = 1;
2019     eeprom->BM_type_chip = 1;
2020
2021     eeprom->in_is_isochronous = 0;
2022     eeprom->out_is_isochronous = 0;
2023     eeprom->suspend_pull_downs = 0;
2024
2025     eeprom->use_serial = 0;
2026     eeprom->change_usb_version = 0;
2027     eeprom->usb_version = 0x0200;
2028     eeprom->max_power = 0;
2029
2030     eeprom->manufacturer = NULL;
2031     eeprom->product = NULL;
2032     eeprom->serial = NULL;
2033
2034     eeprom->size = FTDI_DEFAULT_EEPROM_SIZE;
2035 }
2036
2037 /**
2038    Build binary output from ftdi_eeprom structure.
2039    Output is suitable for ftdi_write_eeprom().
2040
2041    \param eeprom Pointer to ftdi_eeprom
2042    \param output Buffer of 128 bytes to store eeprom image to
2043
2044    \retval >0: used eeprom size
2045    \retval -1: eeprom size (128 bytes) exceeded by custom strings
2046 */
2047 int ftdi_eeprom_build(struct ftdi_eeprom *eeprom, unsigned char *output)
2048 {
2049     unsigned char i, j;
2050     unsigned short checksum, value;
2051     unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
2052     int size_check;
2053
2054     if (eeprom->manufacturer != NULL)
2055         manufacturer_size = strlen(eeprom->manufacturer);
2056     if (eeprom->product != NULL)
2057         product_size = strlen(eeprom->product);
2058     if (eeprom->serial != NULL)
2059         serial_size = strlen(eeprom->serial);
2060
2061     size_check = eeprom->size;
2062     size_check -= 28; // 28 are always in use (fixed)
2063
2064     // Top half of a 256byte eeprom is used just for strings and checksum
2065     // it seems that the FTDI chip will not read these strings from the lower half
2066     // Each string starts with two bytes; offset and type (0x03 for string)
2067     // the checksum needs two bytes, so without the string data that 8 bytes from the top half
2068     if (eeprom->size>=256)size_check = 120;
2069     size_check -= manufacturer_size*2;
2070     size_check -= product_size*2;
2071     size_check -= serial_size*2;
2072
2073     // eeprom size exceeded?
2074     if (size_check < 0)
2075         return (-1);
2076
2077     // empty eeprom
2078     memset (output, 0, eeprom->size);
2079
2080     // Addr 00: Stay 00 00
2081     // Addr 02: Vendor ID
2082     output[0x02] = eeprom->vendor_id;
2083     output[0x03] = eeprom->vendor_id >> 8;
2084
2085     // Addr 04: Product ID
2086     output[0x04] = eeprom->product_id;
2087     output[0x05] = eeprom->product_id >> 8;
2088
2089     // Addr 06: Device release number (0400h for BM features)
2090     output[0x06] = 0x00;
2091
2092     if (eeprom->BM_type_chip == 1)
2093         output[0x07] = 0x04;
2094     else
2095         output[0x07] = 0x02;
2096
2097     // Addr 08: Config descriptor
2098     // Bit 7: always 1
2099     // Bit 6: 1 if this device is self powered, 0 if bus powered
2100     // Bit 5: 1 if this device uses remote wakeup
2101     // Bit 4: 1 if this device is battery powered
2102     j = 0x80;
2103     if (eeprom->self_powered == 1)
2104         j |= 0x40;
2105     if (eeprom->remote_wakeup == 1)
2106         j |= 0x20;
2107     output[0x08] = j;
2108
2109     // Addr 09: Max power consumption: max power = value * 2 mA
2110     output[0x09] = eeprom->max_power;
2111
2112     // Addr 0A: Chip configuration
2113     // Bit 7: 0 - reserved
2114     // Bit 6: 0 - reserved
2115     // Bit 5: 0 - reserved
2116     // Bit 4: 1 - Change USB version
2117     // Bit 3: 1 - Use the serial number string
2118     // Bit 2: 1 - Enable suspend pull downs for lower power
2119     // Bit 1: 1 - Out EndPoint is Isochronous
2120     // Bit 0: 1 - In EndPoint is Isochronous
2121     //
2122     j = 0;
2123     if (eeprom->in_is_isochronous == 1)
2124         j = j | 1;
2125     if (eeprom->out_is_isochronous == 1)
2126         j = j | 2;
2127     if (eeprom->suspend_pull_downs == 1)
2128         j = j | 4;
2129     if (eeprom->use_serial == 1)
2130         j = j | 8;
2131     if (eeprom->change_usb_version == 1)
2132         j = j | 16;
2133     output[0x0A] = j;
2134
2135     // Addr 0B: reserved
2136     output[0x0B] = 0x00;
2137
2138     // Addr 0C: USB version low byte when 0x0A bit 4 is set
2139     // Addr 0D: USB version high byte when 0x0A bit 4 is set
2140     if (eeprom->change_usb_version == 1)
2141     {
2142         output[0x0C] = eeprom->usb_version;
2143         output[0x0D] = eeprom->usb_version >> 8;
2144     }
2145
2146
2147     // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
2148     // Addr 0F: Length of manufacturer string
2149     output[0x0F] = manufacturer_size*2 + 2;
2150
2151     // Addr 10: Offset of the product string + 0x80, calculated later
2152     // Addr 11: Length of product string
2153     output[0x11] = product_size*2 + 2;
2154
2155     // Addr 12: Offset of the serial string + 0x80, calculated later
2156     // Addr 13: Length of serial string
2157     output[0x13] = serial_size*2 + 2;
2158
2159     // Dynamic content
2160     i=0x14;
2161     if (eeprom->size>=256) i = 0x80;
2162
2163
2164     // Output manufacturer
2165     output[0x0E] = i | 0x80;  // calculate offset
2166     output[i++] = manufacturer_size*2 + 2;
2167     output[i++] = 0x03; // type: string
2168     for (j = 0; j < manufacturer_size; j++)
2169     {
2170         output[i] = eeprom->manufacturer[j], i++;
2171         output[i] = 0x00, i++;
2172     }
2173
2174     // Output product name
2175     output[0x10] = i | 0x80;  // calculate offset
2176     output[i] = product_size*2 + 2, i++;
2177     output[i] = 0x03, i++;
2178     for (j = 0; j < product_size; j++)
2179     {
2180         output[i] = eeprom->product[j], i++;
2181         output[i] = 0x00, i++;
2182     }
2183
2184     // Output serial
2185     output[0x12] = i | 0x80; // calculate offset
2186     output[i] = serial_size*2 + 2, i++;
2187     output[i] = 0x03, i++;
2188     for (j = 0; j < serial_size; j++)
2189     {
2190         output[i] = eeprom->serial[j], i++;
2191         output[i] = 0x00, i++;
2192     }
2193
2194     // calculate checksum
2195     checksum = 0xAAAA;
2196
2197     for (i = 0; i < eeprom->size/2-1; i++)
2198     {
2199         value = output[i*2];
2200         value += output[(i*2)+1] << 8;
2201
2202         checksum = value^checksum;
2203         checksum = (checksum << 1) | (checksum >> 15);
2204     }
2205
2206     output[eeprom->size-2] = checksum;
2207     output[eeprom->size-1] = checksum >> 8;
2208
2209     return size_check;
2210 }
2211
2212 /**
2213    Decode binary EEPROM image into an ftdi_eeprom structure.
2214
2215    \param eeprom Pointer to ftdi_eeprom which will be filled in.
2216    \param buf Buffer of \a size bytes of raw eeprom data
2217    \param size size size of eeprom data in bytes
2218
2219    \retval 0: all fine
2220    \retval -1: something went wrong
2221
2222    FIXME: How to pass size? How to handle size field in ftdi_eeprom?
2223    FIXME: Strings are malloc'ed here and should be freed somewhere
2224 */
2225 int ftdi_eeprom_decode(struct ftdi_eeprom *eeprom, unsigned char *buf, int size)
2226 {
2227     unsigned char i, j;
2228     unsigned short checksum, eeprom_checksum, value;
2229     unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
2230     int eeprom_size = 128;
2231 #if 0
2232     size_check = eeprom->size;
2233     size_check -= 28; // 28 are always in use (fixed)
2234
2235     // Top half of a 256byte eeprom is used just for strings and checksum
2236     // it seems that the FTDI chip will not read these strings from the lower half
2237     // Each string starts with two bytes; offset and type (0x03 for string)
2238     // the checksum needs two bytes, so without the string data that 8 bytes from the top half
2239     if (eeprom->size>=256)size_check = 120;
2240     size_check -= manufacturer_size*2;
2241     size_check -= product_size*2;
2242     size_check -= serial_size*2;
2243
2244     // eeprom size exceeded?
2245     if (size_check < 0)
2246         return (-1);
2247 #endif
2248
2249     // empty eeprom struct
2250     memset(eeprom, 0, sizeof(struct ftdi_eeprom));
2251
2252     // Addr 00: Stay 00 00
2253
2254     // Addr 02: Vendor ID
2255     eeprom->vendor_id = buf[0x02] + (buf[0x03] << 8);
2256
2257     // Addr 04: Product ID
2258     eeprom->product_id = buf[0x04] + (buf[0x05] << 8);
2259
2260     value = buf[0x06] + (buf[0x07]<<8);
2261     switch (value)
2262     {
2263         case 0x0400:
2264             eeprom->BM_type_chip = 1;
2265             break;
2266         case 0x0200:
2267             eeprom->BM_type_chip = 0;
2268             break;
2269         default: // Unknown device
2270             eeprom->BM_type_chip = 0;
2271             break;
2272     }
2273
2274     // Addr 08: Config descriptor
2275     // Bit 7: always 1
2276     // Bit 6: 1 if this device is self powered, 0 if bus powered
2277     // Bit 5: 1 if this device uses remote wakeup
2278     // Bit 4: 1 if this device is battery powered
2279     j = buf[0x08];
2280     if (j&0x40) eeprom->self_powered = 1;
2281     if (j&0x20) eeprom->remote_wakeup = 1;
2282
2283     // Addr 09: Max power consumption: max power = value * 2 mA
2284     eeprom->max_power = buf[0x09];
2285
2286     // Addr 0A: Chip configuration
2287     // Bit 7: 0 - reserved
2288     // Bit 6: 0 - reserved
2289     // Bit 5: 0 - reserved
2290     // Bit 4: 1 - Change USB version
2291     // Bit 3: 1 - Use the serial number string
2292     // Bit 2: 1 - Enable suspend pull downs for lower power
2293     // Bit 1: 1 - Out EndPoint is Isochronous
2294     // Bit 0: 1 - In EndPoint is Isochronous
2295     //
2296     j = buf[0x0A];
2297     if (j&0x01) eeprom->in_is_isochronous = 1;
2298     if (j&0x02) eeprom->out_is_isochronous = 1;
2299     if (j&0x04) eeprom->suspend_pull_downs = 1;
2300     if (j&0x08) eeprom->use_serial = 1;
2301     if (j&0x10) eeprom->change_usb_version = 1;
2302
2303     // Addr 0B: reserved
2304
2305     // Addr 0C: USB version low byte when 0x0A bit 4 is set
2306     // Addr 0D: USB version high byte when 0x0A bit 4 is set
2307     if (eeprom->change_usb_version == 1)
2308     {
2309         eeprom->usb_version = buf[0x0C] + (buf[0x0D] << 8);
2310     }
2311
2312     // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
2313     // Addr 0F: Length of manufacturer string
2314     manufacturer_size = buf[0x0F]/2;
2315     if (manufacturer_size > 0) eeprom->manufacturer = malloc(manufacturer_size);
2316     else eeprom->manufacturer = NULL;
2317
2318     // Addr 10: Offset of the product string + 0x80, calculated later
2319     // Addr 11: Length of product string
2320     product_size = buf[0x11]/2;
2321     if (product_size > 0) eeprom->product = malloc(product_size);
2322     else eeprom->product = NULL;
2323
2324     // Addr 12: Offset of the serial string + 0x80, calculated later
2325     // Addr 13: Length of serial string
2326     serial_size = buf[0x13]/2;
2327     if (serial_size > 0) eeprom->serial = malloc(serial_size);
2328     else eeprom->serial = NULL;
2329
2330     // Decode manufacturer
2331     i = buf[0x0E] & 0x7f; // offset
2332     for (j=0;j<manufacturer_size-1;j++)
2333     {
2334         eeprom->manufacturer[j] = buf[2*j+i+2];
2335     }
2336     eeprom->manufacturer[j] = '\0';
2337
2338     // Decode product name
2339     i = buf[0x10] & 0x7f; // offset
2340     for (j=0;j<product_size-1;j++)
2341     {
2342         eeprom->product[j] = buf[2*j+i+2];
2343     }
2344     eeprom->product[j] = '\0';
2345
2346     // Decode serial
2347     i = buf[0x12] & 0x7f; // offset
2348     for (j=0;j<serial_size-1;j++)
2349     {
2350         eeprom->serial[j] = buf[2*j+i+2];
2351     }
2352     eeprom->serial[j] = '\0';
2353
2354     // verify checksum
2355     checksum = 0xAAAA;
2356
2357     for (i = 0; i < eeprom_size/2-1; i++)
2358     {
2359         value = buf[i*2];
2360         value += buf[(i*2)+1] << 8;
2361
2362         checksum = value^checksum;
2363         checksum = (checksum << 1) | (checksum >> 15);
2364     }
2365
2366     eeprom_checksum = buf[eeprom_size-2] + (buf[eeprom_size-1] << 8);
2367
2368     if (eeprom_checksum != checksum)
2369     {
2370         fprintf(stderr, "Checksum Error: %04x %04x\n", checksum, eeprom_checksum);
2371         return -1;
2372     }
2373
2374     return 0;
2375 }
2376
2377 /**
2378     Read eeprom location
2379
2380     \param ftdi pointer to ftdi_context
2381     \param eeprom_addr Address of eeprom location to be read
2382     \param eeprom_val Pointer to store read eeprom location
2383
2384     \retval  0: all fine
2385     \retval -1: read failed
2386 */
2387 int ftdi_read_eeprom_location (struct ftdi_context *ftdi, int eeprom_addr, unsigned short *eeprom_val)
2388 {
2389     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_READ_EEPROM_REQUEST, 0, eeprom_addr, (char *)eeprom_val, 2, ftdi->usb_read_timeout) != 2)
2390         ftdi_error_return(-1, "reading eeprom failed");
2391
2392     return 0;
2393 }
2394
2395 /**
2396     Read eeprom
2397
2398     \param ftdi pointer to ftdi_context
2399     \param eeprom Pointer to store eeprom into
2400
2401     \retval  0: all fine
2402     \retval -1: read failed
2403 */
2404 int ftdi_read_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
2405 {
2406     int i;
2407
2408     for (i = 0; i < ftdi->eeprom_size/2; i++)
2409     {
2410         if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_READ_EEPROM_REQUEST, 0, i, eeprom+(i*2), 2, ftdi->usb_read_timeout) != 2)
2411             ftdi_error_return(-1, "reading eeprom failed");
2412     }
2413
2414     return 0;
2415 }
2416
2417 /*
2418     ftdi_read_chipid_shift does the bitshift operation needed for the FTDIChip-ID
2419     Function is only used internally
2420     \internal
2421 */
2422 static unsigned char ftdi_read_chipid_shift(unsigned char value)
2423 {
2424     return ((value & 1) << 1) |
2425            ((value & 2) << 5) |
2426            ((value & 4) >> 2) |
2427            ((value & 8) << 4) |
2428            ((value & 16) >> 1) |
2429            ((value & 32) >> 1) |
2430            ((value & 64) >> 4) |
2431            ((value & 128) >> 2);
2432 }
2433
2434 /**
2435     Read the FTDIChip-ID from R-type devices
2436
2437     \param ftdi pointer to ftdi_context
2438     \param chipid Pointer to store FTDIChip-ID
2439
2440     \retval  0: all fine
2441     \retval -1: read failed
2442 */
2443 int ftdi_read_chipid(struct ftdi_context *ftdi, unsigned int *chipid)
2444 {
2445     unsigned int a = 0, b = 0;
2446
2447     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)
2448     {
2449         a = a << 8 | a >> 8;
2450         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)
2451         {
2452             b = b << 8 | b >> 8;
2453             a = (a << 16) | (b & 0xFFFF);
2454             a = ftdi_read_chipid_shift(a) | ftdi_read_chipid_shift(a>>8)<<8
2455                 | ftdi_read_chipid_shift(a>>16)<<16 | ftdi_read_chipid_shift(a>>24)<<24;
2456             *chipid = a ^ 0xa5f0f7d1;
2457             return 0;
2458         }
2459     }
2460
2461     ftdi_error_return(-1, "read of FTDIChip-ID failed");
2462 }
2463
2464 /**
2465    Guesses size of eeprom by reading eeprom and comparing halves - will not work with blank eeprom
2466    Call this function then do a write then call again to see if size changes, if so write again.
2467
2468    \param ftdi pointer to ftdi_context
2469    \param eeprom Pointer to store eeprom into
2470    \param maxsize the size of the buffer to read into
2471
2472    \retval size of eeprom
2473 */
2474 int ftdi_read_eeprom_getsize(struct ftdi_context *ftdi, unsigned char *eeprom, int maxsize)
2475 {
2476     int i=0,j,minsize=32;
2477     int size=minsize;
2478
2479     do
2480     {
2481         for (j = 0; i < maxsize/2 && j<size; j++)
2482         {
2483             if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE,
2484                                         SIO_READ_EEPROM_REQUEST, 0, i,
2485                                         eeprom+(i*2), 2, ftdi->usb_read_timeout) != 2)
2486                 ftdi_error_return(-1, "reading eeprom failed");
2487             i++;
2488         }
2489         size*=2;
2490     }
2491     while (size<=maxsize && memcmp(eeprom,&eeprom[size/2],size/2)!=0);
2492
2493     return size/2;
2494 }
2495
2496 /**
2497     Write eeprom location
2498
2499     \param ftdi pointer to ftdi_context
2500     \param eeprom_addr Address of eeprom location to be written
2501     \param eeprom_val Value to be written
2502
2503     \retval  0: all fine
2504     \retval -1: read failed
2505 */
2506 int ftdi_write_eeprom_location(struct ftdi_context *ftdi, int eeprom_addr, unsigned short eeprom_val)
2507 {
2508     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
2509                                     SIO_WRITE_EEPROM_REQUEST, eeprom_val, eeprom_addr,
2510                                     NULL, 0, ftdi->usb_write_timeout) != 0)
2511         ftdi_error_return(-1, "unable to write eeprom");
2512
2513     return 0;
2514 }
2515
2516 /**
2517     Write eeprom
2518
2519     \param ftdi pointer to ftdi_context
2520     \param eeprom Pointer to read eeprom from
2521
2522     \retval  0: all fine
2523     \retval -1: read failed
2524 */
2525 int ftdi_write_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
2526 {
2527     unsigned short usb_val, status;
2528     int i, ret;
2529
2530     /* These commands were traced while running MProg */
2531     if ((ret = ftdi_usb_reset(ftdi)) != 0)
2532         return ret;
2533     if ((ret = ftdi_poll_modem_status(ftdi, &status)) != 0)
2534         return ret;
2535     if ((ret = ftdi_set_latency_timer(ftdi, 0x77)) != 0)
2536         return ret;
2537
2538     for (i = 0; i < ftdi->eeprom_size/2; i++)
2539     {
2540         usb_val = eeprom[i*2];
2541         usb_val += eeprom[(i*2)+1] << 8;
2542         if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
2543                                     SIO_WRITE_EEPROM_REQUEST, usb_val, i,
2544                                     NULL, 0, ftdi->usb_write_timeout) < 0)
2545             ftdi_error_return(-1, "unable to write eeprom");
2546     }
2547
2548     return 0;
2549 }
2550
2551 /**
2552     Erase eeprom
2553
2554     This is not supported on FT232R/FT245R according to the MProg manual from FTDI.
2555
2556     \param ftdi pointer to ftdi_context
2557
2558     \retval  0: all fine
2559     \retval -1: erase failed
2560 */
2561 int ftdi_erase_eeprom(struct ftdi_context *ftdi)
2562 {
2563     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_ERASE_EEPROM_REQUEST, 0, 0, NULL, 0, ftdi->usb_write_timeout) < 0)
2564         ftdi_error_return(-1, "unable to erase eeprom");
2565
2566     return 0;
2567 }
2568
2569 /**
2570     Get string representation for last error code
2571
2572     \param ftdi pointer to ftdi_context
2573
2574     \retval Pointer to error string
2575 */
2576 char *ftdi_get_error_string (struct ftdi_context *ftdi)
2577 {
2578     return ftdi->error_str;
2579 }
2580
2581 /* @} end of doxygen libftdi group */