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