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