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