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