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