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