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