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