Add unit test for existing baudrate calculcation code
[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 /**
968     ftdi_convert_baudrate returns nearest supported baud rate to that requested.
969     Function is only used internally
970     \internal
971 */
972 static int ftdi_convert_baudrate(int baudrate, struct ftdi_context *ftdi,
973                                  unsigned short *value, unsigned short *index)
974 {
975     static const char am_adjust_up[8] = {0, 0, 0, 1, 0, 3, 2, 1};
976     static const char am_adjust_dn[8] = {0, 0, 0, 1, 0, 1, 2, 3};
977     static const char frac_code[8] = {0, 3, 2, 4, 1, 5, 6, 7};
978     int divisor, best_divisor, best_baud, best_baud_diff;
979     unsigned long encoded_divisor;
980     int i;
981
982     if (baudrate <= 0)
983     {
984         // Return error
985         return -1;
986     }
987
988     divisor = 24000000 / baudrate;
989
990     if (ftdi->type == TYPE_AM)
991     {
992         // Round down to supported fraction (AM only)
993         divisor -= am_adjust_dn[divisor & 7];
994     }
995
996     // Try this divisor and the one above it (because division rounds down)
997     best_divisor = 0;
998     best_baud = 0;
999     best_baud_diff = 0;
1000     for (i = 0; i < 2; i++)
1001     {
1002         int try_divisor = divisor + i;
1003         int baud_estimate;
1004         int baud_diff;
1005
1006         // Round up to supported divisor value
1007         if (try_divisor <= 8)
1008         {
1009             // Round up to minimum supported divisor
1010             try_divisor = 8;
1011         }
1012         else if (ftdi->type != TYPE_AM && try_divisor < 12)
1013         {
1014             // BM doesn't support divisors 9 through 11 inclusive
1015             try_divisor = 12;
1016         }
1017         else if (divisor < 16)
1018         {
1019             // AM doesn't support divisors 9 through 15 inclusive
1020             try_divisor = 16;
1021         }
1022         else
1023         {
1024             if (ftdi->type == TYPE_AM)
1025             {
1026                 // Round up to supported fraction (AM only)
1027                 try_divisor += am_adjust_up[try_divisor & 7];
1028                 if (try_divisor > 0x1FFF8)
1029                 {
1030                     // Round down to maximum supported divisor value (for AM)
1031                     try_divisor = 0x1FFF8;
1032                 }
1033             }
1034             else
1035             {
1036                 if (try_divisor > 0x1FFFF)
1037                 {
1038                     // Round down to maximum supported divisor value (for BM)
1039                     try_divisor = 0x1FFFF;
1040                 }
1041             }
1042         }
1043         // Get estimated baud rate (to nearest integer)
1044         baud_estimate = (24000000 + (try_divisor / 2)) / try_divisor;
1045         // Get absolute difference from requested baud rate
1046         if (baud_estimate < baudrate)
1047         {
1048             baud_diff = baudrate - baud_estimate;
1049         }
1050         else
1051         {
1052             baud_diff = baud_estimate - baudrate;
1053         }
1054         if (i == 0 || baud_diff < best_baud_diff)
1055         {
1056             // Closest to requested baud rate so far
1057             best_divisor = try_divisor;
1058             best_baud = baud_estimate;
1059             best_baud_diff = baud_diff;
1060             if (baud_diff == 0)
1061             {
1062                 // Spot on! No point trying
1063                 break;
1064             }
1065         }
1066     }
1067     // Encode the best divisor value
1068     encoded_divisor = (best_divisor >> 3) | (frac_code[best_divisor & 7] << 14);
1069     // Deal with special cases for encoded value
1070     if (encoded_divisor == 1)
1071     {
1072         encoded_divisor = 0;    // 3000000 baud
1073     }
1074     else if (encoded_divisor == 0x4001)
1075     {
1076         encoded_divisor = 1;    // 2000000 baud (BM only)
1077     }
1078     // Split into "value" and "index" values
1079     *value = (unsigned short)(encoded_divisor & 0xFFFF);
1080     if (ftdi->type == TYPE_2232C || ftdi->type == TYPE_2232H || ftdi->type == TYPE_4232H || ftdi->type == TYPE_232H )
1081     {
1082         *index = (unsigned short)(encoded_divisor >> 8);
1083         *index &= 0xFF00;
1084         *index |= ftdi->index;
1085     }
1086     else
1087         *index = (unsigned short)(encoded_divisor >> 16);
1088
1089     // Return the nearest baud rate
1090     return best_baud;
1091 }
1092
1093 /**
1094  * @brief Wrapper function to export ftdi_convert_baudrate() to the unit test
1095  * Do not use, it's only for the unit test framework
1096  **/
1097 int convert_baudrate_UT_export(int baudrate, struct ftdi_context *ftdi,
1098                                  unsigned short *value, unsigned short *index)
1099 {
1100     return ftdi_convert_baudrate(baudrate, ftdi, value, index);
1101 }
1102
1103 /**
1104     Sets the chip baud rate
1105
1106     \param ftdi pointer to ftdi_context
1107     \param baudrate baud rate to set
1108
1109     \retval  0: all fine
1110     \retval -1: invalid baudrate
1111     \retval -2: setting baudrate failed
1112     \retval -3: USB device unavailable
1113 */
1114 int ftdi_set_baudrate(struct ftdi_context *ftdi, int baudrate)
1115 {
1116     unsigned short value, index;
1117     int actual_baudrate;
1118
1119     if (ftdi == NULL || ftdi->usb_dev == NULL)
1120         ftdi_error_return(-3, "USB device unavailable");
1121
1122     if (ftdi->bitbang_enabled)
1123     {
1124         baudrate = baudrate*4;
1125     }
1126
1127     actual_baudrate = ftdi_convert_baudrate(baudrate, ftdi, &value, &index);
1128     if (actual_baudrate <= 0)
1129         ftdi_error_return (-1, "Silly baudrate <= 0.");
1130
1131     // Check within tolerance (about 5%)
1132     if ((actual_baudrate * 2 < baudrate /* Catch overflows */ )
1133             || ((actual_baudrate < baudrate)
1134                 ? (actual_baudrate * 21 < baudrate * 20)
1135                 : (baudrate * 21 < actual_baudrate * 20)))
1136         ftdi_error_return (-1, "Unsupported baudrate. Note: bitbang baudrates are automatically multiplied by 4");
1137
1138     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1139                                 SIO_SET_BAUDRATE_REQUEST, value,
1140                                 index, NULL, 0, ftdi->usb_write_timeout) < 0)
1141         ftdi_error_return (-2, "Setting new baudrate failed");
1142
1143     ftdi->baudrate = baudrate;
1144     return 0;
1145 }
1146
1147 /**
1148     Set (RS232) line characteristics.
1149     The break type can only be set via ftdi_set_line_property2()
1150     and defaults to "off".
1151
1152     \param ftdi pointer to ftdi_context
1153     \param bits Number of bits
1154     \param sbit Number of stop bits
1155     \param parity Parity mode
1156
1157     \retval  0: all fine
1158     \retval -1: Setting line property failed
1159 */
1160 int ftdi_set_line_property(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
1161                            enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity)
1162 {
1163     return ftdi_set_line_property2(ftdi, bits, sbit, parity, BREAK_OFF);
1164 }
1165
1166 /**
1167     Set (RS232) line characteristics
1168
1169     \param ftdi pointer to ftdi_context
1170     \param bits Number of bits
1171     \param sbit Number of stop bits
1172     \param parity Parity mode
1173     \param break_type Break type
1174
1175     \retval  0: all fine
1176     \retval -1: Setting line property failed
1177     \retval -2: USB device unavailable
1178 */
1179 int ftdi_set_line_property2(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
1180                             enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity,
1181                             enum ftdi_break_type break_type)
1182 {
1183     unsigned short value = bits;
1184
1185     if (ftdi == NULL || ftdi->usb_dev == NULL)
1186         ftdi_error_return(-2, "USB device unavailable");
1187
1188     switch (parity)
1189     {
1190         case NONE:
1191             value |= (0x00 << 8);
1192             break;
1193         case ODD:
1194             value |= (0x01 << 8);
1195             break;
1196         case EVEN:
1197             value |= (0x02 << 8);
1198             break;
1199         case MARK:
1200             value |= (0x03 << 8);
1201             break;
1202         case SPACE:
1203             value |= (0x04 << 8);
1204             break;
1205     }
1206
1207     switch (sbit)
1208     {
1209         case STOP_BIT_1:
1210             value |= (0x00 << 11);
1211             break;
1212         case STOP_BIT_15:
1213             value |= (0x01 << 11);
1214             break;
1215         case STOP_BIT_2:
1216             value |= (0x02 << 11);
1217             break;
1218     }
1219
1220     switch (break_type)
1221     {
1222         case BREAK_OFF:
1223             value |= (0x00 << 14);
1224             break;
1225         case BREAK_ON:
1226             value |= (0x01 << 14);
1227             break;
1228     }
1229
1230     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1231                                 SIO_SET_DATA_REQUEST, value,
1232                                 ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
1233         ftdi_error_return (-1, "Setting new line property failed");
1234
1235     return 0;
1236 }
1237
1238 /**
1239     Writes data in chunks (see ftdi_write_data_set_chunksize()) to the chip
1240
1241     \param ftdi pointer to ftdi_context
1242     \param buf Buffer with the data
1243     \param size Size of the buffer
1244
1245     \retval -666: USB device unavailable
1246     \retval <0: error code from usb_bulk_write()
1247     \retval >0: number of bytes written
1248 */
1249 int ftdi_write_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
1250 {
1251     int offset = 0;
1252     int actual_length;
1253
1254     if (ftdi == NULL || ftdi->usb_dev == NULL)
1255         ftdi_error_return(-666, "USB device unavailable");
1256
1257     while (offset < size)
1258     {
1259         int write_size = ftdi->writebuffer_chunksize;
1260
1261         if (offset+write_size > size)
1262             write_size = size-offset;
1263
1264         if (libusb_bulk_transfer(ftdi->usb_dev, ftdi->in_ep, buf+offset, write_size, &actual_length, ftdi->usb_write_timeout) < 0)
1265             ftdi_error_return(-1, "usb bulk write failed");
1266
1267         offset += actual_length;
1268     }
1269
1270     return offset;
1271 }
1272
1273 static void ftdi_read_data_cb(struct libusb_transfer *transfer)
1274 {
1275     struct ftdi_transfer_control *tc = (struct ftdi_transfer_control *) transfer->user_data;
1276     struct ftdi_context *ftdi = tc->ftdi;
1277     int packet_size, actual_length, num_of_chunks, chunk_remains, i, ret;
1278
1279     packet_size = ftdi->max_packet_size;
1280
1281     actual_length = transfer->actual_length;
1282
1283     if (actual_length > 2)
1284     {
1285         // skip FTDI status bytes.
1286         // Maybe stored in the future to enable modem use
1287         num_of_chunks = actual_length / packet_size;
1288         chunk_remains = actual_length % packet_size;
1289         //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);
1290
1291         ftdi->readbuffer_offset += 2;
1292         actual_length -= 2;
1293
1294         if (actual_length > packet_size - 2)
1295         {
1296             for (i = 1; i < num_of_chunks; i++)
1297                 memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1298                          ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1299                          packet_size - 2);
1300             if (chunk_remains > 2)
1301             {
1302                 memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1303                          ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1304                          chunk_remains-2);
1305                 actual_length -= 2*num_of_chunks;
1306             }
1307             else
1308                 actual_length -= 2*(num_of_chunks-1)+chunk_remains;
1309         }
1310
1311         if (actual_length > 0)
1312         {
1313             // data still fits in buf?
1314             if (tc->offset + actual_length <= tc->size)
1315             {
1316                 memcpy (tc->buf + tc->offset, ftdi->readbuffer + ftdi->readbuffer_offset, actual_length);
1317                 //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
1318                 tc->offset += actual_length;
1319
1320                 ftdi->readbuffer_offset = 0;
1321                 ftdi->readbuffer_remaining = 0;
1322
1323                 /* Did we read exactly the right amount of bytes? */
1324                 if (tc->offset == tc->size)
1325                 {
1326                     //printf("read_data exact rem %d offset %d\n",
1327                     //ftdi->readbuffer_remaining, offset);
1328                     tc->completed = 1;
1329                     return;
1330                 }
1331             }
1332             else
1333             {
1334                 // only copy part of the data or size <= readbuffer_chunksize
1335                 int part_size = tc->size - tc->offset;
1336                 memcpy (tc->buf + tc->offset, ftdi->readbuffer + ftdi->readbuffer_offset, part_size);
1337                 tc->offset += part_size;
1338
1339                 ftdi->readbuffer_offset += part_size;
1340                 ftdi->readbuffer_remaining = actual_length - part_size;
1341
1342                 /* printf("Returning part: %d - size: %d - offset: %d - actual_length: %d - remaining: %d\n",
1343                 part_size, size, offset, actual_length, ftdi->readbuffer_remaining); */
1344                 tc->completed = 1;
1345                 return;
1346             }
1347         }
1348     }
1349     ret = libusb_submit_transfer (transfer);
1350     if (ret < 0)
1351         tc->completed = 1;
1352 }
1353
1354
1355 static void ftdi_write_data_cb(struct libusb_transfer *transfer)
1356 {
1357     struct ftdi_transfer_control *tc = (struct ftdi_transfer_control *) transfer->user_data;
1358     struct ftdi_context *ftdi = tc->ftdi;
1359
1360     tc->offset += transfer->actual_length;
1361
1362     if (tc->offset == tc->size)
1363     {
1364         tc->completed = 1;
1365     }
1366     else
1367     {
1368         int write_size = ftdi->writebuffer_chunksize;
1369         int ret;
1370
1371         if (tc->offset + write_size > tc->size)
1372             write_size = tc->size - tc->offset;
1373
1374         transfer->length = write_size;
1375         transfer->buffer = tc->buf + tc->offset;
1376         ret = libusb_submit_transfer (transfer);
1377         if (ret < 0)
1378             tc->completed = 1;
1379     }
1380 }
1381
1382
1383 /**
1384     Writes data to the chip. Does not wait for completion of the transfer
1385     nor does it make sure that the transfer was successful.
1386
1387     Use libusb 1.0 asynchronous API.
1388
1389     \param ftdi pointer to ftdi_context
1390     \param buf Buffer with the data
1391     \param size Size of the buffer
1392
1393     \retval NULL: Some error happens when submit transfer
1394     \retval !NULL: Pointer to a ftdi_transfer_control
1395 */
1396
1397 struct ftdi_transfer_control *ftdi_write_data_submit(struct ftdi_context *ftdi, unsigned char *buf, int size)
1398 {
1399     struct ftdi_transfer_control *tc;
1400     struct libusb_transfer *transfer;
1401     int write_size, ret;
1402
1403     if (ftdi == NULL || ftdi->usb_dev == NULL)
1404         return NULL;
1405
1406     tc = (struct ftdi_transfer_control *) malloc (sizeof (*tc));
1407     if (!tc)
1408         return NULL;
1409
1410     transfer = libusb_alloc_transfer(0);
1411     if (!transfer)
1412     {
1413         free(tc);
1414         return NULL;
1415     }
1416
1417     tc->ftdi = ftdi;
1418     tc->completed = 0;
1419     tc->buf = buf;
1420     tc->size = size;
1421     tc->offset = 0;
1422
1423     if (size < ftdi->writebuffer_chunksize)
1424         write_size = size;
1425     else
1426         write_size = ftdi->writebuffer_chunksize;
1427
1428     libusb_fill_bulk_transfer(transfer, ftdi->usb_dev, ftdi->in_ep, buf,
1429                               write_size, ftdi_write_data_cb, tc,
1430                               ftdi->usb_write_timeout);
1431     transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
1432
1433     ret = libusb_submit_transfer(transfer);
1434     if (ret < 0)
1435     {
1436         libusb_free_transfer(transfer);
1437         free(tc);
1438         return NULL;
1439     }
1440     tc->transfer = transfer;
1441
1442     return tc;
1443 }
1444
1445 /**
1446     Reads data from the chip. Does not wait for completion of the transfer
1447     nor does it make sure that the transfer was successful.
1448
1449     Use libusb 1.0 asynchronous API.
1450
1451     \param ftdi pointer to ftdi_context
1452     \param buf Buffer with the data
1453     \param size Size of the buffer
1454
1455     \retval NULL: Some error happens when submit transfer
1456     \retval !NULL: Pointer to a ftdi_transfer_control
1457 */
1458
1459 struct ftdi_transfer_control *ftdi_read_data_submit(struct ftdi_context *ftdi, unsigned char *buf, int size)
1460 {
1461     struct ftdi_transfer_control *tc;
1462     struct libusb_transfer *transfer;
1463     int ret;
1464
1465     if (ftdi == NULL || ftdi->usb_dev == NULL)
1466         return NULL;
1467
1468     tc = (struct ftdi_transfer_control *) malloc (sizeof (*tc));
1469     if (!tc)
1470         return NULL;
1471
1472     tc->ftdi = ftdi;
1473     tc->buf = buf;
1474     tc->size = size;
1475
1476     if (size <= ftdi->readbuffer_remaining)
1477     {
1478         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);
1479
1480         // Fix offsets
1481         ftdi->readbuffer_remaining -= size;
1482         ftdi->readbuffer_offset += size;
1483
1484         /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */
1485
1486         tc->completed = 1;
1487         tc->offset = size;
1488         tc->transfer = NULL;
1489         return tc;
1490     }
1491
1492     tc->completed = 0;
1493     if (ftdi->readbuffer_remaining != 0)
1494     {
1495         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);
1496
1497         tc->offset = ftdi->readbuffer_remaining;
1498     }
1499     else
1500         tc->offset = 0;
1501
1502     transfer = libusb_alloc_transfer(0);
1503     if (!transfer)
1504     {
1505         free (tc);
1506         return NULL;
1507     }
1508
1509     ftdi->readbuffer_remaining = 0;
1510     ftdi->readbuffer_offset = 0;
1511
1512     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);
1513     transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
1514
1515     ret = libusb_submit_transfer(transfer);
1516     if (ret < 0)
1517     {
1518         libusb_free_transfer(transfer);
1519         free (tc);
1520         return NULL;
1521     }
1522     tc->transfer = transfer;
1523
1524     return tc;
1525 }
1526
1527 /**
1528     Wait for completion of the transfer.
1529
1530     Use libusb 1.0 asynchronous API.
1531
1532     \param tc pointer to ftdi_transfer_control
1533
1534     \retval < 0: Some error happens
1535     \retval >= 0: Data size transferred
1536 */
1537
1538 int ftdi_transfer_data_done(struct ftdi_transfer_control *tc)
1539 {
1540     int ret;
1541
1542     while (!tc->completed)
1543     {
1544         ret = libusb_handle_events(tc->ftdi->usb_ctx);
1545         if (ret < 0)
1546         {
1547             if (ret == LIBUSB_ERROR_INTERRUPTED)
1548                 continue;
1549             libusb_cancel_transfer(tc->transfer);
1550             while (!tc->completed)
1551                 if (libusb_handle_events(tc->ftdi->usb_ctx) < 0)
1552                     break;
1553             libusb_free_transfer(tc->transfer);
1554             free (tc);
1555             return ret;
1556         }
1557     }
1558
1559     ret = tc->offset;
1560     /**
1561      * tc->transfer could be NULL if "(size <= ftdi->readbuffer_remaining)"
1562      * at ftdi_read_data_submit(). Therefore, we need to check it here.
1563      **/
1564     if (tc->transfer)
1565     {
1566         if (tc->transfer->status != LIBUSB_TRANSFER_COMPLETED)
1567             ret = -1;
1568         libusb_free_transfer(tc->transfer);
1569     }
1570     free(tc);
1571     return ret;
1572 }
1573
1574 /**
1575     Configure write buffer chunk size.
1576     Default is 4096.
1577
1578     \param ftdi pointer to ftdi_context
1579     \param chunksize Chunk size
1580
1581     \retval 0: all fine
1582     \retval -1: ftdi context invalid
1583 */
1584 int ftdi_write_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
1585 {
1586     if (ftdi == NULL)
1587         ftdi_error_return(-1, "ftdi context invalid");
1588
1589     ftdi->writebuffer_chunksize = chunksize;
1590     return 0;
1591 }
1592
1593 /**
1594     Get write buffer chunk size.
1595
1596     \param ftdi pointer to ftdi_context
1597     \param chunksize Pointer to store chunk size in
1598
1599     \retval 0: all fine
1600     \retval -1: ftdi context invalid
1601 */
1602 int ftdi_write_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
1603 {
1604     if (ftdi == NULL)
1605         ftdi_error_return(-1, "ftdi context invalid");
1606
1607     *chunksize = ftdi->writebuffer_chunksize;
1608     return 0;
1609 }
1610
1611 /**
1612     Reads data in chunks (see ftdi_read_data_set_chunksize()) from the chip.
1613
1614     Automatically strips the two modem status bytes transfered during every read.
1615
1616     \param ftdi pointer to ftdi_context
1617     \param buf Buffer to store data in
1618     \param size Size of the buffer
1619
1620     \retval -666: USB device unavailable
1621     \retval <0: error code from libusb_bulk_transfer()
1622     \retval  0: no data was available
1623     \retval >0: number of bytes read
1624
1625 */
1626 int ftdi_read_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
1627 {
1628     int offset = 0, ret, i, num_of_chunks, chunk_remains;
1629     int packet_size = ftdi->max_packet_size;
1630     int actual_length = 1;
1631
1632     if (ftdi == NULL || ftdi->usb_dev == NULL)
1633         ftdi_error_return(-666, "USB device unavailable");
1634
1635     // Packet size sanity check (avoid division by zero)
1636     if (packet_size == 0)
1637         ftdi_error_return(-1, "max_packet_size is bogus (zero)");
1638
1639     // everything we want is still in the readbuffer?
1640     if (size <= ftdi->readbuffer_remaining)
1641     {
1642         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);
1643
1644         // Fix offsets
1645         ftdi->readbuffer_remaining -= size;
1646         ftdi->readbuffer_offset += size;
1647
1648         /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */
1649
1650         return size;
1651     }
1652     // something still in the readbuffer, but not enough to satisfy 'size'?
1653     if (ftdi->readbuffer_remaining != 0)
1654     {
1655         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);
1656
1657         // Fix offset
1658         offset += ftdi->readbuffer_remaining;
1659     }
1660     // do the actual USB read
1661     while (offset < size && actual_length > 0)
1662     {
1663         ftdi->readbuffer_remaining = 0;
1664         ftdi->readbuffer_offset = 0;
1665         /* returns how much received */
1666         ret = libusb_bulk_transfer (ftdi->usb_dev, ftdi->out_ep, ftdi->readbuffer, ftdi->readbuffer_chunksize, &actual_length, ftdi->usb_read_timeout);
1667         if (ret < 0)
1668             ftdi_error_return(ret, "usb bulk read failed");
1669
1670         if (actual_length > 2)
1671         {
1672             // skip FTDI status bytes.
1673             // Maybe stored in the future to enable modem use
1674             num_of_chunks = actual_length / packet_size;
1675             chunk_remains = actual_length % packet_size;
1676             //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);
1677
1678             ftdi->readbuffer_offset += 2;
1679             actual_length -= 2;
1680
1681             if (actual_length > packet_size - 2)
1682             {
1683                 for (i = 1; i < num_of_chunks; i++)
1684                     memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1685                              ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1686                              packet_size - 2);
1687                 if (chunk_remains > 2)
1688                 {
1689                     memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1690                              ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1691                              chunk_remains-2);
1692                     actual_length -= 2*num_of_chunks;
1693                 }
1694                 else
1695                     actual_length -= 2*(num_of_chunks-1)+chunk_remains;
1696             }
1697         }
1698         else if (actual_length <= 2)
1699         {
1700             // no more data to read?
1701             return offset;
1702         }
1703         if (actual_length > 0)
1704         {
1705             // data still fits in buf?
1706             if (offset+actual_length <= size)
1707             {
1708                 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, actual_length);
1709                 //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
1710                 offset += actual_length;
1711
1712                 /* Did we read exactly the right amount of bytes? */
1713                 if (offset == size)
1714                     //printf("read_data exact rem %d offset %d\n",
1715                     //ftdi->readbuffer_remaining, offset);
1716                     return offset;
1717             }
1718             else
1719             {
1720                 // only copy part of the data or size <= readbuffer_chunksize
1721                 int part_size = size-offset;
1722                 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, part_size);
1723
1724                 ftdi->readbuffer_offset += part_size;
1725                 ftdi->readbuffer_remaining = actual_length-part_size;
1726                 offset += part_size;
1727
1728                 /* printf("Returning part: %d - size: %d - offset: %d - actual_length: %d - remaining: %d\n",
1729                 part_size, size, offset, actual_length, ftdi->readbuffer_remaining); */
1730
1731                 return offset;
1732             }
1733         }
1734     }
1735     // never reached
1736     return -127;
1737 }
1738
1739 /**
1740     Configure read buffer chunk size.
1741     Default is 4096.
1742
1743     Automatically reallocates the buffer.
1744
1745     \param ftdi pointer to ftdi_context
1746     \param chunksize Chunk size
1747
1748     \retval 0: all fine
1749     \retval -1: ftdi context invalid
1750 */
1751 int ftdi_read_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
1752 {
1753     unsigned char *new_buf;
1754
1755     if (ftdi == NULL)
1756         ftdi_error_return(-1, "ftdi context invalid");
1757
1758     // Invalidate all remaining data
1759     ftdi->readbuffer_offset = 0;
1760     ftdi->readbuffer_remaining = 0;
1761 #ifdef __linux__
1762     /* We can't set readbuffer_chunksize larger than MAX_BULK_BUFFER_LENGTH,
1763        which is defined in libusb-1.0.  Otherwise, each USB read request will
1764        be divided into multiple URBs.  This will cause issues on Linux kernel
1765        older than 2.6.32.  */
1766     if (chunksize > 16384)
1767         chunksize = 16384;
1768 #endif
1769
1770     if ((new_buf = (unsigned char *)realloc(ftdi->readbuffer, chunksize)) == NULL)
1771         ftdi_error_return(-1, "out of memory for readbuffer");
1772
1773     ftdi->readbuffer = new_buf;
1774     ftdi->readbuffer_chunksize = chunksize;
1775
1776     return 0;
1777 }
1778
1779 /**
1780     Get read buffer chunk size.
1781
1782     \param ftdi pointer to ftdi_context
1783     \param chunksize Pointer to store chunk size in
1784
1785     \retval 0: all fine
1786     \retval -1: FTDI context invalid
1787 */
1788 int ftdi_read_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
1789 {
1790     if (ftdi == NULL)
1791         ftdi_error_return(-1, "FTDI context invalid");
1792
1793     *chunksize = ftdi->readbuffer_chunksize;
1794     return 0;
1795 }
1796
1797
1798 /**
1799     Enable bitbang mode.
1800
1801     \deprecated use \ref ftdi_set_bitmode with mode BITMODE_BITBANG instead
1802
1803     \param ftdi pointer to ftdi_context
1804     \param bitmask Bitmask to configure lines.
1805            HIGH/ON value configures a line as output.
1806
1807     \retval  0: all fine
1808     \retval -1: can't enable bitbang mode
1809     \retval -2: USB device unavailable
1810 */
1811 int ftdi_enable_bitbang(struct ftdi_context *ftdi, unsigned char bitmask)
1812 {
1813     unsigned short usb_val;
1814
1815     if (ftdi == NULL || ftdi->usb_dev == NULL)
1816         ftdi_error_return(-2, "USB device unavailable");
1817
1818     usb_val = bitmask; // low byte: bitmask
1819     /* FT2232C: Set bitbang_mode to 2 to enable SPI */
1820     usb_val |= (ftdi->bitbang_mode << 8);
1821
1822     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1823                                 SIO_SET_BITMODE_REQUEST, usb_val, ftdi->index,
1824                                 NULL, 0, ftdi->usb_write_timeout) < 0)
1825         ftdi_error_return(-1, "unable to enter bitbang mode. Perhaps not a BM type chip?");
1826
1827     ftdi->bitbang_enabled = 1;
1828     return 0;
1829 }
1830
1831 /**
1832     Disable bitbang mode.
1833
1834     \param ftdi pointer to ftdi_context
1835
1836     \retval  0: all fine
1837     \retval -1: can't disable bitbang mode
1838     \retval -2: USB device unavailable
1839 */
1840 int ftdi_disable_bitbang(struct ftdi_context *ftdi)
1841 {
1842     if (ftdi == NULL || ftdi->usb_dev == NULL)
1843         ftdi_error_return(-2, "USB device unavailable");
1844
1845     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)
1846         ftdi_error_return(-1, "unable to leave bitbang mode. Perhaps not a BM type chip?");
1847
1848     ftdi->bitbang_enabled = 0;
1849     return 0;
1850 }
1851
1852 /**
1853     Enable/disable bitbang modes.
1854
1855     \param ftdi pointer to ftdi_context
1856     \param bitmask Bitmask to configure lines.
1857            HIGH/ON value configures a line as output.
1858     \param mode Bitbang mode: use the values defined in \ref ftdi_mpsse_mode
1859
1860     \retval  0: all fine
1861     \retval -1: can't enable bitbang mode
1862     \retval -2: USB device unavailable
1863 */
1864 int ftdi_set_bitmode(struct ftdi_context *ftdi, unsigned char bitmask, unsigned char mode)
1865 {
1866     unsigned short usb_val;
1867
1868     if (ftdi == NULL || ftdi->usb_dev == NULL)
1869         ftdi_error_return(-2, "USB device unavailable");
1870
1871     usb_val = bitmask; // low byte: bitmask
1872     usb_val |= (mode << 8);
1873     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)
1874         ftdi_error_return(-1, "unable to configure bitbang mode. Perhaps not a 2232C type chip?");
1875
1876     ftdi->bitbang_mode = mode;
1877     ftdi->bitbang_enabled = (mode == BITMODE_RESET) ? 0 : 1;
1878     return 0;
1879 }
1880
1881 /**
1882     Directly read pin state, circumventing the read buffer. Useful for bitbang mode.
1883
1884     \param ftdi pointer to ftdi_context
1885     \param pins Pointer to store pins into
1886
1887     \retval  0: all fine
1888     \retval -1: read pins failed
1889     \retval -2: USB device unavailable
1890 */
1891 int ftdi_read_pins(struct ftdi_context *ftdi, unsigned char *pins)
1892 {
1893     if (ftdi == NULL || ftdi->usb_dev == NULL)
1894         ftdi_error_return(-2, "USB device unavailable");
1895
1896     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)
1897         ftdi_error_return(-1, "read pins failed");
1898
1899     return 0;
1900 }
1901
1902 /**
1903     Set latency timer
1904
1905     The FTDI chip keeps data in the internal buffer for a specific
1906     amount of time if the buffer is not full yet to decrease
1907     load on the usb bus.
1908
1909     \param ftdi pointer to ftdi_context
1910     \param latency Value between 1 and 255
1911
1912     \retval  0: all fine
1913     \retval -1: latency out of range
1914     \retval -2: unable to set latency timer
1915     \retval -3: USB device unavailable
1916 */
1917 int ftdi_set_latency_timer(struct ftdi_context *ftdi, unsigned char latency)
1918 {
1919     unsigned short usb_val;
1920
1921     if (latency < 1)
1922         ftdi_error_return(-1, "latency out of range. Only valid for 1-255");
1923
1924     if (ftdi == NULL || ftdi->usb_dev == NULL)
1925         ftdi_error_return(-3, "USB device unavailable");
1926
1927     usb_val = latency;
1928     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)
1929         ftdi_error_return(-2, "unable to set latency timer");
1930
1931     return 0;
1932 }
1933
1934 /**
1935     Get latency timer
1936
1937     \param ftdi pointer to ftdi_context
1938     \param latency Pointer to store latency value in
1939
1940     \retval  0: all fine
1941     \retval -1: unable to get latency timer
1942     \retval -2: USB device unavailable
1943 */
1944 int ftdi_get_latency_timer(struct ftdi_context *ftdi, unsigned char *latency)
1945 {
1946     unsigned short usb_val;
1947
1948     if (ftdi == NULL || ftdi->usb_dev == NULL)
1949         ftdi_error_return(-2, "USB device unavailable");
1950
1951     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)
1952         ftdi_error_return(-1, "reading latency timer failed");
1953
1954     *latency = (unsigned char)usb_val;
1955     return 0;
1956 }
1957
1958 /**
1959     Poll modem status information
1960
1961     This function allows the retrieve the two status bytes of the device.
1962     The device sends these bytes also as a header for each read access
1963     where they are discarded by ftdi_read_data(). The chip generates
1964     the two stripped status bytes in the absence of data every 40 ms.
1965
1966     Layout of the first byte:
1967     - B0..B3 - must be 0
1968     - B4       Clear to send (CTS)
1969                  0 = inactive
1970                  1 = active
1971     - B5       Data set ready (DTS)
1972                  0 = inactive
1973                  1 = active
1974     - B6       Ring indicator (RI)
1975                  0 = inactive
1976                  1 = active
1977     - B7       Receive line signal detect (RLSD)
1978                  0 = inactive
1979                  1 = active
1980
1981     Layout of the second byte:
1982     - B0       Data ready (DR)
1983     - B1       Overrun error (OE)
1984     - B2       Parity error (PE)
1985     - B3       Framing error (FE)
1986     - B4       Break interrupt (BI)
1987     - B5       Transmitter holding register (THRE)
1988     - B6       Transmitter empty (TEMT)
1989     - B7       Error in RCVR FIFO
1990
1991     \param ftdi pointer to ftdi_context
1992     \param status Pointer to store status information in. Must be two bytes.
1993
1994     \retval  0: all fine
1995     \retval -1: unable to retrieve status information
1996     \retval -2: USB device unavailable
1997 */
1998 int ftdi_poll_modem_status(struct ftdi_context *ftdi, unsigned short *status)
1999 {
2000     char usb_val[2];
2001
2002     if (ftdi == NULL || ftdi->usb_dev == NULL)
2003         ftdi_error_return(-2, "USB device unavailable");
2004
2005     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)
2006         ftdi_error_return(-1, "getting modem status failed");
2007
2008     *status = (usb_val[1] << 8) | (usb_val[0] & 0xFF);
2009
2010     return 0;
2011 }
2012
2013 /**
2014     Set flowcontrol for ftdi chip
2015
2016     \param ftdi pointer to ftdi_context
2017     \param flowctrl flow control to use. should be
2018            SIO_DISABLE_FLOW_CTRL, SIO_RTS_CTS_HS, SIO_DTR_DSR_HS or SIO_XON_XOFF_HS
2019
2020     \retval  0: all fine
2021     \retval -1: set flow control failed
2022     \retval -2: USB device unavailable
2023 */
2024 int ftdi_setflowctrl(struct ftdi_context *ftdi, int flowctrl)
2025 {
2026     if (ftdi == NULL || ftdi->usb_dev == NULL)
2027         ftdi_error_return(-2, "USB device unavailable");
2028
2029     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
2030                                 SIO_SET_FLOW_CTRL_REQUEST, 0, (flowctrl | ftdi->index),
2031                                 NULL, 0, ftdi->usb_write_timeout) < 0)
2032         ftdi_error_return(-1, "set flow control failed");
2033
2034     return 0;
2035 }
2036
2037 /**
2038     Set dtr line
2039
2040     \param ftdi pointer to ftdi_context
2041     \param state state to set line to (1 or 0)
2042
2043     \retval  0: all fine
2044     \retval -1: set dtr failed
2045     \retval -2: USB device unavailable
2046 */
2047 int ftdi_setdtr(struct ftdi_context *ftdi, int state)
2048 {
2049     unsigned short usb_val;
2050
2051     if (ftdi == NULL || ftdi->usb_dev == NULL)
2052         ftdi_error_return(-2, "USB device unavailable");
2053
2054     if (state)
2055         usb_val = SIO_SET_DTR_HIGH;
2056     else
2057         usb_val = SIO_SET_DTR_LOW;
2058
2059     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
2060                                 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
2061                                 NULL, 0, ftdi->usb_write_timeout) < 0)
2062         ftdi_error_return(-1, "set dtr failed");
2063
2064     return 0;
2065 }
2066
2067 /**
2068     Set rts line
2069
2070     \param ftdi pointer to ftdi_context
2071     \param state state to set line to (1 or 0)
2072
2073     \retval  0: all fine
2074     \retval -1: set rts failed
2075     \retval -2: USB device unavailable
2076 */
2077 int ftdi_setrts(struct ftdi_context *ftdi, int state)
2078 {
2079     unsigned short usb_val;
2080
2081     if (ftdi == NULL || ftdi->usb_dev == NULL)
2082         ftdi_error_return(-2, "USB device unavailable");
2083
2084     if (state)
2085         usb_val = SIO_SET_RTS_HIGH;
2086     else
2087         usb_val = SIO_SET_RTS_LOW;
2088
2089     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
2090                                 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
2091                                 NULL, 0, ftdi->usb_write_timeout) < 0)
2092         ftdi_error_return(-1, "set of rts failed");
2093
2094     return 0;
2095 }
2096
2097 /**
2098     Set dtr and rts line in one pass
2099
2100     \param ftdi pointer to ftdi_context
2101     \param dtr  DTR state to set line to (1 or 0)
2102     \param rts  RTS state to set line to (1 or 0)
2103
2104     \retval  0: all fine
2105     \retval -1: set dtr/rts failed
2106     \retval -2: USB device unavailable
2107  */
2108 int ftdi_setdtr_rts(struct ftdi_context *ftdi, int dtr, int rts)
2109 {
2110     unsigned short usb_val;
2111
2112     if (ftdi == NULL || ftdi->usb_dev == NULL)
2113         ftdi_error_return(-2, "USB device unavailable");
2114
2115     if (dtr)
2116         usb_val = SIO_SET_DTR_HIGH;
2117     else
2118         usb_val = SIO_SET_DTR_LOW;
2119
2120     if (rts)
2121         usb_val |= SIO_SET_RTS_HIGH;
2122     else
2123         usb_val |= SIO_SET_RTS_LOW;
2124
2125     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
2126                                 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
2127                                 NULL, 0, ftdi->usb_write_timeout) < 0)
2128         ftdi_error_return(-1, "set of rts/dtr failed");
2129
2130     return 0;
2131 }
2132
2133 /**
2134     Set the special event character
2135
2136     \param ftdi pointer to ftdi_context
2137     \param eventch Event character
2138     \param enable 0 to disable the event character, non-zero otherwise
2139
2140     \retval  0: all fine
2141     \retval -1: unable to set event character
2142     \retval -2: USB device unavailable
2143 */
2144 int ftdi_set_event_char(struct ftdi_context *ftdi,
2145                         unsigned char eventch, unsigned char enable)
2146 {
2147     unsigned short usb_val;
2148
2149     if (ftdi == NULL || ftdi->usb_dev == NULL)
2150         ftdi_error_return(-2, "USB device unavailable");
2151
2152     usb_val = eventch;
2153     if (enable)
2154         usb_val |= 1 << 8;
2155
2156     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)
2157         ftdi_error_return(-1, "setting event character failed");
2158
2159     return 0;
2160 }
2161
2162 /**
2163     Set error character
2164
2165     \param ftdi pointer to ftdi_context
2166     \param errorch Error character
2167     \param enable 0 to disable the error character, non-zero otherwise
2168
2169     \retval  0: all fine
2170     \retval -1: unable to set error character
2171     \retval -2: USB device unavailable
2172 */
2173 int ftdi_set_error_char(struct ftdi_context *ftdi,
2174                         unsigned char errorch, unsigned char enable)
2175 {
2176     unsigned short usb_val;
2177
2178     if (ftdi == NULL || ftdi->usb_dev == NULL)
2179         ftdi_error_return(-2, "USB device unavailable");
2180
2181     usb_val = errorch;
2182     if (enable)
2183         usb_val |= 1 << 8;
2184
2185     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)
2186         ftdi_error_return(-1, "setting error character failed");
2187
2188     return 0;
2189 }
2190
2191 /**
2192     Init eeprom with default values for the connected device
2193     \param ftdi pointer to ftdi_context
2194     \param manufacturer String to use as Manufacturer
2195     \param product String to use as Product description
2196     \param serial String to use as Serial number description
2197
2198     \retval  0: all fine
2199     \retval -1: No struct ftdi_context
2200     \retval -2: No struct ftdi_eeprom
2201     \retval -3: No connected device or device not yet opened
2202 */
2203 int ftdi_eeprom_initdefaults(struct ftdi_context *ftdi, char * manufacturer,
2204                              char * product, char * serial)
2205 {
2206     struct ftdi_eeprom *eeprom;
2207
2208     if (ftdi == NULL)
2209         ftdi_error_return(-1, "No struct ftdi_context");
2210
2211     if (ftdi->eeprom == NULL)
2212         ftdi_error_return(-2,"No struct ftdi_eeprom");
2213
2214     eeprom = ftdi->eeprom;
2215     memset(eeprom, 0, sizeof(struct ftdi_eeprom));
2216
2217     if (ftdi->usb_dev == NULL)
2218         ftdi_error_return(-3, "No connected device or device not yet opened");
2219
2220     eeprom->vendor_id = 0x0403;
2221     eeprom->use_serial = USE_SERIAL_NUM;
2222     if ((ftdi->type == TYPE_AM) || (ftdi->type == TYPE_BM) ||
2223             (ftdi->type == TYPE_R))
2224         eeprom->product_id = 0x6001;
2225     else if (ftdi->type == TYPE_4232H)
2226         eeprom->product_id = 0x6011;
2227     else if (ftdi->type == TYPE_232H)
2228         eeprom->product_id = 0x6014;
2229     else
2230         eeprom->product_id = 0x6010;
2231     if (ftdi->type == TYPE_AM)
2232         eeprom->usb_version = 0x0101;
2233     else
2234         eeprom->usb_version = 0x0200;
2235     eeprom->max_power = 100;
2236
2237     if (eeprom->manufacturer)
2238         free (eeprom->manufacturer);
2239     eeprom->manufacturer = NULL;
2240     if (manufacturer)
2241     {
2242         eeprom->manufacturer = malloc(strlen(manufacturer)+1);
2243         if (eeprom->manufacturer)
2244             strcpy(eeprom->manufacturer, manufacturer);
2245     }
2246
2247     if (eeprom->product)
2248         free (eeprom->product);
2249     eeprom->product = NULL;
2250     if(product)
2251     {
2252         eeprom->product = malloc(strlen(product)+1);
2253         if (eeprom->product)
2254             strcpy(eeprom->product, product);
2255     }
2256
2257     if (eeprom->serial)
2258         free (eeprom->serial);
2259     eeprom->serial = NULL;
2260     if (serial)
2261     {
2262         eeprom->serial = malloc(strlen(serial)+1);
2263         if (eeprom->serial)
2264             strcpy(eeprom->serial, serial);
2265     }
2266
2267
2268     if (ftdi->type == TYPE_R)
2269     {
2270         eeprom->max_power = 90;
2271         eeprom->size = 0x80;
2272         eeprom->cbus_function[0] = CBUS_TXLED;
2273         eeprom->cbus_function[1] = CBUS_RXLED;
2274         eeprom->cbus_function[2] = CBUS_TXDEN;
2275         eeprom->cbus_function[3] = CBUS_PWREN;
2276         eeprom->cbus_function[4] = CBUS_SLEEP;
2277     }
2278     else
2279     {
2280         if(ftdi->type == TYPE_232H)
2281         {
2282             int i;
2283             for (i=0; i<10; i++)
2284                 eeprom->cbus_function[i] = CBUSH_TRISTATE;
2285         }
2286         eeprom->size = -1;
2287     }
2288     eeprom->initialized_for_connected_device = 1;
2289     return 0;
2290 }
2291 /*FTD2XX doesn't check for values not fitting in the ACBUS Signal oprtions*/
2292 void set_ft232h_cbus(struct ftdi_eeprom *eeprom, unsigned char * output)
2293 {
2294     int i;
2295     for(i=0; i<5;i++)
2296     {
2297         int mode_low, mode_high;
2298         if (eeprom->cbus_function[2*i]> CBUSH_CLK7_5)
2299             mode_low = CBUSH_TRISTATE;
2300         else
2301             mode_low = eeprom->cbus_function[2*i];
2302         if (eeprom->cbus_function[2*i+1]> CBUSH_CLK7_5)
2303             mode_high = CBUSH_TRISTATE;
2304         else
2305             mode_high = eeprom->cbus_function[2*i];
2306
2307         output[0x18+i] = mode_high <<4 | mode_low;
2308     }
2309 }
2310 /* Return the bits for the encoded EEPROM Structure of a requested Mode
2311  *
2312  */
2313 static unsigned char type2bit(unsigned char type, enum ftdi_chip_type chip)
2314 {
2315     switch (chip)
2316     {
2317     case TYPE_2232H:
2318     case TYPE_2232C:
2319     {
2320         switch (type)
2321         {
2322         case CHANNEL_IS_UART: return 0;
2323         case CHANNEL_IS_FIFO: return 0x01;
2324         case CHANNEL_IS_OPTO: return 0x02;
2325         case CHANNEL_IS_CPU : return 0x04;
2326         default: return 0;
2327         }
2328     }
2329     case TYPE_232H:
2330     {
2331         switch (type)
2332         {
2333         case CHANNEL_IS_UART   : return 0;
2334         case CHANNEL_IS_FIFO   : return 0x01;
2335         case CHANNEL_IS_OPTO   : return 0x02;
2336         case CHANNEL_IS_CPU    : return 0x04;
2337         case CHANNEL_IS_FT1284 : return 0x08;
2338         default: return 0;
2339         }
2340     }
2341     default: return 0;
2342     }
2343     return 0;
2344 }    
2345
2346 /**
2347     Build binary buffer from ftdi_eeprom structure.
2348     Output is suitable for ftdi_write_eeprom().
2349
2350     \param ftdi pointer to ftdi_context
2351
2352     \retval >=0: size of eeprom user area in bytes
2353     \retval -1: eeprom size (128 bytes) exceeded by custom strings
2354     \retval -2: Invalid eeprom or ftdi pointer
2355     \retval -3: Invalid cbus function setting     (FIXME: Not in the code?)
2356     \retval -4: Chip doesn't support invert       (FIXME: Not in the code?)
2357     \retval -5: Chip doesn't support high current drive         (FIXME: Not in the code?)
2358     \retval -6: No connected EEPROM or EEPROM Type unknown
2359 */
2360 int ftdi_eeprom_build(struct ftdi_context *ftdi)
2361 {
2362     unsigned char i, j, eeprom_size_mask;
2363     unsigned short checksum, value;
2364     unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
2365     int user_area_size;
2366     struct ftdi_eeprom *eeprom;
2367     unsigned char * output;
2368
2369     if (ftdi == NULL)
2370         ftdi_error_return(-2,"No context");
2371     if (ftdi->eeprom == NULL)
2372         ftdi_error_return(-2,"No eeprom structure");
2373
2374     eeprom= ftdi->eeprom;
2375     output = eeprom->buf;
2376
2377     if (eeprom->chip == -1)
2378         ftdi_error_return(-6,"No connected EEPROM or EEPROM type unknown");
2379
2380     if ((eeprom->chip == 0x56) || (eeprom->chip == 0x66))
2381         eeprom->size = 0x100;
2382     else
2383         eeprom->size = 0x80;
2384
2385     if (eeprom->manufacturer != NULL)
2386         manufacturer_size = strlen(eeprom->manufacturer);
2387     if (eeprom->product != NULL)
2388         product_size = strlen(eeprom->product);
2389     if (eeprom->serial != NULL)
2390         serial_size = strlen(eeprom->serial);
2391
2392     // eeprom size check
2393     switch (ftdi->type)
2394     {
2395         case TYPE_AM:
2396         case TYPE_BM:
2397             user_area_size = 96;    // base size for strings (total of 48 characters)
2398             break;
2399         case TYPE_2232C:
2400             user_area_size = 90;     // two extra config bytes and 4 bytes PnP stuff
2401             break;
2402         case TYPE_R:
2403             user_area_size = 88;     // four extra config bytes + 4 bytes PnP stuff
2404             break;
2405         case TYPE_2232H:            // six extra config bytes + 4 bytes PnP stuff
2406         case TYPE_4232H:
2407             user_area_size = 86;
2408             break;
2409         case TYPE_232H:
2410             user_area_size = 80;
2411             break;
2412         default:
2413             user_area_size = 0;
2414             break;
2415     }
2416     user_area_size  -= (manufacturer_size + product_size + serial_size) * 2;
2417
2418     if (user_area_size < 0)
2419         ftdi_error_return(-1,"eeprom size exceeded");
2420
2421     // empty eeprom
2422     memset (ftdi->eeprom->buf, 0, FTDI_MAX_EEPROM_SIZE);
2423
2424     // Bytes and Bits set for all Types
2425
2426     // Addr 02: Vendor ID
2427     output[0x02] = eeprom->vendor_id;
2428     output[0x03] = eeprom->vendor_id >> 8;
2429
2430     // Addr 04: Product ID
2431     output[0x04] = eeprom->product_id;
2432     output[0x05] = eeprom->product_id >> 8;
2433
2434     // Addr 06: Device release number (0400h for BM features)
2435     output[0x06] = 0x00;
2436     switch (ftdi->type)
2437     {
2438         case TYPE_AM:
2439             output[0x07] = 0x02;
2440             break;
2441         case TYPE_BM:
2442             output[0x07] = 0x04;
2443             break;
2444         case TYPE_2232C:
2445             output[0x07] = 0x05;
2446             break;
2447         case TYPE_R:
2448             output[0x07] = 0x06;
2449             break;
2450         case TYPE_2232H:
2451             output[0x07] = 0x07;
2452             break;
2453         case TYPE_4232H:
2454             output[0x07] = 0x08;
2455             break;
2456         case TYPE_232H:
2457             output[0x07] = 0x09;
2458             break;
2459         default:
2460             output[0x07] = 0x00;
2461     }
2462
2463     // Addr 08: Config descriptor
2464     // Bit 7: always 1
2465     // Bit 6: 1 if this device is self powered, 0 if bus powered
2466     // Bit 5: 1 if this device uses remote wakeup
2467     // Bit 4-0: reserved - 0
2468     j = 0x80;
2469     if (eeprom->self_powered == 1)
2470         j |= 0x40;
2471     if (eeprom->remote_wakeup == 1)
2472         j |= 0x20;
2473     output[0x08] = j;
2474
2475     // Addr 09: Max power consumption: max power = value * 2 mA
2476     output[0x09] = eeprom->max_power>>1;
2477
2478     if (ftdi->type != TYPE_AM)
2479     {
2480         // Addr 0A: Chip configuration
2481         // Bit 7: 0 - reserved
2482         // Bit 6: 0 - reserved
2483         // Bit 5: 0 - reserved
2484         // Bit 4: 1 - Change USB version
2485         // Bit 3: 1 - Use the serial number string
2486         // Bit 2: 1 - Enable suspend pull downs for lower power
2487         // Bit 1: 1 - Out EndPoint is Isochronous
2488         // Bit 0: 1 - In EndPoint is Isochronous
2489         //
2490         j = 0;
2491         if (eeprom->in_is_isochronous == 1)
2492             j = j | 1;
2493         if (eeprom->out_is_isochronous == 1)
2494             j = j | 2;
2495         output[0x0A] = j;
2496     }
2497
2498     // Dynamic content
2499     // Strings start at 0x94 (TYPE_AM, TYPE_BM)
2500     // 0x96 (TYPE_2232C), 0x98 (TYPE_R) and 0x9a (TYPE_x232H)
2501     // 0xa0 (TYPE_232H)
2502     i = 0;
2503     switch (ftdi->type)
2504     {
2505         case TYPE_232H:
2506             i += 2;
2507         case TYPE_2232H:
2508         case TYPE_4232H:
2509             i += 2;
2510         case TYPE_R:
2511             i += 2;
2512         case TYPE_2232C:
2513             i += 2;
2514         case TYPE_AM:
2515         case TYPE_BM:
2516             i += 0x94;
2517     }
2518     /* Wrap around 0x80 for 128 byte EEPROMS (Internale and 93x46) */
2519     eeprom_size_mask = eeprom->size -1;
2520
2521     // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
2522     // Addr 0F: Length of manufacturer string
2523     // Output manufacturer
2524     output[0x0E] = i;  // calculate offset
2525     output[i & eeprom_size_mask] = manufacturer_size*2 + 2, i++;
2526     output[i & eeprom_size_mask] = 0x03, i++; // type: string
2527     for (j = 0; j < manufacturer_size; j++)
2528     {
2529         output[i & eeprom_size_mask] = eeprom->manufacturer[j], i++;
2530         output[i & eeprom_size_mask] = 0x00, i++;
2531     }
2532     output[0x0F] = manufacturer_size*2 + 2;
2533
2534     // Addr 10: Offset of the product string + 0x80, calculated later
2535     // Addr 11: Length of product string
2536     output[0x10] = i | 0x80;  // calculate offset
2537     output[i & eeprom_size_mask] = product_size*2 + 2, i++;
2538     output[i & eeprom_size_mask] = 0x03, i++;
2539     for (j = 0; j < product_size; j++)
2540     {
2541         output[i & eeprom_size_mask] = eeprom->product[j], i++;
2542         output[i & eeprom_size_mask] = 0x00, i++;
2543     }
2544     output[0x11] = product_size*2 + 2;
2545
2546     // Addr 12: Offset of the serial string + 0x80, calculated later
2547     // Addr 13: Length of serial string
2548     output[0x12] = i | 0x80; // calculate offset
2549     output[i & eeprom_size_mask] = serial_size*2 + 2, i++;
2550     output[i & eeprom_size_mask] = 0x03, i++;
2551     for (j = 0; j < serial_size; j++)
2552     {
2553         output[i & eeprom_size_mask] = eeprom->serial[j], i++;
2554         output[i & eeprom_size_mask] = 0x00, i++;
2555     }
2556
2557     // Legacy port name and PnP fields for FT2232 and newer chips
2558     if (ftdi->type > TYPE_BM)
2559     {
2560         output[i & eeprom_size_mask] = 0x02; /* as seen when written with FTD2XX */
2561         i++;
2562         output[i & eeprom_size_mask] = 0x03; /* as seen when written with FTD2XX */
2563         i++;
2564         output[i & eeprom_size_mask] = eeprom->is_not_pnp; /* as seen when written with FTD2XX */
2565         i++;
2566     }
2567
2568     output[0x13] = serial_size*2 + 2;
2569
2570     if (ftdi->type > TYPE_AM) /* use_serial not used in AM devices */
2571     {
2572         if (eeprom->use_serial == USE_SERIAL_NUM )
2573             output[0x0A] |= USE_SERIAL_NUM;
2574         else
2575             output[0x0A] &= ~USE_SERIAL_NUM;
2576     }
2577
2578     /* Bytes and Bits specific to (some) types
2579        Write linear, as this allows easier fixing*/
2580     switch (ftdi->type)
2581     {
2582         case TYPE_AM:
2583             break;
2584         case TYPE_BM:
2585             output[0x0C] = eeprom->usb_version & 0xff;
2586             output[0x0D] = (eeprom->usb_version>>8) & 0xff;
2587             if (eeprom->use_usb_version == USE_USB_VERSION_BIT)
2588                 output[0x0A] |= USE_USB_VERSION_BIT;
2589             else
2590                 output[0x0A] &= ~USE_USB_VERSION_BIT;
2591
2592             break;
2593         case TYPE_2232C:
2594
2595             output[0x00] = type2bit(eeprom->channel_a_type, TYPE_2232C);
2596             if ( eeprom->channel_a_driver == DRIVER_VCP)
2597                 output[0x00] |= DRIVER_VCP;
2598             else
2599                 output[0x00] &= ~DRIVER_VCP;
2600
2601             if ( eeprom->high_current_a == HIGH_CURRENT_DRIVE)
2602                 output[0x00] |= HIGH_CURRENT_DRIVE;
2603             else
2604                 output[0x00] &= ~HIGH_CURRENT_DRIVE;
2605
2606             output[0x01] = type2bit(eeprom->channel_b_type, TYPE_2232C);
2607             if ( eeprom->channel_b_driver == DRIVER_VCP)
2608                 output[0x01] |= DRIVER_VCP;
2609             else
2610                 output[0x01] &= ~DRIVER_VCP;
2611
2612             if ( eeprom->high_current_b == HIGH_CURRENT_DRIVE)
2613                 output[0x01] |= HIGH_CURRENT_DRIVE;
2614             else
2615                 output[0x01] &= ~HIGH_CURRENT_DRIVE;
2616
2617             if (eeprom->in_is_isochronous == 1)
2618                 output[0x0A] |= 0x1;
2619             else
2620                 output[0x0A] &= ~0x1;
2621             if (eeprom->out_is_isochronous == 1)
2622                 output[0x0A] |= 0x2;
2623             else
2624                 output[0x0A] &= ~0x2;
2625             if (eeprom->suspend_pull_downs == 1)
2626                 output[0x0A] |= 0x4;
2627             else
2628                 output[0x0A] &= ~0x4;
2629             if (eeprom->use_usb_version == USE_USB_VERSION_BIT)
2630                 output[0x0A] |= USE_USB_VERSION_BIT;
2631             else
2632                 output[0x0A] &= ~USE_USB_VERSION_BIT;
2633
2634             output[0x0C] = eeprom->usb_version & 0xff;
2635             output[0x0D] = (eeprom->usb_version>>8) & 0xff;
2636             output[0x14] = eeprom->chip;
2637             break;
2638         case TYPE_R:
2639             if (eeprom->high_current == HIGH_CURRENT_DRIVE_R)
2640                 output[0x00] |= HIGH_CURRENT_DRIVE_R;
2641             output[0x01] = 0x40; /* Hard coded Endpoint Size*/
2642
2643             if (eeprom->suspend_pull_downs == 1)
2644                 output[0x0A] |= 0x4;
2645             else
2646                 output[0x0A] &= ~0x4;
2647             output[0x0B] = eeprom->invert;
2648             output[0x0C] = eeprom->usb_version & 0xff;
2649             output[0x0D] = (eeprom->usb_version>>8) & 0xff;
2650
2651             if (eeprom->cbus_function[0] > CBUS_BB)
2652                 output[0x14] = CBUS_TXLED;
2653             else
2654                 output[0x14] = eeprom->cbus_function[0];
2655
2656             if (eeprom->cbus_function[1] > CBUS_BB)
2657                 output[0x14] |= CBUS_RXLED<<4;
2658             else
2659                 output[0x14] |= eeprom->cbus_function[1]<<4;
2660
2661             if (eeprom->cbus_function[2] > CBUS_BB)
2662                 output[0x15] = CBUS_TXDEN;
2663             else
2664                 output[0x15] = eeprom->cbus_function[2];
2665
2666             if (eeprom->cbus_function[3] > CBUS_BB)
2667                 output[0x15] |= CBUS_PWREN<<4;
2668             else
2669                 output[0x15] |= eeprom->cbus_function[3]<<4;
2670
2671             if (eeprom->cbus_function[4] > CBUS_CLK6)
2672                 output[0x16] = CBUS_SLEEP;
2673             else
2674                 output[0x16] = eeprom->cbus_function[4];
2675             break;
2676         case TYPE_2232H:
2677             output[0x00] = type2bit(eeprom->channel_a_type, TYPE_2232H);
2678             if ( eeprom->channel_a_driver == DRIVER_VCP)
2679                 output[0x00] |= DRIVER_VCP;
2680             else
2681                 output[0x00] &= ~DRIVER_VCP;
2682
2683             output[0x01] = type2bit(eeprom->channel_b_type, TYPE_2232H);
2684             if ( eeprom->channel_b_driver == DRIVER_VCP)
2685                 output[0x01] |= DRIVER_VCP;
2686             else
2687                 output[0x01] &= ~DRIVER_VCP;
2688             if (eeprom->suspend_dbus7 == SUSPEND_DBUS7_BIT)
2689                 output[0x01] |= SUSPEND_DBUS7_BIT;
2690             else
2691                 output[0x01] &= ~SUSPEND_DBUS7_BIT;
2692
2693             if (eeprom->suspend_pull_downs == 1)
2694                 output[0x0A] |= 0x4;
2695             else
2696                 output[0x0A] &= ~0x4;
2697
2698             if (eeprom->group0_drive > DRIVE_16MA)
2699                 output[0x0c] |= DRIVE_16MA;
2700             else
2701                 output[0x0c] |= eeprom->group0_drive;
2702             if (eeprom->group0_schmitt == IS_SCHMITT)
2703                 output[0x0c] |= IS_SCHMITT;
2704             if (eeprom->group0_slew == SLOW_SLEW)
2705                 output[0x0c] |= SLOW_SLEW;
2706
2707             if (eeprom->group1_drive > DRIVE_16MA)
2708                 output[0x0c] |= DRIVE_16MA<<4;
2709             else
2710                 output[0x0c] |= eeprom->group1_drive<<4;
2711             if (eeprom->group1_schmitt == IS_SCHMITT)
2712                 output[0x0c] |= IS_SCHMITT<<4;
2713             if (eeprom->group1_slew == SLOW_SLEW)
2714                 output[0x0c] |= SLOW_SLEW<<4;
2715
2716             if (eeprom->group2_drive > DRIVE_16MA)
2717                 output[0x0d] |= DRIVE_16MA;
2718             else
2719                 output[0x0d] |= eeprom->group2_drive;
2720             if (eeprom->group2_schmitt == IS_SCHMITT)
2721                 output[0x0d] |= IS_SCHMITT;
2722             if (eeprom->group2_slew == SLOW_SLEW)
2723                 output[0x0d] |= SLOW_SLEW;
2724
2725             if (eeprom->group3_drive > DRIVE_16MA)
2726                 output[0x0d] |= DRIVE_16MA<<4;
2727             else
2728                 output[0x0d] |= eeprom->group3_drive<<4;
2729             if (eeprom->group3_schmitt == IS_SCHMITT)
2730                 output[0x0d] |= IS_SCHMITT<<4;
2731             if (eeprom->group3_slew == SLOW_SLEW)
2732                 output[0x0d] |= SLOW_SLEW<<4;
2733
2734             output[0x18] = eeprom->chip;
2735
2736             break;
2737         case TYPE_4232H:
2738             output[0x18] = eeprom->chip;
2739             fprintf(stderr,"FIXME: Build FT4232H specific EEPROM settings\n");
2740             break;
2741         case TYPE_232H:
2742             output[0x00] = type2bit(eeprom->channel_a_type, TYPE_232H);
2743             if ( eeprom->channel_a_driver == DRIVER_VCP)
2744                 output[0x00] |= DRIVER_VCPH;
2745             else
2746                 output[0x00] &= ~DRIVER_VCPH;
2747             if (eeprom->powersave)
2748                 output[0x01] |= POWER_SAVE_DISABLE_H;
2749             else
2750                 output[0x01] &= ~POWER_SAVE_DISABLE_H;
2751             if (eeprom->clock_polarity)
2752                 output[0x01] |= FT1284_CLK_IDLE_STATE;
2753             else
2754                 output[0x01] &= ~FT1284_CLK_IDLE_STATE;
2755             if (eeprom->data_order)
2756                 output[0x01] |= FT1284_DATA_LSB;
2757             else
2758                 output[0x01] &= ~FT1284_DATA_LSB;
2759             if (eeprom->flow_control)
2760                 output[0x01] |= FT1284_FLOW_CONTROL;
2761             else
2762                 output[0x01] &= ~FT1284_FLOW_CONTROL;
2763             if (eeprom->group0_drive > DRIVE_16MA)
2764                 output[0x0c] |= DRIVE_16MA;
2765             else
2766                 output[0x0c] |= eeprom->group0_drive;
2767             if (eeprom->group0_schmitt == IS_SCHMITT)
2768                 output[0x0c] |= IS_SCHMITT;
2769             if (eeprom->group0_slew == SLOW_SLEW)
2770                 output[0x0c] |= SLOW_SLEW;
2771
2772             if (eeprom->group1_drive > DRIVE_16MA)
2773                 output[0x0d] |= DRIVE_16MA;
2774             else
2775                 output[0x0d] |= eeprom->group1_drive;
2776             if (eeprom->group1_schmitt == IS_SCHMITT)
2777                 output[0x0d] |= IS_SCHMITT;
2778             if (eeprom->group1_slew == SLOW_SLEW)
2779                 output[0x0d] |= SLOW_SLEW;
2780
2781             set_ft232h_cbus(eeprom, output);
2782
2783             output[0x1e] = eeprom->chip;
2784             fprintf(stderr,"FIXME: Build FT232H specific EEPROM settings\n");
2785             break;
2786               
2787     }
2788
2789     // calculate checksum
2790     checksum = 0xAAAA;
2791
2792     for (i = 0; i < eeprom->size/2-1; i++)
2793     {
2794         value = output[i*2];
2795         value += output[(i*2)+1] << 8;
2796
2797         checksum = value^checksum;
2798         checksum = (checksum << 1) | (checksum >> 15);
2799     }
2800
2801     output[eeprom->size-2] = checksum;
2802     output[eeprom->size-1] = checksum >> 8;
2803
2804     return user_area_size;
2805 }
2806 /* Decode the encoded EEPROM field for the FTDI Mode into a value for the abstracted 
2807  * EEPROM structure
2808  *
2809  * FTD2XX doesn't allow to set multiple bits in the interface mode bitfield, and so do we
2810  */
2811 static unsigned char bit2type(unsigned char bits)
2812 {
2813     switch (bits)
2814     {
2815     case   0: return CHANNEL_IS_UART;
2816     case   1: return CHANNEL_IS_FIFO;
2817     case   2: return CHANNEL_IS_OPTO;
2818     case   4: return CHANNEL_IS_CPU;
2819     case   8: return CHANNEL_IS_FT1284;
2820     default:
2821         fprintf(stderr," Unexpected value %d for Hardware Interface type\n",
2822                 bits);
2823     }
2824     return 0;
2825 }
2826 /**
2827    Decode binary EEPROM image into an ftdi_eeprom structure.
2828
2829    \param ftdi pointer to ftdi_context
2830    \param verbose Decode EEPROM on stdout
2831
2832    \retval 0: all fine
2833    \retval -1: something went wrong
2834
2835    FIXME: How to pass size? How to handle size field in ftdi_eeprom?
2836    FIXME: Strings are malloc'ed here and should be freed somewhere
2837 */
2838 int ftdi_eeprom_decode(struct ftdi_context *ftdi, int verbose)
2839 {
2840     unsigned char i, j;
2841     unsigned short checksum, eeprom_checksum, value;
2842     unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
2843     int eeprom_size;
2844     struct ftdi_eeprom *eeprom;
2845     unsigned char *buf = ftdi->eeprom->buf;
2846     int release;
2847
2848     if (ftdi == NULL)
2849         ftdi_error_return(-1,"No context");
2850     if (ftdi->eeprom == NULL)
2851         ftdi_error_return(-1,"No eeprom structure");
2852
2853     eeprom = ftdi->eeprom;
2854     eeprom_size = eeprom->size;
2855
2856     // Addr 02: Vendor ID
2857     eeprom->vendor_id = buf[0x02] + (buf[0x03] << 8);
2858
2859     // Addr 04: Product ID
2860     eeprom->product_id = buf[0x04] + (buf[0x05] << 8);
2861
2862     release = buf[0x06] + (buf[0x07]<<8);
2863
2864     // Addr 08: Config descriptor
2865     // Bit 7: always 1
2866     // Bit 6: 1 if this device is self powered, 0 if bus powered
2867     // Bit 5: 1 if this device uses remote wakeup
2868     eeprom->self_powered = buf[0x08] & 0x40;
2869     eeprom->remote_wakeup = buf[0x08] & 0x20;
2870
2871     // Addr 09: Max power consumption: max power = value * 2 mA
2872     eeprom->max_power = buf[0x09];
2873
2874     // Addr 0A: Chip configuration
2875     // Bit 7: 0 - reserved
2876     // Bit 6: 0 - reserved
2877     // Bit 5: 0 - reserved
2878     // Bit 4: 1 - Change USB version on BM and 2232C
2879     // Bit 3: 1 - Use the serial number string
2880     // Bit 2: 1 - Enable suspend pull downs for lower power
2881     // Bit 1: 1 - Out EndPoint is Isochronous
2882     // Bit 0: 1 - In EndPoint is Isochronous
2883     //
2884     eeprom->in_is_isochronous  = buf[0x0A]&0x01;
2885     eeprom->out_is_isochronous = buf[0x0A]&0x02;
2886     eeprom->suspend_pull_downs = buf[0x0A]&0x04;
2887     eeprom->use_serial         = buf[0x0A] & USE_SERIAL_NUM;
2888     eeprom->use_usb_version    = buf[0x0A] & USE_USB_VERSION_BIT;
2889
2890     // Addr 0C: USB version low byte when 0x0A
2891     // Addr 0D: USB version high byte when 0x0A
2892     eeprom->usb_version = buf[0x0C] + (buf[0x0D] << 8);
2893
2894     // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
2895     // Addr 0F: Length of manufacturer string
2896     manufacturer_size = buf[0x0F]/2;
2897     if (eeprom->manufacturer)
2898         free(eeprom->manufacturer);
2899     if (manufacturer_size > 0)
2900     {
2901         eeprom->manufacturer = malloc(manufacturer_size);
2902         if (eeprom->manufacturer)
2903         {
2904             // Decode manufacturer
2905             i = buf[0x0E] & (eeprom_size -1); // offset
2906             for (j=0;j<manufacturer_size-1;j++)
2907             {
2908                 eeprom->manufacturer[j] = buf[2*j+i+2];
2909             }
2910             eeprom->manufacturer[j] = '\0';
2911         }
2912     }
2913     else eeprom->manufacturer = NULL;
2914
2915     // Addr 10: Offset of the product string + 0x80, calculated later
2916     // Addr 11: Length of product string
2917     if (eeprom->product)
2918         free(eeprom->product);
2919     product_size = buf[0x11]/2;
2920     if (product_size > 0)
2921     {
2922         eeprom->product = malloc(product_size);
2923         if (eeprom->product)
2924         {
2925             // Decode product name
2926             i = buf[0x10] & (eeprom_size -1); // offset
2927             for (j=0;j<product_size-1;j++)
2928             {
2929                 eeprom->product[j] = buf[2*j+i+2];
2930             }
2931             eeprom->product[j] = '\0';
2932         }
2933     }
2934     else eeprom->product = NULL;
2935
2936     // Addr 12: Offset of the serial string + 0x80, calculated later
2937     // Addr 13: Length of serial string
2938     if (eeprom->serial)
2939         free(eeprom->serial);
2940     serial_size = buf[0x13]/2;
2941     if (serial_size > 0)
2942     {
2943         eeprom->serial = malloc(serial_size);
2944         if (eeprom->serial)
2945         {
2946             // Decode serial
2947             i = buf[0x12] & (eeprom_size -1); // offset
2948             for (j=0;j<serial_size-1;j++)
2949             {
2950                 eeprom->serial[j] = buf[2*j+i+2];
2951             }
2952             eeprom->serial[j] = '\0';
2953         }
2954     }
2955     else eeprom->serial = NULL;
2956
2957     // verify checksum
2958     checksum = 0xAAAA;
2959
2960     for (i = 0; i < eeprom_size/2-1; i++)
2961     {
2962         value = buf[i*2];
2963         value += buf[(i*2)+1] << 8;
2964
2965         checksum = value^checksum;
2966         checksum = (checksum << 1) | (checksum >> 15);
2967     }
2968
2969     eeprom_checksum = buf[eeprom_size-2] + (buf[eeprom_size-1] << 8);
2970
2971     if (eeprom_checksum != checksum)
2972     {
2973         fprintf(stderr, "Checksum Error: %04x %04x\n", checksum, eeprom_checksum);
2974         ftdi_error_return(-1,"EEPROM checksum error");
2975     }
2976
2977     eeprom->channel_a_type   = 0;
2978     if ((ftdi->type == TYPE_AM) || (ftdi->type == TYPE_BM))
2979     {
2980         eeprom->chip = -1;
2981     }
2982     else if (ftdi->type == TYPE_2232C)
2983     {
2984         eeprom->channel_a_type   = bit2type(buf[0x00] & 0x7);
2985         eeprom->channel_a_driver = buf[0x00] & DRIVER_VCP;
2986         eeprom->high_current_a   = buf[0x00] & HIGH_CURRENT_DRIVE;
2987         eeprom->channel_b_type   = buf[0x01] & 0x7;
2988         eeprom->channel_b_driver = buf[0x01] & DRIVER_VCP;
2989         eeprom->high_current_b   = buf[0x01] & HIGH_CURRENT_DRIVE;
2990         eeprom->chip = buf[0x14];
2991     }
2992     else if (ftdi->type == TYPE_R)
2993     {
2994         /* TYPE_R flags D2XX, not VCP as all others*/
2995         eeprom->channel_a_driver = (~buf[0x00]) & DRIVER_VCP;
2996         eeprom->high_current     = buf[0x00] & HIGH_CURRENT_DRIVE_R;
2997         if ( (buf[0x01]&0x40) != 0x40)
2998             fprintf(stderr,
2999                     "TYPE_R EEPROM byte[0x01] Bit 6 unexpected Endpoint size."
3000                     " If this happened with the\n"
3001                     " EEPROM programmed by FTDI tools, please report "
3002                     "to libftdi@developer.intra2net.com\n");
3003
3004         eeprom->chip = buf[0x16];
3005         // Addr 0B: Invert data lines
3006         // Works only on FT232R, not FT245R, but no way to distinguish
3007         eeprom->invert = buf[0x0B];
3008         // Addr 14: CBUS function: CBUS0, CBUS1
3009         // Addr 15: CBUS function: CBUS2, CBUS3
3010         // Addr 16: CBUS function: CBUS5
3011         eeprom->cbus_function[0] = buf[0x14] & 0x0f;
3012         eeprom->cbus_function[1] = (buf[0x14] >> 4) & 0x0f;
3013         eeprom->cbus_function[2] = buf[0x15] & 0x0f;
3014         eeprom->cbus_function[3] = (buf[0x15] >> 4) & 0x0f;
3015         eeprom->cbus_function[4] = buf[0x16] & 0x0f;
3016     }
3017     else if ((ftdi->type == TYPE_2232H) ||(ftdi->type == TYPE_4232H))
3018     {
3019         eeprom->channel_a_type   = bit2type(buf[0x00] & 0x7);
3020         eeprom->channel_a_driver = buf[0x00] & DRIVER_VCP;
3021         eeprom->channel_b_type   = bit2type(buf[0x01] & 0x7);
3022         eeprom->channel_b_driver = buf[0x01] & DRIVER_VCP;
3023
3024         if (ftdi->type == TYPE_2232H)
3025             eeprom->suspend_dbus7    = buf[0x01] & SUSPEND_DBUS7_BIT;
3026
3027         eeprom->chip = buf[0x18];
3028         eeprom->group0_drive   =  buf[0x0c]       & DRIVE_16MA;
3029         eeprom->group0_schmitt =  buf[0x0c]       & IS_SCHMITT;
3030         eeprom->group0_slew    =  buf[0x0c]       & SLOW_SLEW;
3031         eeprom->group1_drive   = (buf[0x0c] >> 4) & 0x3;
3032         eeprom->group1_schmitt = (buf[0x0c] >> 4) & IS_SCHMITT;
3033         eeprom->group1_slew    = (buf[0x0c] >> 4) & SLOW_SLEW;
3034         eeprom->group2_drive   =  buf[0x0d]       & DRIVE_16MA;
3035         eeprom->group2_schmitt =  buf[0x0d]       & IS_SCHMITT;
3036         eeprom->group2_slew    =  buf[0x0d]       & SLOW_SLEW;
3037         eeprom->group3_drive   = (buf[0x0d] >> 4) & DRIVE_16MA;
3038         eeprom->group3_schmitt = (buf[0x0d] >> 4) & IS_SCHMITT;
3039         eeprom->group3_slew    = (buf[0x0d] >> 4) & SLOW_SLEW;
3040     }
3041     else if (ftdi->type == TYPE_232H)
3042     {
3043         int i;
3044
3045         eeprom->channel_a_type   = buf[0x00] & 0xf;
3046         eeprom->channel_a_driver = (buf[0x00] & DRIVER_VCPH)?DRIVER_VCP:0;
3047         eeprom->clock_polarity =  buf[0x01]       & FT1284_CLK_IDLE_STATE;
3048         eeprom->data_order     =  buf[0x01]       & FT1284_DATA_LSB;
3049         eeprom->flow_control   =  buf[0x01]       & FT1284_FLOW_CONTROL;
3050         eeprom->powersave      =  buf[0x01]       & POWER_SAVE_DISABLE_H;
3051         eeprom->group0_drive   =  buf[0x0c]       & DRIVE_16MA;
3052         eeprom->group0_schmitt =  buf[0x0c]       & IS_SCHMITT;
3053         eeprom->group0_slew    =  buf[0x0c]       & SLOW_SLEW;
3054         eeprom->group1_drive   =  buf[0x0d]       & DRIVE_16MA;
3055         eeprom->group1_schmitt =  buf[0x0d]       & IS_SCHMITT;
3056         eeprom->group1_slew    =  buf[0x0d]       & SLOW_SLEW;
3057
3058         for(i=0; i<5; i++)
3059         {
3060             eeprom->cbus_function[2*i  ] =  buf[0x18+i] & 0x0f;
3061             eeprom->cbus_function[2*i+1] = (buf[0x18+i] >> 4) & 0x0f;
3062         }
3063         eeprom->chip = buf[0x1e];
3064         /*FIXME: Decipher more values*/
3065     }
3066
3067     if (verbose)
3068     {
3069         char *channel_mode[] = {"UART", "FIFO", "CPU", "OPTO", "FT1284"};
3070         fprintf(stdout, "VID:     0x%04x\n",eeprom->vendor_id);
3071         fprintf(stdout, "PID:     0x%04x\n",eeprom->product_id);
3072         fprintf(stdout, "Release: 0x%04x\n",release);
3073
3074         if (eeprom->self_powered)
3075             fprintf(stdout, "Self-Powered%s", (eeprom->remote_wakeup)?", USB Remote Wake Up\n":"\n");
3076         else
3077             fprintf(stdout, "Bus Powered: %3d mA%s", eeprom->max_power * 2,
3078                     (eeprom->remote_wakeup)?" USB Remote Wake Up\n":"\n");
3079         if (eeprom->manufacturer)
3080             fprintf(stdout, "Manufacturer: %s\n",eeprom->manufacturer);
3081         if (eeprom->product)
3082             fprintf(stdout, "Product:      %s\n",eeprom->product);
3083         if (eeprom->serial)
3084             fprintf(stdout, "Serial:       %s\n",eeprom->serial);
3085         fprintf(stdout,     "Checksum      : %04x\n", checksum);
3086         if (ftdi->type == TYPE_R)
3087             fprintf(stdout,     "Internal EEPROM\n");
3088         else if (eeprom->chip >= 0x46)
3089             fprintf(stdout,     "Attached EEPROM: 93x%02x\n", eeprom->chip);
3090         if (eeprom->suspend_dbus7)
3091             fprintf(stdout, "Suspend on DBUS7\n");
3092         if (eeprom->suspend_pull_downs)
3093             fprintf(stdout, "Pull IO pins low during suspend\n");
3094         if(eeprom->powersave)
3095         {
3096             if(ftdi->type >= TYPE_232H)
3097                 fprintf(stdout,"Enter low power state on ACBUS7\n");
3098         } 
3099         if (eeprom->remote_wakeup)
3100             fprintf(stdout, "Enable Remote Wake Up\n");
3101         fprintf(stdout, "PNP: %d\n",(eeprom->is_not_pnp)?0:1);
3102         if (ftdi->type >= TYPE_2232C)
3103             fprintf(stdout,"Channel A has Mode %s%s%s\n",
3104                     channel_mode[eeprom->channel_a_type],
3105                     (eeprom->channel_a_driver)?" VCP":"",
3106                     (eeprom->high_current_a)?" High Current IO":"");
3107         if (ftdi->type >= TYPE_232H)
3108         {
3109             fprintf(stdout,"FT1284 Mode Clock is idle %s, %s first, %sFlow Control\n",
3110                     (eeprom->clock_polarity)?"HIGH":"LOW",
3111                     (eeprom->data_order)?"LSB":"MSB",
3112                     (eeprom->flow_control)?"":"No ");
3113         }        
3114         if ((ftdi->type >= TYPE_2232C) && (ftdi->type != TYPE_R) && (ftdi->type != TYPE_232H))
3115             fprintf(stdout,"Channel B has Mode %s%s%s\n",
3116                     channel_mode[eeprom->channel_b_type],
3117                     (eeprom->channel_b_driver)?" VCP":"",
3118                     (eeprom->high_current_b)?" High Current IO":"");
3119         if (((ftdi->type == TYPE_BM) || (ftdi->type == TYPE_2232C)) &&
3120                 eeprom->use_usb_version == USE_USB_VERSION_BIT)
3121             fprintf(stdout,"Use explicit USB Version %04x\n",eeprom->usb_version);
3122
3123         if ((ftdi->type == TYPE_2232H) || (ftdi->type == TYPE_4232H))
3124         {
3125             fprintf(stdout,"%s has %d mA drive%s%s\n",
3126                     (ftdi->type == TYPE_2232H)?"AL":"A",
3127                     (eeprom->group0_drive+1) *4,
3128                     (eeprom->group0_schmitt)?" Schmitt Input":"",
3129                     (eeprom->group0_slew)?" Slow Slew":"");
3130             fprintf(stdout,"%s has %d mA drive%s%s\n",
3131                     (ftdi->type == TYPE_2232H)?"AH":"B",
3132                     (eeprom->group1_drive+1) *4,
3133                     (eeprom->group1_schmitt)?" Schmitt Input":"",
3134                     (eeprom->group1_slew)?" Slow Slew":"");
3135             fprintf(stdout,"%s has %d mA drive%s%s\n",
3136                     (ftdi->type == TYPE_2232H)?"BL":"C",
3137                     (eeprom->group2_drive+1) *4,
3138                     (eeprom->group2_schmitt)?" Schmitt Input":"",
3139                     (eeprom->group2_slew)?" Slow Slew":"");
3140             fprintf(stdout,"%s has %d mA drive%s%s\n",
3141                     (ftdi->type == TYPE_2232H)?"BH":"D",
3142                     (eeprom->group3_drive+1) *4,
3143                     (eeprom->group3_schmitt)?" Schmitt Input":"",
3144                     (eeprom->group3_slew)?" Slow Slew":"");
3145         }
3146         else if (ftdi->type == TYPE_232H)
3147         {
3148             int i;
3149             char *cbush_mux[] = {"TRISTATE","RXLED","TXLED", "TXRXLED","PWREN",
3150                                 "SLEEP","DRIVE_0","DRIVE_1","IOMODE","TXDEN",
3151                                 "CLK30","CLK15","CLK7_5"
3152                                };
3153             fprintf(stdout,"ACBUS has %d mA drive%s%s\n",
3154                     (eeprom->group0_drive+1) *4,
3155                     (eeprom->group0_schmitt)?" Schmitt Input":"",
3156                     (eeprom->group0_slew)?" Slow Slew":"");
3157             fprintf(stdout,"ADBUS has %d mA drive%s%s\n",
3158                     (eeprom->group1_drive+1) *4,
3159                     (eeprom->group1_schmitt)?" Schmitt Input":"",
3160                     (eeprom->group1_slew)?" Slow Slew":"");
3161             for (i=0; i<10; i++)
3162             {
3163                 if (eeprom->cbus_function[i]<= CBUSH_CLK7_5 )
3164                     fprintf(stdout,"C%d Function: %s\n", i,
3165                             cbush_mux[eeprom->cbus_function[i]]);
3166             }
3167
3168         }
3169
3170         if (ftdi->type == TYPE_R)
3171         {
3172             char *cbus_mux[] = {"TXDEN","PWREN","RXLED", "TXLED","TX+RXLED",
3173                                 "SLEEP","CLK48","CLK24","CLK12","CLK6",
3174                                 "IOMODE","BB_WR","BB_RD"
3175                                };
3176             char *cbus_BB[] = {"RXF","TXE","RD", "WR"};
3177
3178             if (eeprom->invert)
3179             {
3180                 char *r_bits[] = {"TXD","RXD","RTS", "CTS","DTR","DSR","DCD","RI"};
3181                 fprintf(stdout,"Inverted bits:");
3182                 for (i=0; i<8; i++)
3183                     if ((eeprom->invert & (1<<i)) == (1<<i))
3184                         fprintf(stdout," %s",r_bits[i]);
3185                 fprintf(stdout,"\n");
3186             }
3187             for (i=0; i<5; i++)
3188             {
3189                 if (eeprom->cbus_function[i]<CBUS_BB)
3190                     fprintf(stdout,"C%d Function: %s\n", i,
3191                             cbus_mux[eeprom->cbus_function[i]]);
3192                 else
3193                 {
3194                     if (i < 4)
3195                         /* Running MPROG show that C0..3 have fixed function Synchronous
3196                            Bit Bang mode */
3197                         fprintf(stdout,"C%d BB Function: %s\n", i,
3198                                 cbus_BB[i]);
3199                     else
3200                         fprintf(stdout, "Unknown CBUS mode. Might be special mode?\n");
3201                 }
3202             }
3203         }
3204     }
3205     return 0;
3206 }
3207
3208 /**
3209    Get a value from the decoded EEPROM structure
3210
3211    \param ftdi pointer to ftdi_context
3212    \param value_name Enum of the value to query
3213    \param value Pointer to store read value
3214
3215    \retval 0: all fine
3216    \retval -1: Value doesn't exist
3217 */
3218 int ftdi_get_eeprom_value(struct ftdi_context *ftdi, enum ftdi_eeprom_value value_name, int* value)
3219 {
3220     switch (value_name)
3221     {
3222         case VENDOR_ID:
3223             *value = ftdi->eeprom->vendor_id;
3224             break;
3225         case PRODUCT_ID:
3226             *value = ftdi->eeprom->product_id;
3227             break;
3228         case SELF_POWERED:
3229             *value = ftdi->eeprom->self_powered;
3230             break;
3231         case REMOTE_WAKEUP:
3232             *value = ftdi->eeprom->remote_wakeup;
3233             break;
3234         case IS_NOT_PNP:
3235             *value = ftdi->eeprom->is_not_pnp;
3236             break;
3237         case SUSPEND_DBUS7:
3238             *value = ftdi->eeprom->suspend_dbus7;
3239             break;
3240         case IN_IS_ISOCHRONOUS:
3241             *value = ftdi->eeprom->in_is_isochronous;
3242             break;
3243         case OUT_IS_ISOCHRONOUS:
3244             *value = ftdi->eeprom->out_is_isochronous;
3245             break;
3246         case SUSPEND_PULL_DOWNS:
3247             *value = ftdi->eeprom->suspend_pull_downs;
3248             break;
3249         case USE_SERIAL:
3250             *value = ftdi->eeprom->use_serial;
3251             break;
3252         case USB_VERSION:
3253             *value = ftdi->eeprom->usb_version;
3254             break;
3255         case USE_USB_VERSION:
3256             *value = ftdi->eeprom->use_usb_version;
3257             break;
3258         case MAX_POWER:
3259             *value = ftdi->eeprom->max_power;
3260             break;
3261         case CHANNEL_A_TYPE:
3262             *value = ftdi->eeprom->channel_a_type;
3263             break;
3264         case CHANNEL_B_TYPE:
3265             *value = ftdi->eeprom->channel_b_type;
3266             break;
3267         case CHANNEL_A_DRIVER:
3268             *value = ftdi->eeprom->channel_a_driver;
3269             break;
3270         case CHANNEL_B_DRIVER:
3271             *value = ftdi->eeprom->channel_b_driver;
3272             break;
3273         case CBUS_FUNCTION_0:
3274             *value = ftdi->eeprom->cbus_function[0];
3275             break;
3276         case CBUS_FUNCTION_1:
3277             *value = ftdi->eeprom->cbus_function[1];
3278             break;
3279         case CBUS_FUNCTION_2:
3280             *value = ftdi->eeprom->cbus_function[2];
3281             break;
3282         case CBUS_FUNCTION_3:
3283             *value = ftdi->eeprom->cbus_function[3];
3284             break;
3285         case CBUS_FUNCTION_4:
3286             *value = ftdi->eeprom->cbus_function[4];
3287             break;
3288         case CBUS_FUNCTION_5:
3289             *value = ftdi->eeprom->cbus_function[5];
3290             break;
3291         case CBUS_FUNCTION_6:
3292             *value = ftdi->eeprom->cbus_function[6];
3293             break;
3294         case CBUS_FUNCTION_7:
3295             *value = ftdi->eeprom->cbus_function[7];
3296             break;
3297         case CBUS_FUNCTION_8:
3298             *value = ftdi->eeprom->cbus_function[8];
3299             break;
3300         case CBUS_FUNCTION_9:
3301             *value = ftdi->eeprom->cbus_function[8];
3302             break;
3303         case HIGH_CURRENT:
3304             *value = ftdi->eeprom->high_current;
3305             break;
3306         case HIGH_CURRENT_A:
3307             *value = ftdi->eeprom->high_current_a;
3308             break;
3309         case HIGH_CURRENT_B:
3310             *value = ftdi->eeprom->high_current_b;
3311             break;
3312         case INVERT:
3313             *value = ftdi->eeprom->invert;
3314             break;
3315         case GROUP0_DRIVE:
3316             *value = ftdi->eeprom->group0_drive;
3317             break;
3318         case GROUP0_SCHMITT:
3319             *value = ftdi->eeprom->group0_schmitt;
3320             break;
3321         case GROUP0_SLEW:
3322             *value = ftdi->eeprom->group0_slew;
3323             break;
3324         case GROUP1_DRIVE:
3325             *value = ftdi->eeprom->group1_drive;
3326             break;
3327         case GROUP1_SCHMITT:
3328             *value = ftdi->eeprom->group1_schmitt;
3329             break;
3330         case GROUP1_SLEW:
3331             *value = ftdi->eeprom->group1_slew;
3332             break;
3333         case GROUP2_DRIVE:
3334             *value = ftdi->eeprom->group2_drive;
3335             break;
3336         case GROUP2_SCHMITT:
3337             *value = ftdi->eeprom->group2_schmitt;
3338             break;
3339         case GROUP2_SLEW:
3340             *value = ftdi->eeprom->group2_slew;
3341             break;
3342         case GROUP3_DRIVE:
3343             *value = ftdi->eeprom->group3_drive;
3344             break;
3345         case GROUP3_SCHMITT:
3346             *value = ftdi->eeprom->group3_schmitt;
3347             break;
3348         case GROUP3_SLEW:
3349             *value = ftdi->eeprom->group3_slew;
3350             break;
3351          case POWER_SAVE:
3352             *value = ftdi->eeprom->powersave;
3353             break;
3354           case CLOCK_POLARITY:
3355             *value = ftdi->eeprom->clock_polarity;
3356             break;
3357          case DATA_ORDER:
3358             *value = ftdi->eeprom->data_order;
3359             break;
3360          case FLOW_CONTROL:
3361             *value = ftdi->eeprom->flow_control;
3362             break;
3363        case CHIP_TYPE:
3364             *value = ftdi->eeprom->chip;
3365             break;
3366         case CHIP_SIZE:
3367             *value = ftdi->eeprom->size;
3368             break;
3369         default:
3370             ftdi_error_return(-1, "Request for unknown EEPROM value");
3371     }
3372     return 0;
3373 }
3374
3375 /**
3376    Set a value in the decoded EEPROM Structure
3377    No parameter checking is performed
3378
3379    \param ftdi pointer to ftdi_context
3380    \param value_name Enum of the value to set
3381    \param value to set
3382
3383    \retval 0: all fine
3384    \retval -1: Value doesn't exist
3385    \retval -2: Value not user settable
3386 */
3387 int ftdi_set_eeprom_value(struct ftdi_context *ftdi, enum ftdi_eeprom_value value_name, int value)
3388 {
3389     switch (value_name)
3390     {
3391         case VENDOR_ID:
3392             ftdi->eeprom->vendor_id = value;
3393             break;
3394         case PRODUCT_ID:
3395             ftdi->eeprom->product_id = value;
3396             break;
3397         case SELF_POWERED:
3398             ftdi->eeprom->self_powered = value;
3399             break;
3400         case REMOTE_WAKEUP:
3401             ftdi->eeprom->remote_wakeup = value;
3402             break;
3403         case IS_NOT_PNP:
3404             ftdi->eeprom->is_not_pnp = value;
3405             break;
3406         case SUSPEND_DBUS7:
3407             ftdi->eeprom->suspend_dbus7 = value;
3408             break;
3409         case IN_IS_ISOCHRONOUS:
3410             ftdi->eeprom->in_is_isochronous = value;
3411             break;
3412         case OUT_IS_ISOCHRONOUS:
3413             ftdi->eeprom->out_is_isochronous = value;
3414             break;
3415         case SUSPEND_PULL_DOWNS:
3416             ftdi->eeprom->suspend_pull_downs = value;
3417             break;
3418         case USE_SERIAL:
3419             ftdi->eeprom->use_serial = value;
3420             break;
3421         case USB_VERSION:
3422             ftdi->eeprom->usb_version = value;
3423             break;
3424         case USE_USB_VERSION:
3425             ftdi->eeprom->use_usb_version = value;
3426             break;
3427         case MAX_POWER:
3428             ftdi->eeprom->max_power = value;
3429             break;
3430         case CHANNEL_A_TYPE:
3431             ftdi->eeprom->channel_a_type = value;
3432             break;
3433         case CHANNEL_B_TYPE:
3434             ftdi->eeprom->channel_b_type = value;
3435             break;
3436         case CHANNEL_A_DRIVER:
3437             ftdi->eeprom->channel_a_driver = value;
3438             break;
3439         case CHANNEL_B_DRIVER:
3440             ftdi->eeprom->channel_b_driver = value;
3441             break;
3442         case CBUS_FUNCTION_0:
3443             ftdi->eeprom->cbus_function[0] = value;
3444             break;
3445         case CBUS_FUNCTION_1:
3446             ftdi->eeprom->cbus_function[1] = value;
3447             break;
3448         case CBUS_FUNCTION_2:
3449             ftdi->eeprom->cbus_function[2] = value;
3450             break;
3451         case CBUS_FUNCTION_3:
3452             ftdi->eeprom->cbus_function[3] = value;
3453             break;
3454         case CBUS_FUNCTION_4:
3455             ftdi->eeprom->cbus_function[4] = value;
3456             break;
3457         case CBUS_FUNCTION_5:
3458             ftdi->eeprom->cbus_function[5] = value;
3459             break;
3460         case CBUS_FUNCTION_6:
3461             ftdi->eeprom->cbus_function[6] = value;
3462             break;
3463         case CBUS_FUNCTION_7:
3464             ftdi->eeprom->cbus_function[7] = value;
3465             break;
3466         case CBUS_FUNCTION_8:
3467             ftdi->eeprom->cbus_function[8] = value;
3468             break;
3469         case CBUS_FUNCTION_9:
3470             ftdi->eeprom->cbus_function[9] = value;
3471             break;
3472         case HIGH_CURRENT:
3473             ftdi->eeprom->high_current = value;
3474             break;
3475         case HIGH_CURRENT_A:
3476             ftdi->eeprom->high_current_a = value;
3477             break;
3478         case HIGH_CURRENT_B:
3479             ftdi->eeprom->high_current_b = value;
3480             break;
3481         case INVERT:
3482             ftdi->eeprom->invert = value;
3483             break;
3484         case GROUP0_DRIVE:
3485             ftdi->eeprom->group0_drive = value;
3486             break;
3487         case GROUP0_SCHMITT:
3488             ftdi->eeprom->group0_schmitt = value;
3489             break;
3490         case GROUP0_SLEW:
3491             ftdi->eeprom->group0_slew = value;
3492             break;
3493         case GROUP1_DRIVE:
3494             ftdi->eeprom->group1_drive = value;
3495             break;
3496         case GROUP1_SCHMITT:
3497             ftdi->eeprom->group1_schmitt = value;
3498             break;
3499         case GROUP1_SLEW:
3500             ftdi->eeprom->group1_slew = value;
3501             break;
3502         case GROUP2_DRIVE:
3503             ftdi->eeprom->group2_drive = value;
3504             break;
3505         case GROUP2_SCHMITT:
3506             ftdi->eeprom->group2_schmitt = value;
3507             break;
3508         case GROUP2_SLEW:
3509             ftdi->eeprom->group2_slew = value;
3510             break;
3511         case GROUP3_DRIVE:
3512             ftdi->eeprom->group3_drive = value;
3513             break;
3514         case GROUP3_SCHMITT:
3515             ftdi->eeprom->group3_schmitt = value;
3516             break;
3517         case GROUP3_SLEW:
3518             ftdi->eeprom->group3_slew = value;
3519             break;
3520         case CHIP_TYPE:
3521             ftdi->eeprom->chip = value;
3522             break;
3523          case POWER_SAVE:
3524             ftdi->eeprom->powersave = value;
3525             break;
3526          case CLOCK_POLARITY:
3527             ftdi->eeprom->clock_polarity = value;
3528             break;
3529          case DATA_ORDER:
3530             ftdi->eeprom->data_order = value;
3531             break;
3532          case FLOW_CONTROL:
3533             ftdi->eeprom->flow_control = value;
3534             break;
3535         case CHIP_SIZE:
3536             ftdi_error_return(-2, "EEPROM Value can't be changed");
3537         default :
3538             ftdi_error_return(-1, "Request to unknown EEPROM value");
3539     }
3540     return 0;
3541 }
3542
3543 /** Get the read-only buffer to the binary EEPROM content
3544
3545     \param ftdi pointer to ftdi_context
3546     \param buf buffer to receive EEPROM content
3547     \param size Size of receiving buffer
3548
3549     \retval 0: All fine
3550     \retval -1: struct ftdi_contxt or ftdi_eeprom missing
3551     \retval -2: Not enough room to store eeprom
3552 */
3553 int ftdi_get_eeprom_buf(struct ftdi_context *ftdi, unsigned char * buf, int size)
3554 {
3555     if (!ftdi || !(ftdi->eeprom))
3556         ftdi_error_return(-1, "No appropriate structure");
3557
3558     if (!buf || size < ftdi->eeprom->size)
3559         ftdi_error_return(-1, "Not enough room to store eeprom");
3560
3561     // Only copy up to FTDI_MAX_EEPROM_SIZE bytes
3562     if (size > FTDI_MAX_EEPROM_SIZE)
3563         size = FTDI_MAX_EEPROM_SIZE;
3564
3565     memcpy(buf, ftdi->eeprom->buf, size);
3566
3567     return 0;
3568 }
3569
3570 /** Set the EEPROM content from the user-supplied prefilled buffer
3571
3572     \param ftdi pointer to ftdi_context
3573     \param buf buffer to read EEPROM content
3574     \param size Size of buffer
3575
3576     \retval 0: All fine
3577     \retval -1: struct ftdi_contxt or ftdi_eeprom of buf missing
3578 */
3579 int ftdi_set_eeprom_buf(struct ftdi_context *ftdi, const unsigned char * buf, int size)
3580 {
3581     if (!ftdi || !(ftdi->eeprom) || !buf)
3582         ftdi_error_return(-1, "No appropriate structure");
3583
3584     // Only copy up to FTDI_MAX_EEPROM_SIZE bytes
3585     if (size > FTDI_MAX_EEPROM_SIZE)
3586         size = FTDI_MAX_EEPROM_SIZE;
3587
3588     memcpy(ftdi->eeprom->buf, buf, size);
3589
3590     return 0;
3591 }
3592
3593 /**
3594     Read eeprom location
3595
3596     \param ftdi pointer to ftdi_context
3597     \param eeprom_addr Address of eeprom location to be read
3598     \param eeprom_val Pointer to store read eeprom location
3599
3600     \retval  0: all fine
3601     \retval -1: read failed
3602     \retval -2: USB device unavailable
3603 */
3604 int ftdi_read_eeprom_location (struct ftdi_context *ftdi, int eeprom_addr, unsigned short *eeprom_val)
3605 {
3606     if (ftdi == NULL || ftdi->usb_dev == NULL)
3607         ftdi_error_return(-2, "USB device unavailable");
3608
3609     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)
3610         ftdi_error_return(-1, "reading eeprom failed");
3611
3612     return 0;
3613 }
3614
3615 /**
3616     Read eeprom
3617
3618     \param ftdi pointer to ftdi_context
3619
3620     \retval  0: all fine
3621     \retval -1: read failed
3622     \retval -2: USB device unavailable
3623 */
3624 int ftdi_read_eeprom(struct ftdi_context *ftdi)
3625 {
3626     int i;
3627     unsigned char *buf;
3628
3629     if (ftdi == NULL || ftdi->usb_dev == NULL)
3630         ftdi_error_return(-2, "USB device unavailable");
3631     buf = ftdi->eeprom->buf;
3632
3633     for (i = 0; i < FTDI_MAX_EEPROM_SIZE/2; i++)
3634     {
3635         if (libusb_control_transfer(
3636                     ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE,SIO_READ_EEPROM_REQUEST, 0, i,
3637                     buf+(i*2), 2, ftdi->usb_read_timeout) != 2)
3638             ftdi_error_return(-1, "reading eeprom failed");
3639     }
3640
3641     if (ftdi->type == TYPE_R)
3642         ftdi->eeprom->size = 0x80;
3643     /*    Guesses size of eeprom by comparing halves
3644           - will not work with blank eeprom */
3645     else if (strrchr((const char *)buf, 0xff) == ((const char *)buf +FTDI_MAX_EEPROM_SIZE -1))
3646         ftdi->eeprom->size = -1;
3647     else if (memcmp(buf,&buf[0x80],0x80) == 0)
3648         ftdi->eeprom->size = 0x80;
3649     else if (memcmp(buf,&buf[0x40],0x40) == 0)
3650         ftdi->eeprom->size = 0x40;
3651     else
3652         ftdi->eeprom->size = 0x100;
3653     return 0;
3654 }
3655
3656 /*
3657     ftdi_read_chipid_shift does the bitshift operation needed for the FTDIChip-ID
3658     Function is only used internally
3659     \internal
3660 */
3661 static unsigned char ftdi_read_chipid_shift(unsigned char value)
3662 {
3663     return ((value & 1) << 1) |
3664            ((value & 2) << 5) |
3665            ((value & 4) >> 2) |
3666            ((value & 8) << 4) |
3667            ((value & 16) >> 1) |
3668            ((value & 32) >> 1) |
3669            ((value & 64) >> 4) |
3670            ((value & 128) >> 2);
3671 }
3672
3673 /**
3674     Read the FTDIChip-ID from R-type devices
3675
3676     \param ftdi pointer to ftdi_context
3677     \param chipid Pointer to store FTDIChip-ID
3678
3679     \retval  0: all fine
3680     \retval -1: read failed
3681     \retval -2: USB device unavailable
3682 */
3683 int ftdi_read_chipid(struct ftdi_context *ftdi, unsigned int *chipid)
3684 {
3685     unsigned int a = 0, b = 0;
3686
3687     if (ftdi == NULL || ftdi->usb_dev == NULL)
3688         ftdi_error_return(-2, "USB device unavailable");
3689
3690     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)
3691     {
3692         a = a << 8 | a >> 8;
3693         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)
3694         {
3695             b = b << 8 | b >> 8;
3696             a = (a << 16) | (b & 0xFFFF);
3697             a = ftdi_read_chipid_shift(a) | ftdi_read_chipid_shift(a>>8)<<8
3698                 | ftdi_read_chipid_shift(a>>16)<<16 | ftdi_read_chipid_shift(a>>24)<<24;
3699             *chipid = a ^ 0xa5f0f7d1;
3700             return 0;
3701         }
3702     }
3703
3704     ftdi_error_return(-1, "read of FTDIChip-ID failed");
3705 }
3706
3707 /**
3708     Write eeprom location
3709
3710     \param ftdi pointer to ftdi_context
3711     \param eeprom_addr Address of eeprom location to be written
3712     \param eeprom_val Value to be written
3713
3714     \retval  0: all fine
3715     \retval -1: write failed
3716     \retval -2: USB device unavailable
3717     \retval -3: Invalid access to checksum protected area below 0x80
3718     \retval -4: Device can't access unprotected area
3719     \retval -5: Reading chip type failed
3720 */
3721 int ftdi_write_eeprom_location(struct ftdi_context *ftdi, int eeprom_addr,
3722                                unsigned short eeprom_val)
3723 {
3724     int chip_type_location;
3725     unsigned short chip_type;
3726
3727     if (ftdi == NULL || ftdi->usb_dev == NULL)
3728         ftdi_error_return(-2, "USB device unavailable");
3729
3730     if (eeprom_addr <0x80)
3731         ftdi_error_return(-2, "Invalid access to checksum protected area  below 0x80");
3732
3733
3734     switch (ftdi->type)
3735     {
3736         case TYPE_BM:
3737         case  TYPE_2232C:
3738             chip_type_location = 0x14;
3739             break;
3740         case TYPE_2232H:
3741         case TYPE_4232H:
3742             chip_type_location = 0x18;
3743             break;
3744         case TYPE_232H:
3745             chip_type_location = 0x1e;
3746             break;
3747         default:
3748             ftdi_error_return(-4, "Device can't access unprotected area");
3749     }
3750
3751     if (ftdi_read_eeprom_location( ftdi, chip_type_location>>1, &chip_type))
3752         ftdi_error_return(-5, "Reading failed failed");
3753     fprintf(stderr," loc 0x%04x val 0x%04x\n", chip_type_location,chip_type);
3754     if ((chip_type & 0xff) != 0x66)
3755     {
3756         ftdi_error_return(-6, "EEPROM is not of 93x66");
3757     }
3758
3759     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
3760                                 SIO_WRITE_EEPROM_REQUEST, eeprom_val, eeprom_addr,
3761                                 NULL, 0, ftdi->usb_write_timeout) != 0)
3762         ftdi_error_return(-1, "unable to write eeprom");
3763
3764     return 0;
3765 }
3766
3767 /**
3768     Write eeprom
3769
3770     \param ftdi pointer to ftdi_context
3771
3772     \retval  0: all fine
3773     \retval -1: read failed
3774     \retval -2: USB device unavailable
3775     \retval -3: EEPROM not initialized for the connected device;
3776 */
3777 int ftdi_write_eeprom(struct ftdi_context *ftdi)
3778 {
3779     unsigned short usb_val, status;
3780     int i, ret;
3781     unsigned char *eeprom;
3782
3783     if (ftdi == NULL || ftdi->usb_dev == NULL)
3784         ftdi_error_return(-2, "USB device unavailable");
3785
3786     if(ftdi->eeprom->initialized_for_connected_device == 0)
3787         ftdi_error_return(-3, "EEPROM not initialized for the connected device");
3788
3789     eeprom = ftdi->eeprom->buf;
3790
3791     /* These commands were traced while running MProg */
3792     if ((ret = ftdi_usb_reset(ftdi)) != 0)
3793         return ret;
3794     if ((ret = ftdi_poll_modem_status(ftdi, &status)) != 0)
3795         return ret;
3796     if ((ret = ftdi_set_latency_timer(ftdi, 0x77)) != 0)
3797         return ret;
3798
3799     for (i = 0; i < ftdi->eeprom->size/2; i++)
3800     {
3801         usb_val = eeprom[i*2];
3802         usb_val += eeprom[(i*2)+1] << 8;
3803         if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
3804                                     SIO_WRITE_EEPROM_REQUEST, usb_val, i,
3805                                     NULL, 0, ftdi->usb_write_timeout) < 0)
3806             ftdi_error_return(-1, "unable to write eeprom");
3807     }
3808
3809     return 0;
3810 }
3811
3812 /**
3813     Erase eeprom
3814
3815     This is not supported on FT232R/FT245R according to the MProg manual from FTDI.
3816
3817     \param ftdi pointer to ftdi_context
3818
3819     \retval  0: all fine
3820     \retval -1: erase failed
3821     \retval -2: USB device unavailable
3822     \retval -3: Writing magic failed
3823     \retval -4: Read EEPROM failed
3824     \retval -5: Unexpected EEPROM value
3825 */
3826 #define MAGIC 0x55aa
3827 int ftdi_erase_eeprom(struct ftdi_context *ftdi)
3828 {
3829     unsigned short eeprom_value;
3830     if (ftdi == NULL || ftdi->usb_dev == NULL)
3831         ftdi_error_return(-2, "USB device unavailable");
3832
3833     if (ftdi->type == TYPE_R)
3834     {
3835         ftdi->eeprom->chip = 0;
3836         return 0;
3837     }
3838
3839     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_ERASE_EEPROM_REQUEST,
3840                                 0, 0, NULL, 0, ftdi->usb_write_timeout) < 0)
3841         ftdi_error_return(-1, "unable to erase eeprom");
3842
3843
3844     /* detect chip type by writing 0x55AA as magic at word position 0xc0
3845        Chip is 93x46 if magic is read at word position 0x00, as wraparound happens around 0x40
3846        Chip is 93x56 if magic is read at word position 0x40, as wraparound happens around 0x80
3847        Chip is 93x66 if magic is only read at word position 0xc0*/
3848     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
3849                                 SIO_WRITE_EEPROM_REQUEST, MAGIC, 0xc0,
3850                                 NULL, 0, ftdi->usb_write_timeout) != 0)
3851         ftdi_error_return(-3, "Writing magic failed");
3852     if (ftdi_read_eeprom_location( ftdi, 0x00, &eeprom_value))
3853         ftdi_error_return(-4, "Reading failed failed");
3854     if (eeprom_value == MAGIC)
3855     {
3856         ftdi->eeprom->chip = 0x46;
3857     }
3858     else
3859     {
3860         if (ftdi_read_eeprom_location( ftdi, 0x40, &eeprom_value))
3861             ftdi_error_return(-4, "Reading failed failed");
3862         if (eeprom_value == MAGIC)
3863             ftdi->eeprom->chip = 0x56;
3864         else
3865         {
3866             if (ftdi_read_eeprom_location( ftdi, 0xc0, &eeprom_value))
3867                 ftdi_error_return(-4, "Reading failed failed");
3868             if (eeprom_value == MAGIC)
3869                 ftdi->eeprom->chip = 0x66;
3870             else
3871             {
3872                 ftdi->eeprom->chip = -1;
3873             }
3874         }
3875     }
3876     if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_ERASE_EEPROM_REQUEST,
3877                                 0, 0, NULL, 0, ftdi->usb_write_timeout) < 0)
3878         ftdi_error_return(-1, "unable to erase eeprom");
3879     return 0;
3880 }
3881
3882 /**
3883     Get string representation for last error code
3884
3885     \param ftdi pointer to ftdi_context
3886
3887     \retval Pointer to error string
3888 */
3889 char *ftdi_get_error_string (struct ftdi_context *ftdi)
3890 {
3891     if (ftdi == NULL)
3892         return "";
3893
3894     return ftdi->error_str;
3895 }
3896
3897 /* @} end of doxygen libftdi group */