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