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