Round the returned baudrate in ftdi_to_clkbits and adjust the changed values in test...
[libftdi] / src / ftdi.c
1 /***************************************************************************
2                           ftdi.c  -  description
3                              -------------------
4     begin                : Fri Apr 4 2003
5     copyright            : (C) 2003-2011 by Intra2net AG and the libftdi developers
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         if(ftdi->eeprom)
67             ftdi->eeprom->initialized_for_connected_device = 0;
68     }
69 }
70
71 /**
72     Initializes a ftdi_context.
73
74     \param ftdi pointer to ftdi_context
75
76     \retval  0: all fine
77     \retval -1: couldn't allocate read buffer
78     \retval -2: couldn't allocate struct  buffer
79     \retval -3: libusb_init() failed
80
81     \remark This should be called before all functions
82 */
83 int ftdi_init(struct ftdi_context *ftdi)
84 {
85     struct ftdi_eeprom* eeprom = (struct ftdi_eeprom *)malloc(sizeof(struct ftdi_eeprom));
86     ftdi->usb_ctx = NULL;
87     ftdi->usb_dev = NULL;
88     ftdi->usb_read_timeout = 5000;
89     ftdi->usb_write_timeout = 5000;
90
91     ftdi->type = TYPE_BM;    /* chip type */
92     ftdi->baudrate = -1;
93     ftdi->bitbang_enabled = 0;  /* 0: normal mode 1: any of the bitbang modes enabled */
94
95     ftdi->readbuffer = NULL;
96     ftdi->readbuffer_offset = 0;
97     ftdi->readbuffer_remaining = 0;
98     ftdi->writebuffer_chunksize = 4096;
99     ftdi->max_packet_size = 0;
100     ftdi->error_str = NULL;
101     ftdi->module_detach_mode = AUTO_DETACH_SIO_MODULE;
102
103     if (libusb_init(&ftdi->usb_ctx) < 0)
104         ftdi_error_return(-3, "libusb_init() failed");
105
106     ftdi_set_interface(ftdi, INTERFACE_ANY);
107     ftdi->bitbang_mode = 1; /* when bitbang is enabled this holds the number of the mode  */
108
109     if (eeprom == 0)
110         ftdi_error_return(-2, "Can't malloc struct ftdi_eeprom");
111     memset(eeprom, 0, sizeof(struct ftdi_eeprom));
112     ftdi->eeprom = eeprom;
113
114     /* All fine. Now allocate the readbuffer */
115     return ftdi_read_data_set_chunksize(ftdi, 4096);
116 }
117
118 /**
119     Allocate and initialize a new ftdi_context
120
121     \return a pointer to a new ftdi_context, or NULL on failure
122 */
123 struct ftdi_context *ftdi_new(void)
124 {
125     struct ftdi_context * ftdi = (struct ftdi_context *)malloc(sizeof(struct ftdi_context));
126
127     if (ftdi == NULL)
128     {
129         return NULL;
130     }
131
132     if (ftdi_init(ftdi) != 0)
133     {
134         free(ftdi);
135         return NULL;
136     }
137
138     return ftdi;
139 }
140
141 /**
142     Open selected channels on a chip, otherwise use first channel.
143
144     \param ftdi pointer to ftdi_context
145     \param interface Interface to use for FT2232C/2232H/4232H chips.
146
147     \retval  0: all fine
148     \retval -1: unknown interface
149     \retval -2: USB device unavailable
150 */
151 int ftdi_set_interface(struct ftdi_context *ftdi, enum ftdi_interface interface)
152 {
153     if (ftdi == NULL)
154         ftdi_error_return(-2, "USB device unavailable");
155
156     switch (interface)
157     {
158         case INTERFACE_ANY:
159         case INTERFACE_A:
160             ftdi->interface = 0;
161             ftdi->index     = INTERFACE_A;
162             ftdi->in_ep     = 0x02;
163             ftdi->out_ep    = 0x81;
164             break;
165         case INTERFACE_B:
166             ftdi->interface = 1;
167             ftdi->index     = INTERFACE_B;
168             ftdi->in_ep     = 0x04;
169             ftdi->out_ep    = 0x83;
170             break;
171         case INTERFACE_C:
172             ftdi->interface = 2;
173             ftdi->index     = INTERFACE_C;
174             ftdi->in_ep     = 0x06;
175             ftdi->out_ep    = 0x85;
176             break;
177         case INTERFACE_D:
178             ftdi->interface = 3;
179             ftdi->index     = INTERFACE_D;
180             ftdi->in_ep     = 0x08;
181             ftdi->out_ep    = 0x87;
182             break;
183         default:
184             ftdi_error_return(-1, "Unknown interface");
185     }
186     return 0;
187 }
188
189 /**
190     Deinitializes a ftdi_context.
191
192     \param ftdi pointer to ftdi_context
193 */
194 void ftdi_deinit(struct ftdi_context *ftdi)
195 {
196     if (ftdi == NULL)
197         return;
198
199     ftdi_usb_close_internal (ftdi);
200
201     if (ftdi->readbuffer != NULL)
202     {
203         free(ftdi->readbuffer);
204         ftdi->readbuffer = NULL;
205     }
206
207     if (ftdi->eeprom != NULL)
208     {
209         if (ftdi->eeprom->manufacturer != 0)
210         {
211             free(ftdi->eeprom->manufacturer);
212             ftdi->eeprom->manufacturer = 0;
213         }
214         if (ftdi->eeprom->product != 0)
215         {
216             free(ftdi->eeprom->product);
217             ftdi->eeprom->product = 0;
218         }
219         if (ftdi->eeprom->serial != 0)
220         {
221             free(ftdi->eeprom->serial);
222             ftdi->eeprom->serial = 0;
223         }
224         free(ftdi->eeprom);
225         ftdi->eeprom = NULL;
226     }
227
228     if (ftdi->usb_ctx)
229     {
230         libusb_exit(ftdi->usb_ctx);
231         ftdi->usb_ctx = NULL;
232     }
233 }
234
235 /**
236     Deinitialize and free an ftdi_context.
237
238     \param ftdi pointer to ftdi_context
239 */
240 void ftdi_free(struct ftdi_context *ftdi)
241 {
242     ftdi_deinit(ftdi);
243     free(ftdi);
244 }
245
246 /**
247     Use an already open libusb device.
248
249     \param ftdi pointer to ftdi_context
250     \param usb libusb libusb_device_handle to use
251 */
252 void ftdi_set_usbdev (struct ftdi_context *ftdi, libusb_device_handle *usb)
253 {
254     if (ftdi == NULL)
255         return;
256
257     ftdi->usb_dev = usb;
258 }
259
260
261 /**
262     Finds all ftdi devices with given VID:PID on the usb bus. Creates a new
263     ftdi_device_list which needs to be deallocated by ftdi_list_free() after
264     use.  With VID:PID 0:0, search for the default devices
265     (0x403:0x6001, 0x403:0x6010, 0x403:0x6011, 0x403:0x6014) 
266
267     \param ftdi pointer to ftdi_context
268     \param devlist Pointer where to store list of found devices
269     \param vendor Vendor ID to search for
270     \param product Product ID to search for
271
272     \retval >0: number of devices found
273     \retval -3: out of memory
274     \retval -5: libusb_get_device_list() failed
275     \retval -6: libusb_get_device_descriptor() failed
276 */
277 int ftdi_usb_find_all(struct ftdi_context *ftdi, struct ftdi_device_list **devlist, int vendor, int product)
278 {
279     struct ftdi_device_list **curdev;
280     libusb_device *dev;
281     libusb_device **devs;
282     int count = 0;
283     int i = 0;
284
285     if (libusb_get_device_list(ftdi->usb_ctx, &devs) < 0)
286         ftdi_error_return(-5, "libusb_get_device_list() failed");
287
288     curdev = devlist;
289     *curdev = NULL;
290
291     while ((dev = devs[i++]) != NULL)
292     {
293         struct libusb_device_descriptor desc;
294
295         if (libusb_get_device_descriptor(dev, &desc) < 0)
296             ftdi_error_return_free_device_list(-6, "libusb_get_device_descriptor() failed", devs);
297
298         if (((vendor != 0 && product != 0) && 
299              desc.idVendor == vendor && desc.idProduct == product) ||
300             ((vendor == 0 && product == 0) && 
301              (desc.idVendor == 0x403) && (desc.idProduct == 0x6001 || desc.idProduct == 0x6010
302                                           || desc.idProduct == 0x6011 || desc.idProduct == 0x6014)))
303         {
304             *curdev = (struct ftdi_device_list*)malloc(sizeof(struct ftdi_device_list));
305             if (!*curdev)
306                 ftdi_error_return_free_device_list(-3, "out of memory", devs);
307
308             (*curdev)->next = NULL;
309             (*curdev)->dev = dev;
310             libusb_ref_device(dev);
311             curdev = &(*curdev)->next;
312             count++;
313         }
314     }
315     libusb_free_device_list(devs,1);
316     return count;
317 }
318
319 /**
320     Frees a usb device list.
321
322     \param devlist USB device list created by ftdi_usb_find_all()
323 */
324 void ftdi_list_free(struct ftdi_device_list **devlist)
325 {
326     struct ftdi_device_list *curdev, *next;
327
328     for (curdev = *devlist; curdev != NULL;)
329     {
330         next = curdev->next;
331         libusb_unref_device(curdev->dev);
332         free(curdev);
333         curdev = next;
334     }
335
336     *devlist = NULL;
337 }
338
339 /**
340     Frees a usb device list.
341
342     \param devlist USB device list created by ftdi_usb_find_all()
343 */
344 void ftdi_list_free2(struct ftdi_device_list *devlist)
345 {
346     ftdi_list_free(&devlist);
347 }
348
349 /**
350     Return device ID strings from the usb device.
351
352     The parameters manufacturer, description and serial may be NULL
353     or pointer to buffers to store the fetched strings.
354
355     \note Use this function only in combination with ftdi_usb_find_all()
356           as it closes the internal "usb_dev" after use.
357
358     \param ftdi pointer to ftdi_context
359     \param dev libusb usb_dev to use
360     \param manufacturer Store manufacturer string here if not NULL
361     \param mnf_len Buffer size of manufacturer string
362     \param description Store product description string here if not NULL
363     \param desc_len Buffer size of product description string
364     \param serial Store serial string here if not NULL
365     \param serial_len Buffer size of serial string
366
367     \retval   0: all fine
368     \retval  -1: wrong arguments
369     \retval  -4: unable to open device
370     \retval  -7: get product manufacturer failed
371     \retval  -8: get product description failed
372     \retval  -9: get serial number failed
373     \retval -11: libusb_get_device_descriptor() failed
374 */
375 int ftdi_usb_get_strings(struct ftdi_context * ftdi, struct libusb_device * dev,
376                          char * manufacturer, int mnf_len, char * description, int desc_len, char * serial, int serial_len)
377 {
378     struct libusb_device_descriptor desc;
379
380     if ((ftdi==NULL) || (dev==NULL))
381         return -1;
382
383     if (libusb_open(dev, &ftdi->usb_dev) < 0)
384         ftdi_error_return(-4, "libusb_open() failed");
385
386     if (libusb_get_device_descriptor(dev, &desc) < 0)
387         ftdi_error_return(-11, "libusb_get_device_descriptor() failed");
388
389     if (manufacturer != NULL)
390     {
391         if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iManufacturer, (unsigned char *)manufacturer, mnf_len) < 0)
392         {
393             ftdi_usb_close_internal (ftdi);
394             ftdi_error_return(-7, "libusb_get_string_descriptor_ascii() failed");
395         }
396     }
397
398     if (description != NULL)
399     {
400         if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iProduct, (unsigned char *)description, desc_len) < 0)
401         {
402             ftdi_usb_close_internal (ftdi);
403             ftdi_error_return(-8, "libusb_get_string_descriptor_ascii() failed");
404         }
405     }
406
407     if (serial != NULL)
408     {
409         if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iSerialNumber, (unsigned char *)serial, serial_len) < 0)
410         {
411             ftdi_usb_close_internal (ftdi);
412             ftdi_error_return(-9, "libusb_get_string_descriptor_ascii() failed");
413         }
414     }
415
416     ftdi_usb_close_internal (ftdi);
417
418     return 0;
419 }
420
421 /**
422  * Internal function to determine the maximum packet size.
423  * \param ftdi pointer to ftdi_context
424  * \param dev libusb usb_dev to use
425  * \retval Maximum packet size for this device
426  */
427 static unsigned int _ftdi_determine_max_packet_size(struct ftdi_context *ftdi, libusb_device *dev)
428 {
429     struct libusb_device_descriptor desc;
430     struct libusb_config_descriptor *config0;
431     unsigned int packet_size;
432
433     // Sanity check
434     if (ftdi == NULL || dev == NULL)
435         return 64;
436
437     // Determine maximum packet size. Init with default value.
438     // New hi-speed devices from FTDI use a packet size of 512 bytes
439     // but could be connected to a normal speed USB hub -> 64 bytes packet size.
440     if (ftdi->type == TYPE_2232H || ftdi->type == TYPE_4232H || ftdi->type == TYPE_232H )
441         packet_size = 512;
442     else
443         packet_size = 64;
444
445     if (libusb_get_device_descriptor(dev, &desc) < 0)
446         return packet_size;
447
448     if (libusb_get_config_descriptor(dev, 0, &config0) < 0)
449         return packet_size;
450
451     if (desc.bNumConfigurations > 0)
452     {
453         if (ftdi->interface < config0->bNumInterfaces)
454         {
455             struct libusb_interface interface = config0->interface[ftdi->interface];
456             if (interface.num_altsetting > 0)
457             {
458                 struct libusb_interface_descriptor descriptor = interface.altsetting[0];
459                 if (descriptor.bNumEndpoints > 0)
460                 {
461                     packet_size = descriptor.endpoint[0].wMaxPacketSize;
462                 }
463             }
464         }
465     }
466
467     libusb_free_config_descriptor (config0);
468     return packet_size;
469 }
470
471 /**
472     Opens a ftdi device given by an usb_device.
473
474     \param ftdi pointer to ftdi_context
475     \param dev libusb usb_dev to use
476
477     \retval  0: all fine
478     \retval -3: unable to config device
479     \retval -4: unable to open device
480     \retval -5: unable to claim device
481     \retval -6: reset failed
482     \retval -7: set baudrate failed
483     \retval -8: ftdi context invalid
484     \retval -9: libusb_get_device_descriptor() failed
485     \retval -10: libusb_get_config_descriptor() failed
486     \retval -11: libusb_detach_kernel_driver() failed
487     \retval -12: libusb_get_configuration() failed
488 */
489 int ftdi_usb_open_dev(struct ftdi_context *ftdi, libusb_device *dev)
490 {
491     struct libusb_device_descriptor desc;
492     struct libusb_config_descriptor *config0;
493     int cfg, cfg0, detach_errno = 0;
494
495     if (ftdi == NULL)
496         ftdi_error_return(-8, "ftdi context invalid");
497
498     if (libusb_open(dev, &ftdi->usb_dev) < 0)
499         ftdi_error_return(-4, "libusb_open() failed");
500
501     if (libusb_get_device_descriptor(dev, &desc) < 0)
502         ftdi_error_return(-9, "libusb_get_device_descriptor() failed");
503
504     if (libusb_get_config_descriptor(dev, 0, &config0) < 0)
505         ftdi_error_return(-10, "libusb_get_config_descriptor() failed");
506     cfg0 = config0->bConfigurationValue;
507     libusb_free_config_descriptor (config0);
508
509     // Try to detach ftdi_sio kernel module.
510     //
511     // The return code is kept in a separate variable and only parsed
512     // if usb_set_configuration() or usb_claim_interface() fails as the
513     // detach operation might be denied and everything still works fine.
514     // Likely scenario is a static ftdi_sio kernel module.
515     if (ftdi->module_detach_mode == AUTO_DETACH_SIO_MODULE)
516     {
517         if (libusb_detach_kernel_driver(ftdi->usb_dev, ftdi->interface) !=0)
518             detach_errno = errno;
519     }
520
521     if (libusb_get_configuration (ftdi->usb_dev, &cfg) < 0)
522         ftdi_error_return(-12, "libusb_get_configuration () failed");
523     // set configuration (needed especially for windows)
524     // tolerate EBUSY: one device with one configuration, but two interfaces
525     //    and libftdi sessions to both interfaces (e.g. FT2232)
526     if (desc.bNumConfigurations > 0 && cfg != cfg0)
527     {
528         if (libusb_set_configuration(ftdi->usb_dev, cfg0) < 0)
529         {
530             ftdi_usb_close_internal (ftdi);
531             if (detach_errno == EPERM)
532             {
533                 ftdi_error_return(-8, "inappropriate permissions on device!");
534             }
535             else
536             {
537                 ftdi_error_return(-3, "unable to set usb configuration. Make sure the default FTDI driver is not in use");
538             }
539         }
540     }
541
542     if (libusb_claim_interface(ftdi->usb_dev, ftdi->interface) < 0)
543     {
544         ftdi_usb_close_internal (ftdi);
545         if (detach_errno == EPERM)
546         {
547             ftdi_error_return(-8, "inappropriate permissions on device!");
548         }
549         else
550         {
551             ftdi_error_return(-5, "unable to claim usb device. Make sure the default FTDI driver is not in use");
552         }
553     }
554
555     if (ftdi_usb_reset (ftdi) != 0)
556     {
557         ftdi_usb_close_internal (ftdi);
558         ftdi_error_return(-6, "ftdi_usb_reset failed");
559     }
560
561     // Try to guess chip type
562     // Bug in the BM type chips: bcdDevice is 0x200 for serial == 0
563     if (desc.bcdDevice == 0x400 || (desc.bcdDevice == 0x200
564                                     && desc.iSerialNumber == 0))
565         ftdi->type = TYPE_BM;
566     else if (desc.bcdDevice == 0x200)
567         ftdi->type = TYPE_AM;
568     else if (desc.bcdDevice == 0x500)
569         ftdi->type = TYPE_2232C;
570     else if (desc.bcdDevice == 0x600)
571         ftdi->type = TYPE_R;
572     else if (desc.bcdDevice == 0x700)
573         ftdi->type = TYPE_2232H;
574     else if (desc.bcdDevice == 0x800)
575         ftdi->type = TYPE_4232H;
576     else if (desc.bcdDevice == 0x900)
577         ftdi->type = TYPE_232H;
578
579     // Determine maximum packet size
580     ftdi->max_packet_size = _ftdi_determine_max_packet_size(ftdi, dev);
581
582     if (ftdi_set_baudrate (ftdi, 9600) != 0)
583     {
584         ftdi_usb_close_internal (ftdi);
585         ftdi_error_return(-7, "set baudrate failed");
586     }
587
588     ftdi_error_return(0, "all fine");
589 }
590
591 /**
592     Opens the first device with a given vendor and product ids.
593
594     \param ftdi pointer to ftdi_context
595     \param vendor Vendor ID
596     \param product Product ID
597
598     \retval same as ftdi_usb_open_desc()
599 */
600 int ftdi_usb_open(struct ftdi_context *ftdi, int vendor, int product)
601 {
602     return ftdi_usb_open_desc(ftdi, vendor, product, NULL, NULL);
603 }
604
605 /**
606     Opens the first device with a given, vendor id, product id,
607     description and serial.
608
609     \param ftdi pointer to ftdi_context
610     \param vendor Vendor ID
611     \param product Product ID
612     \param description Description to search for. Use NULL if not needed.
613     \param serial Serial to search for. Use NULL if not needed.
614
615     \retval  0: all fine
616     \retval -3: usb device not found
617     \retval -4: unable to open device
618     \retval -5: unable to claim device
619     \retval -6: reset failed
620     \retval -7: set baudrate failed
621     \retval -8: get product description failed
622     \retval -9: get serial number failed
623     \retval -12: libusb_get_device_list() failed
624     \retval -13: libusb_get_device_descriptor() failed
625 */
626 int ftdi_usb_open_desc(struct ftdi_context *ftdi, int vendor, int product,
627                        const char* description, const char* serial)
628 {
629     return ftdi_usb_open_desc_index(ftdi,vendor,product,description,serial,0);
630 }
631
632 /**
633     Opens the index-th device with a given, vendor id, product id,
634     description and serial.
635
636     \param ftdi pointer to ftdi_context
637     \param vendor Vendor ID
638     \param product Product ID
639     \param description Description to search for. Use NULL if not needed.
640     \param serial Serial to search for. Use NULL if not needed.
641     \param index Number of matching device to open if there are more than one, starts with 0.
642
643     \retval  0: all fine
644     \retval -1: usb_find_busses() failed
645     \retval -2: usb_find_devices() failed
646     \retval -3: usb device not found
647     \retval -4: unable to open device
648     \retval -5: unable to claim device
649     \retval -6: reset failed
650     \retval -7: set baudrate failed
651     \retval -8: get product description failed
652     \retval -9: get serial number failed
653     \retval -10: unable to close device
654     \retval -11: ftdi context invalid
655 */
656 int ftdi_usb_open_desc_index(struct ftdi_context *ftdi, int vendor, int product,
657                              const char* description, const char* serial, unsigned int index)
658 {
659     libusb_device *dev;
660     libusb_device **devs;
661     char string[256];
662     int i = 0;
663
664     if (ftdi == NULL)
665         ftdi_error_return(-11, "ftdi context invalid");
666
667     if (libusb_get_device_list(ftdi->usb_ctx, &devs) < 0)
668         ftdi_error_return(-12, "libusb_get_device_list() failed");
669
670     while ((dev = devs[i++]) != NULL)
671     {
672         struct libusb_device_descriptor desc;
673         int res;
674
675         if (libusb_get_device_descriptor(dev, &desc) < 0)
676             ftdi_error_return_free_device_list(-13, "libusb_get_device_descriptor() failed", devs);
677
678         if (desc.idVendor == vendor && desc.idProduct == product)
679         {
680             if (libusb_open(dev, &ftdi->usb_dev) < 0)
681                 ftdi_error_return_free_device_list(-4, "usb_open() failed", devs);
682
683             if (description != NULL)
684             {
685                 if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iProduct, (unsigned char *)string, sizeof(string)) < 0)
686                 {
687                     ftdi_usb_close_internal (ftdi);
688                     ftdi_error_return_free_device_list(-8, "unable to fetch product description", devs);
689                 }
690                 if (strncmp(string, description, sizeof(string)) != 0)
691                 {
692                     ftdi_usb_close_internal (ftdi);
693                     continue;
694                 }
695             }
696             if (serial != NULL)
697             {
698                 if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iSerialNumber, (unsigned char *)string, sizeof(string)) < 0)
699                 {
700                     ftdi_usb_close_internal (ftdi);
701                     ftdi_error_return_free_device_list(-9, "unable to fetch serial number", devs);
702                 }
703                 if (strncmp(string, serial, sizeof(string)) != 0)
704                 {
705                     ftdi_usb_close_internal (ftdi);
706                     continue;
707                 }
708             }
709
710             ftdi_usb_close_internal (ftdi);
711
712             if (index > 0)
713             {
714                 index--;
715                 continue;
716             }
717
718             res = ftdi_usb_open_dev(ftdi, dev);
719             libusb_free_device_list(devs,1);
720             return res;
721         }
722     }
723
724     // device not found
725     ftdi_error_return_free_device_list(-3, "device not found", devs);
726 }
727
728 /**
729     Opens the ftdi-device described by a description-string.
730     Intended to be used for parsing a device-description given as commandline argument.
731
732     \param ftdi pointer to ftdi_context
733     \param description NULL-terminated description-string, using this format:
734         \li <tt>d:\<devicenode></tt> path of bus and device-node (e.g. "003/001") within usb device tree (usually at /proc/bus/usb/)
735         \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")
736         \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
737         \li <tt>s:\<vendor>:\<product>:\<serial></tt> first device with given vendor id, product id and serial string
738
739     \note The description format may be extended in later versions.
740
741     \retval  0: all fine
742     \retval -2: libusb_get_device_list() failed
743     \retval -3: usb device not found
744     \retval -4: unable to open device
745     \retval -5: unable to claim device
746     \retval -6: reset failed
747     \retval -7: set baudrate failed
748     \retval -8: get product description failed
749     \retval -9: get serial number failed
750     \retval -10: unable to close device
751     \retval -11: illegal description format
752     \retval -12: ftdi context invalid
753 */
754 int ftdi_usb_open_string(struct ftdi_context *ftdi, const char* description)
755 {
756     if (ftdi == NULL)
757         ftdi_error_return(-12, "ftdi context invalid");
758
759     if (description[0] == 0 || description[1] != ':')
760         ftdi_error_return(-11, "illegal description format");
761
762     if (description[0] == 'd')
763     {
764         libusb_device *dev;
765         libusb_device **devs;
766         unsigned int bus_number, device_address;
767         int i = 0;
768
769         if (libusb_get_device_list(ftdi->usb_ctx, &devs) < 0)
770             ftdi_error_return(-2, "libusb_get_device_list() failed");
771
772         /* XXX: This doesn't handle symlinks/odd paths/etc... */
773         if (sscanf (description + 2, "%u/%u", &bus_number, &device_address) != 2)
774             ftdi_error_return_free_device_list(-11, "illegal description format", devs);
775
776         while ((dev = devs[i++]) != NULL)
777         {
778             int ret;
779             if (bus_number == libusb_get_bus_number (dev)
780                     && device_address == libusb_get_device_address (dev))
781             {
782                 ret = ftdi_usb_open_dev(ftdi, dev);
783                 libusb_free_device_list(devs,1);
784                 return ret;
785             }
786         }
787
788         // device not found
789         ftdi_error_return_free_device_list(-3, "device not found", devs);
790     }
791     else if (description[0] == 'i' || description[0] == 's')
792     {
793         unsigned int vendor;
794         unsigned int product;
795         unsigned int index=0;
796         const char *serial=NULL;
797         const char *startp, *endp;
798
799         errno=0;
800         startp=description+2;
801         vendor=strtoul((char*)startp,(char**)&endp,0);
802         if (*endp != ':' || endp == startp || errno != 0)
803             ftdi_error_return(-11, "illegal description format");
804
805         startp=endp+1;
806         product=strtoul((char*)startp,(char**)&endp,0);
807         if (endp == startp || errno != 0)
808             ftdi_error_return(-11, "illegal description format");
809
810         if (description[0] == 'i' && *endp != 0)
811         {
812             /* optional index field in i-mode */
813             if (*endp != ':')
814                 ftdi_error_return(-11, "illegal description format");
815
816             startp=endp+1;
817             index=strtoul((char*)startp,(char**)&endp,0);
818             if (*endp != 0 || endp == startp || errno != 0)
819                 ftdi_error_return(-11, "illegal description format");
820         }
821         if (description[0] == 's')
822         {
823             if (*endp != ':')
824                 ftdi_error_return(-11, "illegal description format");
825
826             /* rest of the description is the serial */
827             serial=endp+1;
828         }
829
830         return ftdi_usb_open_desc_index(ftdi, vendor, product, NULL, serial, index);
831     }
832     else
833     {
834         ftdi_error_return(-11, "illegal description format");
835     }
836 }
837
838 /**
839     Resets the ftdi device.
840
841     \param ftdi pointer to ftdi_context
842
843     \retval  0: all fine
844     \retval -1: FTDI reset failed
845     \retval -2: USB device unavailable
846 */
847 int ftdi_usb_reset(struct ftdi_context *ftdi)
848 {
849     if (ftdi == NULL || ftdi->usb_dev == NULL)
850         ftdi_error_return(-2, "USB device unavailable");
851
852     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
853                                 SIO_RESET_REQUEST, SIO_RESET_SIO,
854                                 ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
855         ftdi_error_return(-1,"FTDI reset failed");
856
857     // Invalidate data in the readbuffer
858     ftdi->readbuffer_offset = 0;
859     ftdi->readbuffer_remaining = 0;
860
861     return 0;
862 }
863
864 /**
865     Clears the read buffer on the chip and the internal read buffer.
866
867     \param ftdi pointer to ftdi_context
868
869     \retval  0: all fine
870     \retval -1: read buffer purge failed
871     \retval -2: USB device unavailable
872 */
873 int ftdi_usb_purge_rx_buffer(struct ftdi_context *ftdi)
874 {
875     if (ftdi == NULL || ftdi->usb_dev == NULL)
876         ftdi_error_return(-2, "USB device unavailable");
877
878     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
879                                 SIO_RESET_REQUEST, SIO_RESET_PURGE_RX,
880                                 ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
881         ftdi_error_return(-1, "FTDI purge of RX buffer failed");
882
883     // Invalidate data in the readbuffer
884     ftdi->readbuffer_offset = 0;
885     ftdi->readbuffer_remaining = 0;
886
887     return 0;
888 }
889
890 /**
891     Clears the write buffer on the chip.
892
893     \param ftdi pointer to ftdi_context
894
895     \retval  0: all fine
896     \retval -1: write buffer purge failed
897     \retval -2: USB device unavailable
898 */
899 int ftdi_usb_purge_tx_buffer(struct ftdi_context *ftdi)
900 {
901     if (ftdi == NULL || ftdi->usb_dev == NULL)
902         ftdi_error_return(-2, "USB device unavailable");
903
904     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
905                                 SIO_RESET_REQUEST, SIO_RESET_PURGE_TX,
906                                 ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
907         ftdi_error_return(-1, "FTDI purge of TX buffer failed");
908
909     return 0;
910 }
911
912 /**
913     Clears the buffers on the chip and the internal read buffer.
914
915     \param ftdi pointer to ftdi_context
916
917     \retval  0: all fine
918     \retval -1: read buffer purge failed
919     \retval -2: write buffer purge failed
920     \retval -3: USB device unavailable
921 */
922 int ftdi_usb_purge_buffers(struct ftdi_context *ftdi)
923 {
924     int result;
925
926     if (ftdi == NULL || ftdi->usb_dev == NULL)
927         ftdi_error_return(-3, "USB device unavailable");
928
929     result = ftdi_usb_purge_rx_buffer(ftdi);
930     if (result < 0)
931         return -1;
932
933     result = ftdi_usb_purge_tx_buffer(ftdi);
934     if (result < 0)
935         return -2;
936
937     return 0;
938 }
939
940
941
942 /**
943     Closes the ftdi device. Call ftdi_deinit() if you're cleaning up.
944
945     \param ftdi pointer to ftdi_context
946
947     \retval  0: all fine
948     \retval -1: usb_release failed
949     \retval -3: ftdi context invalid
950 */
951 int ftdi_usb_close(struct ftdi_context *ftdi)
952 {
953     int rtn = 0;
954
955     if (ftdi == NULL)
956         ftdi_error_return(-3, "ftdi context invalid");
957
958     if (ftdi->usb_dev != NULL)
959         if (libusb_release_interface(ftdi->usb_dev, ftdi->interface) < 0)
960             rtn = -1;
961
962     ftdi_usb_close_internal (ftdi);
963
964     return rtn;
965 }
966
967 /*  ftdi_to_clkbits_AM For the AM device, convert a requested baudrate 
968                     to encoded divisor and the achievable baudrate
969     Function is only used internally
970     \internal
971
972     See AN120
973    clk/1   -> 0
974    clk/1.5 -> 1
975    clk/2   -> 2
976    From /2, 0.125/ 0.25 and 0.5 steps may be taken
977    The fractional part has frac_code encoding
978 */
979 static int ftdi_to_clkbits_AM(int baudrate, unsigned long *encoded_divisor)
980
981 {
982     static const char frac_code[8] = {0, 3, 2, 4, 1, 5, 6, 7};
983     static const char am_adjust_up[8] = {0, 0, 0, 1, 0, 3, 2, 1};
984     static const char am_adjust_dn[8] = {0, 0, 0, 1, 0, 1, 2, 3};
985     int divisor, best_divisor, best_baud, best_baud_diff;
986     divisor = 24000000 / baudrate;
987     int i;
988
989     // Round down to supported fraction (AM only)
990     divisor -= am_adjust_dn[divisor & 7];
991
992     // Try this divisor and the one above it (because division rounds down)
993     best_divisor = 0;
994     best_baud = 0;
995     best_baud_diff = 0;
996     for (i = 0; i < 2; i++)
997     {
998         int try_divisor = divisor + i;
999         int baud_estimate;
1000         int baud_diff;
1001
1002         // Round up to supported divisor value
1003         if (try_divisor <= 8)
1004         {
1005             // Round up to minimum supported divisor
1006             try_divisor = 8;
1007         }
1008         else if (divisor < 16)
1009         {
1010             // AM doesn't support divisors 9 through 15 inclusive
1011             try_divisor = 16;
1012         }
1013         else
1014         {
1015             // Round up to supported fraction (AM only)
1016             try_divisor += am_adjust_up[try_divisor & 7];
1017             if (try_divisor > 0x1FFF8)
1018             {
1019                 // Round down to maximum supported divisor value (for AM)
1020                 try_divisor = 0x1FFF8;
1021             }
1022         }
1023         // Get estimated baud rate (to nearest integer)
1024         baud_estimate = (24000000 + (try_divisor / 2)) / try_divisor;
1025         // Get absolute difference from requested baud rate
1026         if (baud_estimate < baudrate)
1027         {
1028             baud_diff = baudrate - baud_estimate;
1029         }
1030         else
1031         {
1032             baud_diff = baud_estimate - baudrate;
1033         }
1034         if (i == 0 || baud_diff < best_baud_diff)
1035         {
1036             // Closest to requested baud rate so far
1037             best_divisor = try_divisor;
1038             best_baud = baud_estimate;
1039             best_baud_diff = baud_diff;
1040             if (baud_diff == 0)
1041             {
1042                 // Spot on! No point trying
1043                 break;
1044             }
1045         }
1046     }
1047     // Encode the best divisor value
1048     *encoded_divisor = (best_divisor >> 3) | (frac_code[best_divisor & 7] << 14);
1049     // Deal with special cases for encoded value
1050     if (*encoded_divisor == 1)
1051     {
1052         *encoded_divisor = 0;    // 3000000 baud
1053     }
1054     else if (*encoded_divisor == 0x4001)
1055     {
1056         *encoded_divisor = 1;    // 2000000 baud (BM only)
1057     }
1058     return best_baud;
1059 }
1060
1061 /*  ftdi_to_clkbits Convert a requested baudrate for a given system clock  and predivisor
1062                     to encoded divisor and the achievable baudrate
1063     Function is only used internally
1064     \internal
1065
1066     See AN120
1067    clk/1   -> 0
1068    clk/1.5 -> 1
1069    clk/2   -> 2
1070    From /2, 0.125 steps may be taken.
1071    The fractional part has frac_code encoding
1072
1073    value[13:0] of value is the divisor
1074    index[9] mean 12 MHz Base(120 MHz/10) rate versus 3 MHz (48 MHz/16) else
1075
1076    H Type have all features above with
1077    {index[8],value[15:14]} is the encoded subdivisor
1078
1079    FT232R, FT2232 and FT232BM have no option for 12 MHz and with 
1080    {index[0],value[15:14]} is the encoded subdivisor
1081
1082    AM Type chips have only four fractional subdivisors at value[15:14]
1083    for subdivisors 0, 0.5, 0.25, 0.125
1084 */
1085 static int ftdi_to_clkbits(int baudrate, unsigned int clk, int clk_div, unsigned long *encoded_divisor)
1086 {
1087     static const char frac_code[8] = {0, 3, 2, 4, 1, 5, 6, 7};
1088     int best_baud = 0;
1089     int divisor, best_divisor;
1090     if (baudrate >=  clk/clk_div)
1091     {
1092         *encoded_divisor = 0;
1093         best_baud = clk/clk_div;
1094     }
1095     else if (baudrate >=  clk/(clk_div + clk_div/2))
1096     {
1097         *encoded_divisor = 1;
1098         best_baud = clk/(clk_div + clk_div/2);
1099     }
1100     else if (baudrate >=  clk/(2*clk_div))
1101     {
1102         *encoded_divisor = 2;
1103         best_baud = clk/(2*clk_div);
1104     }
1105     else
1106     {
1107         /* We divide by 16 to have 3 fractional bits and one bit for rounding */
1108         divisor = clk*16/clk_div / baudrate;
1109         if (divisor & 1) /* Decide if to round up or down*/
1110             best_divisor = divisor /2 +1;
1111         else
1112             best_divisor = divisor/2;
1113         if(best_divisor > 0x20000)
1114             best_divisor = 0x1ffff;
1115         best_baud = clk*16/clk_div/best_divisor;
1116         if (best_baud & 1) /* Decide if to round up or down*/
1117             best_baud = best_baud /2 +1;
1118         else
1119             best_baud = best_baud /2;
1120         *encoded_divisor = (best_divisor >> 3) | (frac_code[best_divisor & 0x7] << 14);
1121     }
1122     return best_baud;
1123
1124 /**
1125     ftdi_convert_baudrate returns nearest supported baud rate to that requested.
1126     Function is only used internally
1127     \internal
1128 */
1129 static int ftdi_convert_baudrate(int baudrate, struct ftdi_context *ftdi,
1130                                  unsigned short *value, unsigned short *index)
1131 {
1132     int best_baud;
1133     unsigned long encoded_divisor;
1134
1135     if (baudrate <= 0)
1136     {
1137         // Return error
1138         return -1;
1139     }
1140
1141 #define H_CLK 120000000
1142 #define C_CLK  48000000
1143     if ((ftdi->type == TYPE_2232H) || (ftdi->type == TYPE_4232H) || (ftdi->type == TYPE_232H ))
1144     {
1145         if(baudrate*10 > H_CLK /0x3fff)
1146         {
1147             /* On H Devices, use 12 000 000 Baudrate when possible
1148                We have a 14 bit divisor, a 1 bit divisor switch (10 or 16) 
1149                three fractional bits and a 120 MHz clock
1150                Assume AN_120 "Sub-integer divisors between 0 and 2 are not allowed" holds for
1151                DIV/10 CLK too, so /1, /1.5 and /2 can be handled the same*/
1152             best_baud = ftdi_to_clkbits(baudrate, H_CLK, 10, &encoded_divisor);
1153             encoded_divisor |= 0x20000; /* switch on CLK/10*/
1154         }
1155         else
1156             best_baud = ftdi_to_clkbits(baudrate, C_CLK, 16, &encoded_divisor);
1157     }
1158     else if ((ftdi->type == TYPE_BM) || (ftdi->type == TYPE_2232C) || (ftdi->type == TYPE_R ))
1159     {
1160         best_baud = ftdi_to_clkbits(baudrate, C_CLK, 16, &encoded_divisor);
1161     }
1162     else
1163     {
1164         best_baud = ftdi_to_clkbits_AM(baudrate, &encoded_divisor);
1165     }
1166     // Split into "value" and "index" values
1167     *value = (unsigned short)(encoded_divisor & 0xFFFF);
1168     if (ftdi->type == TYPE_2232H || 
1169         ftdi->type == TYPE_4232H || ftdi->type == TYPE_232H )
1170     {
1171         *index = (unsigned short)(encoded_divisor >> 8);
1172         *index &= 0xFF00;
1173         *index |= ftdi->index;
1174     }
1175     else
1176         *index = (unsigned short)(encoded_divisor >> 16);
1177
1178     // Return the nearest baud rate
1179     return best_baud;
1180 }
1181
1182 /**
1183  * @brief Wrapper function to export ftdi_convert_baudrate() to the unit test
1184  * Do not use, it's only for the unit test framework
1185  **/
1186 int convert_baudrate_UT_export(int baudrate, struct ftdi_context *ftdi,
1187                                  unsigned short *value, unsigned short *index)
1188 {
1189     return ftdi_convert_baudrate(baudrate, ftdi, value, index);
1190 }
1191
1192 /**
1193     Sets the chip baud rate
1194
1195     \param ftdi pointer to ftdi_context
1196     \param baudrate baud rate to set
1197
1198     \retval  0: all fine
1199     \retval -1: invalid baudrate
1200     \retval -2: setting baudrate failed
1201     \retval -3: USB device unavailable
1202 */
1203 int ftdi_set_baudrate(struct ftdi_context *ftdi, int baudrate)
1204 {
1205     unsigned short value, index;
1206     int actual_baudrate;
1207
1208     if (ftdi == NULL || ftdi->usb_dev == NULL)
1209         ftdi_error_return(-3, "USB device unavailable");
1210
1211     if (ftdi->bitbang_enabled)
1212     {
1213         baudrate = baudrate*4;
1214     }
1215
1216     actual_baudrate = ftdi_convert_baudrate(baudrate, ftdi, &value, &index);
1217     if (actual_baudrate <= 0)
1218         ftdi_error_return (-1, "Silly baudrate <= 0.");
1219
1220     // Check within tolerance (about 5%)
1221     if ((actual_baudrate * 2 < baudrate /* Catch overflows */ )
1222             || ((actual_baudrate < baudrate)
1223                 ? (actual_baudrate * 21 < baudrate * 20)
1224                 : (baudrate * 21 < actual_baudrate * 20)))
1225         ftdi_error_return (-1, "Unsupported baudrate. Note: bitbang baudrates are automatically multiplied by 4");
1226
1227     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1228                                 SIO_SET_BAUDRATE_REQUEST, value,
1229                                 index, NULL, 0, ftdi->usb_write_timeout) < 0)
1230         ftdi_error_return (-2, "Setting new baudrate failed");
1231
1232     ftdi->baudrate = baudrate;
1233     return 0;
1234 }
1235
1236 /**
1237     Set (RS232) line characteristics.
1238     The break type can only be set via ftdi_set_line_property2()
1239     and defaults to "off".
1240
1241     \param ftdi pointer to ftdi_context
1242     \param bits Number of bits
1243     \param sbit Number of stop bits
1244     \param parity Parity mode
1245
1246     \retval  0: all fine
1247     \retval -1: Setting line property failed
1248 */
1249 int ftdi_set_line_property(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
1250                            enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity)
1251 {
1252     return ftdi_set_line_property2(ftdi, bits, sbit, parity, BREAK_OFF);
1253 }
1254
1255 /**
1256     Set (RS232) line characteristics
1257
1258     \param ftdi pointer to ftdi_context
1259     \param bits Number of bits
1260     \param sbit Number of stop bits
1261     \param parity Parity mode
1262     \param break_type Break type
1263
1264     \retval  0: all fine
1265     \retval -1: Setting line property failed
1266     \retval -2: USB device unavailable
1267 */
1268 int ftdi_set_line_property2(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
1269                             enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity,
1270                             enum ftdi_break_type break_type)
1271 {
1272     unsigned short value = bits;
1273
1274     if (ftdi == NULL || ftdi->usb_dev == NULL)
1275         ftdi_error_return(-2, "USB device unavailable");
1276
1277     switch (parity)
1278     {
1279         case NONE:
1280             value |= (0x00 << 8);
1281             break;
1282         case ODD:
1283             value |= (0x01 << 8);
1284             break;
1285         case EVEN:
1286             value |= (0x02 << 8);
1287             break;
1288         case MARK:
1289             value |= (0x03 << 8);
1290             break;
1291         case SPACE:
1292             value |= (0x04 << 8);
1293             break;
1294     }
1295
1296     switch (sbit)
1297     {
1298         case STOP_BIT_1:
1299             value |= (0x00 << 11);
1300             break;
1301         case STOP_BIT_15:
1302             value |= (0x01 << 11);
1303             break;
1304         case STOP_BIT_2:
1305             value |= (0x02 << 11);
1306             break;
1307     }
1308
1309     switch (break_type)
1310     {
1311         case BREAK_OFF:
1312             value |= (0x00 << 14);
1313             break;
1314         case BREAK_ON:
1315             value |= (0x01 << 14);
1316             break;
1317     }
1318
1319     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1320                                 SIO_SET_DATA_REQUEST, value,
1321                                 ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
1322         ftdi_error_return (-1, "Setting new line property failed");
1323
1324     return 0;
1325 }
1326
1327 /**
1328     Writes data in chunks (see ftdi_write_data_set_chunksize()) to the chip
1329
1330     \param ftdi pointer to ftdi_context
1331     \param buf Buffer with the data
1332     \param size Size of the buffer
1333
1334     \retval -666: USB device unavailable
1335     \retval <0: error code from usb_bulk_write()
1336     \retval >0: number of bytes written
1337 */
1338 int ftdi_write_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
1339 {
1340     int offset = 0;
1341     int actual_length;
1342
1343     if (ftdi == NULL || ftdi->usb_dev == NULL)
1344         ftdi_error_return(-666, "USB device unavailable");
1345
1346     while (offset < size)
1347     {
1348         int write_size = ftdi->writebuffer_chunksize;
1349
1350         if (offset+write_size > size)
1351             write_size = size-offset;
1352
1353         if (libusb_bulk_transfer(ftdi->usb_dev, ftdi->in_ep, buf+offset, write_size, &actual_length, ftdi->usb_write_timeout) < 0)
1354             ftdi_error_return(-1, "usb bulk write failed");
1355
1356         offset += actual_length;
1357     }
1358
1359     return offset;
1360 }
1361
1362 static void ftdi_read_data_cb(struct libusb_transfer *transfer)
1363 {
1364     struct ftdi_transfer_control *tc = (struct ftdi_transfer_control *) transfer->user_data;
1365     struct ftdi_context *ftdi = tc->ftdi;
1366     int packet_size, actual_length, num_of_chunks, chunk_remains, i, ret;
1367
1368     packet_size = ftdi->max_packet_size;
1369
1370     actual_length = transfer->actual_length;
1371
1372     if (actual_length > 2)
1373     {
1374         // skip FTDI status bytes.
1375         // Maybe stored in the future to enable modem use
1376         num_of_chunks = actual_length / packet_size;
1377         chunk_remains = actual_length % packet_size;
1378         //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);
1379
1380         ftdi->readbuffer_offset += 2;
1381         actual_length -= 2;
1382
1383         if (actual_length > packet_size - 2)
1384         {
1385             for (i = 1; i < num_of_chunks; i++)
1386                 memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1387                          ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1388                          packet_size - 2);
1389             if (chunk_remains > 2)
1390             {
1391                 memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1392                          ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1393                          chunk_remains-2);
1394                 actual_length -= 2*num_of_chunks;
1395             }
1396             else
1397                 actual_length -= 2*(num_of_chunks-1)+chunk_remains;
1398         }
1399
1400         if (actual_length > 0)
1401         {
1402             // data still fits in buf?
1403             if (tc->offset + actual_length <= tc->size)
1404             {
1405                 memcpy (tc->buf + tc->offset, ftdi->readbuffer + ftdi->readbuffer_offset, actual_length);
1406                 //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
1407                 tc->offset += actual_length;
1408
1409                 ftdi->readbuffer_offset = 0;
1410                 ftdi->readbuffer_remaining = 0;
1411
1412                 /* Did we read exactly the right amount of bytes? */
1413                 if (tc->offset == tc->size)
1414                 {
1415                     //printf("read_data exact rem %d offset %d\n",
1416                     //ftdi->readbuffer_remaining, offset);
1417                     tc->completed = 1;
1418                     return;
1419                 }
1420             }
1421             else
1422             {
1423                 // only copy part of the data or size <= readbuffer_chunksize
1424                 int part_size = tc->size - tc->offset;
1425                 memcpy (tc->buf + tc->offset, ftdi->readbuffer + ftdi->readbuffer_offset, part_size);
1426                 tc->offset += part_size;
1427
1428                 ftdi->readbuffer_offset += part_size;
1429                 ftdi->readbuffer_remaining = actual_length - part_size;
1430
1431                 /* printf("Returning part: %d - size: %d - offset: %d - actual_length: %d - remaining: %d\n",
1432                 part_size, size, offset, actual_length, ftdi->readbuffer_remaining); */
1433                 tc->completed = 1;
1434                 return;
1435             }
1436         }
1437     }
1438     ret = libusb_submit_transfer (transfer);
1439     if (ret < 0)
1440         tc->completed = 1;
1441 }
1442
1443
1444 static void ftdi_write_data_cb(struct libusb_transfer *transfer)
1445 {
1446     struct ftdi_transfer_control *tc = (struct ftdi_transfer_control *) transfer->user_data;
1447     struct ftdi_context *ftdi = tc->ftdi;
1448
1449     tc->offset += transfer->actual_length;
1450
1451     if (tc->offset == tc->size)
1452     {
1453         tc->completed = 1;
1454     }
1455     else
1456     {
1457         int write_size = ftdi->writebuffer_chunksize;
1458         int ret;
1459
1460         if (tc->offset + write_size > tc->size)
1461             write_size = tc->size - tc->offset;
1462
1463         transfer->length = write_size;
1464         transfer->buffer = tc->buf + tc->offset;
1465         ret = libusb_submit_transfer (transfer);
1466         if (ret < 0)
1467             tc->completed = 1;
1468     }
1469 }
1470
1471
1472 /**
1473     Writes data to the chip. Does not wait for completion of the transfer
1474     nor does it make sure that the transfer was successful.
1475
1476     Use libusb 1.0 asynchronous API.
1477
1478     \param ftdi pointer to ftdi_context
1479     \param buf Buffer with the data
1480     \param size Size of the buffer
1481
1482     \retval NULL: Some error happens when submit transfer
1483     \retval !NULL: Pointer to a ftdi_transfer_control
1484 */
1485
1486 struct ftdi_transfer_control *ftdi_write_data_submit(struct ftdi_context *ftdi, unsigned char *buf, int size)
1487 {
1488     struct ftdi_transfer_control *tc;
1489     struct libusb_transfer *transfer;
1490     int write_size, ret;
1491
1492     if (ftdi == NULL || ftdi->usb_dev == NULL)
1493         return NULL;
1494
1495     tc = (struct ftdi_transfer_control *) malloc (sizeof (*tc));
1496     if (!tc)
1497         return NULL;
1498
1499     transfer = libusb_alloc_transfer(0);
1500     if (!transfer)
1501     {
1502         free(tc);
1503         return NULL;
1504     }
1505
1506     tc->ftdi = ftdi;
1507     tc->completed = 0;
1508     tc->buf = buf;
1509     tc->size = size;
1510     tc->offset = 0;
1511
1512     if (size < ftdi->writebuffer_chunksize)
1513         write_size = size;
1514     else
1515         write_size = ftdi->writebuffer_chunksize;
1516
1517     libusb_fill_bulk_transfer(transfer, ftdi->usb_dev, ftdi->in_ep, buf,
1518                               write_size, ftdi_write_data_cb, tc,
1519                               ftdi->usb_write_timeout);
1520     transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
1521
1522     ret = libusb_submit_transfer(transfer);
1523     if (ret < 0)
1524     {
1525         libusb_free_transfer(transfer);
1526         free(tc);
1527         return NULL;
1528     }
1529     tc->transfer = transfer;
1530
1531     return tc;
1532 }
1533
1534 /**
1535     Reads data from the chip. Does not wait for completion of the transfer
1536     nor does it make sure that the transfer was successful.
1537
1538     Use libusb 1.0 asynchronous API.
1539
1540     \param ftdi pointer to ftdi_context
1541     \param buf Buffer with the data
1542     \param size Size of the buffer
1543
1544     \retval NULL: Some error happens when submit transfer
1545     \retval !NULL: Pointer to a ftdi_transfer_control
1546 */
1547
1548 struct ftdi_transfer_control *ftdi_read_data_submit(struct ftdi_context *ftdi, unsigned char *buf, int size)
1549 {
1550     struct ftdi_transfer_control *tc;
1551     struct libusb_transfer *transfer;
1552     int ret;
1553
1554     if (ftdi == NULL || ftdi->usb_dev == NULL)
1555         return NULL;
1556
1557     tc = (struct ftdi_transfer_control *) malloc (sizeof (*tc));
1558     if (!tc)
1559         return NULL;
1560
1561     tc->ftdi = ftdi;
1562     tc->buf = buf;
1563     tc->size = size;
1564
1565     if (size <= ftdi->readbuffer_remaining)
1566     {
1567         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);
1568
1569         // Fix offsets
1570         ftdi->readbuffer_remaining -= size;
1571         ftdi->readbuffer_offset += size;
1572
1573         /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */
1574
1575         tc->completed = 1;
1576         tc->offset = size;
1577         tc->transfer = NULL;
1578         return tc;
1579     }
1580
1581     tc->completed = 0;
1582     if (ftdi->readbuffer_remaining != 0)
1583     {
1584         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);
1585
1586         tc->offset = ftdi->readbuffer_remaining;
1587     }
1588     else
1589         tc->offset = 0;
1590
1591     transfer = libusb_alloc_transfer(0);
1592     if (!transfer)
1593     {
1594         free (tc);
1595         return NULL;
1596     }
1597
1598     ftdi->readbuffer_remaining = 0;
1599     ftdi->readbuffer_offset = 0;
1600
1601     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);
1602     transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
1603
1604     ret = libusb_submit_transfer(transfer);
1605     if (ret < 0)
1606     {
1607         libusb_free_transfer(transfer);
1608         free (tc);
1609         return NULL;
1610     }
1611     tc->transfer = transfer;
1612
1613     return tc;
1614 }
1615
1616 /**
1617     Wait for completion of the transfer.
1618
1619     Use libusb 1.0 asynchronous API.
1620
1621     \param tc pointer to ftdi_transfer_control
1622
1623     \retval < 0: Some error happens
1624     \retval >= 0: Data size transferred
1625 */
1626
1627 int ftdi_transfer_data_done(struct ftdi_transfer_control *tc)
1628 {
1629     int ret;
1630
1631     while (!tc->completed)
1632     {
1633         ret = libusb_handle_events(tc->ftdi->usb_ctx);
1634         if (ret < 0)
1635         {
1636             if (ret == LIBUSB_ERROR_INTERRUPTED)
1637                 continue;
1638             libusb_cancel_transfer(tc->transfer);
1639             while (!tc->completed)
1640                 if (libusb_handle_events(tc->ftdi->usb_ctx) < 0)
1641                     break;
1642             libusb_free_transfer(tc->transfer);
1643             free (tc);
1644             return ret;
1645         }
1646     }
1647
1648     ret = tc->offset;
1649     /**
1650      * tc->transfer could be NULL if "(size <= ftdi->readbuffer_remaining)"
1651      * at ftdi_read_data_submit(). Therefore, we need to check it here.
1652      **/
1653     if (tc->transfer)
1654     {
1655         if (tc->transfer->status != LIBUSB_TRANSFER_COMPLETED)
1656             ret = -1;
1657         libusb_free_transfer(tc->transfer);
1658     }
1659     free(tc);
1660     return ret;
1661 }
1662
1663 /**
1664     Configure write buffer chunk size.
1665     Default is 4096.
1666
1667     \param ftdi pointer to ftdi_context
1668     \param chunksize Chunk size
1669
1670     \retval 0: all fine
1671     \retval -1: ftdi context invalid
1672 */
1673 int ftdi_write_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
1674 {
1675     if (ftdi == NULL)
1676         ftdi_error_return(-1, "ftdi context invalid");
1677
1678     ftdi->writebuffer_chunksize = chunksize;
1679     return 0;
1680 }
1681
1682 /**
1683     Get write buffer chunk size.
1684
1685     \param ftdi pointer to ftdi_context
1686     \param chunksize Pointer to store chunk size in
1687
1688     \retval 0: all fine
1689     \retval -1: ftdi context invalid
1690 */
1691 int ftdi_write_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
1692 {
1693     if (ftdi == NULL)
1694         ftdi_error_return(-1, "ftdi context invalid");
1695
1696     *chunksize = ftdi->writebuffer_chunksize;
1697     return 0;
1698 }
1699
1700 /**
1701     Reads data in chunks (see ftdi_read_data_set_chunksize()) from the chip.
1702
1703     Automatically strips the two modem status bytes transfered during every read.
1704
1705     \param ftdi pointer to ftdi_context
1706     \param buf Buffer to store data in
1707     \param size Size of the buffer
1708
1709     \retval -666: USB device unavailable
1710     \retval <0: error code from libusb_bulk_transfer()
1711     \retval  0: no data was available
1712     \retval >0: number of bytes read
1713
1714 */
1715 int ftdi_read_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
1716 {
1717     int offset = 0, ret, i, num_of_chunks, chunk_remains;
1718     int packet_size = ftdi->max_packet_size;
1719     int actual_length = 1;
1720
1721     if (ftdi == NULL || ftdi->usb_dev == NULL)
1722         ftdi_error_return(-666, "USB device unavailable");
1723
1724     // Packet size sanity check (avoid division by zero)
1725     if (packet_size == 0)
1726         ftdi_error_return(-1, "max_packet_size is bogus (zero)");
1727
1728     // everything we want is still in the readbuffer?
1729     if (size <= ftdi->readbuffer_remaining)
1730     {
1731         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);
1732
1733         // Fix offsets
1734         ftdi->readbuffer_remaining -= size;
1735         ftdi->readbuffer_offset += size;
1736
1737         /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */
1738
1739         return size;
1740     }
1741     // something still in the readbuffer, but not enough to satisfy 'size'?
1742     if (ftdi->readbuffer_remaining != 0)
1743     {
1744         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);
1745
1746         // Fix offset
1747         offset += ftdi->readbuffer_remaining;
1748     }
1749     // do the actual USB read
1750     while (offset < size && actual_length > 0)
1751     {
1752         ftdi->readbuffer_remaining = 0;
1753         ftdi->readbuffer_offset = 0;
1754         /* returns how much received */
1755         ret = libusb_bulk_transfer (ftdi->usb_dev, ftdi->out_ep, ftdi->readbuffer, ftdi->readbuffer_chunksize, &actual_length, ftdi->usb_read_timeout);
1756         if (ret < 0)
1757             ftdi_error_return(ret, "usb bulk read failed");
1758
1759         if (actual_length > 2)
1760         {
1761             // skip FTDI status bytes.
1762             // Maybe stored in the future to enable modem use
1763             num_of_chunks = actual_length / packet_size;
1764             chunk_remains = actual_length % packet_size;
1765             //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);
1766
1767             ftdi->readbuffer_offset += 2;
1768             actual_length -= 2;
1769
1770             if (actual_length > packet_size - 2)
1771             {
1772                 for (i = 1; i < num_of_chunks; i++)
1773                     memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1774                              ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1775                              packet_size - 2);
1776                 if (chunk_remains > 2)
1777                 {
1778                     memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1779                              ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1780                              chunk_remains-2);
1781                     actual_length -= 2*num_of_chunks;
1782                 }
1783                 else
1784                     actual_length -= 2*(num_of_chunks-1)+chunk_remains;
1785             }
1786         }
1787         else if (actual_length <= 2)
1788         {
1789             // no more data to read?
1790             return offset;
1791         }
1792         if (actual_length > 0)
1793         {
1794             // data still fits in buf?
1795             if (offset+actual_length <= size)
1796             {
1797                 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, actual_length);
1798                 //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
1799                 offset += actual_length;
1800
1801                 /* Did we read exactly the right amount of bytes? */
1802                 if (offset == size)
1803                     //printf("read_data exact rem %d offset %d\n",
1804                     //ftdi->readbuffer_remaining, offset);
1805                     return offset;
1806             }
1807             else
1808             {
1809                 // only copy part of the data or size <= readbuffer_chunksize
1810                 int part_size = size-offset;
1811                 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, part_size);
1812
1813                 ftdi->readbuffer_offset += part_size;
1814                 ftdi->readbuffer_remaining = actual_length-part_size;
1815                 offset += part_size;
1816
1817                 /* printf("Returning part: %d - size: %d - offset: %d - actual_length: %d - remaining: %d\n",
1818                 part_size, size, offset, actual_length, ftdi->readbuffer_remaining); */
1819
1820                 return offset;
1821             }
1822         }
1823     }
1824     // never reached
1825     return -127;
1826 }
1827
1828 /**
1829     Configure read buffer chunk size.
1830     Default is 4096.
1831
1832     Automatically reallocates the buffer.
1833
1834     \param ftdi pointer to ftdi_context
1835     \param chunksize Chunk size
1836
1837     \retval 0: all fine
1838     \retval -1: ftdi context invalid
1839 */
1840 int ftdi_read_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
1841 {
1842     unsigned char *new_buf;
1843
1844     if (ftdi == NULL)
1845         ftdi_error_return(-1, "ftdi context invalid");
1846
1847     // Invalidate all remaining data
1848     ftdi->readbuffer_offset = 0;
1849     ftdi->readbuffer_remaining = 0;
1850 #ifdef __linux__
1851     /* We can't set readbuffer_chunksize larger than MAX_BULK_BUFFER_LENGTH,
1852        which is defined in libusb-1.0.  Otherwise, each USB read request will
1853        be divided into multiple URBs.  This will cause issues on Linux kernel
1854        older than 2.6.32.  */
1855     if (chunksize > 16384)
1856         chunksize = 16384;
1857 #endif
1858
1859     if ((new_buf = (unsigned char *)realloc(ftdi->readbuffer, chunksize)) == NULL)
1860         ftdi_error_return(-1, "out of memory for readbuffer");
1861
1862     ftdi->readbuffer = new_buf;
1863     ftdi->readbuffer_chunksize = chunksize;
1864
1865     return 0;
1866 }
1867
1868 /**
1869     Get read buffer chunk size.
1870
1871     \param ftdi pointer to ftdi_context
1872     \param chunksize Pointer to store chunk size in
1873
1874     \retval 0: all fine
1875     \retval -1: FTDI context invalid
1876 */
1877 int ftdi_read_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
1878 {
1879     if (ftdi == NULL)
1880         ftdi_error_return(-1, "FTDI context invalid");
1881
1882     *chunksize = ftdi->readbuffer_chunksize;
1883     return 0;
1884 }
1885
1886
1887 /**
1888     Enable bitbang mode.
1889
1890     \deprecated use \ref ftdi_set_bitmode with mode BITMODE_BITBANG instead
1891
1892     \param ftdi pointer to ftdi_context
1893     \param bitmask Bitmask to configure lines.
1894            HIGH/ON value configures a line as output.
1895
1896     \retval  0: all fine
1897     \retval -1: can't enable bitbang mode
1898     \retval -2: USB device unavailable
1899 */
1900 int ftdi_enable_bitbang(struct ftdi_context *ftdi, unsigned char bitmask)
1901 {
1902     unsigned short usb_val;
1903
1904     if (ftdi == NULL || ftdi->usb_dev == NULL)
1905         ftdi_error_return(-2, "USB device unavailable");
1906
1907     usb_val = bitmask; // low byte: bitmask
1908     /* FT2232C: Set bitbang_mode to 2 to enable SPI */
1909     usb_val |= (ftdi->bitbang_mode << 8);
1910
1911     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1912                                 SIO_SET_BITMODE_REQUEST, usb_val, ftdi->index,
1913                                 NULL, 0, ftdi->usb_write_timeout) < 0)
1914         ftdi_error_return(-1, "unable to enter bitbang mode. Perhaps not a BM type chip?");
1915
1916     ftdi->bitbang_enabled = 1;
1917     return 0;
1918 }
1919
1920 /**
1921     Disable bitbang mode.
1922
1923     \param ftdi pointer to ftdi_context
1924
1925     \retval  0: all fine
1926     \retval -1: can't disable bitbang mode
1927     \retval -2: USB device unavailable
1928 */
1929 int ftdi_disable_bitbang(struct ftdi_context *ftdi)
1930 {
1931     if (ftdi == NULL || ftdi->usb_dev == NULL)
1932         ftdi_error_return(-2, "USB device unavailable");
1933
1934     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)
1935         ftdi_error_return(-1, "unable to leave bitbang mode. Perhaps not a BM type chip?");
1936
1937     ftdi->bitbang_enabled = 0;
1938     return 0;
1939 }
1940
1941 /**
1942     Enable/disable bitbang modes.
1943
1944     \param ftdi pointer to ftdi_context
1945     \param bitmask Bitmask to configure lines.
1946            HIGH/ON value configures a line as output.
1947     \param mode Bitbang mode: use the values defined in \ref ftdi_mpsse_mode
1948
1949     \retval  0: all fine
1950     \retval -1: can't enable bitbang mode
1951     \retval -2: USB device unavailable
1952 */
1953 int ftdi_set_bitmode(struct ftdi_context *ftdi, unsigned char bitmask, unsigned char mode)
1954 {
1955     unsigned short usb_val;
1956
1957     if (ftdi == NULL || ftdi->usb_dev == NULL)
1958         ftdi_error_return(-2, "USB device unavailable");
1959
1960     usb_val = bitmask; // low byte: bitmask
1961     usb_val |= (mode << 8);
1962     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)
1963         ftdi_error_return(-1, "unable to configure bitbang mode. Perhaps not a 2232C type chip?");
1964
1965     ftdi->bitbang_mode = mode;
1966     ftdi->bitbang_enabled = (mode == BITMODE_RESET) ? 0 : 1;
1967     return 0;
1968 }
1969
1970 /**
1971     Directly read pin state, circumventing the read buffer. Useful for bitbang mode.
1972
1973     \param ftdi pointer to ftdi_context
1974     \param pins Pointer to store pins into
1975
1976     \retval  0: all fine
1977     \retval -1: read pins failed
1978     \retval -2: USB device unavailable
1979 */
1980 int ftdi_read_pins(struct ftdi_context *ftdi, unsigned char *pins)
1981 {
1982     if (ftdi == NULL || ftdi->usb_dev == NULL)
1983         ftdi_error_return(-2, "USB device unavailable");
1984
1985     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)
1986         ftdi_error_return(-1, "read pins failed");
1987
1988     return 0;
1989 }
1990
1991 /**
1992     Set latency timer
1993
1994     The FTDI chip keeps data in the internal buffer for a specific
1995     amount of time if the buffer is not full yet to decrease
1996     load on the usb bus.
1997
1998     \param ftdi pointer to ftdi_context
1999     \param latency Value between 1 and 255
2000
2001     \retval  0: all fine
2002     \retval -1: latency out of range
2003     \retval -2: unable to set latency timer
2004     \retval -3: USB device unavailable
2005 */
2006 int ftdi_set_latency_timer(struct ftdi_context *ftdi, unsigned char latency)
2007 {
2008     unsigned short usb_val;
2009
2010     if (latency < 1)
2011         ftdi_error_return(-1, "latency out of range. Only valid for 1-255");
2012
2013     if (ftdi == NULL || ftdi->usb_dev == NULL)
2014         ftdi_error_return(-3, "USB device unavailable");
2015
2016     usb_val = latency;
2017     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)
2018         ftdi_error_return(-2, "unable to set latency timer");
2019
2020     return 0;
2021 }
2022
2023 /**
2024     Get latency timer
2025
2026     \param ftdi pointer to ftdi_context
2027     \param latency Pointer to store latency value in
2028
2029     \retval  0: all fine
2030     \retval -1: unable to get latency timer
2031     \retval -2: USB device unavailable
2032 */
2033 int ftdi_get_latency_timer(struct ftdi_context *ftdi, unsigned char *latency)
2034 {
2035     unsigned short usb_val;
2036
2037     if (ftdi == NULL || ftdi->usb_dev == NULL)
2038         ftdi_error_return(-2, "USB device unavailable");
2039
2040     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)
2041         ftdi_error_return(-1, "reading latency timer failed");
2042
2043     *latency = (unsigned char)usb_val;
2044     return 0;
2045 }
2046
2047 /**
2048     Poll modem status information
2049
2050     This function allows the retrieve the two status bytes of the device.
2051     The device sends these bytes also as a header for each read access
2052     where they are discarded by ftdi_read_data(). The chip generates
2053     the two stripped status bytes in the absence of data every 40 ms.
2054
2055     Layout of the first byte:
2056     - B0..B3 - must be 0
2057     - B4       Clear to send (CTS)
2058                  0 = inactive
2059                  1 = active
2060     - B5       Data set ready (DTS)
2061                  0 = inactive
2062                  1 = active
2063     - B6       Ring indicator (RI)
2064                  0 = inactive
2065                  1 = active
2066     - B7       Receive line signal detect (RLSD)
2067                  0 = inactive
2068                  1 = active
2069
2070     Layout of the second byte:
2071     - B0       Data ready (DR)
2072     - B1       Overrun error (OE)
2073     - B2       Parity error (PE)
2074     - B3       Framing error (FE)
2075     - B4       Break interrupt (BI)
2076     - B5       Transmitter holding register (THRE)
2077     - B6       Transmitter empty (TEMT)
2078     - B7       Error in RCVR FIFO
2079
2080     \param ftdi pointer to ftdi_context
2081     \param status Pointer to store status information in. Must be two bytes.
2082
2083     \retval  0: all fine
2084     \retval -1: unable to retrieve status information
2085     \retval -2: USB device unavailable
2086 */
2087 int ftdi_poll_modem_status(struct ftdi_context *ftdi, unsigned short *status)
2088 {
2089     char usb_val[2];
2090
2091     if (ftdi == NULL || ftdi->usb_dev == NULL)
2092         ftdi_error_return(-2, "USB device unavailable");
2093
2094     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)
2095         ftdi_error_return(-1, "getting modem status failed");
2096
2097     *status = (usb_val[1] << 8) | (usb_val[0] & 0xFF);
2098
2099     return 0;
2100 }
2101
2102 /**
2103     Set flowcontrol for ftdi chip
2104
2105     \param ftdi pointer to ftdi_context
2106     \param flowctrl flow control to use. should be
2107            SIO_DISABLE_FLOW_CTRL, SIO_RTS_CTS_HS, SIO_DTR_DSR_HS or SIO_XON_XOFF_HS
2108
2109     \retval  0: all fine
2110     \retval -1: set flow control failed
2111     \retval -2: USB device unavailable
2112 */
2113 int ftdi_setflowctrl(struct ftdi_context *ftdi, int flowctrl)
2114 {
2115     if (ftdi == NULL || ftdi->usb_dev == NULL)
2116         ftdi_error_return(-2, "USB device unavailable");
2117
2118     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
2119                                 SIO_SET_FLOW_CTRL_REQUEST, 0, (flowctrl | ftdi->index),
2120                                 NULL, 0, ftdi->usb_write_timeout) < 0)
2121         ftdi_error_return(-1, "set flow control failed");
2122
2123     return 0;
2124 }
2125
2126 /**
2127     Set dtr line
2128
2129     \param ftdi pointer to ftdi_context
2130     \param state state to set line to (1 or 0)
2131
2132     \retval  0: all fine
2133     \retval -1: set dtr failed
2134     \retval -2: USB device unavailable
2135 */
2136 int ftdi_setdtr(struct ftdi_context *ftdi, int state)
2137 {
2138     unsigned short usb_val;
2139
2140     if (ftdi == NULL || ftdi->usb_dev == NULL)
2141         ftdi_error_return(-2, "USB device unavailable");
2142
2143     if (state)
2144         usb_val = SIO_SET_DTR_HIGH;
2145     else
2146         usb_val = SIO_SET_DTR_LOW;
2147
2148     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
2149                                 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
2150                                 NULL, 0, ftdi->usb_write_timeout) < 0)
2151         ftdi_error_return(-1, "set dtr failed");
2152
2153     return 0;
2154 }
2155
2156 /**
2157     Set rts line
2158
2159     \param ftdi pointer to ftdi_context
2160     \param state state to set line to (1 or 0)
2161
2162     \retval  0: all fine
2163     \retval -1: set rts failed
2164     \retval -2: USB device unavailable
2165 */
2166 int ftdi_setrts(struct ftdi_context *ftdi, int state)
2167 {
2168     unsigned short usb_val;
2169
2170     if (ftdi == NULL || ftdi->usb_dev == NULL)
2171         ftdi_error_return(-2, "USB device unavailable");
2172
2173     if (state)
2174         usb_val = SIO_SET_RTS_HIGH;
2175     else
2176         usb_val = SIO_SET_RTS_LOW;
2177
2178     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
2179                                 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
2180                                 NULL, 0, ftdi->usb_write_timeout) < 0)
2181         ftdi_error_return(-1, "set of rts failed");
2182
2183     return 0;
2184 }
2185
2186 /**
2187     Set dtr and rts line in one pass
2188
2189     \param ftdi pointer to ftdi_context
2190     \param dtr  DTR state to set line to (1 or 0)
2191     \param rts  RTS state to set line to (1 or 0)
2192
2193     \retval  0: all fine
2194     \retval -1: set dtr/rts failed
2195     \retval -2: USB device unavailable
2196  */
2197 int ftdi_setdtr_rts(struct ftdi_context *ftdi, int dtr, int rts)
2198 {
2199     unsigned short usb_val;
2200
2201     if (ftdi == NULL || ftdi->usb_dev == NULL)
2202         ftdi_error_return(-2, "USB device unavailable");
2203
2204     if (dtr)
2205         usb_val = SIO_SET_DTR_HIGH;
2206     else
2207         usb_val = SIO_SET_DTR_LOW;
2208
2209     if (rts)
2210         usb_val |= SIO_SET_RTS_HIGH;
2211     else
2212         usb_val |= SIO_SET_RTS_LOW;
2213
2214     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
2215                                 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
2216                                 NULL, 0, ftdi->usb_write_timeout) < 0)
2217         ftdi_error_return(-1, "set of rts/dtr failed");
2218
2219     return 0;
2220 }
2221
2222 /**
2223     Set the special event character
2224
2225     \param ftdi pointer to ftdi_context
2226     \param eventch Event character
2227     \param enable 0 to disable the event character, non-zero otherwise
2228
2229     \retval  0: all fine
2230     \retval -1: unable to set event character
2231     \retval -2: USB device unavailable
2232 */
2233 int ftdi_set_event_char(struct ftdi_context *ftdi,
2234                         unsigned char eventch, unsigned char enable)
2235 {
2236     unsigned short usb_val;
2237
2238     if (ftdi == NULL || ftdi->usb_dev == NULL)
2239         ftdi_error_return(-2, "USB device unavailable");
2240
2241     usb_val = eventch;
2242     if (enable)
2243         usb_val |= 1 << 8;
2244
2245     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)
2246         ftdi_error_return(-1, "setting event character failed");
2247
2248     return 0;
2249 }
2250
2251 /**
2252     Set error character
2253
2254     \param ftdi pointer to ftdi_context
2255     \param errorch Error character
2256     \param enable 0 to disable the error character, non-zero otherwise
2257
2258     \retval  0: all fine
2259     \retval -1: unable to set error character
2260     \retval -2: USB device unavailable
2261 */
2262 int ftdi_set_error_char(struct ftdi_context *ftdi,
2263                         unsigned char errorch, unsigned char enable)
2264 {
2265     unsigned short usb_val;
2266
2267     if (ftdi == NULL || ftdi->usb_dev == NULL)
2268         ftdi_error_return(-2, "USB device unavailable");
2269
2270     usb_val = errorch;
2271     if (enable)
2272         usb_val |= 1 << 8;
2273
2274     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)
2275         ftdi_error_return(-1, "setting error character failed");
2276
2277     return 0;
2278 }
2279
2280 /**
2281     Init eeprom with default values for the connected device
2282     \param ftdi pointer to ftdi_context
2283     \param manufacturer String to use as Manufacturer
2284     \param product String to use as Product description
2285     \param serial String to use as Serial number description
2286
2287     \retval  0: all fine
2288     \retval -1: No struct ftdi_context
2289     \retval -2: No struct ftdi_eeprom
2290     \retval -3: No connected device or device not yet opened
2291 */
2292 int ftdi_eeprom_initdefaults(struct ftdi_context *ftdi, char * manufacturer,
2293                              char * product, char * serial)
2294 {
2295     struct ftdi_eeprom *eeprom;
2296
2297     if (ftdi == NULL)
2298         ftdi_error_return(-1, "No struct ftdi_context");
2299
2300     if (ftdi->eeprom == NULL)
2301         ftdi_error_return(-2,"No struct ftdi_eeprom");
2302
2303     eeprom = ftdi->eeprom;
2304     memset(eeprom, 0, sizeof(struct ftdi_eeprom));
2305
2306     if (ftdi->usb_dev == NULL)
2307         ftdi_error_return(-3, "No connected device or device not yet opened");
2308
2309     eeprom->vendor_id = 0x0403;
2310     eeprom->use_serial = 1;
2311     if ((ftdi->type == TYPE_AM) || (ftdi->type == TYPE_BM) ||
2312             (ftdi->type == TYPE_R))
2313         eeprom->product_id = 0x6001;
2314     else if (ftdi->type == TYPE_4232H)
2315         eeprom->product_id = 0x6011;
2316     else if (ftdi->type == TYPE_232H)
2317         eeprom->product_id = 0x6014;
2318     else
2319         eeprom->product_id = 0x6010;
2320     if (ftdi->type == TYPE_AM)
2321         eeprom->usb_version = 0x0101;
2322     else
2323         eeprom->usb_version = 0x0200;
2324     eeprom->max_power = 100;
2325
2326     if (eeprom->manufacturer)
2327         free (eeprom->manufacturer);
2328     eeprom->manufacturer = NULL;
2329     if (manufacturer)
2330     {
2331         eeprom->manufacturer = malloc(strlen(manufacturer)+1);
2332         if (eeprom->manufacturer)
2333             strcpy(eeprom->manufacturer, manufacturer);
2334     }
2335
2336     if (eeprom->product)
2337         free (eeprom->product);
2338     eeprom->product = NULL;
2339     if(product)
2340     {
2341         eeprom->product = malloc(strlen(product)+1);
2342         if (eeprom->product)
2343             strcpy(eeprom->product, product);
2344     }
2345     else
2346     {
2347         const char* default_product;
2348         switch(ftdi->type)
2349         {
2350         case TYPE_AM:    default_product = "AM"; break;
2351         case TYPE_BM:    default_product = "BM"; break;
2352         case TYPE_2232C: default_product = "Dual RS232"; break;
2353         case TYPE_R:     default_product = "FT232R USB UART"; break;
2354         case TYPE_2232H: default_product = "Dual RS232-HS"; break;
2355         case TYPE_4232H: default_product = "FT4232H"; break;
2356         case TYPE_232H:  default_product = "Single-RS232-HS"; break;
2357         default:
2358         ftdi_error_return(-3, "Unknown chip type");
2359         }
2360         eeprom->product = malloc(strlen(default_product) +1);
2361         if (eeprom->product)
2362             strcpy(eeprom->product, default_product);
2363     }
2364
2365     if (eeprom->serial)
2366         free (eeprom->serial);
2367     eeprom->serial = NULL;
2368     if (serial)
2369     {
2370         eeprom->serial = malloc(strlen(serial)+1);
2371         if (eeprom->serial)
2372             strcpy(eeprom->serial, serial);
2373     }
2374
2375
2376     if (ftdi->type == TYPE_R)
2377     {
2378         eeprom->max_power = 90;
2379         eeprom->size = 0x80;
2380         eeprom->cbus_function[0] = CBUS_TXLED;
2381         eeprom->cbus_function[1] = CBUS_RXLED;
2382         eeprom->cbus_function[2] = CBUS_TXDEN;
2383         eeprom->cbus_function[3] = CBUS_PWREN;
2384         eeprom->cbus_function[4] = CBUS_SLEEP;
2385     }
2386     else
2387     {
2388         if(ftdi->type == TYPE_232H)
2389         {
2390             int i;
2391             for (i=0; i<10; i++)
2392                 eeprom->cbus_function[i] = CBUSH_TRISTATE;
2393         }
2394         eeprom->size = -1;
2395     }
2396     eeprom->initialized_for_connected_device = 1;
2397     return 0;
2398 }
2399 /*FTD2XX doesn't check for values not fitting in the ACBUS Signal oprtions*/
2400 void set_ft232h_cbus(struct ftdi_eeprom *eeprom, unsigned char * output)
2401 {
2402     int i;
2403     for(i=0; i<5;i++)
2404     {
2405         int mode_low, mode_high;
2406         if (eeprom->cbus_function[2*i]> CBUSH_CLK7_5)
2407             mode_low = CBUSH_TRISTATE;
2408         else
2409             mode_low = eeprom->cbus_function[2*i];
2410         if (eeprom->cbus_function[2*i+1]> CBUSH_CLK7_5)
2411             mode_high = CBUSH_TRISTATE;
2412         else
2413             mode_high = eeprom->cbus_function[2*i];
2414
2415         output[0x18+i] = mode_high <<4 | mode_low;
2416     }
2417 }
2418 /* Return the bits for the encoded EEPROM Structure of a requested Mode
2419  *
2420  */
2421 static unsigned char type2bit(unsigned char type, enum ftdi_chip_type chip)
2422 {
2423     switch (chip)
2424     {
2425     case TYPE_2232H:
2426     case TYPE_2232C:
2427     {
2428         switch (type)
2429         {
2430         case CHANNEL_IS_UART: return 0;
2431         case CHANNEL_IS_FIFO: return 0x01;
2432         case CHANNEL_IS_OPTO: return 0x02;
2433         case CHANNEL_IS_CPU : return 0x04;
2434         default: return 0;
2435         }
2436     }
2437     case TYPE_232H:
2438     {
2439         switch (type)
2440         {
2441         case CHANNEL_IS_UART   : return 0;
2442         case CHANNEL_IS_FIFO   : return 0x01;
2443         case CHANNEL_IS_OPTO   : return 0x02;
2444         case CHANNEL_IS_CPU    : return 0x04;
2445         case CHANNEL_IS_FT1284 : return 0x08;
2446         default: return 0;
2447         }
2448     }
2449     default: return 0;
2450     }
2451     return 0;
2452 }    
2453
2454 /**
2455     Build binary buffer from ftdi_eeprom structure.
2456     Output is suitable for ftdi_write_eeprom().
2457
2458     \param ftdi pointer to ftdi_context
2459
2460     \retval >=0: size of eeprom user area in bytes
2461     \retval -1: eeprom size (128 bytes) exceeded by custom strings
2462     \retval -2: Invalid eeprom or ftdi pointer
2463     \retval -3: Invalid cbus function setting     (FIXME: Not in the code?)
2464     \retval -4: Chip doesn't support invert       (FIXME: Not in the code?)
2465     \retval -5: Chip doesn't support high current drive         (FIXME: Not in the code?)
2466     \retval -6: No connected EEPROM or EEPROM Type unknown
2467 */
2468 int ftdi_eeprom_build(struct ftdi_context *ftdi)
2469 {
2470     unsigned char i, j, eeprom_size_mask;
2471     unsigned short checksum, value;
2472     unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
2473     int user_area_size;
2474     struct ftdi_eeprom *eeprom;
2475     unsigned char * output;
2476
2477     if (ftdi == NULL)
2478         ftdi_error_return(-2,"No context");
2479     if (ftdi->eeprom == NULL)
2480         ftdi_error_return(-2,"No eeprom structure");
2481
2482     eeprom= ftdi->eeprom;
2483     output = eeprom->buf;
2484
2485     if (eeprom->chip == -1)
2486         ftdi_error_return(-6,"No connected EEPROM or EEPROM type unknown");
2487
2488     if ((eeprom->chip == 0x56) || (eeprom->chip == 0x66))
2489         eeprom->size = 0x100;
2490     else
2491         eeprom->size = 0x80;
2492
2493     if (eeprom->manufacturer != NULL)
2494         manufacturer_size = strlen(eeprom->manufacturer);
2495     if (eeprom->product != NULL)
2496         product_size = strlen(eeprom->product);
2497     if (eeprom->serial != NULL)
2498         serial_size = strlen(eeprom->serial);
2499
2500     // eeprom size check
2501     switch (ftdi->type)
2502     {
2503         case TYPE_AM:
2504         case TYPE_BM:
2505             user_area_size = 96;    // base size for strings (total of 48 characters)
2506             break;
2507         case TYPE_2232C:
2508             user_area_size = 90;     // two extra config bytes and 4 bytes PnP stuff
2509             break;
2510         case TYPE_R:
2511             user_area_size = 88;     // four extra config bytes + 4 bytes PnP stuff
2512             break;
2513         case TYPE_2232H:            // six extra config bytes + 4 bytes PnP stuff
2514         case TYPE_4232H:
2515             user_area_size = 86;
2516             break;
2517         case TYPE_232H:
2518             user_area_size = 80;
2519             break;
2520         default:
2521             user_area_size = 0;
2522             break;
2523     }
2524     user_area_size  -= (manufacturer_size + product_size + serial_size) * 2;
2525
2526     if (user_area_size < 0)
2527         ftdi_error_return(-1,"eeprom size exceeded");
2528
2529     // empty eeprom
2530     memset (ftdi->eeprom->buf, 0, FTDI_MAX_EEPROM_SIZE);
2531
2532     // Bytes and Bits set for all Types
2533
2534     // Addr 02: Vendor ID
2535     output[0x02] = eeprom->vendor_id;
2536     output[0x03] = eeprom->vendor_id >> 8;
2537
2538     // Addr 04: Product ID
2539     output[0x04] = eeprom->product_id;
2540     output[0x05] = eeprom->product_id >> 8;
2541
2542     // Addr 06: Device release number (0400h for BM features)
2543     output[0x06] = 0x00;
2544     switch (ftdi->type)
2545     {
2546         case TYPE_AM:
2547             output[0x07] = 0x02;
2548             break;
2549         case TYPE_BM:
2550             output[0x07] = 0x04;
2551             break;
2552         case TYPE_2232C:
2553             output[0x07] = 0x05;
2554             break;
2555         case TYPE_R:
2556             output[0x07] = 0x06;
2557             break;
2558         case TYPE_2232H:
2559             output[0x07] = 0x07;
2560             break;
2561         case TYPE_4232H:
2562             output[0x07] = 0x08;
2563             break;
2564         case TYPE_232H:
2565             output[0x07] = 0x09;
2566             break;
2567         default:
2568             output[0x07] = 0x00;
2569     }
2570
2571     // Addr 08: Config descriptor
2572     // Bit 7: always 1
2573     // Bit 6: 1 if this device is self powered, 0 if bus powered
2574     // Bit 5: 1 if this device uses remote wakeup
2575     // Bit 4-0: reserved - 0
2576     j = 0x80;
2577     if (eeprom->self_powered == 1)
2578         j |= 0x40;
2579     if (eeprom->remote_wakeup == 1)
2580         j |= 0x20;
2581     output[0x08] = j;
2582
2583     // Addr 09: Max power consumption: max power = value * 2 mA
2584     output[0x09] = eeprom->max_power>>1;
2585
2586     if (ftdi->type != TYPE_AM)
2587     {
2588         // Addr 0A: Chip configuration
2589         // Bit 7: 0 - reserved
2590         // Bit 6: 0 - reserved
2591         // Bit 5: 0 - reserved
2592         // Bit 4: 1 - Change USB version
2593         // Bit 3: 1 - Use the serial number string
2594         // Bit 2: 1 - Enable suspend pull downs for lower power
2595         // Bit 1: 1 - Out EndPoint is Isochronous
2596         // Bit 0: 1 - In EndPoint is Isochronous
2597         //
2598         j = 0;
2599         if (eeprom->in_is_isochronous == 1)
2600             j = j | 1;
2601         if (eeprom->out_is_isochronous == 1)
2602             j = j | 2;
2603         output[0x0A] = j;
2604     }
2605
2606     // Dynamic content
2607     // Strings start at 0x94 (TYPE_AM, TYPE_BM)
2608     // 0x96 (TYPE_2232C), 0x98 (TYPE_R) and 0x9a (TYPE_x232H)
2609     // 0xa0 (TYPE_232H)
2610     i = 0;
2611     switch (ftdi->type)
2612     {
2613         case TYPE_232H:
2614             i += 2;
2615         case TYPE_2232H:
2616         case TYPE_4232H:
2617             i += 2;
2618         case TYPE_R:
2619             i += 2;
2620         case TYPE_2232C:
2621             i += 2;
2622         case TYPE_AM:
2623         case TYPE_BM:
2624             i += 0x94;
2625     }
2626     /* Wrap around 0x80 for 128 byte EEPROMS (Internale and 93x46) */
2627     eeprom_size_mask = eeprom->size -1;
2628
2629     // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
2630     // Addr 0F: Length of manufacturer string
2631     // Output manufacturer
2632     output[0x0E] = i;  // calculate offset
2633     output[i & eeprom_size_mask] = manufacturer_size*2 + 2, i++;
2634     output[i & eeprom_size_mask] = 0x03, i++; // type: string
2635     for (j = 0; j < manufacturer_size; j++)
2636     {
2637         output[i & eeprom_size_mask] = eeprom->manufacturer[j], i++;
2638         output[i & eeprom_size_mask] = 0x00, i++;
2639     }
2640     output[0x0F] = manufacturer_size*2 + 2;
2641
2642     // Addr 10: Offset of the product string + 0x80, calculated later
2643     // Addr 11: Length of product string
2644     output[0x10] = i | 0x80;  // calculate offset
2645     output[i & eeprom_size_mask] = product_size*2 + 2, i++;
2646     output[i & eeprom_size_mask] = 0x03, i++;
2647     for (j = 0; j < product_size; j++)
2648     {
2649         output[i & eeprom_size_mask] = eeprom->product[j], i++;
2650         output[i & eeprom_size_mask] = 0x00, i++;
2651     }
2652     output[0x11] = product_size*2 + 2;
2653
2654     // Addr 12: Offset of the serial string + 0x80, calculated later
2655     // Addr 13: Length of serial string
2656     output[0x12] = i | 0x80; // calculate offset
2657     output[i & eeprom_size_mask] = serial_size*2 + 2, i++;
2658     output[i & eeprom_size_mask] = 0x03, i++;
2659     for (j = 0; j < serial_size; j++)
2660     {
2661         output[i & eeprom_size_mask] = eeprom->serial[j], i++;
2662         output[i & eeprom_size_mask] = 0x00, i++;
2663     }
2664
2665     // Legacy port name and PnP fields for FT2232 and newer chips
2666     if (ftdi->type > TYPE_BM)
2667     {
2668         output[i & eeprom_size_mask] = 0x02; /* as seen when written with FTD2XX */
2669         i++;
2670         output[i & eeprom_size_mask] = 0x03; /* as seen when written with FTD2XX */
2671         i++;
2672         output[i & eeprom_size_mask] = eeprom->is_not_pnp; /* as seen when written with FTD2XX */
2673         i++;
2674     }
2675
2676     output[0x13] = serial_size*2 + 2;
2677
2678     if (ftdi->type > TYPE_AM) /* use_serial not used in AM devices */
2679     {
2680         if (eeprom->use_serial)
2681             output[0x0A] |= USE_SERIAL_NUM;
2682         else
2683             output[0x0A] &= ~USE_SERIAL_NUM;
2684     }
2685
2686     /* Bytes and Bits specific to (some) types
2687        Write linear, as this allows easier fixing*/
2688     switch (ftdi->type)
2689     {
2690         case TYPE_AM:
2691             break;
2692         case TYPE_BM:
2693             output[0x0C] = eeprom->usb_version & 0xff;
2694             output[0x0D] = (eeprom->usb_version>>8) & 0xff;
2695             if (eeprom->use_usb_version == USE_USB_VERSION_BIT)
2696                 output[0x0A] |= USE_USB_VERSION_BIT;
2697             else
2698                 output[0x0A] &= ~USE_USB_VERSION_BIT;
2699
2700             break;
2701         case TYPE_2232C:
2702
2703             output[0x00] = type2bit(eeprom->channel_a_type, TYPE_2232C);
2704             if ( eeprom->channel_a_driver == DRIVER_VCP)
2705                 output[0x00] |= DRIVER_VCP;
2706             else
2707                 output[0x00] &= ~DRIVER_VCP;
2708
2709             if ( eeprom->high_current_a == HIGH_CURRENT_DRIVE)
2710                 output[0x00] |= HIGH_CURRENT_DRIVE;
2711             else
2712                 output[0x00] &= ~HIGH_CURRENT_DRIVE;
2713
2714             output[0x01] = type2bit(eeprom->channel_b_type, TYPE_2232C);
2715             if ( eeprom->channel_b_driver == DRIVER_VCP)
2716                 output[0x01] |= DRIVER_VCP;
2717             else
2718                 output[0x01] &= ~DRIVER_VCP;
2719
2720             if ( eeprom->high_current_b == HIGH_CURRENT_DRIVE)
2721                 output[0x01] |= HIGH_CURRENT_DRIVE;
2722             else
2723                 output[0x01] &= ~HIGH_CURRENT_DRIVE;
2724
2725             if (eeprom->in_is_isochronous == 1)
2726                 output[0x0A] |= 0x1;
2727             else
2728                 output[0x0A] &= ~0x1;
2729             if (eeprom->out_is_isochronous == 1)
2730                 output[0x0A] |= 0x2;
2731             else
2732                 output[0x0A] &= ~0x2;
2733             if (eeprom->suspend_pull_downs == 1)
2734                 output[0x0A] |= 0x4;
2735             else
2736                 output[0x0A] &= ~0x4;
2737             if (eeprom->use_usb_version == USE_USB_VERSION_BIT)
2738                 output[0x0A] |= USE_USB_VERSION_BIT;
2739             else
2740                 output[0x0A] &= ~USE_USB_VERSION_BIT;
2741
2742             output[0x0C] = eeprom->usb_version & 0xff;
2743             output[0x0D] = (eeprom->usb_version>>8) & 0xff;
2744             output[0x14] = eeprom->chip;
2745             break;
2746         case TYPE_R:
2747             if (eeprom->high_current == HIGH_CURRENT_DRIVE_R)
2748                 output[0x00] |= HIGH_CURRENT_DRIVE_R;
2749             output[0x01] = 0x40; /* Hard coded Endpoint Size*/
2750
2751             if (eeprom->suspend_pull_downs == 1)
2752                 output[0x0A] |= 0x4;
2753             else
2754                 output[0x0A] &= ~0x4;
2755             output[0x0B] = eeprom->invert;
2756             output[0x0C] = eeprom->usb_version & 0xff;
2757             output[0x0D] = (eeprom->usb_version>>8) & 0xff;
2758
2759             if (eeprom->cbus_function[0] > CBUS_BB)
2760                 output[0x14] = CBUS_TXLED;
2761             else
2762                 output[0x14] = eeprom->cbus_function[0];
2763
2764             if (eeprom->cbus_function[1] > CBUS_BB)
2765                 output[0x14] |= CBUS_RXLED<<4;
2766             else
2767                 output[0x14] |= eeprom->cbus_function[1]<<4;
2768
2769             if (eeprom->cbus_function[2] > CBUS_BB)
2770                 output[0x15] = CBUS_TXDEN;
2771             else
2772                 output[0x15] = eeprom->cbus_function[2];
2773
2774             if (eeprom->cbus_function[3] > CBUS_BB)
2775                 output[0x15] |= CBUS_PWREN<<4;
2776             else
2777                 output[0x15] |= eeprom->cbus_function[3]<<4;
2778
2779             if (eeprom->cbus_function[4] > CBUS_CLK6)
2780                 output[0x16] = CBUS_SLEEP;
2781             else
2782                 output[0x16] = eeprom->cbus_function[4];
2783             break;
2784         case TYPE_2232H:
2785             output[0x00] = type2bit(eeprom->channel_a_type, TYPE_2232H);
2786             if ( eeprom->channel_a_driver == DRIVER_VCP)
2787                 output[0x00] |= DRIVER_VCP;
2788             else
2789                 output[0x00] &= ~DRIVER_VCP;
2790
2791             output[0x01] = type2bit(eeprom->channel_b_type, TYPE_2232H);
2792             if ( eeprom->channel_b_driver == DRIVER_VCP)
2793                 output[0x01] |= DRIVER_VCP;
2794             else
2795                 output[0x01] &= ~DRIVER_VCP;
2796             if (eeprom->suspend_dbus7 == SUSPEND_DBUS7_BIT)
2797                 output[0x01] |= SUSPEND_DBUS7_BIT;
2798             else
2799                 output[0x01] &= ~SUSPEND_DBUS7_BIT;
2800
2801             if (eeprom->suspend_pull_downs == 1)
2802                 output[0x0A] |= 0x4;
2803             else
2804                 output[0x0A] &= ~0x4;
2805
2806             if (eeprom->group0_drive > DRIVE_16MA)
2807                 output[0x0c] |= DRIVE_16MA;
2808             else
2809                 output[0x0c] |= eeprom->group0_drive;
2810             if (eeprom->group0_schmitt == IS_SCHMITT)
2811                 output[0x0c] |= IS_SCHMITT;
2812             if (eeprom->group0_slew == SLOW_SLEW)
2813                 output[0x0c] |= SLOW_SLEW;
2814
2815             if (eeprom->group1_drive > DRIVE_16MA)
2816                 output[0x0c] |= DRIVE_16MA<<4;
2817             else
2818                 output[0x0c] |= eeprom->group1_drive<<4;
2819             if (eeprom->group1_schmitt == IS_SCHMITT)
2820                 output[0x0c] |= IS_SCHMITT<<4;
2821             if (eeprom->group1_slew == SLOW_SLEW)
2822                 output[0x0c] |= SLOW_SLEW<<4;
2823
2824             if (eeprom->group2_drive > DRIVE_16MA)
2825                 output[0x0d] |= DRIVE_16MA;
2826             else
2827                 output[0x0d] |= eeprom->group2_drive;
2828             if (eeprom->group2_schmitt == IS_SCHMITT)
2829                 output[0x0d] |= IS_SCHMITT;
2830             if (eeprom->group2_slew == SLOW_SLEW)
2831                 output[0x0d] |= SLOW_SLEW;
2832
2833             if (eeprom->group3_drive > DRIVE_16MA)
2834                 output[0x0d] |= DRIVE_16MA<<4;
2835             else
2836                 output[0x0d] |= eeprom->group3_drive<<4;
2837             if (eeprom->group3_schmitt == IS_SCHMITT)
2838                 output[0x0d] |= IS_SCHMITT<<4;
2839             if (eeprom->group3_slew == SLOW_SLEW)
2840                 output[0x0d] |= SLOW_SLEW<<4;
2841
2842             output[0x18] = eeprom->chip;
2843
2844             break;
2845         case TYPE_4232H:
2846             output[0x18] = eeprom->chip;
2847             fprintf(stderr,"FIXME: Build FT4232H specific EEPROM settings\n");
2848             break;
2849         case TYPE_232H:
2850             output[0x00] = type2bit(eeprom->channel_a_type, TYPE_232H);
2851             if ( eeprom->channel_a_driver == DRIVER_VCP)
2852                 output[0x00] |= DRIVER_VCPH;
2853             else
2854                 output[0x00] &= ~DRIVER_VCPH;
2855             if (eeprom->powersave)
2856                 output[0x01] |= POWER_SAVE_DISABLE_H;
2857             else
2858                 output[0x01] &= ~POWER_SAVE_DISABLE_H;
2859             if (eeprom->clock_polarity)
2860                 output[0x01] |= FT1284_CLK_IDLE_STATE;
2861             else
2862                 output[0x01] &= ~FT1284_CLK_IDLE_STATE;
2863             if (eeprom->data_order)
2864                 output[0x01] |= FT1284_DATA_LSB;
2865             else
2866                 output[0x01] &= ~FT1284_DATA_LSB;
2867             if (eeprom->flow_control)
2868                 output[0x01] |= FT1284_FLOW_CONTROL;
2869             else
2870                 output[0x01] &= ~FT1284_FLOW_CONTROL;
2871             if (eeprom->group0_drive > DRIVE_16MA)
2872                 output[0x0c] |= DRIVE_16MA;
2873             else
2874                 output[0x0c] |= eeprom->group0_drive;
2875             if (eeprom->group0_schmitt == IS_SCHMITT)
2876                 output[0x0c] |= IS_SCHMITT;
2877             if (eeprom->group0_slew == SLOW_SLEW)
2878                 output[0x0c] |= SLOW_SLEW;
2879
2880             if (eeprom->group1_drive > DRIVE_16MA)
2881                 output[0x0d] |= DRIVE_16MA;
2882             else
2883                 output[0x0d] |= eeprom->group1_drive;
2884             if (eeprom->group1_schmitt == IS_SCHMITT)
2885                 output[0x0d] |= IS_SCHMITT;
2886             if (eeprom->group1_slew == SLOW_SLEW)
2887                 output[0x0d] |= SLOW_SLEW;
2888
2889             set_ft232h_cbus(eeprom, output);
2890
2891             output[0x1e] = eeprom->chip;
2892             fprintf(stderr,"FIXME: Build FT232H specific EEPROM settings\n");
2893             break;
2894               
2895     }
2896
2897     // calculate checksum
2898     checksum = 0xAAAA;
2899
2900     for (i = 0; i < eeprom->size/2-1; i++)
2901     {
2902         value = output[i*2];
2903         value += output[(i*2)+1] << 8;
2904
2905         checksum = value^checksum;
2906         checksum = (checksum << 1) | (checksum >> 15);
2907     }
2908
2909     output[eeprom->size-2] = checksum;
2910     output[eeprom->size-1] = checksum >> 8;
2911
2912     return user_area_size;
2913 }
2914 /* Decode the encoded EEPROM field for the FTDI Mode into a value for the abstracted 
2915  * EEPROM structure
2916  *
2917  * FTD2XX doesn't allow to set multiple bits in the interface mode bitfield, and so do we
2918  */
2919 static unsigned char bit2type(unsigned char bits)
2920 {
2921     switch (bits)
2922     {
2923     case   0: return CHANNEL_IS_UART;
2924     case   1: return CHANNEL_IS_FIFO;
2925     case   2: return CHANNEL_IS_OPTO;
2926     case   4: return CHANNEL_IS_CPU;
2927     case   8: return CHANNEL_IS_FT1284;
2928     default:
2929         fprintf(stderr," Unexpected value %d for Hardware Interface type\n",
2930                 bits);
2931     }
2932     return 0;
2933 }
2934 /**
2935    Decode binary EEPROM image into an ftdi_eeprom structure.
2936
2937    \param ftdi pointer to ftdi_context
2938    \param verbose Decode EEPROM on stdout
2939
2940    \retval 0: all fine
2941    \retval -1: something went wrong
2942
2943    FIXME: How to pass size? How to handle size field in ftdi_eeprom?
2944    FIXME: Strings are malloc'ed here and should be freed somewhere
2945 */
2946 int ftdi_eeprom_decode(struct ftdi_context *ftdi, int verbose)
2947 {
2948     unsigned char i, j;
2949     unsigned short checksum, eeprom_checksum, value;
2950     unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
2951     int eeprom_size;
2952     struct ftdi_eeprom *eeprom;
2953     unsigned char *buf = ftdi->eeprom->buf;
2954     int release;
2955
2956     if (ftdi == NULL)
2957         ftdi_error_return(-1,"No context");
2958     if (ftdi->eeprom == NULL)
2959         ftdi_error_return(-1,"No eeprom structure");
2960
2961     eeprom = ftdi->eeprom;
2962     eeprom_size = eeprom->size;
2963
2964     // Addr 02: Vendor ID
2965     eeprom->vendor_id = buf[0x02] + (buf[0x03] << 8);
2966
2967     // Addr 04: Product ID
2968     eeprom->product_id = buf[0x04] + (buf[0x05] << 8);
2969
2970     release = buf[0x06] + (buf[0x07]<<8);
2971
2972     // Addr 08: Config descriptor
2973     // Bit 7: always 1
2974     // Bit 6: 1 if this device is self powered, 0 if bus powered
2975     // Bit 5: 1 if this device uses remote wakeup
2976     eeprom->self_powered = buf[0x08] & 0x40;
2977     eeprom->remote_wakeup = buf[0x08] & 0x20;
2978
2979     // Addr 09: Max power consumption: max power = value * 2 mA
2980     eeprom->max_power = buf[0x09];
2981
2982     // Addr 0A: Chip configuration
2983     // Bit 7: 0 - reserved
2984     // Bit 6: 0 - reserved
2985     // Bit 5: 0 - reserved
2986     // Bit 4: 1 - Change USB version on BM and 2232C
2987     // Bit 3: 1 - Use the serial number string
2988     // Bit 2: 1 - Enable suspend pull downs for lower power
2989     // Bit 1: 1 - Out EndPoint is Isochronous
2990     // Bit 0: 1 - In EndPoint is Isochronous
2991     //
2992     eeprom->in_is_isochronous  = buf[0x0A]&0x01;
2993     eeprom->out_is_isochronous = buf[0x0A]&0x02;
2994     eeprom->suspend_pull_downs = buf[0x0A]&0x04;
2995     eeprom->use_serial         = (buf[0x0A] & USE_SERIAL_NUM)?1:0;
2996     eeprom->use_usb_version    = buf[0x0A] & USE_USB_VERSION_BIT;
2997
2998     // Addr 0C: USB version low byte when 0x0A
2999     // Addr 0D: USB version high byte when 0x0A
3000     eeprom->usb_version = buf[0x0C] + (buf[0x0D] << 8);
3001
3002     // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
3003     // Addr 0F: Length of manufacturer string
3004     manufacturer_size = buf[0x0F]/2;
3005     if (eeprom->manufacturer)
3006         free(eeprom->manufacturer);
3007     if (manufacturer_size > 0)
3008     {
3009         eeprom->manufacturer = malloc(manufacturer_size);
3010         if (eeprom->manufacturer)
3011         {
3012             // Decode manufacturer
3013             i = buf[0x0E] & (eeprom_size -1); // offset
3014             for (j=0;j<manufacturer_size-1;j++)
3015             {
3016                 eeprom->manufacturer[j] = buf[2*j+i+2];
3017             }
3018             eeprom->manufacturer[j] = '\0';
3019         }
3020     }
3021     else eeprom->manufacturer = NULL;
3022
3023     // Addr 10: Offset of the product string + 0x80, calculated later
3024     // Addr 11: Length of product string
3025     if (eeprom->product)
3026         free(eeprom->product);
3027     product_size = buf[0x11]/2;
3028     if (product_size > 0)
3029     {
3030         eeprom->product = malloc(product_size);
3031         if (eeprom->product)
3032         {
3033             // Decode product name
3034             i = buf[0x10] & (eeprom_size -1); // offset
3035             for (j=0;j<product_size-1;j++)
3036             {
3037                 eeprom->product[j] = buf[2*j+i+2];
3038             }
3039             eeprom->product[j] = '\0';
3040         }
3041     }
3042     else eeprom->product = NULL;
3043
3044     // Addr 12: Offset of the serial string + 0x80, calculated later
3045     // Addr 13: Length of serial string
3046     if (eeprom->serial)
3047         free(eeprom->serial);
3048     serial_size = buf[0x13]/2;
3049     if (serial_size > 0)
3050     {
3051         eeprom->serial = malloc(serial_size);
3052         if (eeprom->serial)
3053         {
3054             // Decode serial
3055             i = buf[0x12] & (eeprom_size -1); // offset
3056             for (j=0;j<serial_size-1;j++)
3057             {
3058                 eeprom->serial[j] = buf[2*j+i+2];
3059             }
3060             eeprom->serial[j] = '\0';
3061         }
3062     }
3063     else eeprom->serial = NULL;
3064
3065     // verify checksum
3066     checksum = 0xAAAA;
3067
3068     for (i = 0; i < eeprom_size/2-1; i++)
3069     {
3070         value = buf[i*2];
3071         value += buf[(i*2)+1] << 8;
3072
3073         checksum = value^checksum;
3074         checksum = (checksum << 1) | (checksum >> 15);
3075     }
3076
3077     eeprom_checksum = buf[eeprom_size-2] + (buf[eeprom_size-1] << 8);
3078
3079     if (eeprom_checksum != checksum)
3080     {
3081         fprintf(stderr, "Checksum Error: %04x %04x\n", checksum, eeprom_checksum);
3082         ftdi_error_return(-1,"EEPROM checksum error");
3083     }
3084
3085     eeprom->channel_a_type   = 0;
3086     if ((ftdi->type == TYPE_AM) || (ftdi->type == TYPE_BM))
3087     {
3088         eeprom->chip = -1;
3089     }
3090     else if (ftdi->type == TYPE_2232C)
3091     {
3092         eeprom->channel_a_type   = bit2type(buf[0x00] & 0x7);
3093         eeprom->channel_a_driver = buf[0x00] & DRIVER_VCP;
3094         eeprom->high_current_a   = buf[0x00] & HIGH_CURRENT_DRIVE;
3095         eeprom->channel_b_type   = buf[0x01] & 0x7;
3096         eeprom->channel_b_driver = buf[0x01] & DRIVER_VCP;
3097         eeprom->high_current_b   = buf[0x01] & HIGH_CURRENT_DRIVE;
3098         eeprom->chip = buf[0x14];
3099     }
3100     else if (ftdi->type == TYPE_R)
3101     {
3102         /* TYPE_R flags D2XX, not VCP as all others*/
3103         eeprom->channel_a_driver = (~buf[0x00]) & DRIVER_VCP;
3104         eeprom->high_current     = buf[0x00] & HIGH_CURRENT_DRIVE_R;
3105         if ( (buf[0x01]&0x40) != 0x40)
3106             fprintf(stderr,
3107                     "TYPE_R EEPROM byte[0x01] Bit 6 unexpected Endpoint size."
3108                     " If this happened with the\n"
3109                     " EEPROM programmed by FTDI tools, please report "
3110                     "to libftdi@developer.intra2net.com\n");
3111
3112         eeprom->chip = buf[0x16];
3113         // Addr 0B: Invert data lines
3114         // Works only on FT232R, not FT245R, but no way to distinguish
3115         eeprom->invert = buf[0x0B];
3116         // Addr 14: CBUS function: CBUS0, CBUS1
3117         // Addr 15: CBUS function: CBUS2, CBUS3
3118         // Addr 16: CBUS function: CBUS5
3119         eeprom->cbus_function[0] = buf[0x14] & 0x0f;
3120         eeprom->cbus_function[1] = (buf[0x14] >> 4) & 0x0f;
3121         eeprom->cbus_function[2] = buf[0x15] & 0x0f;
3122         eeprom->cbus_function[3] = (buf[0x15] >> 4) & 0x0f;
3123         eeprom->cbus_function[4] = buf[0x16] & 0x0f;
3124     }
3125     else if ((ftdi->type == TYPE_2232H) ||(ftdi->type == TYPE_4232H))
3126     {
3127         eeprom->channel_a_type   = bit2type(buf[0x00] & 0x7);
3128         eeprom->channel_a_driver = buf[0x00] & DRIVER_VCP;
3129         eeprom->channel_b_type   = bit2type(buf[0x01] & 0x7);
3130         eeprom->channel_b_driver = buf[0x01] & DRIVER_VCP;
3131
3132         if (ftdi->type == TYPE_2232H)
3133             eeprom->suspend_dbus7    = buf[0x01] & SUSPEND_DBUS7_BIT;
3134
3135         eeprom->chip = buf[0x18];
3136         eeprom->group0_drive   =  buf[0x0c]       & DRIVE_16MA;
3137         eeprom->group0_schmitt =  buf[0x0c]       & IS_SCHMITT;
3138         eeprom->group0_slew    =  buf[0x0c]       & SLOW_SLEW;
3139         eeprom->group1_drive   = (buf[0x0c] >> 4) & 0x3;
3140         eeprom->group1_schmitt = (buf[0x0c] >> 4) & IS_SCHMITT;
3141         eeprom->group1_slew    = (buf[0x0c] >> 4) & SLOW_SLEW;
3142         eeprom->group2_drive   =  buf[0x0d]       & DRIVE_16MA;
3143         eeprom->group2_schmitt =  buf[0x0d]       & IS_SCHMITT;
3144         eeprom->group2_slew    =  buf[0x0d]       & SLOW_SLEW;
3145         eeprom->group3_drive   = (buf[0x0d] >> 4) & DRIVE_16MA;
3146         eeprom->group3_schmitt = (buf[0x0d] >> 4) & IS_SCHMITT;
3147         eeprom->group3_slew    = (buf[0x0d] >> 4) & SLOW_SLEW;
3148     }
3149     else if (ftdi->type == TYPE_232H)
3150     {
3151         int i;
3152
3153         eeprom->channel_a_type   = buf[0x00] & 0xf;
3154         eeprom->channel_a_driver = (buf[0x00] & DRIVER_VCPH)?DRIVER_VCP:0;
3155         eeprom->clock_polarity =  buf[0x01]       & FT1284_CLK_IDLE_STATE;
3156         eeprom->data_order     =  buf[0x01]       & FT1284_DATA_LSB;
3157         eeprom->flow_control   =  buf[0x01]       & FT1284_FLOW_CONTROL;
3158         eeprom->powersave      =  buf[0x01]       & POWER_SAVE_DISABLE_H;
3159         eeprom->group0_drive   =  buf[0x0c]       & DRIVE_16MA;
3160         eeprom->group0_schmitt =  buf[0x0c]       & IS_SCHMITT;
3161         eeprom->group0_slew    =  buf[0x0c]       & SLOW_SLEW;
3162         eeprom->group1_drive   =  buf[0x0d]       & DRIVE_16MA;
3163         eeprom->group1_schmitt =  buf[0x0d]       & IS_SCHMITT;
3164         eeprom->group1_slew    =  buf[0x0d]       & SLOW_SLEW;
3165
3166         for(i=0; i<5; i++)
3167         {
3168             eeprom->cbus_function[2*i  ] =  buf[0x18+i] & 0x0f;
3169             eeprom->cbus_function[2*i+1] = (buf[0x18+i] >> 4) & 0x0f;
3170         }
3171         eeprom->chip = buf[0x1e];
3172         /*FIXME: Decipher more values*/
3173     }
3174
3175     if (verbose)
3176     {
3177         char *channel_mode[] = {"UART", "FIFO", "CPU", "OPTO", "FT1284"};
3178         fprintf(stdout, "VID:     0x%04x\n",eeprom->vendor_id);
3179         fprintf(stdout, "PID:     0x%04x\n",eeprom->product_id);
3180         fprintf(stdout, "Release: 0x%04x\n",release);
3181
3182         if (eeprom->self_powered)
3183             fprintf(stdout, "Self-Powered%s", (eeprom->remote_wakeup)?", USB Remote Wake Up\n":"\n");
3184         else
3185             fprintf(stdout, "Bus Powered: %3d mA%s", eeprom->max_power * 2,
3186                     (eeprom->remote_wakeup)?" USB Remote Wake Up\n":"\n");
3187         if (eeprom->manufacturer)
3188             fprintf(stdout, "Manufacturer: %s\n",eeprom->manufacturer);
3189         if (eeprom->product)
3190             fprintf(stdout, "Product:      %s\n",eeprom->product);
3191         if (eeprom->serial)
3192             fprintf(stdout, "Serial:       %s\n",eeprom->serial);
3193         fprintf(stdout,     "Checksum      : %04x\n", checksum);
3194         if (ftdi->type == TYPE_R)
3195             fprintf(stdout,     "Internal EEPROM\n");
3196         else if (eeprom->chip >= 0x46)
3197             fprintf(stdout,     "Attached EEPROM: 93x%02x\n", eeprom->chip);
3198         if (eeprom->suspend_dbus7)
3199             fprintf(stdout, "Suspend on DBUS7\n");
3200         if (eeprom->suspend_pull_downs)
3201             fprintf(stdout, "Pull IO pins low during suspend\n");
3202         if(eeprom->powersave)
3203         {
3204             if(ftdi->type >= TYPE_232H)
3205                 fprintf(stdout,"Enter low power state on ACBUS7\n");
3206         } 
3207         if (eeprom->remote_wakeup)
3208             fprintf(stdout, "Enable Remote Wake Up\n");
3209         fprintf(stdout, "PNP: %d\n",(eeprom->is_not_pnp)?0:1);
3210         if (ftdi->type >= TYPE_2232C)
3211             fprintf(stdout,"Channel A has Mode %s%s%s\n",
3212                     channel_mode[eeprom->channel_a_type],
3213                     (eeprom->channel_a_driver)?" VCP":"",
3214                     (eeprom->high_current_a)?" High Current IO":"");
3215         if (ftdi->type >= TYPE_232H)
3216         {
3217             fprintf(stdout,"FT1284 Mode Clock is idle %s, %s first, %sFlow Control\n",
3218                     (eeprom->clock_polarity)?"HIGH":"LOW",
3219                     (eeprom->data_order)?"LSB":"MSB",
3220                     (eeprom->flow_control)?"":"No ");
3221         }        
3222         if ((ftdi->type >= TYPE_2232C) && (ftdi->type != TYPE_R) && (ftdi->type != TYPE_232H))
3223             fprintf(stdout,"Channel B has Mode %s%s%s\n",
3224                     channel_mode[eeprom->channel_b_type],
3225                     (eeprom->channel_b_driver)?" VCP":"",
3226                     (eeprom->high_current_b)?" High Current IO":"");
3227         if (((ftdi->type == TYPE_BM) || (ftdi->type == TYPE_2232C)) &&
3228                 eeprom->use_usb_version == USE_USB_VERSION_BIT)
3229             fprintf(stdout,"Use explicit USB Version %04x\n",eeprom->usb_version);
3230
3231         if ((ftdi->type == TYPE_2232H) || (ftdi->type == TYPE_4232H))
3232         {
3233             fprintf(stdout,"%s has %d mA drive%s%s\n",
3234                     (ftdi->type == TYPE_2232H)?"AL":"A",
3235                     (eeprom->group0_drive+1) *4,
3236                     (eeprom->group0_schmitt)?" Schmitt Input":"",
3237                     (eeprom->group0_slew)?" Slow Slew":"");
3238             fprintf(stdout,"%s has %d mA drive%s%s\n",
3239                     (ftdi->type == TYPE_2232H)?"AH":"B",
3240                     (eeprom->group1_drive+1) *4,
3241                     (eeprom->group1_schmitt)?" Schmitt Input":"",
3242                     (eeprom->group1_slew)?" Slow Slew":"");
3243             fprintf(stdout,"%s has %d mA drive%s%s\n",
3244                     (ftdi->type == TYPE_2232H)?"BL":"C",
3245                     (eeprom->group2_drive+1) *4,
3246                     (eeprom->group2_schmitt)?" Schmitt Input":"",
3247                     (eeprom->group2_slew)?" Slow Slew":"");
3248             fprintf(stdout,"%s has %d mA drive%s%s\n",
3249                     (ftdi->type == TYPE_2232H)?"BH":"D",
3250                     (eeprom->group3_drive+1) *4,
3251                     (eeprom->group3_schmitt)?" Schmitt Input":"",
3252                     (eeprom->group3_slew)?" Slow Slew":"");
3253         }
3254         else if (ftdi->type == TYPE_232H)
3255         {
3256             int i;
3257             char *cbush_mux[] = {"TRISTATE","RXLED","TXLED", "TXRXLED","PWREN",
3258                                 "SLEEP","DRIVE_0","DRIVE_1","IOMODE","TXDEN",
3259                                 "CLK30","CLK15","CLK7_5"
3260                                };
3261             fprintf(stdout,"ACBUS has %d mA drive%s%s\n",
3262                     (eeprom->group0_drive+1) *4,
3263                     (eeprom->group0_schmitt)?" Schmitt Input":"",
3264                     (eeprom->group0_slew)?" Slow Slew":"");
3265             fprintf(stdout,"ADBUS has %d mA drive%s%s\n",
3266                     (eeprom->group1_drive+1) *4,
3267                     (eeprom->group1_schmitt)?" Schmitt Input":"",
3268                     (eeprom->group1_slew)?" Slow Slew":"");
3269             for (i=0; i<10; i++)
3270             {
3271                 if (eeprom->cbus_function[i]<= CBUSH_CLK7_5 )
3272                     fprintf(stdout,"C%d Function: %s\n", i,
3273                             cbush_mux[eeprom->cbus_function[i]]);
3274             }
3275
3276         }
3277
3278         if (ftdi->type == TYPE_R)
3279         {
3280             char *cbus_mux[] = {"TXDEN","PWREN","RXLED", "TXLED","TX+RXLED",
3281                                 "SLEEP","CLK48","CLK24","CLK12","CLK6",
3282                                 "IOMODE","BB_WR","BB_RD"
3283                                };
3284             char *cbus_BB[] = {"RXF","TXE","RD", "WR"};
3285
3286             if (eeprom->invert)
3287             {
3288                 char *r_bits[] = {"TXD","RXD","RTS", "CTS","DTR","DSR","DCD","RI"};
3289                 fprintf(stdout,"Inverted bits:");
3290                 for (i=0; i<8; i++)
3291                     if ((eeprom->invert & (1<<i)) == (1<<i))
3292                         fprintf(stdout," %s",r_bits[i]);
3293                 fprintf(stdout,"\n");
3294             }
3295             for (i=0; i<5; i++)
3296             {
3297                 if (eeprom->cbus_function[i]<CBUS_BB)
3298                     fprintf(stdout,"C%d Function: %s\n", i,
3299                             cbus_mux[eeprom->cbus_function[i]]);
3300                 else
3301                 {
3302                     if (i < 4)
3303                         /* Running MPROG show that C0..3 have fixed function Synchronous
3304                            Bit Bang mode */
3305                         fprintf(stdout,"C%d BB Function: %s\n", i,
3306                                 cbus_BB[i]);
3307                     else
3308                         fprintf(stdout, "Unknown CBUS mode. Might be special mode?\n");
3309                 }
3310             }
3311         }
3312     }
3313     return 0;
3314 }
3315
3316 /**
3317    Get a value from the decoded EEPROM structure
3318
3319    \param ftdi pointer to ftdi_context
3320    \param value_name Enum of the value to query
3321    \param value Pointer to store read value
3322
3323    \retval 0: all fine
3324    \retval -1: Value doesn't exist
3325 */
3326 int ftdi_get_eeprom_value(struct ftdi_context *ftdi, enum ftdi_eeprom_value value_name, int* value)
3327 {
3328     switch (value_name)
3329     {
3330         case VENDOR_ID:
3331             *value = ftdi->eeprom->vendor_id;
3332             break;
3333         case PRODUCT_ID:
3334             *value = ftdi->eeprom->product_id;
3335             break;
3336         case SELF_POWERED:
3337             *value = ftdi->eeprom->self_powered;
3338             break;
3339         case REMOTE_WAKEUP:
3340             *value = ftdi->eeprom->remote_wakeup;
3341             break;
3342         case IS_NOT_PNP:
3343             *value = ftdi->eeprom->is_not_pnp;
3344             break;
3345         case SUSPEND_DBUS7:
3346             *value = ftdi->eeprom->suspend_dbus7;
3347             break;
3348         case IN_IS_ISOCHRONOUS:
3349             *value = ftdi->eeprom->in_is_isochronous;
3350             break;
3351         case OUT_IS_ISOCHRONOUS:
3352             *value = ftdi->eeprom->out_is_isochronous;
3353             break;
3354         case SUSPEND_PULL_DOWNS:
3355             *value = ftdi->eeprom->suspend_pull_downs;
3356             break;
3357         case USE_SERIAL:
3358             *value = ftdi->eeprom->use_serial;
3359             break;
3360         case USB_VERSION:
3361             *value = ftdi->eeprom->usb_version;
3362             break;
3363         case USE_USB_VERSION:
3364             *value = ftdi->eeprom->use_usb_version;
3365             break;
3366         case MAX_POWER:
3367             *value = ftdi->eeprom->max_power;
3368             break;
3369         case CHANNEL_A_TYPE:
3370             *value = ftdi->eeprom->channel_a_type;
3371             break;
3372         case CHANNEL_B_TYPE:
3373             *value = ftdi->eeprom->channel_b_type;
3374             break;
3375         case CHANNEL_A_DRIVER:
3376             *value = ftdi->eeprom->channel_a_driver;
3377             break;
3378         case CHANNEL_B_DRIVER:
3379             *value = ftdi->eeprom->channel_b_driver;
3380             break;
3381         case CBUS_FUNCTION_0:
3382             *value = ftdi->eeprom->cbus_function[0];
3383             break;
3384         case CBUS_FUNCTION_1:
3385             *value = ftdi->eeprom->cbus_function[1];
3386             break;
3387         case CBUS_FUNCTION_2:
3388             *value = ftdi->eeprom->cbus_function[2];
3389             break;
3390         case CBUS_FUNCTION_3:
3391             *value = ftdi->eeprom->cbus_function[3];
3392             break;
3393         case CBUS_FUNCTION_4:
3394             *value = ftdi->eeprom->cbus_function[4];
3395             break;
3396         case CBUS_FUNCTION_5:
3397             *value = ftdi->eeprom->cbus_function[5];
3398             break;
3399         case CBUS_FUNCTION_6:
3400             *value = ftdi->eeprom->cbus_function[6];
3401             break;
3402         case CBUS_FUNCTION_7:
3403             *value = ftdi->eeprom->cbus_function[7];
3404             break;
3405         case CBUS_FUNCTION_8:
3406             *value = ftdi->eeprom->cbus_function[8];
3407             break;
3408         case CBUS_FUNCTION_9:
3409             *value = ftdi->eeprom->cbus_function[8];
3410             break;
3411         case HIGH_CURRENT:
3412             *value = ftdi->eeprom->high_current;
3413             break;
3414         case HIGH_CURRENT_A:
3415             *value = ftdi->eeprom->high_current_a;
3416             break;
3417         case HIGH_CURRENT_B:
3418             *value = ftdi->eeprom->high_current_b;
3419             break;
3420         case INVERT:
3421             *value = ftdi->eeprom->invert;
3422             break;
3423         case GROUP0_DRIVE:
3424             *value = ftdi->eeprom->group0_drive;
3425             break;
3426         case GROUP0_SCHMITT:
3427             *value = ftdi->eeprom->group0_schmitt;
3428             break;
3429         case GROUP0_SLEW:
3430             *value = ftdi->eeprom->group0_slew;
3431             break;
3432         case GROUP1_DRIVE:
3433             *value = ftdi->eeprom->group1_drive;
3434             break;
3435         case GROUP1_SCHMITT:
3436             *value = ftdi->eeprom->group1_schmitt;
3437             break;
3438         case GROUP1_SLEW:
3439             *value = ftdi->eeprom->group1_slew;
3440             break;
3441         case GROUP2_DRIVE:
3442             *value = ftdi->eeprom->group2_drive;
3443             break;
3444         case GROUP2_SCHMITT:
3445             *value = ftdi->eeprom->group2_schmitt;
3446             break;
3447         case GROUP2_SLEW:
3448             *value = ftdi->eeprom->group2_slew;
3449             break;
3450         case GROUP3_DRIVE:
3451             *value = ftdi->eeprom->group3_drive;
3452             break;
3453         case GROUP3_SCHMITT:
3454             *value = ftdi->eeprom->group3_schmitt;
3455             break;
3456         case GROUP3_SLEW:
3457             *value = ftdi->eeprom->group3_slew;
3458             break;
3459          case POWER_SAVE:
3460             *value = ftdi->eeprom->powersave;
3461             break;
3462           case CLOCK_POLARITY:
3463             *value = ftdi->eeprom->clock_polarity;
3464             break;
3465          case DATA_ORDER:
3466             *value = ftdi->eeprom->data_order;
3467             break;
3468          case FLOW_CONTROL:
3469             *value = ftdi->eeprom->flow_control;
3470             break;
3471        case CHIP_TYPE:
3472             *value = ftdi->eeprom->chip;
3473             break;
3474         case CHIP_SIZE:
3475             *value = ftdi->eeprom->size;
3476             break;
3477         default:
3478             ftdi_error_return(-1, "Request for unknown EEPROM value");
3479     }
3480     return 0;
3481 }
3482
3483 /**
3484    Set a value in the decoded EEPROM Structure
3485    No parameter checking is performed
3486
3487    \param ftdi pointer to ftdi_context
3488    \param value_name Enum of the value to set
3489    \param value to set
3490
3491    \retval 0: all fine
3492    \retval -1: Value doesn't exist
3493    \retval -2: Value not user settable
3494 */
3495 int ftdi_set_eeprom_value(struct ftdi_context *ftdi, enum ftdi_eeprom_value value_name, int value)
3496 {
3497     switch (value_name)
3498     {
3499         case VENDOR_ID:
3500             ftdi->eeprom->vendor_id = value;
3501             break;
3502         case PRODUCT_ID:
3503             ftdi->eeprom->product_id = value;
3504             break;
3505         case SELF_POWERED:
3506             ftdi->eeprom->self_powered = value;
3507             break;
3508         case REMOTE_WAKEUP:
3509             ftdi->eeprom->remote_wakeup = value;
3510             break;
3511         case IS_NOT_PNP:
3512             ftdi->eeprom->is_not_pnp = value;
3513             break;
3514         case SUSPEND_DBUS7:
3515             ftdi->eeprom->suspend_dbus7 = value;
3516             break;
3517         case IN_IS_ISOCHRONOUS:
3518             ftdi->eeprom->in_is_isochronous = value;
3519             break;
3520         case OUT_IS_ISOCHRONOUS:
3521             ftdi->eeprom->out_is_isochronous = value;
3522             break;
3523         case SUSPEND_PULL_DOWNS:
3524             ftdi->eeprom->suspend_pull_downs = value;
3525             break;
3526         case USE_SERIAL:
3527             ftdi->eeprom->use_serial = value;
3528             break;
3529         case USB_VERSION:
3530             ftdi->eeprom->usb_version = value;
3531             break;
3532         case USE_USB_VERSION:
3533             ftdi->eeprom->use_usb_version = value;
3534             break;
3535         case MAX_POWER:
3536             ftdi->eeprom->max_power = value;
3537             break;
3538         case CHANNEL_A_TYPE:
3539             ftdi->eeprom->channel_a_type = value;
3540             break;
3541         case CHANNEL_B_TYPE:
3542             ftdi->eeprom->channel_b_type = value;
3543             break;
3544         case CHANNEL_A_DRIVER:
3545             ftdi->eeprom->channel_a_driver = value;
3546             break;
3547         case CHANNEL_B_DRIVER:
3548             ftdi->eeprom->channel_b_driver = value;
3549             break;
3550         case CBUS_FUNCTION_0:
3551             ftdi->eeprom->cbus_function[0] = value;
3552             break;
3553         case CBUS_FUNCTION_1:
3554             ftdi->eeprom->cbus_function[1] = value;
3555             break;
3556         case CBUS_FUNCTION_2:
3557             ftdi->eeprom->cbus_function[2] = value;
3558             break;
3559         case CBUS_FUNCTION_3:
3560             ftdi->eeprom->cbus_function[3] = value;
3561             break;
3562         case CBUS_FUNCTION_4:
3563             ftdi->eeprom->cbus_function[4] = value;
3564             break;
3565         case CBUS_FUNCTION_5:
3566             ftdi->eeprom->cbus_function[5] = value;
3567             break;
3568         case CBUS_FUNCTION_6:
3569             ftdi->eeprom->cbus_function[6] = value;
3570             break;
3571         case CBUS_FUNCTION_7:
3572             ftdi->eeprom->cbus_function[7] = value;
3573             break;
3574         case CBUS_FUNCTION_8:
3575             ftdi->eeprom->cbus_function[8] = value;
3576             break;
3577         case CBUS_FUNCTION_9:
3578             ftdi->eeprom->cbus_function[9] = value;
3579             break;
3580         case HIGH_CURRENT:
3581             ftdi->eeprom->high_current = value;
3582             break;
3583         case HIGH_CURRENT_A:
3584             ftdi->eeprom->high_current_a = value;
3585             break;
3586         case HIGH_CURRENT_B:
3587             ftdi->eeprom->high_current_b = value;
3588             break;
3589         case INVERT:
3590             ftdi->eeprom->invert = value;
3591             break;
3592         case GROUP0_DRIVE:
3593             ftdi->eeprom->group0_drive = value;
3594             break;
3595         case GROUP0_SCHMITT:
3596             ftdi->eeprom->group0_schmitt = value;
3597             break;
3598         case GROUP0_SLEW:
3599             ftdi->eeprom->group0_slew = value;
3600             break;
3601         case GROUP1_DRIVE:
3602             ftdi->eeprom->group1_drive = value;
3603             break;
3604         case GROUP1_SCHMITT:
3605             ftdi->eeprom->group1_schmitt = value;
3606             break;
3607         case GROUP1_SLEW:
3608             ftdi->eeprom->group1_slew = value;
3609             break;
3610         case GROUP2_DRIVE:
3611             ftdi->eeprom->group2_drive = value;
3612             break;
3613         case GROUP2_SCHMITT:
3614             ftdi->eeprom->group2_schmitt = value;
3615             break;
3616         case GROUP2_SLEW:
3617             ftdi->eeprom->group2_slew = value;
3618             break;
3619         case GROUP3_DRIVE:
3620             ftdi->eeprom->group3_drive = value;
3621             break;
3622         case GROUP3_SCHMITT:
3623             ftdi->eeprom->group3_schmitt = value;
3624             break;
3625         case GROUP3_SLEW:
3626             ftdi->eeprom->group3_slew = value;
3627             break;
3628         case CHIP_TYPE:
3629             ftdi->eeprom->chip = value;
3630             break;
3631          case POWER_SAVE:
3632             ftdi->eeprom->powersave = value;
3633             break;
3634          case CLOCK_POLARITY:
3635             ftdi->eeprom->clock_polarity = value;
3636             break;
3637          case DATA_ORDER:
3638             ftdi->eeprom->data_order = value;
3639             break;
3640          case FLOW_CONTROL:
3641             ftdi->eeprom->flow_control = value;
3642             break;
3643         case CHIP_SIZE:
3644             ftdi_error_return(-2, "EEPROM Value can't be changed");
3645         default :
3646             ftdi_error_return(-1, "Request to unknown EEPROM value");
3647     }
3648     return 0;
3649 }
3650
3651 /** Get the read-only buffer to the binary EEPROM content
3652
3653     \param ftdi pointer to ftdi_context
3654     \param buf buffer to receive EEPROM content
3655     \param size Size of receiving buffer
3656
3657     \retval 0: All fine
3658     \retval -1: struct ftdi_contxt or ftdi_eeprom missing
3659     \retval -2: Not enough room to store eeprom
3660 */
3661 int ftdi_get_eeprom_buf(struct ftdi_context *ftdi, unsigned char * buf, int size)
3662 {
3663     if (!ftdi || !(ftdi->eeprom))
3664         ftdi_error_return(-1, "No appropriate structure");
3665
3666     if (!buf || size < ftdi->eeprom->size)
3667         ftdi_error_return(-1, "Not enough room to store eeprom");
3668
3669     // Only copy up to FTDI_MAX_EEPROM_SIZE bytes
3670     if (size > FTDI_MAX_EEPROM_SIZE)
3671         size = FTDI_MAX_EEPROM_SIZE;
3672
3673     memcpy(buf, ftdi->eeprom->buf, size);
3674
3675     return 0;
3676 }
3677
3678 /** Set the EEPROM content from the user-supplied prefilled buffer
3679
3680     \param ftdi pointer to ftdi_context
3681     \param buf buffer to read EEPROM content
3682     \param size Size of buffer
3683
3684     \retval 0: All fine
3685     \retval -1: struct ftdi_contxt or ftdi_eeprom of buf missing
3686 */
3687 int ftdi_set_eeprom_buf(struct ftdi_context *ftdi, const unsigned char * buf, int size)
3688 {
3689     if (!ftdi || !(ftdi->eeprom) || !buf)
3690         ftdi_error_return(-1, "No appropriate structure");
3691
3692     // Only copy up to FTDI_MAX_EEPROM_SIZE bytes
3693     if (size > FTDI_MAX_EEPROM_SIZE)
3694         size = FTDI_MAX_EEPROM_SIZE;
3695
3696     memcpy(ftdi->eeprom->buf, buf, size);
3697
3698     return 0;
3699 }
3700
3701 /**
3702     Read eeprom location
3703
3704     \param ftdi pointer to ftdi_context
3705     \param eeprom_addr Address of eeprom location to be read
3706     \param eeprom_val Pointer to store read eeprom location
3707
3708     \retval  0: all fine
3709     \retval -1: read failed
3710     \retval -2: USB device unavailable
3711 */
3712 int ftdi_read_eeprom_location (struct ftdi_context *ftdi, int eeprom_addr, unsigned short *eeprom_val)
3713 {
3714     if (ftdi == NULL || ftdi->usb_dev == NULL)
3715         ftdi_error_return(-2, "USB device unavailable");
3716
3717     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)
3718         ftdi_error_return(-1, "reading eeprom failed");
3719
3720     return 0;
3721 }
3722
3723 /**
3724     Read eeprom
3725
3726     \param ftdi pointer to ftdi_context
3727
3728     \retval  0: all fine
3729     \retval -1: read failed
3730     \retval -2: USB device unavailable
3731 */
3732 int ftdi_read_eeprom(struct ftdi_context *ftdi)
3733 {
3734     int i;
3735     unsigned char *buf;
3736
3737     if (ftdi == NULL || ftdi->usb_dev == NULL)
3738         ftdi_error_return(-2, "USB device unavailable");
3739     buf = ftdi->eeprom->buf;
3740
3741     for (i = 0; i < FTDI_MAX_EEPROM_SIZE/2; i++)
3742     {
3743         if (libusb_control_transfer(
3744                     ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE,SIO_READ_EEPROM_REQUEST, 0, i,
3745                     buf+(i*2), 2, ftdi->usb_read_timeout) != 2)
3746             ftdi_error_return(-1, "reading eeprom failed");
3747     }
3748
3749     if (ftdi->type == TYPE_R)
3750         ftdi->eeprom->size = 0x80;
3751     /*    Guesses size of eeprom by comparing halves
3752           - will not work with blank eeprom */
3753     else if (strrchr((const char *)buf, 0xff) == ((const char *)buf +FTDI_MAX_EEPROM_SIZE -1))
3754         ftdi->eeprom->size = -1;
3755     else if (memcmp(buf,&buf[0x80],0x80) == 0)
3756         ftdi->eeprom->size = 0x80;
3757     else if (memcmp(buf,&buf[0x40],0x40) == 0)
3758         ftdi->eeprom->size = 0x40;
3759     else
3760         ftdi->eeprom->size = 0x100;
3761     return 0;
3762 }
3763
3764 /*
3765     ftdi_read_chipid_shift does the bitshift operation needed for the FTDIChip-ID
3766     Function is only used internally
3767     \internal
3768 */
3769 static unsigned char ftdi_read_chipid_shift(unsigned char value)
3770 {
3771     return ((value & 1) << 1) |
3772            ((value & 2) << 5) |
3773            ((value & 4) >> 2) |
3774            ((value & 8) << 4) |
3775            ((value & 16) >> 1) |
3776            ((value & 32) >> 1) |
3777            ((value & 64) >> 4) |
3778            ((value & 128) >> 2);
3779 }
3780
3781 /**
3782     Read the FTDIChip-ID from R-type devices
3783
3784     \param ftdi pointer to ftdi_context
3785     \param chipid Pointer to store FTDIChip-ID
3786
3787     \retval  0: all fine
3788     \retval -1: read failed
3789     \retval -2: USB device unavailable
3790 */
3791 int ftdi_read_chipid(struct ftdi_context *ftdi, unsigned int *chipid)
3792 {
3793     unsigned int a = 0, b = 0;
3794
3795     if (ftdi == NULL || ftdi->usb_dev == NULL)
3796         ftdi_error_return(-2, "USB device unavailable");
3797
3798     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)
3799     {
3800         a = a << 8 | a >> 8;
3801         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)
3802         {
3803             b = b << 8 | b >> 8;
3804             a = (a << 16) | (b & 0xFFFF);
3805             a = ftdi_read_chipid_shift(a) | ftdi_read_chipid_shift(a>>8)<<8
3806                 | ftdi_read_chipid_shift(a>>16)<<16 | ftdi_read_chipid_shift(a>>24)<<24;
3807             *chipid = a ^ 0xa5f0f7d1;
3808             return 0;
3809         }
3810     }
3811
3812     ftdi_error_return(-1, "read of FTDIChip-ID failed");
3813 }
3814
3815 /**
3816     Write eeprom location
3817
3818     \param ftdi pointer to ftdi_context
3819     \param eeprom_addr Address of eeprom location to be written
3820     \param eeprom_val Value to be written
3821
3822     \retval  0: all fine
3823     \retval -1: write failed
3824     \retval -2: USB device unavailable
3825     \retval -3: Invalid access to checksum protected area below 0x80
3826     \retval -4: Device can't access unprotected area
3827     \retval -5: Reading chip type failed
3828 */
3829 int ftdi_write_eeprom_location(struct ftdi_context *ftdi, int eeprom_addr,
3830                                unsigned short eeprom_val)
3831 {
3832     int chip_type_location;
3833     unsigned short chip_type;
3834
3835     if (ftdi == NULL || ftdi->usb_dev == NULL)
3836         ftdi_error_return(-2, "USB device unavailable");
3837
3838     if (eeprom_addr <0x80)
3839         ftdi_error_return(-2, "Invalid access to checksum protected area  below 0x80");
3840
3841
3842     switch (ftdi->type)
3843     {
3844         case TYPE_BM:
3845         case  TYPE_2232C:
3846             chip_type_location = 0x14;
3847             break;
3848         case TYPE_2232H:
3849         case TYPE_4232H:
3850             chip_type_location = 0x18;
3851             break;
3852         case TYPE_232H:
3853             chip_type_location = 0x1e;
3854             break;
3855         default:
3856             ftdi_error_return(-4, "Device can't access unprotected area");
3857     }
3858
3859     if (ftdi_read_eeprom_location( ftdi, chip_type_location>>1, &chip_type))
3860         ftdi_error_return(-5, "Reading failed failed");
3861     fprintf(stderr," loc 0x%04x val 0x%04x\n", chip_type_location,chip_type);
3862     if ((chip_type & 0xff) != 0x66)
3863     {
3864         ftdi_error_return(-6, "EEPROM is not of 93x66");
3865     }
3866
3867     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
3868                                 SIO_WRITE_EEPROM_REQUEST, eeprom_val, eeprom_addr,
3869                                 NULL, 0, ftdi->usb_write_timeout) != 0)
3870         ftdi_error_return(-1, "unable to write eeprom");
3871
3872     return 0;
3873 }
3874
3875 /**
3876     Write eeprom
3877
3878     \param ftdi pointer to ftdi_context
3879
3880     \retval  0: all fine
3881     \retval -1: read failed
3882     \retval -2: USB device unavailable
3883     \retval -3: EEPROM not initialized for the connected device;
3884 */
3885 int ftdi_write_eeprom(struct ftdi_context *ftdi)
3886 {
3887     unsigned short usb_val, status;
3888     int i, ret;
3889     unsigned char *eeprom;
3890
3891     if (ftdi == NULL || ftdi->usb_dev == NULL)
3892         ftdi_error_return(-2, "USB device unavailable");
3893
3894     if(ftdi->eeprom->initialized_for_connected_device == 0)
3895         ftdi_error_return(-3, "EEPROM not initialized for the connected device");
3896
3897     eeprom = ftdi->eeprom->buf;
3898
3899     /* These commands were traced while running MProg */
3900     if ((ret = ftdi_usb_reset(ftdi)) != 0)
3901         return ret;
3902     if ((ret = ftdi_poll_modem_status(ftdi, &status)) != 0)
3903         return ret;
3904     if ((ret = ftdi_set_latency_timer(ftdi, 0x77)) != 0)
3905         return ret;
3906
3907     for (i = 0; i < ftdi->eeprom->size/2; i++)
3908     {
3909         usb_val = eeprom[i*2];
3910         usb_val += eeprom[(i*2)+1] << 8;
3911         if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
3912                                     SIO_WRITE_EEPROM_REQUEST, usb_val, i,
3913                                     NULL, 0, ftdi->usb_write_timeout) < 0)
3914             ftdi_error_return(-1, "unable to write eeprom");
3915     }
3916
3917     return 0;
3918 }
3919
3920 /**
3921     Erase eeprom
3922
3923     This is not supported on FT232R/FT245R according to the MProg manual from FTDI.
3924
3925     \param ftdi pointer to ftdi_context
3926
3927     \retval  0: all fine
3928     \retval -1: erase failed
3929     \retval -2: USB device unavailable
3930     \retval -3: Writing magic failed
3931     \retval -4: Read EEPROM failed
3932     \retval -5: Unexpected EEPROM value
3933 */
3934 #define MAGIC 0x55aa
3935 int ftdi_erase_eeprom(struct ftdi_context *ftdi)
3936 {
3937     unsigned short eeprom_value;
3938     if (ftdi == NULL || ftdi->usb_dev == NULL)
3939         ftdi_error_return(-2, "USB device unavailable");
3940
3941     if (ftdi->type == TYPE_R)
3942     {
3943         ftdi->eeprom->chip = 0;
3944         return 0;
3945     }
3946
3947     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_ERASE_EEPROM_REQUEST,
3948                                 0, 0, NULL, 0, ftdi->usb_write_timeout) < 0)
3949         ftdi_error_return(-1, "unable to erase eeprom");
3950
3951
3952     /* detect chip type by writing 0x55AA as magic at word position 0xc0
3953        Chip is 93x46 if magic is read at word position 0x00, as wraparound happens around 0x40
3954        Chip is 93x56 if magic is read at word position 0x40, as wraparound happens around 0x80
3955        Chip is 93x66 if magic is only read at word position 0xc0*/
3956     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
3957                                 SIO_WRITE_EEPROM_REQUEST, MAGIC, 0xc0,
3958                                 NULL, 0, ftdi->usb_write_timeout) != 0)
3959         ftdi_error_return(-3, "Writing magic failed");
3960     if (ftdi_read_eeprom_location( ftdi, 0x00, &eeprom_value))
3961         ftdi_error_return(-4, "Reading failed failed");
3962     if (eeprom_value == MAGIC)
3963     {
3964         ftdi->eeprom->chip = 0x46;
3965     }
3966     else
3967     {
3968         if (ftdi_read_eeprom_location( ftdi, 0x40, &eeprom_value))
3969             ftdi_error_return(-4, "Reading failed failed");
3970         if (eeprom_value == MAGIC)
3971             ftdi->eeprom->chip = 0x56;
3972         else
3973         {
3974             if (ftdi_read_eeprom_location( ftdi, 0xc0, &eeprom_value))
3975                 ftdi_error_return(-4, "Reading failed failed");
3976             if (eeprom_value == MAGIC)
3977                 ftdi->eeprom->chip = 0x66;
3978             else
3979             {
3980                 ftdi->eeprom->chip = -1;
3981             }
3982         }
3983     }
3984     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_ERASE_EEPROM_REQUEST,
3985                                 0, 0, NULL, 0, ftdi->usb_write_timeout) < 0)
3986         ftdi_error_return(-1, "unable to erase eeprom");
3987     return 0;
3988 }
3989
3990 /**
3991     Get string representation for last error code
3992
3993     \param ftdi pointer to ftdi_context
3994
3995     \retval Pointer to error string
3996 */
3997 char *ftdi_get_error_string (struct ftdi_context *ftdi)
3998 {
3999     if (ftdi == NULL)
4000         return "";
4001
4002     return ftdi->error_str;
4003 }
4004
4005 /* @} end of doxygen libftdi group */