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