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