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