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