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