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