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