Provide internal eeprom structure buffer with internal byte buffer Purge external...
[libftdi] / src / ftdi.c
1 /***************************************************************************
2                           ftdi.c  -  description
3                              -------------------
4     begin                : Fri Apr 4 2003
5     copyright            : (C) 2003-2010 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/en/developer/libftdi/
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 <libusb.h>
32 #include <string.h>
33 #include <errno.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36
37 #include "ftdi.h"
38
39 #define ftdi_error_return(code, str) do {  \
40         ftdi->error_str = str;             \
41         return code;                       \
42    } while(0);
43
44 #define ftdi_error_return_free_device_list(code, str, devs) do {    \
45         libusb_free_device_list(devs,1);   \
46         ftdi->error_str = str;             \
47         return code;                       \
48    } while(0);
49
50
51 /**
52     Internal function to close usb device pointer.
53     Sets ftdi->usb_dev to NULL.
54     \internal
55
56     \param ftdi pointer to ftdi_context
57
58     \retval none
59 */
60 static void ftdi_usb_close_internal (struct ftdi_context *ftdi)
61 {
62     if (ftdi && ftdi->usb_dev)
63     {
64        libusb_close (ftdi->usb_dev);
65        ftdi->usb_dev = NULL;
66     }
67 }
68
69 /**
70     Initializes a ftdi_context.
71
72     \param ftdi pointer to ftdi_context
73
74     \retval  0: all fine
75     \retval -1: couldn't allocate read buffer
76     \retval -2: couldn't allocate struct  buffer
77
78     \remark This should be called before all functions
79 */
80 int ftdi_init(struct ftdi_context *ftdi)
81 {
82     struct ftdi_eeprom* eeprom = (struct ftdi_eeprom *)malloc(sizeof(struct ftdi_eeprom));
83     ftdi->usb_ctx = NULL;
84     ftdi->usb_dev = NULL;
85     ftdi->usb_read_timeout = 5000;
86     ftdi->usb_write_timeout = 5000;
87
88     ftdi->type = TYPE_BM;    /* chip type */
89     ftdi->baudrate = -1;
90     ftdi->bitbang_enabled = 0;  /* 0: normal mode 1: any of the bitbang modes enabled */
91
92     ftdi->readbuffer = NULL;
93     ftdi->readbuffer_offset = 0;
94     ftdi->readbuffer_remaining = 0;
95     ftdi->writebuffer_chunksize = 4096;
96     ftdi->max_packet_size = 0;
97
98     ftdi->interface = 0;
99     ftdi->index = 0;
100     ftdi->in_ep = 0x02;
101     ftdi->out_ep = 0x81;
102     ftdi->bitbang_mode = 1; /* when bitbang is enabled this holds the number of the mode  */
103
104     ftdi->error_str = NULL;
105
106     if (eeprom == 0)
107         ftdi_error_return(-2, "Can't malloc struct ftdi_eeprom");
108     ftdi->eeprom = eeprom;
109
110     /* All fine. Now allocate the readbuffer */
111     return ftdi_read_data_set_chunksize(ftdi, 4096);
112 }
113
114 /**
115     Allocate and initialize a new ftdi_context
116
117     \return a pointer to a new ftdi_context, or NULL on failure
118 */
119 struct ftdi_context *ftdi_new(void)
120 {
121     struct ftdi_context * ftdi = (struct ftdi_context *)malloc(sizeof(struct ftdi_context));
122
123     if (ftdi == NULL)
124     {
125         return NULL;
126     }
127
128     if (ftdi_init(ftdi) != 0)
129     {
130         free(ftdi);
131         return NULL;
132     }
133
134     return ftdi;
135 }
136
137 /**
138     Open selected channels on a chip, otherwise use first channel.
139
140     \param ftdi pointer to ftdi_context
141     \param interface Interface to use for FT2232C/2232H/4232H chips.
142
143     \retval  0: all fine
144     \retval -1: unknown interface
145     \retval -2: USB device unavailable
146 */
147 int ftdi_set_interface(struct ftdi_context *ftdi, enum ftdi_interface interface)
148 {
149     if (ftdi == NULL)
150         ftdi_error_return(-2, "USB device unavailable");
151
152     switch (interface)
153     {
154         case INTERFACE_ANY:
155         case INTERFACE_A:
156             /* ftdi_usb_open_desc cares to set the right index, depending on the found chip */
157             break;
158         case INTERFACE_B:
159             ftdi->interface = 1;
160             ftdi->index     = INTERFACE_B;
161             ftdi->in_ep     = 0x04;
162             ftdi->out_ep    = 0x83;
163             break;
164         case INTERFACE_C:
165             ftdi->interface = 2;
166             ftdi->index     = INTERFACE_C;
167             ftdi->in_ep     = 0x06;
168             ftdi->out_ep    = 0x85;
169             break;
170         case INTERFACE_D:
171             ftdi->interface = 3;
172             ftdi->index     = INTERFACE_D;
173             ftdi->in_ep     = 0x08;
174             ftdi->out_ep    = 0x87;
175             break;
176         default:
177             ftdi_error_return(-1, "Unknown interface");
178     }
179     return 0;
180 }
181
182 /**
183     Deinitializes a ftdi_context.
184
185     \param ftdi pointer to ftdi_context
186 */
187 void ftdi_deinit(struct ftdi_context *ftdi)
188 {
189     if (ftdi == NULL)
190         return;
191
192     ftdi_usb_close_internal (ftdi);
193
194     if (ftdi->readbuffer != NULL)
195     {
196         free(ftdi->readbuffer);
197         ftdi->readbuffer = NULL;
198     }
199
200     if (ftdi->eeprom != NULL)
201     {
202         free(ftdi->eeprom);
203         ftdi->eeprom = NULL;
204     }
205     libusb_exit(ftdi->usb_ctx);
206 }
207
208 /**
209     Deinitialize and free an ftdi_context.
210
211     \param ftdi pointer to ftdi_context
212 */
213 void ftdi_free(struct ftdi_context *ftdi)
214 {
215     ftdi_deinit(ftdi);
216     free(ftdi);
217 }
218
219 /**
220     Use an already open libusb device.
221
222     \param ftdi pointer to ftdi_context
223     \param usb libusb libusb_device_handle to use
224 */
225 void ftdi_set_usbdev (struct ftdi_context *ftdi, libusb_device_handle *usb)
226 {
227     if (ftdi == NULL)
228         return;
229
230     ftdi->usb_dev = usb;
231 }
232
233
234 /**
235     Finds all ftdi devices on the usb bus. Creates a new ftdi_device_list which
236     needs to be deallocated by ftdi_list_free() after use.
237
238     \param ftdi pointer to ftdi_context
239     \param devlist Pointer where to store list of found devices
240     \param vendor Vendor ID to search for
241     \param product Product ID to search for
242
243     \retval >0: number of devices found
244     \retval -3: out of memory
245     \retval -4: libusb_init() failed
246     \retval -5: libusb_get_device_list() failed
247     \retval -6: libusb_get_device_descriptor() failed
248 */
249 int ftdi_usb_find_all(struct ftdi_context *ftdi, struct ftdi_device_list **devlist, int vendor, int product)
250 {
251     struct ftdi_device_list **curdev;
252     libusb_device *dev;
253     libusb_device **devs;
254     int count = 0;
255     int i = 0;
256
257     if (libusb_init(&ftdi->usb_ctx) < 0)
258         ftdi_error_return(-4, "libusb_init() failed");
259
260     if (libusb_get_device_list(ftdi->usb_ctx, &devs) < 0)
261         ftdi_error_return(-5, "libusb_get_device_list() failed");
262
263     curdev = devlist;
264     *curdev = NULL;
265
266     while ((dev = devs[i++]) != NULL)
267     {
268         struct libusb_device_descriptor desc;
269
270         if (libusb_get_device_descriptor(dev, &desc) < 0)
271             ftdi_error_return(-6, "libusb_get_device_descriptor() failed");
272
273         if (desc.idVendor == vendor && desc.idProduct == product)
274         {
275             *curdev = (struct ftdi_device_list*)malloc(sizeof(struct ftdi_device_list));
276             if (!*curdev)
277                 ftdi_error_return(-3, "out of memory");
278               
279             (*curdev)->next = NULL;
280             (*curdev)->dev = dev;
281
282             curdev = &(*curdev)->next;
283             count++;
284         }
285     }
286
287     return count;
288 }
289
290 /**
291     Frees a usb device list.
292
293     \param devlist USB device list created by ftdi_usb_find_all()
294 */
295 void ftdi_list_free(struct ftdi_device_list **devlist)
296 {
297     struct ftdi_device_list *curdev, *next;
298
299     for (curdev = *devlist; curdev != NULL;)
300     {
301         next = curdev->next;
302         free(curdev);
303         curdev = next;
304     }
305
306     *devlist = NULL;
307 }
308
309 /**
310     Frees a usb device list.
311
312     \param devlist USB device list created by ftdi_usb_find_all()
313 */
314 void ftdi_list_free2(struct ftdi_device_list *devlist)
315 {
316     ftdi_list_free(&devlist);
317 }
318
319 /**
320     Return device ID strings from the usb device.
321
322     The parameters manufacturer, description and serial may be NULL
323     or pointer to buffers to store the fetched strings.
324
325     \note Use this function only in combination with ftdi_usb_find_all()
326           as it closes the internal "usb_dev" after use.
327
328     \param ftdi pointer to ftdi_context
329     \param dev libusb usb_dev to use
330     \param manufacturer Store manufacturer string here if not NULL
331     \param mnf_len Buffer size of manufacturer string
332     \param description Store product description string here if not NULL
333     \param desc_len Buffer size of product description string
334     \param serial Store serial string here if not NULL
335     \param serial_len Buffer size of serial string
336
337     \retval   0: all fine
338     \retval  -1: wrong arguments
339     \retval  -4: unable to open device
340     \retval  -7: get product manufacturer failed
341     \retval  -8: get product description failed
342     \retval  -9: get serial number failed
343     \retval -11: libusb_get_device_descriptor() failed
344 */
345 int ftdi_usb_get_strings(struct ftdi_context * ftdi, struct libusb_device * dev,
346                          char * manufacturer, int mnf_len, char * description, int desc_len, char * serial, int serial_len)
347 {
348     struct libusb_device_descriptor desc;
349
350     if ((ftdi==NULL) || (dev==NULL))
351         return -1;
352
353     if (libusb_open(dev, &ftdi->usb_dev) < 0)
354         ftdi_error_return(-4, "libusb_open() failed");
355
356     if (libusb_get_device_descriptor(dev, &desc) < 0)
357         ftdi_error_return(-11, "libusb_get_device_descriptor() failed");
358
359     if (manufacturer != NULL)
360     {
361         if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iManufacturer, (unsigned char *)manufacturer, mnf_len) < 0)
362         {
363             ftdi_usb_close_internal (ftdi);
364             ftdi_error_return(-7, "libusb_get_string_descriptor_ascii() failed");
365         }
366     }
367
368     if (description != NULL)
369     {
370         if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iProduct, (unsigned char *)description, desc_len) < 0)
371         {
372             ftdi_usb_close_internal (ftdi);
373             ftdi_error_return(-8, "libusb_get_string_descriptor_ascii() failed");
374         }
375     }
376
377     if (serial != NULL)
378     {
379         if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iSerialNumber, (unsigned char *)serial, serial_len) < 0)
380         {
381             ftdi_usb_close_internal (ftdi);
382             ftdi_error_return(-9, "libusb_get_string_descriptor_ascii() failed");
383         }
384     }
385
386     ftdi_usb_close_internal (ftdi);
387
388     return 0;
389 }
390
391 /**
392  * Internal function to determine the maximum packet size.
393  * \param ftdi pointer to ftdi_context
394  * \param dev libusb usb_dev to use
395  * \retval Maximum packet size for this device
396  */
397 static unsigned int _ftdi_determine_max_packet_size(struct ftdi_context *ftdi, libusb_device *dev)
398 {
399     struct libusb_device_descriptor desc;
400     struct libusb_config_descriptor *config0;
401     unsigned int packet_size;
402
403     // Sanity check
404     if (ftdi == NULL || dev == NULL)
405         return 64;
406
407     // Determine maximum packet size. Init with default value.
408     // New hi-speed devices from FTDI use a packet size of 512 bytes
409     // but could be connected to a normal speed USB hub -> 64 bytes packet size.
410     if (ftdi->type == TYPE_2232H || ftdi->type == TYPE_4232H)
411         packet_size = 512;
412     else
413         packet_size = 64;
414
415     if (libusb_get_device_descriptor(dev, &desc) < 0)
416         return packet_size;
417
418     if (libusb_get_config_descriptor(dev, 0, &config0) < 0)
419         return packet_size;
420
421     if (desc.bNumConfigurations > 0)
422     {
423         if (ftdi->interface < config0->bNumInterfaces)
424         {
425             struct libusb_interface interface = config0->interface[ftdi->interface];
426             if (interface.num_altsetting > 0)
427             {
428                 struct libusb_interface_descriptor descriptor = interface.altsetting[0];
429                 if (descriptor.bNumEndpoints > 0)
430                 {
431                     packet_size = descriptor.endpoint[0].wMaxPacketSize;
432                 }
433             }
434         }
435     }
436
437     libusb_free_config_descriptor (config0);
438     return packet_size;
439 }
440
441 /**
442     Opens a ftdi device given by an usb_device.
443
444     \param ftdi pointer to ftdi_context
445     \param dev libusb usb_dev to use
446
447     \retval  0: all fine
448     \retval -3: unable to config device
449     \retval -4: unable to open device
450     \retval -5: unable to claim device
451     \retval -6: reset failed
452     \retval -7: set baudrate failed
453     \retval -8: ftdi context invalid
454     \retval -9: libusb_get_device_descriptor() failed
455     \retval -10: libusb_get_config_descriptor() failed
456     \retval -11: libusb_etach_kernel_driver() failed
457     \retval -12: libusb_get_configuration() failed
458 */
459 int ftdi_usb_open_dev(struct ftdi_context *ftdi, libusb_device *dev)
460 {
461     struct libusb_device_descriptor desc;
462     struct libusb_config_descriptor *config0;
463     int cfg, cfg0, detach_errno = 0;
464
465     if (ftdi == NULL)
466         ftdi_error_return(-8, "ftdi context invalid");
467
468     if (libusb_open(dev, &ftdi->usb_dev) < 0)
469         ftdi_error_return(-4, "libusb_open() failed");
470
471     if (libusb_get_device_descriptor(dev, &desc) < 0)
472         ftdi_error_return(-9, "libusb_get_device_descriptor() failed");
473
474     if (libusb_get_config_descriptor(dev, 0, &config0) < 0)
475         ftdi_error_return(-10, "libusb_get_config_descriptor() failed");
476     cfg0 = config0->bConfigurationValue;
477     libusb_free_config_descriptor (config0);
478
479     // Try to detach ftdi_sio kernel module.
480     //
481     // The return code is kept in a separate variable and only parsed
482     // if usb_set_configuration() or usb_claim_interface() fails as the
483     // detach operation might be denied and everything still works fine.
484     // Likely scenario is a static ftdi_sio kernel module.
485     if (libusb_detach_kernel_driver(ftdi->usb_dev, ftdi->interface) !=0)
486         detach_errno = errno;
487
488     if (libusb_get_configuration (ftdi->usb_dev, &cfg) < 0)
489         ftdi_error_return(-12, "libusb_get_configuration () failed");
490     // set configuration (needed especially for windows)
491     // tolerate EBUSY: one device with one configuration, but two interfaces
492     //    and libftdi sessions to both interfaces (e.g. FT2232)
493     if (desc.bNumConfigurations > 0 && cfg != cfg0)
494     {
495         if (libusb_set_configuration(ftdi->usb_dev, cfg0) < 0)
496         {
497             ftdi_usb_close_internal (ftdi);
498             if(detach_errno == EPERM)
499             {
500                 ftdi_error_return(-8, "inappropriate permissions on device!");
501             }
502             else
503             {
504                 ftdi_error_return(-3, "unable to set usb configuration. Make sure the default FTDI driver is not in use");
505             }
506         }
507     }
508
509     if (libusb_claim_interface(ftdi->usb_dev, ftdi->interface) < 0)
510     {
511         ftdi_usb_close_internal (ftdi);
512         if(detach_errno == EPERM)
513         {
514             ftdi_error_return(-8, "inappropriate permissions on device!");
515         }
516         else
517         {
518             ftdi_error_return(-5, "unable to claim usb device. Make sure the default FTDI driver is not in use");
519         }
520     }
521
522     if (ftdi_usb_reset (ftdi) != 0)
523     {
524         ftdi_usb_close_internal (ftdi);
525         ftdi_error_return(-6, "ftdi_usb_reset failed");
526     }
527
528     // Try to guess chip type
529     // Bug in the BM type chips: bcdDevice is 0x200 for serial == 0
530     if (desc.bcdDevice == 0x400 || (desc.bcdDevice == 0x200
531             && desc.iSerialNumber == 0))
532         ftdi->type = TYPE_BM;
533     else if (desc.bcdDevice == 0x200)
534         ftdi->type = TYPE_AM;
535     else if (desc.bcdDevice == 0x500)
536         ftdi->type = TYPE_2232C;
537     else if (desc.bcdDevice == 0x600)
538         ftdi->type = TYPE_R;
539     else if (desc.bcdDevice == 0x700)
540         ftdi->type = TYPE_2232H;
541     else if (desc.bcdDevice == 0x800)
542         ftdi->type = TYPE_4232H;
543
544     // Set default interface on dual/quad type chips
545     switch(ftdi->type)
546     {
547         case TYPE_2232C:
548         case TYPE_2232H:
549         case TYPE_4232H:
550             if (!ftdi->index)
551                 ftdi->index = INTERFACE_A;
552             break;
553         default:
554             break;
555     }
556
557     // Determine maximum packet size
558     ftdi->max_packet_size = _ftdi_determine_max_packet_size(ftdi, dev);
559
560     if (ftdi_set_baudrate (ftdi, 9600) != 0)
561     {
562         ftdi_usb_close_internal (ftdi);
563         ftdi_error_return(-7, "set baudrate failed");
564     }
565
566     ftdi_error_return(0, "all fine");
567 }
568
569 /**
570     Opens the first device with a given vendor and product ids.
571
572     \param ftdi pointer to ftdi_context
573     \param vendor Vendor ID
574     \param product Product ID
575
576     \retval same as ftdi_usb_open_desc()
577 */
578 int ftdi_usb_open(struct ftdi_context *ftdi, int vendor, int product)
579 {
580     return ftdi_usb_open_desc(ftdi, vendor, product, NULL, NULL);
581 }
582
583 /**
584     Opens the first device with a given, vendor id, product id,
585     description and serial.
586
587     \param ftdi pointer to ftdi_context
588     \param vendor Vendor ID
589     \param product Product ID
590     \param description Description to search for. Use NULL if not needed.
591     \param serial Serial to search for. Use NULL if not needed.
592
593     \retval  0: all fine
594     \retval -3: usb device not found
595     \retval -4: unable to open device
596     \retval -5: unable to claim device
597     \retval -6: reset failed
598     \retval -7: set baudrate failed
599     \retval -8: get product description failed
600     \retval -9: get serial number failed
601     \retval -11: libusb_init() failed
602     \retval -12: libusb_get_device_list() failed
603     \retval -13: libusb_get_device_descriptor() failed
604 */
605 int ftdi_usb_open_desc(struct ftdi_context *ftdi, int vendor, int product,
606                        const char* description, const char* serial)
607 {
608     return ftdi_usb_open_desc_index(ftdi,vendor,product,description,serial,0);
609 }
610
611 /**
612     Opens the index-th device with a given, vendor id, product id,
613     description and serial.
614
615     \param ftdi pointer to ftdi_context
616     \param vendor Vendor ID
617     \param product Product ID
618     \param description Description to search for. Use NULL if not needed.
619     \param serial Serial to search for. Use NULL if not needed.
620     \param index Number of matching device to open if there are more than one, starts with 0.
621
622     \retval  0: all fine
623     \retval -1: usb_find_busses() failed
624     \retval -2: usb_find_devices() failed
625     \retval -3: usb device not found
626     \retval -4: unable to open device
627     \retval -5: unable to claim device
628     \retval -6: reset failed
629     \retval -7: set baudrate failed
630     \retval -8: get product description failed
631     \retval -9: get serial number failed
632     \retval -10: unable to close device
633     \retval -11: ftdi context invalid
634 */
635 int ftdi_usb_open_desc_index(struct ftdi_context *ftdi, int vendor, int product,
636                        const char* description, const char* serial, unsigned int index)
637 {
638     libusb_device *dev;
639     libusb_device **devs;
640     char string[256];
641     int i = 0;
642
643     if (libusb_init(&ftdi->usb_ctx) < 0)
644         ftdi_error_return(-11, "libusb_init() failed");
645
646     if (ftdi == NULL)
647         ftdi_error_return(-11, "ftdi context invalid");
648
649     if (libusb_get_device_list(ftdi->usb_ctx, &devs) < 0)
650         ftdi_error_return(-12, "libusb_get_device_list() failed");
651
652     while ((dev = devs[i++]) != NULL)
653     {
654         struct libusb_device_descriptor desc;
655         int res;
656
657         if (libusb_get_device_descriptor(dev, &desc) < 0)
658             ftdi_error_return_free_device_list(-13, "libusb_get_device_descriptor() failed", devs);
659
660         if (desc.idVendor == vendor && desc.idProduct == product)
661         {
662             if (libusb_open(dev, &ftdi->usb_dev) < 0)
663                 ftdi_error_return_free_device_list(-4, "usb_open() failed", devs);
664
665             if (description != NULL)
666             {
667                 if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iProduct, (unsigned char *)string, sizeof(string)) < 0)
668                 {
669                     libusb_close (ftdi->usb_dev);
670                     ftdi_error_return_free_device_list(-8, "unable to fetch product description", devs);
671                 }
672                 if (strncmp(string, description, sizeof(string)) != 0)
673                 {
674                     libusb_close (ftdi->usb_dev);
675                     continue;
676                 }
677             }
678             if (serial != NULL)
679             {
680                 if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iSerialNumber, (unsigned char *)string, sizeof(string)) < 0)
681                 {
682                     ftdi_usb_close_internal (ftdi);
683                     ftdi_error_return_free_device_list(-9, "unable to fetch serial number", devs);
684                 }
685                 if (strncmp(string, serial, sizeof(string)) != 0)
686                 {
687                     ftdi_usb_close_internal (ftdi);
688                     continue;
689                 }
690             }
691
692             ftdi_usb_close_internal (ftdi);
693
694                 if (index > 0)
695                 {
696                     index--;
697                     continue;
698                 }
699
700             res = ftdi_usb_open_dev(ftdi, dev);
701             libusb_free_device_list(devs,1);
702             return res;
703         }
704     }
705
706     // device not found
707     ftdi_error_return_free_device_list(-3, "device not found", devs);
708 }
709
710 /**
711     Opens the ftdi-device described by a description-string.
712     Intended to be used for parsing a device-description given as commandline argument.
713
714     \param ftdi pointer to ftdi_context
715     \param description NULL-terminated description-string, using this format:
716         \li <tt>d:\<devicenode></tt> path of bus and device-node (e.g. "003/001") within usb device tree (usually at /proc/bus/usb/)
717         \li <tt>i:\<vendor>:\<product></tt> first device with given vendor and product id, ids can be decimal, octal (preceded by "0") or hex (preceded by "0x")
718         \li <tt>i:\<vendor>:\<product>:\<index></tt> as above with index being the number of the device (starting with 0) if there are more than one
719         \li <tt>s:\<vendor>:\<product>:\<serial></tt> first device with given vendor id, product id and serial string
720
721     \note The description format may be extended in later versions.
722
723     \retval  0: all fine
724     \retval -1: libusb_init() failed
725     \retval -2: libusb_get_device_list() failed
726     \retval -3: usb device not found
727     \retval -4: unable to open device
728     \retval -5: unable to claim device
729     \retval -6: reset failed
730     \retval -7: set baudrate failed
731     \retval -8: get product description failed
732     \retval -9: get serial number failed
733     \retval -10: unable to close device
734     \retval -11: illegal description format
735     \retval -12: ftdi context invalid
736 */
737 int ftdi_usb_open_string(struct ftdi_context *ftdi, const char* description)
738 {
739     if (ftdi == NULL)
740         ftdi_error_return(-12, "ftdi context invalid");
741
742     if (description[0] == 0 || description[1] != ':')
743         ftdi_error_return(-11, "illegal description format");
744
745     if (description[0] == 'd')
746     {
747         libusb_device *dev;
748         libusb_device **devs;
749         unsigned int bus_number, device_address;
750         int i = 0;
751
752         if (libusb_init (&ftdi->usb_ctx) < 0)
753             ftdi_error_return(-1, "libusb_init() failed");
754
755         if (libusb_get_device_list(ftdi->usb_ctx, &devs) < 0)
756             ftdi_error_return(-2, "libusb_get_device_list() failed");
757
758         /* XXX: This doesn't handle symlinks/odd paths/etc... */
759         if (sscanf (description + 2, "%u/%u", &bus_number, &device_address) != 2)
760             ftdi_error_return_free_device_list(-11, "illegal description format", devs);
761
762         while ((dev = devs[i++]) != NULL)
763         {
764             int ret;
765             if (bus_number == libusb_get_bus_number (dev)
766                 && device_address == libusb_get_device_address (dev))
767             {
768                 ret = ftdi_usb_open_dev(ftdi, dev);
769                 libusb_free_device_list(devs,1);
770                 return ret;
771             }
772         }
773
774         // device not found
775         ftdi_error_return_free_device_list(-3, "device not found", devs);
776     }
777     else if (description[0] == 'i' || description[0] == 's')
778     {
779         unsigned int vendor;
780         unsigned int product;
781         unsigned int index=0;
782         const char *serial=NULL;
783         const char *startp, *endp;
784
785         errno=0;
786         startp=description+2;
787         vendor=strtoul((char*)startp,(char**)&endp,0);
788         if (*endp != ':' || endp == startp || errno != 0)
789             ftdi_error_return(-11, "illegal description format");
790
791         startp=endp+1;
792         product=strtoul((char*)startp,(char**)&endp,0);
793         if (endp == startp || errno != 0)
794             ftdi_error_return(-11, "illegal description format");
795
796         if (description[0] == 'i' && *endp != 0)
797         {
798             /* optional index field in i-mode */
799             if (*endp != ':')
800                 ftdi_error_return(-11, "illegal description format");
801
802             startp=endp+1;
803             index=strtoul((char*)startp,(char**)&endp,0);
804             if (*endp != 0 || endp == startp || errno != 0)
805                 ftdi_error_return(-11, "illegal description format");
806         }
807         if (description[0] == 's')
808         {
809             if (*endp != ':')
810                 ftdi_error_return(-11, "illegal description format");
811
812             /* rest of the description is the serial */
813             serial=endp+1;
814         }
815
816         return ftdi_usb_open_desc_index(ftdi, vendor, product, NULL, serial, index);
817     }
818     else
819     {
820         ftdi_error_return(-11, "illegal description format");
821     }
822 }
823
824 /**
825     Resets the ftdi device.
826
827     \param ftdi pointer to ftdi_context
828
829     \retval  0: all fine
830     \retval -1: FTDI reset failed
831     \retval -2: USB device unavailable
832 */
833 int ftdi_usb_reset(struct ftdi_context *ftdi)
834 {
835     if (ftdi == NULL || ftdi->usb_dev == NULL)
836         ftdi_error_return(-2, "USB device unavailable");
837
838     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
839                                 SIO_RESET_REQUEST, SIO_RESET_SIO,
840                                 ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
841         ftdi_error_return(-1,"FTDI reset failed");
842
843     // Invalidate data in the readbuffer
844     ftdi->readbuffer_offset = 0;
845     ftdi->readbuffer_remaining = 0;
846
847     return 0;
848 }
849
850 /**
851     Clears the read buffer on the chip and the internal read buffer.
852
853     \param ftdi pointer to ftdi_context
854
855     \retval  0: all fine
856     \retval -1: read buffer purge failed
857     \retval -2: USB device unavailable
858 */
859 int ftdi_usb_purge_rx_buffer(struct ftdi_context *ftdi)
860 {
861     if (ftdi == NULL || ftdi->usb_dev == NULL)
862         ftdi_error_return(-2, "USB device unavailable");
863
864     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
865                                 SIO_RESET_REQUEST, SIO_RESET_PURGE_RX,
866                                 ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
867         ftdi_error_return(-1, "FTDI purge of RX buffer failed");
868
869     // Invalidate data in the readbuffer
870     ftdi->readbuffer_offset = 0;
871     ftdi->readbuffer_remaining = 0;
872
873     return 0;
874 }
875
876 /**
877     Clears the write buffer on the chip.
878
879     \param ftdi pointer to ftdi_context
880
881     \retval  0: all fine
882     \retval -1: write buffer purge failed
883     \retval -2: USB device unavailable
884 */
885 int ftdi_usb_purge_tx_buffer(struct ftdi_context *ftdi)
886 {
887     if (ftdi == NULL || ftdi->usb_dev == NULL)
888         ftdi_error_return(-2, "USB device unavailable");
889
890     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
891                                 SIO_RESET_REQUEST, SIO_RESET_PURGE_TX,
892                                 ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
893         ftdi_error_return(-1, "FTDI purge of TX buffer failed");
894
895     return 0;
896 }
897
898 /**
899     Clears the buffers on the chip and the internal read buffer.
900
901     \param ftdi pointer to ftdi_context
902
903     \retval  0: all fine
904     \retval -1: read buffer purge failed
905     \retval -2: write buffer purge failed
906     \retval -3: USB device unavailable
907 */
908 int ftdi_usb_purge_buffers(struct ftdi_context *ftdi)
909 {
910     int result;
911
912     if (ftdi == NULL || ftdi->usb_dev == NULL)
913         ftdi_error_return(-3, "USB device unavailable");
914
915     result = ftdi_usb_purge_rx_buffer(ftdi);
916     if (result < 0)
917         return -1;
918
919     result = ftdi_usb_purge_tx_buffer(ftdi);
920     if (result < 0)
921         return -2;
922
923     return 0;
924 }
925
926
927
928 /**
929     Closes the ftdi device. Call ftdi_deinit() if you're cleaning up.
930
931     \param ftdi pointer to ftdi_context
932
933     \retval  0: all fine
934     \retval -1: usb_release failed
935     \retval -3: ftdi context invalid
936 */
937 int ftdi_usb_close(struct ftdi_context *ftdi)
938 {
939     int rtn = 0;
940
941     if (ftdi == NULL)
942         ftdi_error_return(-3, "ftdi context invalid");
943
944     if (ftdi->usb_dev != NULL)
945         if (libusb_release_interface(ftdi->usb_dev, ftdi->interface) < 0)
946             rtn = -1;
947
948     ftdi_usb_close_internal (ftdi);
949
950     return rtn;
951 }
952
953 /**
954     ftdi_convert_baudrate returns nearest supported baud rate to that requested.
955     Function is only used internally
956     \internal
957 */
958 static int ftdi_convert_baudrate(int baudrate, struct ftdi_context *ftdi,
959                                  unsigned short *value, unsigned short *index)
960 {
961     static const char am_adjust_up[8] = {0, 0, 0, 1, 0, 3, 2, 1};
962     static const char am_adjust_dn[8] = {0, 0, 0, 1, 0, 1, 2, 3};
963     static const char frac_code[8] = {0, 3, 2, 4, 1, 5, 6, 7};
964     int divisor, best_divisor, best_baud, best_baud_diff;
965     unsigned long encoded_divisor;
966     int i;
967
968     if (baudrate <= 0)
969     {
970         // Return error
971         return -1;
972     }
973
974     divisor = 24000000 / baudrate;
975
976     if (ftdi->type == TYPE_AM)
977     {
978         // Round down to supported fraction (AM only)
979         divisor -= am_adjust_dn[divisor & 7];
980     }
981
982     // Try this divisor and the one above it (because division rounds down)
983     best_divisor = 0;
984     best_baud = 0;
985     best_baud_diff = 0;
986     for (i = 0; i < 2; i++)
987     {
988         int try_divisor = divisor + i;
989         int baud_estimate;
990         int baud_diff;
991
992         // Round up to supported divisor value
993         if (try_divisor <= 8)
994         {
995             // Round up to minimum supported divisor
996             try_divisor = 8;
997         }
998         else if (ftdi->type != TYPE_AM && try_divisor < 12)
999         {
1000             // BM doesn't support divisors 9 through 11 inclusive
1001             try_divisor = 12;
1002         }
1003         else if (divisor < 16)
1004         {
1005             // AM doesn't support divisors 9 through 15 inclusive
1006             try_divisor = 16;
1007         }
1008         else
1009         {
1010             if (ftdi->type == TYPE_AM)
1011             {
1012                 // Round up to supported fraction (AM only)
1013                 try_divisor += am_adjust_up[try_divisor & 7];
1014                 if (try_divisor > 0x1FFF8)
1015                 {
1016                     // Round down to maximum supported divisor value (for AM)
1017                     try_divisor = 0x1FFF8;
1018                 }
1019             }
1020             else
1021             {
1022                 if (try_divisor > 0x1FFFF)
1023                 {
1024                     // Round down to maximum supported divisor value (for BM)
1025                     try_divisor = 0x1FFFF;
1026                 }
1027             }
1028         }
1029         // Get estimated baud rate (to nearest integer)
1030         baud_estimate = (24000000 + (try_divisor / 2)) / try_divisor;
1031         // Get absolute difference from requested baud rate
1032         if (baud_estimate < baudrate)
1033         {
1034             baud_diff = baudrate - baud_estimate;
1035         }
1036         else
1037         {
1038             baud_diff = baud_estimate - baudrate;
1039         }
1040         if (i == 0 || baud_diff < best_baud_diff)
1041         {
1042             // Closest to requested baud rate so far
1043             best_divisor = try_divisor;
1044             best_baud = baud_estimate;
1045             best_baud_diff = baud_diff;
1046             if (baud_diff == 0)
1047             {
1048                 // Spot on! No point trying
1049                 break;
1050             }
1051         }
1052     }
1053     // Encode the best divisor value
1054     encoded_divisor = (best_divisor >> 3) | (frac_code[best_divisor & 7] << 14);
1055     // Deal with special cases for encoded value
1056     if (encoded_divisor == 1)
1057     {
1058         encoded_divisor = 0;    // 3000000 baud
1059     }
1060     else if (encoded_divisor == 0x4001)
1061     {
1062         encoded_divisor = 1;    // 2000000 baud (BM only)
1063     }
1064     // Split into "value" and "index" values
1065     *value = (unsigned short)(encoded_divisor & 0xFFFF);
1066     if (ftdi->type == TYPE_2232C || ftdi->type == TYPE_2232H || ftdi->type == TYPE_4232H)
1067     {
1068         *index = (unsigned short)(encoded_divisor >> 8);
1069         *index &= 0xFF00;
1070         *index |= ftdi->index;
1071     }
1072     else
1073         *index = (unsigned short)(encoded_divisor >> 16);
1074
1075     // Return the nearest baud rate
1076     return best_baud;
1077 }
1078
1079 /**
1080     Sets the chip baud rate
1081
1082     \param ftdi pointer to ftdi_context
1083     \param baudrate baud rate to set
1084
1085     \retval  0: all fine
1086     \retval -1: invalid baudrate
1087     \retval -2: setting baudrate failed
1088     \retval -3: USB device unavailable
1089 */
1090 int ftdi_set_baudrate(struct ftdi_context *ftdi, int baudrate)
1091 {
1092     unsigned short value, index;
1093     int actual_baudrate;
1094
1095     if (ftdi == NULL || ftdi->usb_dev == NULL)
1096         ftdi_error_return(-3, "USB device unavailable");
1097
1098     if (ftdi->bitbang_enabled)
1099     {
1100         baudrate = baudrate*4;
1101     }
1102
1103     actual_baudrate = ftdi_convert_baudrate(baudrate, ftdi, &value, &index);
1104     if (actual_baudrate <= 0)
1105         ftdi_error_return (-1, "Silly baudrate <= 0.");
1106
1107     // Check within tolerance (about 5%)
1108     if ((actual_baudrate * 2 < baudrate /* Catch overflows */ )
1109             || ((actual_baudrate < baudrate)
1110                 ? (actual_baudrate * 21 < baudrate * 20)
1111                 : (baudrate * 21 < actual_baudrate * 20)))
1112         ftdi_error_return (-1, "Unsupported baudrate. Note: bitbang baudrates are automatically multiplied by 4");
1113
1114     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1115                                 SIO_SET_BAUDRATE_REQUEST, value,
1116                                 index, NULL, 0, ftdi->usb_write_timeout) < 0)
1117         ftdi_error_return (-2, "Setting new baudrate failed");
1118
1119     ftdi->baudrate = baudrate;
1120     return 0;
1121 }
1122
1123 /**
1124     Set (RS232) line characteristics.
1125     The break type can only be set via ftdi_set_line_property2()
1126     and defaults to "off".
1127
1128     \param ftdi pointer to ftdi_context
1129     \param bits Number of bits
1130     \param sbit Number of stop bits
1131     \param parity Parity mode
1132
1133     \retval  0: all fine
1134     \retval -1: Setting line property failed
1135 */
1136 int ftdi_set_line_property(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
1137                            enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity)
1138 {
1139     return ftdi_set_line_property2(ftdi, bits, sbit, parity, BREAK_OFF);
1140 }
1141
1142 /**
1143     Set (RS232) line characteristics
1144
1145     \param ftdi pointer to ftdi_context
1146     \param bits Number of bits
1147     \param sbit Number of stop bits
1148     \param parity Parity mode
1149     \param break_type Break type
1150
1151     \retval  0: all fine
1152     \retval -1: Setting line property failed
1153     \retval -2: USB device unavailable
1154 */
1155 int ftdi_set_line_property2(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
1156                             enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity,
1157                             enum ftdi_break_type break_type)
1158 {
1159     unsigned short value = bits;
1160
1161     if (ftdi == NULL || ftdi->usb_dev == NULL)
1162         ftdi_error_return(-2, "USB device unavailable");
1163
1164     switch (parity)
1165     {
1166         case NONE:
1167             value |= (0x00 << 8);
1168             break;
1169         case ODD:
1170             value |= (0x01 << 8);
1171             break;
1172         case EVEN:
1173             value |= (0x02 << 8);
1174             break;
1175         case MARK:
1176             value |= (0x03 << 8);
1177             break;
1178         case SPACE:
1179             value |= (0x04 << 8);
1180             break;
1181     }
1182
1183     switch (sbit)
1184     {
1185         case STOP_BIT_1:
1186             value |= (0x00 << 11);
1187             break;
1188         case STOP_BIT_15:
1189             value |= (0x01 << 11);
1190             break;
1191         case STOP_BIT_2:
1192             value |= (0x02 << 11);
1193             break;
1194     }
1195
1196     switch (break_type)
1197     {
1198         case BREAK_OFF:
1199             value |= (0x00 << 14);
1200             break;
1201         case BREAK_ON:
1202             value |= (0x01 << 14);
1203             break;
1204     }
1205
1206     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1207                                 SIO_SET_DATA_REQUEST, value,
1208                                 ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
1209         ftdi_error_return (-1, "Setting new line property failed");
1210
1211     return 0;
1212 }
1213
1214 /**
1215     Writes data in chunks (see ftdi_write_data_set_chunksize()) to the chip
1216
1217     \param ftdi pointer to ftdi_context
1218     \param buf Buffer with the data
1219     \param size Size of the buffer
1220
1221     \retval -666: USB device unavailable
1222     \retval <0: error code from usb_bulk_write()
1223     \retval >0: number of bytes written
1224 */
1225 int ftdi_write_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
1226 {
1227     int offset = 0;
1228     int actual_length;
1229
1230     if (ftdi == NULL || ftdi->usb_dev == NULL)
1231         ftdi_error_return(-666, "USB device unavailable");
1232
1233     while (offset < size)
1234     {
1235         int write_size = ftdi->writebuffer_chunksize;
1236
1237         if (offset+write_size > size)
1238             write_size = size-offset;
1239
1240         if (libusb_bulk_transfer(ftdi->usb_dev, ftdi->in_ep, buf+offset, write_size, &actual_length, ftdi->usb_write_timeout) < 0)
1241             ftdi_error_return(-1, "usb bulk write failed");
1242
1243         offset += actual_length;
1244     }
1245
1246     return offset;
1247 }
1248
1249 static void ftdi_read_data_cb(struct libusb_transfer *transfer)
1250 {
1251     struct ftdi_transfer_control *tc = (struct ftdi_transfer_control *) transfer->user_data;
1252     struct ftdi_context *ftdi = tc->ftdi;
1253     int packet_size, actual_length, num_of_chunks, chunk_remains, i, ret;
1254
1255     packet_size = ftdi->max_packet_size;
1256
1257     actual_length = transfer->actual_length;
1258
1259     if (actual_length > 2)
1260     {
1261         // skip FTDI status bytes.
1262         // Maybe stored in the future to enable modem use
1263         num_of_chunks = actual_length / packet_size;
1264         chunk_remains = actual_length % packet_size;
1265         //printf("actual_length = %X, num_of_chunks = %X, chunk_remains = %X, readbuffer_offset = %X\n", actual_length, num_of_chunks, chunk_remains, ftdi->readbuffer_offset);
1266
1267         ftdi->readbuffer_offset += 2;
1268         actual_length -= 2;
1269
1270         if (actual_length > packet_size - 2)
1271         {
1272             for (i = 1; i < num_of_chunks; i++)
1273               memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1274                        ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1275                        packet_size - 2);
1276             if (chunk_remains > 2)
1277             {
1278                 memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1279                          ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1280                          chunk_remains-2);
1281                 actual_length -= 2*num_of_chunks;
1282             }
1283             else
1284               actual_length -= 2*(num_of_chunks-1)+chunk_remains;
1285         }
1286
1287         if (actual_length > 0)
1288         {
1289             // data still fits in buf?
1290             if (tc->offset + actual_length <= tc->size)
1291             {
1292                 memcpy (tc->buf + tc->offset, ftdi->readbuffer + ftdi->readbuffer_offset, actual_length);
1293                 //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
1294                 tc->offset += actual_length;
1295
1296                 ftdi->readbuffer_offset = 0;
1297                 ftdi->readbuffer_remaining = 0;
1298
1299                 /* Did we read exactly the right amount of bytes? */
1300                 if (tc->offset == tc->size)
1301                 {
1302                     //printf("read_data exact rem %d offset %d\n",
1303                     //ftdi->readbuffer_remaining, offset);
1304                     tc->completed = 1;
1305                     return;
1306                 }
1307             }
1308             else
1309             {
1310                 // only copy part of the data or size <= readbuffer_chunksize
1311                 int part_size = tc->size - tc->offset;
1312                 memcpy (tc->buf + tc->offset, ftdi->readbuffer + ftdi->readbuffer_offset, part_size);
1313                 tc->offset += part_size;
1314
1315                 ftdi->readbuffer_offset += part_size;
1316                 ftdi->readbuffer_remaining = actual_length - part_size;
1317
1318                 /* printf("Returning part: %d - size: %d - offset: %d - actual_length: %d - remaining: %d\n",
1319                 part_size, size, offset, actual_length, ftdi->readbuffer_remaining); */
1320                 tc->completed = 1;
1321                 return;
1322             }
1323         }
1324     }
1325     ret = libusb_submit_transfer (transfer);
1326     if (ret < 0)
1327         tc->completed = 1;
1328 }
1329
1330
1331 static void ftdi_write_data_cb(struct libusb_transfer *transfer)
1332 {
1333     struct ftdi_transfer_control *tc = (struct ftdi_transfer_control *) transfer->user_data;
1334     struct ftdi_context *ftdi = tc->ftdi;
1335     
1336     tc->offset += transfer->actual_length;
1337     
1338     if (tc->offset == tc->size)
1339     {
1340         tc->completed = 1;
1341     }
1342     else
1343     {
1344         int write_size = ftdi->writebuffer_chunksize;
1345         int ret;
1346
1347         if (tc->offset + write_size > tc->size)
1348             write_size = tc->size - tc->offset;
1349
1350         transfer->length = write_size;
1351         transfer->buffer = tc->buf + tc->offset;
1352         ret = libusb_submit_transfer (transfer);
1353         if (ret < 0)
1354             tc->completed = 1;
1355     }
1356 }
1357
1358
1359 /**
1360     Writes data to the chip. Does not wait for completion of the transfer
1361     nor does it make sure that the transfer was successful.
1362
1363     Use libusb 1.0 asynchronous API.
1364
1365     \param ftdi pointer to ftdi_context
1366     \param buf Buffer with the data
1367     \param size Size of the buffer
1368
1369     \retval NULL: Some error happens when submit transfer
1370     \retval !NULL: Pointer to a ftdi_transfer_control
1371 */
1372
1373 struct ftdi_transfer_control *ftdi_write_data_submit(struct ftdi_context *ftdi, unsigned char *buf, int size)
1374 {
1375     struct ftdi_transfer_control *tc;
1376     struct libusb_transfer *transfer = libusb_alloc_transfer(0);
1377     int write_size, ret;
1378
1379     if (ftdi == NULL || ftdi->usb_dev == NULL)
1380     {
1381         libusb_free_transfer(transfer);
1382         return NULL;
1383     }
1384
1385     tc = (struct ftdi_transfer_control *) malloc (sizeof (*tc));
1386
1387     if (!tc || !transfer)
1388         return NULL;
1389
1390     tc->ftdi = ftdi;
1391     tc->completed = 0;
1392     tc->buf = buf;
1393     tc->size = size;
1394     tc->offset = 0;
1395
1396     if (size < ftdi->writebuffer_chunksize)
1397       write_size = size;
1398     else
1399       write_size = ftdi->writebuffer_chunksize;
1400
1401     libusb_fill_bulk_transfer(transfer, ftdi->usb_dev, ftdi->in_ep, buf,
1402                               write_size, ftdi_write_data_cb, tc,
1403                               ftdi->usb_write_timeout);
1404     transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
1405
1406     ret = libusb_submit_transfer(transfer);
1407     if (ret < 0)
1408     {
1409         libusb_free_transfer(transfer);
1410         tc->completed = 1;
1411         tc->transfer = NULL;
1412         return NULL;
1413     }
1414     tc->transfer = transfer;
1415
1416     return tc;
1417 }
1418
1419 /**
1420     Reads data from the chip. Does not wait for completion of the transfer
1421     nor does it make sure that the transfer was successful.
1422
1423     Use libusb 1.0 asynchronous API.
1424
1425     \param ftdi pointer to ftdi_context
1426     \param buf Buffer with the data
1427     \param size Size of the buffer
1428
1429     \retval NULL: Some error happens when submit transfer
1430     \retval !NULL: Pointer to a ftdi_transfer_control
1431 */
1432
1433 struct ftdi_transfer_control *ftdi_read_data_submit(struct ftdi_context *ftdi, unsigned char *buf, int size)
1434 {
1435     struct ftdi_transfer_control *tc;
1436     struct libusb_transfer *transfer;
1437     int ret;
1438
1439     if (ftdi == NULL || ftdi->usb_dev == NULL)
1440         return NULL;
1441
1442     tc = (struct ftdi_transfer_control *) malloc (sizeof (*tc));
1443     if (!tc)
1444         return NULL;
1445
1446     tc->ftdi = ftdi;
1447     tc->buf = buf;
1448     tc->size = size;
1449
1450     if (size <= ftdi->readbuffer_remaining)
1451     {
1452         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);
1453
1454         // Fix offsets
1455         ftdi->readbuffer_remaining -= size;
1456         ftdi->readbuffer_offset += size;
1457
1458         /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */
1459
1460         tc->completed = 1;
1461         tc->offset = size;
1462         tc->transfer = NULL;
1463         return tc;
1464     }
1465
1466     tc->completed = 0;
1467     if (ftdi->readbuffer_remaining != 0)
1468     {
1469         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);
1470
1471         tc->offset = ftdi->readbuffer_remaining;
1472     }
1473     else
1474         tc->offset = 0;
1475
1476     transfer = libusb_alloc_transfer(0);
1477     if (!transfer)
1478     {
1479         free (tc);
1480         return NULL;
1481     }
1482
1483     ftdi->readbuffer_remaining = 0;
1484     ftdi->readbuffer_offset = 0;
1485
1486     libusb_fill_bulk_transfer(transfer, ftdi->usb_dev, ftdi->out_ep, ftdi->readbuffer, ftdi->readbuffer_chunksize, ftdi_read_data_cb, tc, ftdi->usb_read_timeout);
1487     transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
1488
1489     ret = libusb_submit_transfer(transfer);
1490     if (ret < 0)
1491     {
1492         libusb_free_transfer(transfer);
1493         free (tc);
1494         return NULL;
1495     }
1496     tc->transfer = transfer;
1497
1498     return tc;
1499 }
1500
1501 /**
1502     Wait for completion of the transfer.
1503
1504     Use libusb 1.0 asynchronous API.
1505
1506     \param tc pointer to ftdi_transfer_control
1507
1508     \retval < 0: Some error happens
1509     \retval >= 0: Data size transferred
1510 */
1511
1512 int ftdi_transfer_data_done(struct ftdi_transfer_control *tc)
1513 {
1514     int ret;
1515
1516     while (!tc->completed)
1517     {
1518         ret = libusb_handle_events(tc->ftdi->usb_ctx);
1519         if (ret < 0)
1520         {
1521             if (ret == LIBUSB_ERROR_INTERRUPTED)
1522                 continue;
1523             libusb_cancel_transfer(tc->transfer);
1524             while (!tc->completed)
1525                 if (libusb_handle_events(tc->ftdi->usb_ctx) < 0)
1526                     break;
1527             libusb_free_transfer(tc->transfer);
1528             free (tc);
1529             return ret;
1530         }
1531     }
1532
1533     ret = tc->offset;
1534     /**
1535      * tc->transfer could be NULL if "(size <= ftdi->readbuffer_remaining)"
1536      * at ftdi_read_data_submit(). Therefore, we need to check it here.
1537      **/
1538     if (tc->transfer)
1539     {
1540         if (tc->transfer->status != LIBUSB_TRANSFER_COMPLETED)
1541             ret = -1;
1542         libusb_free_transfer(tc->transfer);
1543     }
1544     free(tc);
1545     return ret;
1546 }
1547
1548 /**
1549     Configure write buffer chunk size.
1550     Default is 4096.
1551
1552     \param ftdi pointer to ftdi_context
1553     \param chunksize Chunk size
1554
1555     \retval 0: all fine
1556     \retval -1: ftdi context invalid
1557 */
1558 int ftdi_write_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
1559 {
1560     if (ftdi == NULL)
1561         ftdi_error_return(-1, "ftdi context invalid");
1562
1563     ftdi->writebuffer_chunksize = chunksize;
1564     return 0;
1565 }
1566
1567 /**
1568     Get write buffer chunk size.
1569
1570     \param ftdi pointer to ftdi_context
1571     \param chunksize Pointer to store chunk size in
1572
1573     \retval 0: all fine
1574     \retval -1: ftdi context invalid
1575 */
1576 int ftdi_write_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
1577 {
1578     if (ftdi == NULL)
1579         ftdi_error_return(-1, "ftdi context invalid");
1580
1581     *chunksize = ftdi->writebuffer_chunksize;
1582     return 0;
1583 }
1584
1585 /**
1586     Reads data in chunks (see ftdi_read_data_set_chunksize()) from the chip.
1587
1588     Automatically strips the two modem status bytes transfered during every read.
1589
1590     \param ftdi pointer to ftdi_context
1591     \param buf Buffer to store data in
1592     \param size Size of the buffer
1593
1594     \retval -666: USB device unavailable
1595     \retval <0: error code from libusb_bulk_transfer()
1596     \retval  0: no data was available
1597     \retval >0: number of bytes read
1598
1599 */
1600 int ftdi_read_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
1601 {
1602     int offset = 0, ret, i, num_of_chunks, chunk_remains;
1603     int packet_size = ftdi->max_packet_size;
1604     int actual_length = 1;
1605
1606     if (ftdi == NULL || ftdi->usb_dev == NULL)
1607         ftdi_error_return(-666, "USB device unavailable");
1608
1609     // Packet size sanity check (avoid division by zero)
1610     if (packet_size == 0)
1611         ftdi_error_return(-1, "max_packet_size is bogus (zero)");
1612
1613     // everything we want is still in the readbuffer?
1614     if (size <= ftdi->readbuffer_remaining)
1615     {
1616         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);
1617
1618         // Fix offsets
1619         ftdi->readbuffer_remaining -= size;
1620         ftdi->readbuffer_offset += size;
1621
1622         /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */
1623
1624         return size;
1625     }
1626     // something still in the readbuffer, but not enough to satisfy 'size'?
1627     if (ftdi->readbuffer_remaining != 0)
1628     {
1629         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);
1630
1631         // Fix offset
1632         offset += ftdi->readbuffer_remaining;
1633     }
1634     // do the actual USB read
1635     while (offset < size && actual_length > 0)
1636     {
1637         ftdi->readbuffer_remaining = 0;
1638         ftdi->readbuffer_offset = 0;
1639         /* returns how much received */
1640         ret = libusb_bulk_transfer (ftdi->usb_dev, ftdi->out_ep, ftdi->readbuffer, ftdi->readbuffer_chunksize, &actual_length, ftdi->usb_read_timeout);
1641         if (ret < 0)
1642             ftdi_error_return(ret, "usb bulk read failed");
1643
1644         if (actual_length > 2)
1645         {
1646             // skip FTDI status bytes.
1647             // Maybe stored in the future to enable modem use
1648             num_of_chunks = actual_length / packet_size;
1649             chunk_remains = actual_length % packet_size;
1650             //printf("actual_length = %X, num_of_chunks = %X, chunk_remains = %X, readbuffer_offset = %X\n", actual_length, num_of_chunks, chunk_remains, ftdi->readbuffer_offset);
1651
1652             ftdi->readbuffer_offset += 2;
1653             actual_length -= 2;
1654
1655             if (actual_length > packet_size - 2)
1656             {
1657                 for (i = 1; i < num_of_chunks; i++)
1658                     memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1659                              ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1660                              packet_size - 2);
1661                 if (chunk_remains > 2)
1662                 {
1663                     memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1664                              ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1665                              chunk_remains-2);
1666                     actual_length -= 2*num_of_chunks;
1667                 }
1668                 else
1669                     actual_length -= 2*(num_of_chunks-1)+chunk_remains;
1670             }
1671         }
1672         else if (actual_length <= 2)
1673         {
1674             // no more data to read?
1675             return offset;
1676         }
1677         if (actual_length > 0)
1678         {
1679             // data still fits in buf?
1680             if (offset+actual_length <= size)
1681             {
1682                 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, actual_length);
1683                 //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
1684                 offset += actual_length;
1685
1686                 /* Did we read exactly the right amount of bytes? */
1687                 if (offset == size)
1688                     //printf("read_data exact rem %d offset %d\n",
1689                     //ftdi->readbuffer_remaining, offset);
1690                     return offset;
1691             }
1692             else
1693             {
1694                 // only copy part of the data or size <= readbuffer_chunksize
1695                 int part_size = size-offset;
1696                 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, part_size);
1697
1698                 ftdi->readbuffer_offset += part_size;
1699                 ftdi->readbuffer_remaining = actual_length-part_size;
1700                 offset += part_size;
1701
1702                 /* printf("Returning part: %d - size: %d - offset: %d - actual_length: %d - remaining: %d\n",
1703                 part_size, size, offset, actual_length, ftdi->readbuffer_remaining); */
1704
1705                 return offset;
1706             }
1707         }
1708     }
1709     // never reached
1710     return -127;
1711 }
1712
1713 /**
1714     Configure read buffer chunk size.
1715     Default is 4096.
1716
1717     Automatically reallocates the buffer.
1718
1719     \param ftdi pointer to ftdi_context
1720     \param chunksize Chunk size
1721
1722     \retval 0: all fine
1723     \retval -1: ftdi context invalid
1724 */
1725 int ftdi_read_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
1726 {
1727     unsigned char *new_buf;
1728
1729     if (ftdi == NULL)
1730         ftdi_error_return(-1, "ftdi context invalid");
1731
1732     // Invalidate all remaining data
1733     ftdi->readbuffer_offset = 0;
1734     ftdi->readbuffer_remaining = 0;
1735 #ifdef __linux__
1736     /* We can't set readbuffer_chunksize larger than MAX_BULK_BUFFER_LENGTH,
1737        which is defined in libusb-1.0.  Otherwise, each USB read request will
1738        be divided into multiple URBs.  This will cause issues on Linux kernel
1739        older than 2.6.32.  */
1740     if (chunksize > 16384)
1741         chunksize = 16384;
1742 #endif
1743
1744     if ((new_buf = (unsigned char *)realloc(ftdi->readbuffer, chunksize)) == NULL)
1745         ftdi_error_return(-1, "out of memory for readbuffer");
1746
1747     ftdi->readbuffer = new_buf;
1748     ftdi->readbuffer_chunksize = chunksize;
1749
1750     return 0;
1751 }
1752
1753 /**
1754     Get read buffer chunk size.
1755
1756     \param ftdi pointer to ftdi_context
1757     \param chunksize Pointer to store chunk size in
1758
1759     \retval 0: all fine
1760     \retval -1: FTDI context invalid
1761 */
1762 int ftdi_read_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
1763 {
1764     if (ftdi == NULL)
1765         ftdi_error_return(-1, "FTDI context invalid");
1766
1767     *chunksize = ftdi->readbuffer_chunksize;
1768     return 0;
1769 }
1770
1771
1772 /**
1773     Enable bitbang mode.
1774
1775     \deprecated use \ref ftdi_set_bitmode with mode BITMODE_BITBANG instead
1776
1777     \param ftdi pointer to ftdi_context
1778     \param bitmask Bitmask to configure lines.
1779            HIGH/ON value configures a line as output.
1780
1781     \retval  0: all fine
1782     \retval -1: can't enable bitbang mode
1783     \retval -2: USB device unavailable
1784 */
1785 int ftdi_enable_bitbang(struct ftdi_context *ftdi, unsigned char bitmask)
1786 {
1787     unsigned short usb_val;
1788
1789     if (ftdi == NULL || ftdi->usb_dev == NULL)
1790         ftdi_error_return(-2, "USB device unavailable");
1791
1792     usb_val = bitmask; // low byte: bitmask
1793     /* FT2232C: Set bitbang_mode to 2 to enable SPI */
1794     usb_val |= (ftdi->bitbang_mode << 8);
1795
1796     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1797                                 SIO_SET_BITMODE_REQUEST, usb_val, ftdi->index,
1798                                 NULL, 0, ftdi->usb_write_timeout) < 0)
1799         ftdi_error_return(-1, "unable to enter bitbang mode. Perhaps not a BM type chip?");
1800
1801     ftdi->bitbang_enabled = 1;
1802     return 0;
1803 }
1804
1805 /**
1806     Disable bitbang mode.
1807
1808     \param ftdi pointer to ftdi_context
1809
1810     \retval  0: all fine
1811     \retval -1: can't disable bitbang mode
1812     \retval -2: USB device unavailable
1813 */
1814 int ftdi_disable_bitbang(struct ftdi_context *ftdi)
1815 {
1816     if (ftdi == NULL || ftdi->usb_dev == NULL)
1817         ftdi_error_return(-2, "USB device unavailable");
1818
1819     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_SET_BITMODE_REQUEST, 0, ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
1820         ftdi_error_return(-1, "unable to leave bitbang mode. Perhaps not a BM type chip?");
1821
1822     ftdi->bitbang_enabled = 0;
1823     return 0;
1824 }
1825
1826 /**
1827     Enable/disable bitbang modes.
1828
1829     \param ftdi pointer to ftdi_context
1830     \param bitmask Bitmask to configure lines.
1831            HIGH/ON value configures a line as output.
1832     \param mode Bitbang mode: use the values defined in \ref ftdi_mpsse_mode
1833
1834     \retval  0: all fine
1835     \retval -1: can't enable bitbang mode
1836     \retval -2: USB device unavailable
1837 */
1838 int ftdi_set_bitmode(struct ftdi_context *ftdi, unsigned char bitmask, unsigned char mode)
1839 {
1840     unsigned short usb_val;
1841
1842     if (ftdi == NULL || ftdi->usb_dev == NULL)
1843         ftdi_error_return(-2, "USB device unavailable");
1844
1845     usb_val = bitmask; // low byte: bitmask
1846     usb_val |= (mode << 8);
1847     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_SET_BITMODE_REQUEST, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
1848         ftdi_error_return(-1, "unable to configure bitbang mode. Perhaps not a 2232C type chip?");
1849
1850     ftdi->bitbang_mode = mode;
1851     ftdi->bitbang_enabled = (mode == BITMODE_RESET) ? 0 : 1;
1852     return 0;
1853 }
1854
1855 /**
1856     Directly read pin state, circumventing the read buffer. Useful for bitbang mode.
1857
1858     \param ftdi pointer to ftdi_context
1859     \param pins Pointer to store pins into
1860
1861     \retval  0: all fine
1862     \retval -1: read pins failed
1863     \retval -2: USB device unavailable
1864 */
1865 int ftdi_read_pins(struct ftdi_context *ftdi, unsigned char *pins)
1866 {
1867     if (ftdi == NULL || ftdi->usb_dev == NULL)
1868         ftdi_error_return(-2, "USB device unavailable");
1869
1870     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_READ_PINS_REQUEST, 0, ftdi->index, (unsigned char *)pins, 1, ftdi->usb_read_timeout) != 1)
1871         ftdi_error_return(-1, "read pins failed");
1872
1873     return 0;
1874 }
1875
1876 /**
1877     Set latency timer
1878
1879     The FTDI chip keeps data in the internal buffer for a specific
1880     amount of time if the buffer is not full yet to decrease
1881     load on the usb bus.
1882
1883     \param ftdi pointer to ftdi_context
1884     \param latency Value between 1 and 255
1885
1886     \retval  0: all fine
1887     \retval -1: latency out of range
1888     \retval -2: unable to set latency timer
1889     \retval -3: USB device unavailable
1890 */
1891 int ftdi_set_latency_timer(struct ftdi_context *ftdi, unsigned char latency)
1892 {
1893     unsigned short usb_val;
1894
1895     if (latency < 1)
1896         ftdi_error_return(-1, "latency out of range. Only valid for 1-255");
1897
1898     if (ftdi == NULL || ftdi->usb_dev == NULL)
1899         ftdi_error_return(-3, "USB device unavailable");
1900
1901     usb_val = latency;
1902     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_SET_LATENCY_TIMER_REQUEST, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
1903         ftdi_error_return(-2, "unable to set latency timer");
1904
1905     return 0;
1906 }
1907
1908 /**
1909     Get latency timer
1910
1911     \param ftdi pointer to ftdi_context
1912     \param latency Pointer to store latency value in
1913
1914     \retval  0: all fine
1915     \retval -1: unable to get latency timer
1916     \retval -2: USB device unavailable
1917 */
1918 int ftdi_get_latency_timer(struct ftdi_context *ftdi, unsigned char *latency)
1919 {
1920     unsigned short usb_val;
1921
1922     if (ftdi == NULL || ftdi->usb_dev == NULL)
1923         ftdi_error_return(-2, "USB device unavailable");
1924
1925     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_GET_LATENCY_TIMER_REQUEST, 0, ftdi->index, (unsigned char *)&usb_val, 1, ftdi->usb_read_timeout) != 1)
1926         ftdi_error_return(-1, "reading latency timer failed");
1927
1928     *latency = (unsigned char)usb_val;
1929     return 0;
1930 }
1931
1932 /**
1933     Poll modem status information
1934
1935     This function allows the retrieve the two status bytes of the device.
1936     The device sends these bytes also as a header for each read access
1937     where they are discarded by ftdi_read_data(). The chip generates
1938     the two stripped status bytes in the absence of data every 40 ms.
1939
1940     Layout of the first byte:
1941     - B0..B3 - must be 0
1942     - B4       Clear to send (CTS)
1943                  0 = inactive
1944                  1 = active
1945     - B5       Data set ready (DTS)
1946                  0 = inactive
1947                  1 = active
1948     - B6       Ring indicator (RI)
1949                  0 = inactive
1950                  1 = active
1951     - B7       Receive line signal detect (RLSD)
1952                  0 = inactive
1953                  1 = active
1954
1955     Layout of the second byte:
1956     - B0       Data ready (DR)
1957     - B1       Overrun error (OE)
1958     - B2       Parity error (PE)
1959     - B3       Framing error (FE)
1960     - B4       Break interrupt (BI)
1961     - B5       Transmitter holding register (THRE)
1962     - B6       Transmitter empty (TEMT)
1963     - B7       Error in RCVR FIFO
1964
1965     \param ftdi pointer to ftdi_context
1966     \param status Pointer to store status information in. Must be two bytes.
1967
1968     \retval  0: all fine
1969     \retval -1: unable to retrieve status information
1970     \retval -2: USB device unavailable
1971 */
1972 int ftdi_poll_modem_status(struct ftdi_context *ftdi, unsigned short *status)
1973 {
1974     char usb_val[2];
1975
1976     if (ftdi == NULL || ftdi->usb_dev == NULL)
1977         ftdi_error_return(-2, "USB device unavailable");
1978
1979     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_POLL_MODEM_STATUS_REQUEST, 0, ftdi->index, (unsigned char *)usb_val, 2, ftdi->usb_read_timeout) != 2)
1980         ftdi_error_return(-1, "getting modem status failed");
1981
1982     *status = (usb_val[1] << 8) | usb_val[0];
1983
1984     return 0;
1985 }
1986
1987 /**
1988     Set flowcontrol for ftdi chip
1989
1990     \param ftdi pointer to ftdi_context
1991     \param flowctrl flow control to use. should be
1992            SIO_DISABLE_FLOW_CTRL, SIO_RTS_CTS_HS, SIO_DTR_DSR_HS or SIO_XON_XOFF_HS
1993
1994     \retval  0: all fine
1995     \retval -1: set flow control failed
1996     \retval -2: USB device unavailable
1997 */
1998 int ftdi_setflowctrl(struct ftdi_context *ftdi, int flowctrl)
1999 {
2000     if (ftdi == NULL || ftdi->usb_dev == NULL)
2001         ftdi_error_return(-2, "USB device unavailable");
2002
2003     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
2004                                 SIO_SET_FLOW_CTRL_REQUEST, 0, (flowctrl | ftdi->index),
2005                                 NULL, 0, ftdi->usb_write_timeout) < 0)
2006         ftdi_error_return(-1, "set flow control failed");
2007
2008     return 0;
2009 }
2010
2011 /**
2012     Set dtr line
2013
2014     \param ftdi pointer to ftdi_context
2015     \param state state to set line to (1 or 0)
2016
2017     \retval  0: all fine
2018     \retval -1: set dtr failed
2019     \retval -2: USB device unavailable
2020 */
2021 int ftdi_setdtr(struct ftdi_context *ftdi, int state)
2022 {
2023     unsigned short usb_val;
2024
2025     if (ftdi == NULL || ftdi->usb_dev == NULL)
2026         ftdi_error_return(-2, "USB device unavailable");
2027
2028     if (state)
2029         usb_val = SIO_SET_DTR_HIGH;
2030     else
2031         usb_val = SIO_SET_DTR_LOW;
2032
2033     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
2034                                 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
2035                                 NULL, 0, ftdi->usb_write_timeout) < 0)
2036         ftdi_error_return(-1, "set dtr failed");
2037
2038     return 0;
2039 }
2040
2041 /**
2042     Set rts line
2043
2044     \param ftdi pointer to ftdi_context
2045     \param state state to set line to (1 or 0)
2046
2047     \retval  0: all fine
2048     \retval -1: set rts failed
2049     \retval -2: USB device unavailable
2050 */
2051 int ftdi_setrts(struct ftdi_context *ftdi, int state)
2052 {
2053     unsigned short usb_val;
2054
2055     if (ftdi == NULL || ftdi->usb_dev == NULL)
2056         ftdi_error_return(-2, "USB device unavailable");
2057
2058     if (state)
2059         usb_val = SIO_SET_RTS_HIGH;
2060     else
2061         usb_val = SIO_SET_RTS_LOW;
2062
2063     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
2064                                 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
2065                                 NULL, 0, ftdi->usb_write_timeout) < 0)
2066         ftdi_error_return(-1, "set of rts failed");
2067
2068     return 0;
2069 }
2070
2071 /**
2072     Set dtr and rts line in one pass
2073
2074     \param ftdi pointer to ftdi_context
2075     \param dtr  DTR state to set line to (1 or 0)
2076     \param rts  RTS state to set line to (1 or 0)
2077
2078     \retval  0: all fine
2079     \retval -1: set dtr/rts failed
2080     \retval -2: USB device unavailable
2081  */
2082 int ftdi_setdtr_rts(struct ftdi_context *ftdi, int dtr, int rts)
2083 {
2084     unsigned short usb_val;
2085
2086     if (ftdi == NULL || ftdi->usb_dev == NULL)
2087         ftdi_error_return(-2, "USB device unavailable");
2088
2089     if (dtr)
2090         usb_val = SIO_SET_DTR_HIGH;
2091     else
2092         usb_val = SIO_SET_DTR_LOW;
2093
2094     if (rts)
2095         usb_val |= SIO_SET_RTS_HIGH;
2096     else
2097         usb_val |= SIO_SET_RTS_LOW;
2098
2099     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
2100                                 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
2101                                 NULL, 0, ftdi->usb_write_timeout) < 0)
2102         ftdi_error_return(-1, "set of rts/dtr failed");
2103
2104     return 0;
2105 }
2106
2107 /**
2108     Set the special event character
2109
2110     \param ftdi pointer to ftdi_context
2111     \param eventch Event character
2112     \param enable 0 to disable the event character, non-zero otherwise
2113
2114     \retval  0: all fine
2115     \retval -1: unable to set event character
2116     \retval -2: USB device unavailable
2117 */
2118 int ftdi_set_event_char(struct ftdi_context *ftdi,
2119                         unsigned char eventch, unsigned char enable)
2120 {
2121     unsigned short usb_val;
2122
2123     if (ftdi == NULL || ftdi->usb_dev == NULL)
2124         ftdi_error_return(-2, "USB device unavailable");
2125
2126     usb_val = eventch;
2127     if (enable)
2128         usb_val |= 1 << 8;
2129
2130     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_SET_EVENT_CHAR_REQUEST, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
2131         ftdi_error_return(-1, "setting event character failed");
2132
2133     return 0;
2134 }
2135
2136 /**
2137     Set error character
2138
2139     \param ftdi pointer to ftdi_context
2140     \param errorch Error character
2141     \param enable 0 to disable the error character, non-zero otherwise
2142
2143     \retval  0: all fine
2144     \retval -1: unable to set error character
2145     \retval -2: USB device unavailable
2146 */
2147 int ftdi_set_error_char(struct ftdi_context *ftdi,
2148                         unsigned char errorch, unsigned char enable)
2149 {
2150     unsigned short usb_val;
2151
2152     if (ftdi == NULL || ftdi->usb_dev == NULL)
2153         ftdi_error_return(-2, "USB device unavailable");
2154
2155     usb_val = errorch;
2156     if (enable)
2157         usb_val |= 1 << 8;
2158
2159     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_SET_ERROR_CHAR_REQUEST, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
2160         ftdi_error_return(-1, "setting error character failed");
2161
2162     return 0;
2163 }
2164
2165 /**
2166     Init eeprom with default values.
2167     \param ftdi pointer to ftdi_context
2168
2169 */
2170 void ftdi_eeprom_initdefaults(struct ftdi_context *ftdi)
2171 {
2172     struct ftdi_eeprom *eeprom;
2173
2174     if (ftdi == NULL)
2175         return;
2176
2177     if (ftdi->eeprom == NULL)
2178         return;
2179
2180     eeprom = ftdi->eeprom;
2181     memset(eeprom, 0, sizeof(struct ftdi_eeprom));
2182
2183     eeprom->vendor_id = 0x0403;
2184     eeprom->use_serial = USE_SERIAL_NUM;
2185     if((ftdi->type == TYPE_AM) || (ftdi->type == TYPE_BM) ||
2186        (ftdi->type == TYPE_R))
2187         eeprom->product_id = 0x6001;
2188     else
2189         eeprom->product_id = 0x6010;
2190     if (ftdi->type == TYPE_AM)
2191         eeprom->usb_version = 0x0101;
2192     else
2193         eeprom->usb_version = 0x0200;
2194     eeprom->max_power = 50;
2195
2196     eeprom->manufacturer = NULL;
2197     eeprom->product = NULL;
2198     eeprom->serial = NULL;
2199
2200     if(ftdi->type == TYPE_R)
2201     {
2202         eeprom->max_power = 45;
2203         eeprom->size = 0x80;
2204         eeprom->cbus_function[0] = CBUS_TXLED;
2205         eeprom->cbus_function[1] = CBUS_RXLED;
2206         eeprom->cbus_function[2] = CBUS_TXDEN;
2207         eeprom->cbus_function[3] = CBUS_PWREN;
2208         eeprom->cbus_function[4] = CBUS_SLEEP;
2209     }
2210     else
2211         eeprom->size = -1;
2212 }
2213
2214 /**
2215     Frees allocated memory in eeprom.
2216
2217     \param ftdi pointer to ftdi_context
2218 */
2219 void ftdi_eeprom_free(struct ftdi_context *ftdi)
2220 {
2221     if (!ftdi)
2222         return;
2223     if (ftdi->eeprom)
2224     {
2225         struct ftdi_eeprom *eeprom = ftdi->eeprom;
2226
2227         if (eeprom->manufacturer != 0) {
2228             free(eeprom->manufacturer);
2229             eeprom->manufacturer = 0;
2230         }
2231         if (eeprom->product != 0) {
2232             free(eeprom->product);
2233             eeprom->product = 0;
2234         }
2235         if (eeprom->serial != 0) {
2236             free(eeprom->serial);
2237             eeprom->serial = 0;
2238         }
2239     }
2240 }
2241
2242 /**
2243     Build binary buffer from ftdi_eeprom structure.
2244     Output is suitable for ftdi_write_eeprom().
2245
2246     \param ftdi pointer to ftdi_context
2247
2248     \retval >0: free eeprom size
2249     \retval -1: eeprom size (128 bytes) exceeded by custom strings
2250     \retval -2: Invalid eeprom pointer
2251     \retval -3: Invalid cbus function setting
2252     \retval -4: Chip doesn't support invert
2253     \retval -5: Chip doesn't support high current drive
2254     \retval -6: No connected EEPROM or EEPROM Type unknown
2255 */
2256 int ftdi_eeprom_build(struct ftdi_context *ftdi)
2257 {
2258     unsigned char i, j, k;
2259     unsigned short checksum, value;
2260     unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
2261     int size_check;
2262     struct ftdi_eeprom *eeprom;
2263     unsigned char * output;
2264
2265     if (ftdi == NULL)
2266         ftdi_error_return(-2,"No context");
2267     if (ftdi->eeprom == NULL)
2268         ftdi_error_return(-2,"No eeprom structure");
2269
2270     eeprom= ftdi->eeprom;
2271     output = eeprom->buf;
2272
2273     if(eeprom->chip == -1)
2274         ftdi_error_return(-5,"No connected EEPROM or EEPROM Type unknown");
2275
2276     if ((eeprom->chip == 0x56) || (eeprom->chip == 0x66))
2277         eeprom->size = 0x100;
2278     else
2279         eeprom->size = 0x80;
2280
2281     if (eeprom->manufacturer != NULL)
2282         manufacturer_size = strlen(eeprom->manufacturer);
2283     if (eeprom->product != NULL)
2284         product_size = strlen(eeprom->product);
2285     if (eeprom->serial != NULL)
2286         serial_size = strlen(eeprom->serial);
2287
2288     size_check = 0x80;
2289     switch(ftdi->type)
2290     {
2291     case TYPE_2232H:
2292     case TYPE_4232H:
2293         size_check -= 4;
2294     case TYPE_R:
2295         size_check -= 4;
2296     case TYPE_2232C:
2297         size_check -= 4;
2298     case TYPE_AM:
2299     case TYPE_BM:
2300         size_check -= 0x14*2;
2301     }
2302
2303     size_check -= manufacturer_size*2;
2304     size_check -= product_size*2;
2305     size_check -= serial_size*2;
2306
2307     /* Space for the string type and pointer bytes */
2308     size_check -= -6;
2309
2310     // eeprom size exceeded?
2311     if (size_check < 0)
2312         return (-1);
2313
2314     // empty eeprom
2315     memset (ftdi->eeprom->buf, 0, FTDI_MAX_EEPROM_SIZE);
2316
2317     // Bytes and Bits set for all Types
2318
2319     // Addr 02: Vendor ID
2320     output[0x02] = eeprom->vendor_id;
2321     output[0x03] = eeprom->vendor_id >> 8;
2322
2323     // Addr 04: Product ID
2324     output[0x04] = eeprom->product_id;
2325     output[0x05] = eeprom->product_id >> 8;
2326
2327     // Addr 06: Device release number (0400h for BM features)
2328     output[0x06] = 0x00;
2329     switch (ftdi->type) {
2330         case TYPE_AM:
2331             output[0x07] = 0x02;
2332             break;
2333         case TYPE_BM:
2334             output[0x07] = 0x04;
2335             break;
2336         case TYPE_2232C:
2337             output[0x07] = 0x05;
2338             break;
2339         case TYPE_R:
2340             output[0x07] = 0x06;
2341             break;
2342          case TYPE_2232H:
2343             output[0x07] = 0x07;
2344             break;
2345          case TYPE_4232H:
2346             output[0x07] = 0x08;
2347             break;
2348         default:
2349             output[0x07] = 0x00;
2350     }
2351
2352     // Addr 08: Config descriptor
2353     // Bit 7: always 1
2354     // Bit 6: 1 if this device is self powered, 0 if bus powered
2355     // Bit 5: 1 if this device uses remote wakeup
2356     // Bit 4: 1 if this device is battery powered
2357     j = 0x80;
2358     if (eeprom->self_powered == 1)
2359         j |= 0x40;
2360     if (eeprom->remote_wakeup == 1)
2361         j |= 0x20;
2362     output[0x08] = j;
2363
2364     // Addr 09: Max power consumption: max power = value * 2 mA
2365     output[0x09] = eeprom->max_power;
2366
2367     if(ftdi->type != TYPE_AM)
2368     {
2369         // Addr 0A: Chip configuration
2370         // Bit 7: 0 - reserved
2371         // Bit 6: 0 - reserved
2372         // Bit 5: 0 - reserved
2373         // Bit 4: 1 - Change USB version 
2374         // Bit 3: 1 - Use the serial number string
2375         // Bit 2: 1 - Enable suspend pull downs for lower power
2376         // Bit 1: 1 - Out EndPoint is Isochronous
2377         // Bit 0: 1 - In EndPoint is Isochronous
2378         //
2379         j = 0;
2380         if (eeprom->in_is_isochronous == 1)
2381             j = j | 1;
2382         if (eeprom->out_is_isochronous == 1)
2383             j = j | 2;
2384         output[0x0A] = j;
2385     }
2386
2387     // Dynamic content
2388     // Strings start at 0x94 (TYPE_AM, TYPE_BM)
2389     // 0x96 (TYPE_2232C), 0x98 (TYPE_R) and 0x9a (TYPE_x232H)
2390     i = 0;
2391     switch(ftdi->type)
2392     {
2393     case TYPE_2232H:
2394     case TYPE_4232H:
2395         i += 2;
2396     case TYPE_R:
2397         i += 2;
2398     case TYPE_2232C:
2399         i += 2;
2400     case TYPE_AM:
2401     case TYPE_BM:
2402         i += 0x94;
2403     }
2404     /* Wrap around 0x80 for 128 byte EEPROMS (Internale and 93x46) */
2405     k = eeprom->size -1;
2406
2407     // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
2408     // Addr 0F: Length of manufacturer string
2409     // Output manufacturer
2410     output[0x0E] = i;  // calculate offset
2411     output[i++ & k] = manufacturer_size*2 + 2;
2412     output[i++ & k] = 0x03; // type: string
2413     for (j = 0; j < manufacturer_size; j++)
2414     {
2415         output[i & k] = eeprom->manufacturer[j], i++;
2416         output[i & k] = 0x00, i++;
2417     }
2418     output[0x0F] = manufacturer_size*2 + 2;
2419
2420     // Addr 10: Offset of the product string + 0x80, calculated later
2421     // Addr 11: Length of product string
2422     output[0x10] = i | 0x80;  // calculate offset
2423     output[i & k] = product_size*2 + 2, i++;
2424     output[i & k] = 0x03, i++;
2425     for (j = 0; j < product_size; j++)
2426     {
2427         output[i & k] = eeprom->product[j], i++;
2428         output[i & k] = 0x00, i++;
2429     }
2430     output[0x11] = product_size*2 + 2;
2431     
2432     // Addr 12: Offset of the serial string + 0x80, calculated later
2433     // Addr 13: Length of serial string
2434     output[0x12] = i | 0x80; // calculate offset
2435     output[i & k] = serial_size*2 + 2, i++;
2436     output[i & k] = 0x03, i++;
2437     for (j = 0; j < serial_size; j++)
2438     {
2439         output[i & k] = eeprom->serial[j], i++;
2440         output[i & k] = 0x00, i++;
2441     }
2442     output[0x13] = serial_size*2 + 2;
2443
2444     /* Fixme: ftd2xx seems to append 0x02, 0x03 and 0x01 for PnP = 0 or 0x00 else */
2445     // calculate checksum
2446
2447     /* Bytes and Bits specific to (some) types
2448        Write linear, as this allows easier fixing*/
2449     switch(ftdi->type)
2450     {
2451     case TYPE_AM:
2452         break;
2453     case TYPE_BM:
2454         output[0x0C] = eeprom->usb_version & 0xff;
2455         output[0x0D] = (eeprom->usb_version>>8) & 0xff;
2456         if (eeprom->use_serial == 1)
2457             output[0x0A] |= 0x8;
2458         else
2459             output[0x0A] &= ~0x8;
2460         output[0x14] = eeprom->chip;
2461         break;
2462     case TYPE_2232C:
2463
2464         output[0x00] = (eeprom->channel_a_type);
2465         if ( eeprom->channel_a_driver == DRIVER_VCP)
2466             output[0x00] |= DRIVER_VCP;
2467         else
2468             output[0x00] &= ~DRIVER_VCP;
2469             
2470         if ( eeprom->high_current_a == HIGH_CURRENT_DRIVE)
2471             output[0x00] |= HIGH_CURRENT_DRIVE;
2472         else
2473             output[0x00] &= ~HIGH_CURRENT_DRIVE;
2474
2475         output[0x01] = (eeprom->channel_b_type);
2476         if ( eeprom->channel_b_driver == DRIVER_VCP)
2477             output[0x01] |= DRIVER_VCP;
2478         else
2479             output[0x01] &= ~DRIVER_VCP;
2480             
2481         if ( eeprom->high_current_b == HIGH_CURRENT_DRIVE)
2482             output[0x01] |= HIGH_CURRENT_DRIVE;
2483         else
2484             output[0x01] &= ~HIGH_CURRENT_DRIVE;
2485
2486         if (eeprom->in_is_isochronous == 1)
2487             output[0x0A] |= 0x1;
2488         else
2489             output[0x0A] &= ~0x1;
2490         if (eeprom->out_is_isochronous == 1)
2491             output[0x0A] |= 0x2;
2492         else
2493             output[0x0A] &= ~0x2;
2494         if (eeprom->suspend_pull_downs == 1)
2495             output[0x0A] |= 0x4;
2496         else
2497             output[0x0A] &= ~0x4;
2498         if (eeprom->use_serial == USE_SERIAL_NUM )
2499             output[0x0A] |= USE_SERIAL_NUM;
2500         else
2501             output[0x0A] &= ~0x8;
2502         output[0x0C] = eeprom->usb_version & 0xff;
2503         output[0x0D] = (eeprom->usb_version>>8) & 0xff;
2504         output[0x14] = eeprom->chip;
2505         break;
2506     case TYPE_R:
2507         if(eeprom->high_current == HIGH_CURRENT_DRIVE_R)
2508             output[0x00] |= HIGH_CURRENT_DRIVE_R;
2509         output[0x01] = 0x40; /* Hard coded Endpoint Size*/
2510         
2511         if (eeprom->suspend_pull_downs == 1)
2512             output[0x0A] |= 0x4;
2513         else
2514             output[0x0A] &= ~0x4;
2515         if (eeprom->use_serial == USE_SERIAL_NUM)
2516             output[0x0A] |= USE_SERIAL_NUM;
2517         else
2518             output[0x0A] &= ~0x8;
2519         output[0x0B] = eeprom->invert;
2520         output[0x0C] = eeprom->usb_version & 0xff;
2521         output[0x0D] = (eeprom->usb_version>>8) & 0xff;
2522         
2523         if(eeprom->cbus_function[0] > CBUS_BB)
2524             output[0x14] = CBUS_TXLED;
2525         else
2526             output[0x14] = eeprom->cbus_function[0];
2527         
2528         if(eeprom->cbus_function[1] > CBUS_BB)
2529             output[0x14] |= CBUS_RXLED<<4;
2530         else
2531             output[0x14] |= eeprom->cbus_function[1]<<4;
2532         
2533         if(eeprom->cbus_function[2] > CBUS_BB)
2534             output[0x15] = CBUS_TXDEN;
2535         else
2536             output[0x15] = eeprom->cbus_function[2];
2537         
2538         if(eeprom->cbus_function[3] > CBUS_BB)
2539             output[0x15] |= CBUS_PWREN<<4;
2540         else
2541             output[0x15] |= eeprom->cbus_function[3]<<4;
2542         
2543         if(eeprom->cbus_function[4] > CBUS_CLK6)
2544             output[0x16] = CBUS_SLEEP;
2545         else
2546             output[0x16] = eeprom->cbus_function[4];
2547         break;
2548     case TYPE_2232H:
2549         output[0x00] = (eeprom->channel_a_type);
2550         if ( eeprom->channel_a_driver == DRIVER_VCP)
2551             output[0x00] |= DRIVER_VCP;
2552         else
2553             output[0x00] &= ~DRIVER_VCP;
2554         
2555         output[0x01] = (eeprom->channel_b_type);
2556         if ( eeprom->channel_b_driver == DRIVER_VCP)
2557             output[0x01] |= DRIVER_VCP;
2558         else
2559             output[0x01] &= ~DRIVER_VCP;
2560         if(eeprom->suspend_dbus7 == SUSPEND_DBUS7)
2561             output[0x01] |= SUSPEND_DBUS7;
2562         else
2563             output[0x01] &= ~SUSPEND_DBUS7;
2564         
2565         if(eeprom->group0_drive > DRIVE_16MA)
2566             output[0x0c] |= DRIVE_16MA;
2567         else
2568             output[0x0c] |= eeprom->group0_drive;
2569         if (eeprom->group0_schmitt == IS_SCHMITT)
2570             output[0x0c] |= IS_SCHMITT;
2571         if (eeprom->group0_slew == SLOW_SLEW)
2572             output[0x0c] |= SLOW_SLEW;
2573
2574         if(eeprom->group1_drive > DRIVE_16MA)
2575             output[0x0c] |= DRIVE_16MA<<4;
2576         else
2577             output[0x0c] |= eeprom->group1_drive<<4;
2578         if (eeprom->group1_schmitt == IS_SCHMITT)
2579             output[0x0c] |= IS_SCHMITT<<4;
2580         if (eeprom->group1_slew == SLOW_SLEW)
2581             output[0x0c] |= SLOW_SLEW<<4;
2582         
2583         if(eeprom->group2_drive > DRIVE_16MA)
2584             output[0x0d] |= DRIVE_16MA;
2585         else
2586             output[0x0d] |= eeprom->group2_drive;
2587         if (eeprom->group2_schmitt == IS_SCHMITT)
2588             output[0x0d] |= IS_SCHMITT;
2589         if (eeprom->group2_slew == SLOW_SLEW)
2590             output[0x0d] |= SLOW_SLEW;
2591
2592         if(eeprom->group3_drive > DRIVE_16MA)
2593             output[0x0d] |= DRIVE_16MA<<4;
2594         else
2595             output[0x0d] |= eeprom->group3_drive<<4;
2596         if (eeprom->group3_schmitt == IS_SCHMITT)
2597             output[0x0d] |= IS_SCHMITT<<4;
2598         if (eeprom->group3_slew == SLOW_SLEW)
2599             output[0x0d] |= SLOW_SLEW<<4;
2600
2601         output[0x18] = eeprom->chip;
2602
2603         break;
2604     }
2605
2606     // calculate checksum
2607     checksum = 0xAAAA;
2608
2609     for (i = 0; i < eeprom->size/2-1; i++)
2610     {
2611         value = output[i*2];
2612         value += output[(i*2)+1] << 8;
2613
2614         checksum = value^checksum;
2615         checksum = (checksum << 1) | (checksum >> 15);
2616     }
2617
2618     output[eeprom->size-2] = checksum;
2619     output[eeprom->size-1] = checksum >> 8;
2620
2621     return size_check;
2622 }
2623
2624 /**
2625    Decode binary EEPROM image into an ftdi_eeprom structure.
2626
2627    \param ftdi pointer to ftdi_context
2628    \param verbose Decode EEPROM on stdout
2629    
2630    \retval 0: all fine
2631    \retval -1: something went wrong
2632
2633    FIXME: How to pass size? How to handle size field in ftdi_eeprom?
2634    FIXME: Strings are malloc'ed here and should be freed somewhere
2635 */
2636 int ftdi_eeprom_decode(struct ftdi_context *ftdi, int verbose)
2637 {
2638     unsigned char i, j;
2639     unsigned short checksum, eeprom_checksum, value;
2640     unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
2641     int eeprom_size;
2642     struct ftdi_eeprom *eeprom;
2643     unsigned char *buf = ftdi->eeprom->buf;
2644     int release;
2645
2646     if (ftdi == NULL)
2647         ftdi_error_return(-1,"No context");
2648     if (ftdi->eeprom == NULL)
2649         ftdi_error_return(-1,"No eeprom structure");
2650  
2651     eeprom = ftdi->eeprom;
2652     eeprom_size = eeprom->size;
2653
2654     // Addr 02: Vendor ID
2655     eeprom->vendor_id = buf[0x02] + (buf[0x03] << 8);
2656
2657     // Addr 04: Product ID
2658     eeprom->product_id = buf[0x04] + (buf[0x05] << 8);
2659
2660     release = buf[0x06] + (buf[0x07]<<8);
2661
2662     // Addr 08: Config descriptor
2663     // Bit 7: always 1
2664     // Bit 6: 1 if this device is self powered, 0 if bus powered
2665     // Bit 5: 1 if this device uses remote wakeup
2666     // Bit 4: 1 if this device is battery powered
2667     eeprom->self_powered = buf[0x08] & 0x40;
2668     eeprom->remote_wakeup = buf[0x08] & 0x20;;
2669
2670     // Addr 09: Max power consumption: max power = value * 2 mA
2671     eeprom->max_power = buf[0x09];
2672
2673     // Addr 0A: Chip configuration
2674     // Bit 7: 0 - reserved
2675     // Bit 6: 0 - reserved
2676     // Bit 5: 0 - reserved
2677     // Bit 4: 1 - Change USB version
2678     //            Not seen on FT2232(D)
2679     // Bit 3: 1 - Use the serial number string
2680     // Bit 2: 1 - Enable suspend pull downs for lower power
2681     // Bit 1: 1 - Out EndPoint is Isochronous
2682     // Bit 0: 1 - In EndPoint is Isochronous
2683     //
2684     eeprom->in_is_isochronous  = buf[0x0A]&0x01;
2685     eeprom->out_is_isochronous = buf[0x0A]&0x02;
2686     eeprom->suspend_pull_downs = buf[0x0A]&0x04;
2687     eeprom->use_serial         = buf[0x0A] & USE_SERIAL_NUM;
2688     if(buf[0x0A]&0x10)
2689         fprintf(stderr,
2690                 "EEPROM byte[0x0a] Bit 4 unexpected set. If this happened with the EEPROM\n"
2691                 "programmed by FTDI tools, please report to libftdi@developer.intra2net.com\n");
2692
2693
2694     // Addr 0C: USB version low byte when 0x0A
2695     // Addr 0D: USB version high byte when 0x0A 
2696     eeprom->usb_version = buf[0x0C] + (buf[0x0D] << 8);
2697
2698     // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
2699     // Addr 0F: Length of manufacturer string
2700     manufacturer_size = buf[0x0F]/2;
2701     if (manufacturer_size > 0) 
2702     {
2703         eeprom->manufacturer = malloc(manufacturer_size);
2704         if (eeprom->manufacturer)
2705         {
2706             // Decode manufacturer
2707             i = buf[0x0E] & (eeprom_size -1); // offset
2708             for (j=0;j<manufacturer_size-1;j++)
2709             {
2710                 eeprom->manufacturer[j] = buf[2*j+i+2];
2711             }
2712             eeprom->manufacturer[j] = '\0';
2713         }
2714     }
2715     else eeprom->manufacturer = NULL;
2716
2717     // Addr 10: Offset of the product string + 0x80, calculated later
2718     // Addr 11: Length of product string
2719     product_size = buf[0x11]/2;
2720     if (product_size > 0)
2721     {
2722         eeprom->product = malloc(product_size);
2723         if(eeprom->product)
2724         {
2725             // Decode product name
2726             i = buf[0x10] & (eeprom_size -1); // offset
2727             for (j=0;j<product_size-1;j++)
2728             {
2729                 eeprom->product[j] = buf[2*j+i+2];
2730             }
2731             eeprom->product[j] = '\0';
2732         }
2733     }
2734     else eeprom->product = NULL;
2735
2736     // Addr 12: Offset of the serial string + 0x80, calculated later
2737     // Addr 13: Length of serial string
2738     serial_size = buf[0x13]/2;
2739     if (serial_size > 0)
2740     {
2741         eeprom->serial = malloc(serial_size);
2742         if(eeprom->serial)
2743         {
2744             // Decode serial
2745             i = buf[0x12] & (eeprom_size -1); // offset
2746             for (j=0;j<serial_size-1;j++)
2747             {
2748                 eeprom->serial[j] = buf[2*j+i+2];
2749             }
2750             eeprom->serial[j] = '\0';
2751         }
2752     }
2753     else eeprom->serial = NULL;
2754
2755     // verify checksum
2756     checksum = 0xAAAA;
2757
2758     for (i = 0; i < eeprom_size/2-1; i++)
2759     {
2760         value = buf[i*2];
2761         value += buf[(i*2)+1] << 8;
2762
2763         checksum = value^checksum;
2764         checksum = (checksum << 1) | (checksum >> 15);
2765     }
2766
2767     eeprom_checksum = buf[eeprom_size-2] + (buf[eeprom_size-1] << 8);
2768
2769     if (eeprom_checksum != checksum)
2770     {
2771         fprintf(stderr, "Checksum Error: %04x %04x\n", checksum, eeprom_checksum);
2772         ftdi_error_return(-1,"EEPROM checksum error");
2773     }
2774
2775     eeprom->channel_a_type   = 0;
2776     if ((ftdi->type == TYPE_AM) || (ftdi->type == TYPE_BM))
2777     {
2778         eeprom->chip = -1;
2779     }
2780     else if(ftdi->type == TYPE_2232C)
2781     {
2782         eeprom->channel_a_type   = buf[0x00] & 0x7;
2783         eeprom->channel_a_driver = buf[0x00] & DRIVER_VCP;
2784         eeprom->high_current_a   = buf[0x00] & HIGH_CURRENT_DRIVE;
2785         eeprom->channel_b_type   = buf[0x01] & 0x7;
2786         eeprom->channel_b_driver = buf[0x01] & DRIVER_VCP;
2787         eeprom->high_current_b   = buf[0x01] & HIGH_CURRENT_DRIVE;
2788         eeprom->chip = buf[0x14];
2789     }
2790     else if(ftdi->type == TYPE_R)
2791     {
2792         /* TYPE_R flags D2XX, not VCP as all others*/
2793         eeprom->channel_a_driver = (~buf[0x00]) & DRIVER_VCP;
2794         eeprom->high_current     = buf[0x00] & HIGH_CURRENT_DRIVE_R;
2795         if( (buf[0x01]&0x40) != 0x40)
2796         fprintf(stderr,
2797                 "TYPE_R EEPROM byte[0x01] Bit 6 unexpected Endpoint size."
2798                 " If this happened with the\n"
2799                 " EEPROM programmed by FTDI tools, please report "
2800                 "to libftdi@developer.intra2net.com\n");
2801
2802         eeprom->chip = buf[0x16];
2803         // Addr 0B: Invert data lines
2804         // Works only on FT232R, not FT245R, but no way to distinguish
2805         eeprom->invert = buf[0x0B];
2806         // Addr 14: CBUS function: CBUS0, CBUS1
2807         // Addr 15: CBUS function: CBUS2, CBUS3
2808         // Addr 16: CBUS function: CBUS5
2809         eeprom->cbus_function[0] = buf[0x14] & 0x0f;
2810         eeprom->cbus_function[1] = (buf[0x14] >> 4) & 0x0f;
2811         eeprom->cbus_function[2] = buf[0x15] & 0x0f;
2812         eeprom->cbus_function[3] = (buf[0x15] >> 4) & 0x0f;
2813         eeprom->cbus_function[4] = buf[0x16] & 0x0f;
2814     }
2815     else if ((ftdi->type == TYPE_2232H) ||(ftdi->type == TYPE_4232H)) 
2816     {
2817         eeprom->high_current     = buf[0x00] & HIGH_CURRENT_DRIVE_R;
2818         eeprom->channel_a_driver = buf[0x00] & DRIVER_VCP;
2819         eeprom->channel_b_type   = buf[0x01] & 0x7;
2820         eeprom->channel_b_driver = buf[0x01] & DRIVER_VCP;
2821
2822         if(ftdi->type == TYPE_2232H)
2823             eeprom->suspend_dbus7    = buf[0x01] & SUSPEND_DBUS7;
2824
2825         eeprom->chip = buf[0x18];
2826         eeprom->group0_drive   =  buf[0x0c]       & DRIVE_16MA;
2827         eeprom->group0_schmitt =  buf[0x0c]       & IS_SCHMITT;
2828         eeprom->group0_slew    =  buf[0x0c]       & SLOW_SLEW;
2829         eeprom->group1_drive   = (buf[0x0c] >> 4) & 0x3;
2830         eeprom->group1_schmitt = (buf[0x0c] >> 4) & IS_SCHMITT;
2831         eeprom->group1_slew    = (buf[0x0c] >> 4) & SLOW_SLEW;
2832         eeprom->group2_drive   =  buf[0x0d]       & DRIVE_16MA;
2833         eeprom->group2_schmitt =  buf[0x0d]       & IS_SCHMITT;
2834         eeprom->group2_slew    =  buf[0x0d]       & SLOW_SLEW;
2835         eeprom->group3_drive   = (buf[0x0d] >> 4) & DRIVE_16MA;
2836         eeprom->group3_schmitt = (buf[0x0d] >> 4) & IS_SCHMITT;
2837         eeprom->group3_slew    = (buf[0x0d] >> 4) & SLOW_SLEW;
2838     }
2839     
2840     if(verbose)
2841     {
2842         char *channel_mode[] = {"UART","245","CPU", "unknown", "OPTO"};
2843         fprintf(stdout, "VID:     0x%04x\n",eeprom->vendor_id);
2844         fprintf(stdout, "PID:     0x%04x\n",eeprom->product_id);
2845         fprintf(stdout, "Release: 0x%04x\n",release);
2846
2847         if(eeprom->self_powered)
2848             fprintf(stdout, "Self-Powered%s", (eeprom->remote_wakeup)?", USB Remote Wake Up\n":"\n");
2849         else
2850             fprintf(stdout, "Bus Powered: %3d mA%s", eeprom->max_power * 2,
2851                     (eeprom->remote_wakeup)?" USB Remote Wake Up\n":"\n");
2852         if(eeprom->manufacturer)
2853             fprintf(stdout, "Manufacturer: %s\n",eeprom->manufacturer);
2854         if(eeprom->product)
2855             fprintf(stdout, "Product:      %s\n",eeprom->product);
2856         if(eeprom->serial)
2857             fprintf(stdout, "Serial:       %s\n",eeprom->serial);
2858         fprintf(stdout,     "Checksum      : %04x\n", checksum);
2859         if (ftdi->type == TYPE_R)
2860             fprintf(stdout,     "Internal EEPROM\n");
2861         else if (eeprom->chip >= 0x46)
2862             fprintf(stdout,     "Attached EEPROM: 93x%02x\n", eeprom->chip);
2863         if(eeprom->suspend_dbus7)
2864             fprintf(stdout, "Suspend on DBUS7\n");            
2865         if(eeprom->suspend_pull_downs)
2866             fprintf(stdout, "Pull IO pins low during suspend\n");
2867         if(eeprom->remote_wakeup)
2868             fprintf(stdout, "Enable Remote Wake Up\n");
2869         if (ftdi->type >= TYPE_2232C)
2870             fprintf(stdout,"Channel A has Mode %s%s%s\n", 
2871                     channel_mode[eeprom->channel_a_type],
2872                     (eeprom->channel_a_driver)?" VCP":"",
2873                     (eeprom->high_current_a)?" High Current IO":"");
2874         if ((ftdi->type >= TYPE_2232C) && (ftdi->type != TYPE_R)) 
2875             fprintf(stdout,"Channel B has Mode %s%s%s\n", 
2876                     channel_mode[eeprom->channel_b_type],
2877                     (eeprom->channel_b_driver)?" VCP":"",
2878                     (eeprom->high_current_b)?" High Current IO":"");
2879         if ((ftdi->type == TYPE_2232H) || (ftdi->type == TYPE_4232H)) 
2880         {
2881             fprintf(stdout,"%s has %d mA drive%s%s\n",
2882                     (ftdi->type == TYPE_2232H)?"AL":"A",
2883                     (eeprom->group0_drive+1) *4,
2884                     (eeprom->group0_schmitt)?" Schmitt Input":"",
2885                     (eeprom->group0_slew)?" Slow Slew":"");
2886             fprintf(stdout,"%s has %d mA drive%s%s\n",
2887                     (ftdi->type == TYPE_2232H)?"AH":"B",
2888                     (eeprom->group1_drive+1) *4,
2889                     (eeprom->group1_schmitt)?" Schmitt Input":"",
2890                     (eeprom->group1_slew)?" Slow Slew":"");
2891             fprintf(stdout,"%s has %d mA drive%s%s\n",
2892                     (ftdi->type == TYPE_2232H)?"BL":"C",
2893                     (eeprom->group2_drive+1) *4,
2894                     (eeprom->group2_schmitt)?" Schmitt Input":"",
2895                     (eeprom->group2_slew)?" Slow Slew":"");
2896             fprintf(stdout,"%s has %d mA drive%s%s\n",
2897                     (ftdi->type == TYPE_2232H)?"BH":"D",
2898                     (eeprom->group3_drive+1) *4,
2899                     (eeprom->group3_schmitt)?" Schmitt Input":"",
2900                     (eeprom->group3_slew)?" Slow Slew":"");
2901         }
2902         if (ftdi->type == TYPE_R)
2903         {
2904             char *cbus_mux[] = {"TXDEN","PWREN","RXLED", "TXLED","TX+RXLED",
2905                                 "SLEEP","CLK48","CLK24","CLK12","CLK6",
2906                                 "IOMODE","BB_WR","BB_RD"};
2907             char *cbus_BB[] = {"RXF","TXE","RD", "WR"};
2908             int i;
2909             
2910             if(eeprom->invert)
2911             { 
2912                 char *r_bits[] = {"TXD","RXD","RTS", "CTS","DTR","DSR","DCD","RI"};
2913                 fprintf(stdout,"Inverted bits:");
2914                 for (i=0; i<8; i++)
2915                     if((eeprom->invert & (1<<i)) == (1<<i))
2916                         fprintf(stdout," %s",r_bits[i]);
2917                 fprintf(stdout,"\n");
2918             }
2919             for(i=0; i<5; i++)
2920             {
2921                 if(eeprom->cbus_function[i]<CBUS_BB)
2922                     fprintf(stdout,"C%d Function: %s\n", i,
2923                             cbus_mux[eeprom->cbus_function[i]]);
2924                 else
2925                     fprintf(stdout,"C%d BB Function: %s\n", i,
2926                             cbus_BB[i]);
2927             }
2928         }
2929     }
2930     return 0;
2931 }
2932
2933 /**
2934     Read eeprom location
2935
2936     \param ftdi pointer to ftdi_context
2937     \param eeprom_addr Address of eeprom location to be read
2938     \param eeprom_val Pointer to store read eeprom location
2939
2940     \retval  0: all fine
2941     \retval -1: read failed
2942     \retval -2: USB device unavailable
2943 */
2944 int ftdi_read_eeprom_location (struct ftdi_context *ftdi, int eeprom_addr, unsigned short *eeprom_val)
2945 {
2946     if (ftdi == NULL || ftdi->usb_dev == NULL)
2947         ftdi_error_return(-2, "USB device unavailable");
2948
2949     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_READ_EEPROM_REQUEST, 0, eeprom_addr, (unsigned char *)eeprom_val, 2, ftdi->usb_read_timeout) != 2)
2950         ftdi_error_return(-1, "reading eeprom failed");
2951
2952     return 0;
2953 }
2954
2955 /**
2956     Read eeprom
2957
2958     \param ftdi pointer to ftdi_context
2959
2960     \retval  0: all fine
2961     \retval -1: read failed
2962     \retval -2: USB device unavailable
2963 */
2964 int ftdi_read_eeprom(struct ftdi_context *ftdi)
2965 {
2966     int i;
2967     unsigned char *buf;
2968
2969     if (ftdi == NULL || ftdi->usb_dev == NULL)
2970         ftdi_error_return(-2, "USB device unavailable");
2971     buf = ftdi->eeprom->buf;
2972
2973     for (i = 0; i < FTDI_MAX_EEPROM_SIZE/2; i++)
2974     {
2975         if (libusb_control_transfer(
2976                 ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE,SIO_READ_EEPROM_REQUEST, 0, i,
2977                 buf+(i*2), 2, ftdi->usb_read_timeout) != 2)
2978             ftdi_error_return(-1, "reading eeprom failed");
2979     }
2980
2981     if (ftdi->type == TYPE_R)
2982         ftdi->eeprom->size = 0x80;
2983     /*    Guesses size of eeprom by comparing halves 
2984           - will not work with blank eeprom */
2985     else if (strrchr((const char *)buf, 0xff) == ((const char *)buf +FTDI_MAX_EEPROM_SIZE -1))
2986         ftdi->eeprom->size = -1;
2987     else if(memcmp(buf,&buf[0x80],0x80) == 0)
2988         ftdi->eeprom->size = 0x80;
2989     else if(memcmp(buf,&buf[0x40],0x40) == 0)
2990         ftdi->eeprom->size = 0x40;
2991     else
2992         ftdi->eeprom->size = 0x100;
2993     return 0;
2994 }
2995
2996 /*
2997     ftdi_read_chipid_shift does the bitshift operation needed for the FTDIChip-ID
2998     Function is only used internally
2999     \internal
3000 */
3001 static unsigned char ftdi_read_chipid_shift(unsigned char value)
3002 {
3003     return ((value & 1) << 1) |
3004            ((value & 2) << 5) |
3005            ((value & 4) >> 2) |
3006            ((value & 8) << 4) |
3007            ((value & 16) >> 1) |
3008            ((value & 32) >> 1) |
3009            ((value & 64) >> 4) |
3010            ((value & 128) >> 2);
3011 }
3012
3013 /**
3014     Read the FTDIChip-ID from R-type devices
3015
3016     \param ftdi pointer to ftdi_context
3017     \param chipid Pointer to store FTDIChip-ID
3018
3019     \retval  0: all fine
3020     \retval -1: read failed
3021     \retval -2: USB device unavailable
3022 */
3023 int ftdi_read_chipid(struct ftdi_context *ftdi, unsigned int *chipid)
3024 {
3025     unsigned int a = 0, b = 0;
3026
3027     if (ftdi == NULL || ftdi->usb_dev == NULL)
3028         ftdi_error_return(-2, "USB device unavailable");
3029
3030     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_READ_EEPROM_REQUEST, 0, 0x43, (unsigned char *)&a, 2, ftdi->usb_read_timeout) == 2)
3031     {
3032         a = a << 8 | a >> 8;
3033         if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_READ_EEPROM_REQUEST, 0, 0x44, (unsigned char *)&b, 2, ftdi->usb_read_timeout) == 2)
3034         {
3035             b = b << 8 | b >> 8;
3036             a = (a << 16) | (b & 0xFFFF);
3037             a = ftdi_read_chipid_shift(a) | ftdi_read_chipid_shift(a>>8)<<8
3038                 | ftdi_read_chipid_shift(a>>16)<<16 | ftdi_read_chipid_shift(a>>24)<<24;
3039             *chipid = a ^ 0xa5f0f7d1;
3040             return 0;
3041         }
3042     }
3043
3044     ftdi_error_return(-1, "read of FTDIChip-ID failed");
3045 }
3046
3047 /**
3048     Write eeprom location
3049
3050     \param ftdi pointer to ftdi_context
3051     \param eeprom_addr Address of eeprom location to be written
3052     \param eeprom_val Value to be written
3053
3054     \retval  0: all fine
3055     \retval -1: read failed
3056     \retval -2: USB device unavailable
3057 */
3058 int ftdi_write_eeprom_location(struct ftdi_context *ftdi, int eeprom_addr, unsigned short eeprom_val)
3059 {
3060     if (ftdi == NULL || ftdi->usb_dev == NULL)
3061         ftdi_error_return(-2, "USB device unavailable");
3062
3063     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
3064                                     SIO_WRITE_EEPROM_REQUEST, eeprom_val, eeprom_addr,
3065                                     NULL, 0, ftdi->usb_write_timeout) != 0)
3066         ftdi_error_return(-1, "unable to write eeprom");
3067
3068     return 0;
3069 }
3070
3071 /**
3072     Write eeprom
3073
3074     \param ftdi pointer to ftdi_context
3075  
3076     \retval  0: all fine
3077     \retval -1: read failed
3078     \retval -2: USB device unavailable
3079 */
3080 int ftdi_write_eeprom(struct ftdi_context *ftdi)
3081 {
3082     unsigned short usb_val, status;
3083     int i, ret;
3084     unsigned char *eeprom;
3085
3086     if (ftdi == NULL || ftdi->usb_dev == NULL)
3087         ftdi_error_return(-2, "USB device unavailable");
3088     eeprom = ftdi->eeprom->buf;
3089
3090     /* These commands were traced while running MProg */
3091     if ((ret = ftdi_usb_reset(ftdi)) != 0)
3092         return ret;
3093     if ((ret = ftdi_poll_modem_status(ftdi, &status)) != 0)
3094         return ret;
3095     if ((ret = ftdi_set_latency_timer(ftdi, 0x77)) != 0)
3096         return ret;
3097
3098     for (i = 0; i < ftdi->eeprom->size/2; i++)
3099     {
3100         usb_val = eeprom[i*2];
3101         usb_val += eeprom[(i*2)+1] << 8;
3102         if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
3103                                     SIO_WRITE_EEPROM_REQUEST, usb_val, i,
3104                                     NULL, 0, ftdi->usb_write_timeout) < 0)
3105             ftdi_error_return(-1, "unable to write eeprom");
3106     }
3107
3108     return 0;
3109 }
3110
3111 /**
3112     Erase eeprom
3113
3114     This is not supported on FT232R/FT245R according to the MProg manual from FTDI.
3115
3116     \param ftdi pointer to ftdi_context
3117
3118     \retval  0: all fine
3119     \retval -1: erase failed
3120     \retval -2: USB device unavailable
3121     \retval -3: Writing magic failed
3122     \retval -4: Read EEPROM failed
3123     \retval -5: Unexpected EEPROM value
3124 */
3125 #define MAGIC 0x55aa
3126 int ftdi_erase_eeprom(struct ftdi_context *ftdi)
3127 {
3128     unsigned short eeprom_value;
3129     if (ftdi == NULL || ftdi->usb_dev == NULL)
3130         ftdi_error_return(-2, "USB device unavailable");
3131
3132     if(ftdi->type == TYPE_R)
3133     {
3134         ftdi->eeprom->chip = 0;
3135         return 0;
3136     }
3137
3138     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_ERASE_EEPROM_REQUEST, 
3139                                 0, 0, NULL, 0, ftdi->usb_write_timeout) < 0)
3140         ftdi_error_return(-1, "unable to erase eeprom");
3141
3142     
3143     /* detect chip type by writing 0x55AA as magic at word position 0xc0
3144        Chip is 93x46 if magic is read at word position 0x00, as wraparound happens around 0x40
3145        Chip is 93x56 if magic is read at word position 0x40, as wraparound happens around 0x80
3146        Chip is 93x66 if magic is only read at word position 0xc0*/
3147     if( ftdi_write_eeprom_location(ftdi, 0xc0, MAGIC))
3148         ftdi_error_return(-3, "Writing magic failed");
3149     if (ftdi_read_eeprom_location( ftdi, 0x00, &eeprom_value)) 
3150         ftdi_error_return(-4, "Reading failed failed");
3151     if(eeprom_value == MAGIC)
3152     {
3153         ftdi->eeprom->chip = 0x46;
3154     }
3155     else 
3156     {
3157         if (ftdi_read_eeprom_location( ftdi, 0x40, &eeprom_value)) 
3158             ftdi_error_return(-4, "Reading failed failed");
3159         if(eeprom_value == MAGIC)
3160             ftdi->eeprom->chip = 0x56;
3161         else 
3162         {
3163             if (ftdi_read_eeprom_location( ftdi, 0xc0, &eeprom_value)) 
3164                 ftdi_error_return(-4, "Reading failed failed");
3165             if(eeprom_value == MAGIC)
3166                 ftdi->eeprom->chip = 0x66;
3167             else
3168             {
3169                 ftdi->eeprom->chip = -1;
3170             }
3171         }
3172     }
3173     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_ERASE_EEPROM_REQUEST, 
3174                                 0, 0, NULL, 0, ftdi->usb_write_timeout) < 0)
3175         ftdi_error_return(-1, "unable to erase eeprom");
3176     return 0;
3177 }
3178
3179 /**
3180     Get string representation for last error code
3181
3182     \param ftdi pointer to ftdi_context
3183
3184     \retval Pointer to error string
3185 */
3186 char *ftdi_get_error_string (struct ftdi_context *ftdi)
3187 {
3188     if (ftdi == NULL)
3189         return "";
3190
3191     return ftdi->error_str;
3192 }
3193
3194 /* @} end of doxygen libftdi group */