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