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