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