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