avoid PATH_MAX/string copies usage
[libftdi] / src / ftdi.c
1 /***************************************************************************
2                           ftdi.c  -  description
3                              -------------------
4     begin                : Fri Apr 4 2003
5     copyright            : (C) 2003-2008 by Intra2net AG
6     email                : opensource@intra2net.com
7  ***************************************************************************/
8
9 /***************************************************************************
10  *                                                                         *
11  *   This program is free software; you can redistribute it and/or modify  *
12  *   it under the terms of the GNU Lesser General Public License           *
13  *   version 2.1 as published by the Free Software Foundation;             *
14  *                                                                         *
15  ***************************************************************************/
16
17 /**
18     \mainpage libftdi API documentation
19
20     Library to talk to FTDI chips. You find the latest versions of libftdi at
21     http://www.intra2net.com/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 <usb.h>
32 #include <string.h>
33 #include <errno.h>
34 #include <stdio.h>
35
36 #include "ftdi.h"
37
38 /* stuff needed for async write */
39 #ifdef LIBFTDI_LINUX_ASYNC_MODE
40 #include <sys/ioctl.h>
41 #include <sys/time.h>
42 #include <sys/select.h>
43 #include <sys/types.h>
44 #include <unistd.h>
45 #include <linux/usbdevice_fs.h>
46 #endif
47
48 #define ftdi_error_return(code, str) do {  \
49         ftdi->error_str = str;             \
50         return code;                       \
51    } while(0);
52
53
54 /**
55     Internal function to close usb device pointer.
56     Sets ftdi->usb_dev to NULL.
57     \internal
58
59     \param ftdi pointer to ftdi_context
60
61     \retval  zero if all is fine, otherwise error code from usb_close()
62 */
63 static int ftdi_usb_close_internal (struct ftdi_context *ftdi)
64 {
65     int ret = 0;
66
67     if (ftdi->usb_dev)
68     {
69        ret = usb_close (ftdi->usb_dev);
70        ftdi->usb_dev = NULL;
71     }
72
73     return ret;
74 }
75
76 /**
77     Initializes a ftdi_context.
78
79     \param ftdi pointer to ftdi_context
80
81     \retval  0: all fine
82     \retval -1: couldn't allocate read buffer
83
84     \remark This should be called before all functions
85 */
86 int ftdi_init(struct ftdi_context *ftdi)
87 {
88     unsigned int i;
89
90     ftdi->usb_dev = NULL;
91     ftdi->usb_read_timeout = 5000;
92     ftdi->usb_write_timeout = 5000;
93
94     ftdi->type = TYPE_BM;    /* chip type */
95     ftdi->baudrate = -1;
96     ftdi->bitbang_enabled = 0;  /* 0: normal mode 1: any of the bitbang modes enabled */
97
98     ftdi->readbuffer = NULL;
99     ftdi->readbuffer_offset = 0;
100     ftdi->readbuffer_remaining = 0;
101     ftdi->writebuffer_chunksize = 4096;
102     ftdi->max_packet_size = 0;
103
104     ftdi->interface = 0;
105     ftdi->index = 0;
106     ftdi->in_ep = 0x02;
107     ftdi->out_ep = 0x81;
108     ftdi->bitbang_mode = 1; /* when bitbang is enabled this holds the number of the mode  */
109
110     ftdi->error_str = NULL;
111
112 #ifdef LIBFTDI_LINUX_ASYNC_MODE
113     ftdi->async_usb_buffer_size=10;
114     if ((ftdi->async_usb_buffer=malloc(sizeof(struct usbdevfs_urb)*ftdi->async_usb_buffer_size)) == NULL)
115         ftdi_error_return(-1, "out of memory for async usb buffer");
116
117     /* initialize async usb buffer with unused-marker */
118     for (i=0; i < ftdi->async_usb_buffer_size; i++)
119         ((struct usbdevfs_urb*)ftdi->async_usb_buffer)[i].usercontext = FTDI_URB_USERCONTEXT_COOKIE;
120 #else
121     ftdi->async_usb_buffer_size=0;
122     ftdi->async_usb_buffer = NULL;
123 #endif
124
125     ftdi->eeprom_size = FTDI_DEFAULT_EEPROM_SIZE;
126
127     /* All fine. Now allocate the readbuffer */
128     return ftdi_read_data_set_chunksize(ftdi, 4096);
129 }
130
131 /**
132     Allocate and initialize a new ftdi_context
133
134     \return a pointer to a new ftdi_context, or NULL on failure
135 */
136 struct ftdi_context *ftdi_new(void)
137 {
138     struct ftdi_context * ftdi = (struct ftdi_context *)malloc(sizeof(struct ftdi_context));
139
140     if (ftdi == NULL)
141     {
142         return NULL;
143     }
144
145     if (ftdi_init(ftdi) != 0)
146     {
147         free(ftdi);
148         return NULL;
149     }
150
151     return ftdi;
152 }
153
154 /**
155     Open selected channels on a chip, otherwise use first channel.
156
157     \param ftdi pointer to ftdi_context
158     \param interface Interface to use for FT2232C/2232H/4232H chips.
159
160     \retval  0: all fine
161     \retval -1: unknown interface
162 */
163 int ftdi_set_interface(struct ftdi_context *ftdi, enum ftdi_interface interface)
164 {
165     switch (interface)
166     {
167         case INTERFACE_ANY:
168         case INTERFACE_A:
169             /* ftdi_usb_open_desc cares to set the right index, depending on the found chip */
170             break;
171         case INTERFACE_B:
172             ftdi->interface = 1;
173             ftdi->index     = INTERFACE_B;
174             ftdi->in_ep     = 0x04;
175             ftdi->out_ep    = 0x83;
176             break;
177         case INTERFACE_C:
178             ftdi->interface = 2;
179             ftdi->index     = INTERFACE_C;
180             ftdi->in_ep     = 0x06;
181             ftdi->out_ep    = 0x85;
182             break;
183         case INTERFACE_D:
184             ftdi->interface = 3;
185             ftdi->index     = INTERFACE_D;
186             ftdi->in_ep     = 0x08;
187             ftdi->out_ep    = 0x87;
188             break;
189         default:
190             ftdi_error_return(-1, "Unknown interface");
191     }
192     return 0;
193 }
194
195 /**
196     Deinitializes a ftdi_context.
197
198     \param ftdi pointer to ftdi_context
199 */
200 void ftdi_deinit(struct ftdi_context *ftdi)
201 {
202     ftdi_usb_close_internal (ftdi);
203
204     if (ftdi->async_usb_buffer != NULL)
205     {
206         free(ftdi->async_usb_buffer);
207         ftdi->async_usb_buffer = NULL;
208     }
209
210     if (ftdi->readbuffer != NULL)
211     {
212         free(ftdi->readbuffer);
213         ftdi->readbuffer = NULL;
214     }
215 }
216
217 /**
218     Deinitialize and free an ftdi_context.
219
220     \param ftdi pointer to ftdi_context
221 */
222 void ftdi_free(struct ftdi_context *ftdi)
223 {
224     ftdi_deinit(ftdi);
225     free(ftdi);
226 }
227
228 /**
229     Use an already open libusb device.
230
231     \param ftdi pointer to ftdi_context
232     \param usb libusb usb_dev_handle to use
233 */
234 void ftdi_set_usbdev (struct ftdi_context *ftdi, usb_dev_handle *usb)
235 {
236     ftdi->usb_dev = usb;
237 }
238
239
240 /**
241     Finds all ftdi devices on the usb bus. Creates a new ftdi_device_list which
242     needs to be deallocated by ftdi_list_free() after use.
243
244     \param ftdi pointer to ftdi_context
245     \param devlist Pointer where to store list of found devices
246     \param vendor Vendor ID to search for
247     \param product Product ID to search for
248
249     \retval >0: number of devices found
250     \retval -1: usb_find_busses() failed
251     \retval -2: usb_find_devices() failed
252     \retval -3: out of memory
253 */
254 int ftdi_usb_find_all(struct ftdi_context *ftdi, struct ftdi_device_list **devlist, int vendor, int product)
255 {
256     struct ftdi_device_list **curdev;
257     struct usb_bus *bus;
258     struct usb_device *dev;
259     int count = 0;
260
261     usb_init();
262     if (usb_find_busses() < 0)
263         ftdi_error_return(-1, "usb_find_busses() failed");
264     if (usb_find_devices() < 0)
265         ftdi_error_return(-2, "usb_find_devices() failed");
266
267     curdev = devlist;
268     *curdev = NULL;
269     for (bus = usb_get_busses(); bus; bus = bus->next)
270     {
271         for (dev = bus->devices; dev; dev = dev->next)
272         {
273             if (dev->descriptor.idVendor == vendor
274                     && dev->descriptor.idProduct == product)
275             {
276                 *curdev = (struct ftdi_device_list*)malloc(sizeof(struct ftdi_device_list));
277                 if (!*curdev)
278                     ftdi_error_return(-3, "out of memory");
279
280                 (*curdev)->next = NULL;
281                 (*curdev)->dev = dev;
282
283                 curdev = &(*curdev)->next;
284                 count++;
285             }
286         }
287     }
288
289     return count;
290 }
291
292 /**
293     Frees a usb device list.
294
295     \param devlist USB device list created by ftdi_usb_find_all()
296 */
297 void ftdi_list_free(struct ftdi_device_list **devlist)
298 {
299     struct ftdi_device_list *curdev, *next;
300
301     for (curdev = *devlist; curdev != NULL;)
302     {
303         next = curdev->next;
304         free(curdev);
305         curdev = next;
306     }
307
308     *devlist = NULL;
309 }
310
311 /**
312     Frees a usb device list.
313
314     \param devlist USB device list created by ftdi_usb_find_all()
315 */
316 void ftdi_list_free2(struct ftdi_device_list *devlist)
317 {
318     ftdi_list_free(&devlist);
319 }
320
321 /**
322     Return device ID strings from the usb device.
323
324     The parameters manufacturer, description and serial may be NULL
325     or pointer to buffers to store the fetched strings.
326
327     \note Use this function only in combination with ftdi_usb_find_all()
328           as it closes the internal "usb_dev" after use.
329
330     \param ftdi pointer to ftdi_context
331     \param dev libusb usb_dev to use
332     \param manufacturer Store manufacturer string here if not NULL
333     \param mnf_len Buffer size of manufacturer string
334     \param description Store product description string here if not NULL
335     \param desc_len Buffer size of product description string
336     \param serial Store serial string here if not NULL
337     \param serial_len Buffer size of serial string
338
339     \retval   0: all fine
340     \retval  -1: wrong arguments
341     \retval  -4: unable to open device
342     \retval  -7: get product manufacturer failed
343     \retval  -8: get product description failed
344     \retval  -9: get serial number failed
345     \retval -10: unable to close device
346 */
347 int ftdi_usb_get_strings(struct ftdi_context * ftdi, struct usb_device * dev,
348                          char * manufacturer, int mnf_len, char * description, int desc_len, char * serial, int serial_len)
349 {
350     if ((ftdi==NULL) || (dev==NULL))
351         return -1;
352
353     if (!(ftdi->usb_dev = usb_open(dev)))
354         ftdi_error_return(-4, usb_strerror());
355
356     if (manufacturer != NULL)
357     {
358         if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iManufacturer, manufacturer, mnf_len) <= 0)
359         {
360             ftdi_usb_close_internal (ftdi);
361             ftdi_error_return(-7, usb_strerror());
362         }
363     }
364
365     if (description != NULL)
366     {
367         if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iProduct, description, desc_len) <= 0)
368         {
369             ftdi_usb_close_internal (ftdi);
370             ftdi_error_return(-8, usb_strerror());
371         }
372     }
373
374     if (serial != NULL)
375     {
376         if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iSerialNumber, serial, serial_len) <= 0)
377         {
378             ftdi_usb_close_internal (ftdi);
379             ftdi_error_return(-9, usb_strerror());
380         }
381     }
382
383     if (ftdi_usb_close_internal (ftdi) != 0)
384         ftdi_error_return(-10, usb_strerror());
385
386     return 0;
387 }
388
389 /**
390  * Internal function to determine the maximum packet size.
391  * \param ftdi pointer to ftdi_context
392  * \param dev libusb usb_dev to use
393  * \retval Maximum packet size for this device
394  */
395 static unsigned int _ftdi_determine_max_packet_size(struct ftdi_context *ftdi, struct usb_device *dev)
396 {
397     unsigned int packet_size;
398
399     // Determine maximum packet size. Init with default value.
400     // New hi-speed devices from FTDI use a packet size of 512 bytes
401     // but could be connected to a normal speed USB hub -> 64 bytes packet size.
402     if (ftdi->type == TYPE_2232H || ftdi->type == TYPE_4232H)
403         packet_size = 512;
404     else
405         packet_size = 64;
406
407     if (dev->descriptor.bNumConfigurations > 0 && dev->config)
408     {
409         struct usb_config_descriptor config = dev->config[0];
410
411         if (ftdi->interface < config.bNumInterfaces)
412         {
413             struct usb_interface interface = config.interface[ftdi->interface];
414             if (interface.num_altsetting > 0)
415             {
416                 struct usb_interface_descriptor descriptor = interface.altsetting[0];
417                 if (descriptor.bNumEndpoints > 0)
418                 {
419                     packet_size = descriptor.endpoint[0].wMaxPacketSize;
420                 }
421             }
422         }
423     }
424
425     return packet_size;
426 }
427
428 /**
429     Opens a ftdi device given by an usb_device.
430
431     \param ftdi pointer to ftdi_context
432     \param dev libusb usb_dev to use
433
434     \retval  0: all fine
435     \retval -3: unable to config device
436     \retval -4: unable to open device
437     \retval -5: unable to claim device
438     \retval -6: reset failed
439     \retval -7: set baudrate failed
440 */
441 int ftdi_usb_open_dev(struct ftdi_context *ftdi, struct usb_device *dev)
442 {
443     int detach_errno = 0;
444     int config_val = 1;
445     if (!(ftdi->usb_dev = usb_open(dev)))
446         ftdi_error_return(-4, "usb_open() failed");
447
448 #ifdef LIBUSB_HAS_GET_DRIVER_NP
449     // Try to detach ftdi_sio kernel module.
450     // Returns ENODATA if driver is not loaded.
451     //
452     // The return code is kept in a separate variable and only parsed
453     // if usb_set_configuration() or usb_claim_interface() fails as the
454     // detach operation might be denied and everything still works fine.
455     // Likely scenario is a static ftdi_sio kernel module.
456     if (usb_detach_kernel_driver_np(ftdi->usb_dev, ftdi->interface) != 0 && errno != ENODATA)
457         detach_errno = errno;
458 #endif
459
460 #ifdef __WIN32__
461     // set configuration (needed especially for windows)
462     // tolerate EBUSY: one device with one configuration, but two interfaces
463     //    and libftdi sessions to both interfaces (e.g. FT2232)
464
465     if (dev->descriptor.bNumConfigurations > 0)
466     {
467         // libusb-win32 on Windows 64 can return a null pointer for a valid device
468         if (dev->config)
469             config_val = dev->config[0].bConfigurationValue;
470
471         if (usb_set_configuration(ftdi->usb_dev, config_val) &&
472             errno != EBUSY)
473         {
474             ftdi_usb_close_internal (ftdi);
475             if (detach_errno == EPERM)
476             {
477                 ftdi_error_return(-8, "inappropriate permissions on device!");
478             }
479             else
480             {
481                 ftdi_error_return(-3, "unable to set usb configuration. Make sure ftdi_sio is unloaded!");
482             }
483         }
484     }
485 #endif
486
487     if (usb_claim_interface(ftdi->usb_dev, ftdi->interface) != 0)
488     {
489         ftdi_usb_close_internal (ftdi);
490         if (detach_errno == EPERM)
491         {
492             ftdi_error_return(-8, "inappropriate permissions on device!");
493         }
494         else
495         {
496             ftdi_error_return(-5, "unable to claim usb device. Make sure ftdi_sio is unloaded!");
497         }
498     }
499
500     if (ftdi_usb_reset (ftdi) != 0)
501     {
502         ftdi_usb_close_internal (ftdi);
503         ftdi_error_return(-6, "ftdi_usb_reset failed");
504     }
505
506     // Try to guess chip type
507     // Bug in the BM type chips: bcdDevice is 0x200 for serial == 0
508     if (dev->descriptor.bcdDevice == 0x400 || (dev->descriptor.bcdDevice == 0x200
509             && dev->descriptor.iSerialNumber == 0))
510         ftdi->type = TYPE_BM;
511     else if (dev->descriptor.bcdDevice == 0x200)
512         ftdi->type = TYPE_AM;
513     else if (dev->descriptor.bcdDevice == 0x500)
514         ftdi->type = TYPE_2232C;
515     else if (dev->descriptor.bcdDevice == 0x600)
516         ftdi->type = TYPE_R;
517     else if (dev->descriptor.bcdDevice == 0x700)
518         ftdi->type = TYPE_2232H;
519     else if (dev->descriptor.bcdDevice == 0x800)
520         ftdi->type = TYPE_4232H;
521
522     // Set default interface on dual/quad type chips
523     switch(ftdi->type)
524     {
525         case TYPE_2232C:
526         case TYPE_2232H:
527         case TYPE_4232H:
528             if (!ftdi->index)
529                 ftdi->index = INTERFACE_A;
530             break;
531         default:
532             break;
533     }
534
535     // Determine maximum packet size
536     ftdi->max_packet_size = _ftdi_determine_max_packet_size(ftdi, dev);
537
538     if (ftdi_set_baudrate (ftdi, 9600) != 0)
539     {
540         ftdi_usb_close_internal (ftdi);
541         ftdi_error_return(-7, "set baudrate failed");
542     }
543
544     ftdi_error_return(0, "all fine");
545 }
546
547 /**
548     Opens the first device with a given vendor and product ids.
549
550     \param ftdi pointer to ftdi_context
551     \param vendor Vendor ID
552     \param product Product ID
553
554     \retval same as ftdi_usb_open_desc()
555 */
556 int ftdi_usb_open(struct ftdi_context *ftdi, int vendor, int product)
557 {
558     return ftdi_usb_open_desc(ftdi, vendor, product, NULL, NULL);
559 }
560
561 /**
562     Opens the first device with a given, vendor id, product id,
563     description and serial.
564
565     \param ftdi pointer to ftdi_context
566     \param vendor Vendor ID
567     \param product Product ID
568     \param description Description to search for. Use NULL if not needed.
569     \param serial Serial to search for. Use NULL if not needed.
570
571     \retval  0: all fine
572     \retval -1: usb_find_busses() failed
573     \retval -2: usb_find_devices() failed
574     \retval -3: usb device not found
575     \retval -4: unable to open device
576     \retval -5: unable to claim device
577     \retval -6: reset failed
578     \retval -7: set baudrate failed
579     \retval -8: get product description failed
580     \retval -9: get serial number failed
581     \retval -10: unable to close device
582 */
583 int ftdi_usb_open_desc(struct ftdi_context *ftdi, int vendor, int product,
584                        const char* description, const char* serial)
585 {
586     return ftdi_usb_open_desc_index(ftdi,vendor,product,description,serial,0);
587 }
588
589 /**
590     Opens the index-th device with a given, vendor id, product id,
591     description and serial.
592
593     \param ftdi pointer to ftdi_context
594     \param vendor Vendor ID
595     \param product Product ID
596     \param description Description to search for. Use NULL if not needed.
597     \param serial Serial to search for. Use NULL if not needed.
598     \param index Number of matching device to open if there are more than one, starts with 0.
599
600     \retval  0: all fine
601     \retval -1: usb_find_busses() failed
602     \retval -2: usb_find_devices() failed
603     \retval -3: usb device not found
604     \retval -4: unable to open device
605     \retval -5: unable to claim device
606     \retval -6: reset failed
607     \retval -7: set baudrate failed
608     \retval -8: get product description failed
609     \retval -9: get serial number failed
610     \retval -10: unable to close device
611 */
612 int ftdi_usb_open_desc_index(struct ftdi_context *ftdi, int vendor, int product,
613                        const char* description, const char* serial, unsigned int index)
614 {
615     struct usb_bus *bus;
616     struct usb_device *dev;
617     char string[256];
618
619     usb_init();
620
621     if (usb_find_busses() < 0)
622         ftdi_error_return(-1, "usb_find_busses() failed");
623     if (usb_find_devices() < 0)
624         ftdi_error_return(-2, "usb_find_devices() failed");
625
626     for (bus = usb_get_busses(); bus; bus = bus->next)
627     {
628         for (dev = bus->devices; dev; dev = dev->next)
629         {
630             if (dev->descriptor.idVendor == vendor
631                     && dev->descriptor.idProduct == product)
632             {
633                 if (!(ftdi->usb_dev = usb_open(dev)))
634                     ftdi_error_return(-4, "usb_open() failed");
635
636                 if (description != NULL)
637                 {
638                     if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iProduct, string, sizeof(string)) <= 0)
639                     {
640                         ftdi_usb_close_internal (ftdi);
641                         ftdi_error_return(-8, "unable to fetch product description");
642                     }
643                     if (strncmp(string, description, sizeof(string)) != 0)
644                     {
645                         if (ftdi_usb_close_internal (ftdi) != 0)
646                             ftdi_error_return(-10, "unable to close device");
647                         continue;
648                     }
649                 }
650                 if (serial != NULL)
651                 {
652                     if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iSerialNumber, string, sizeof(string)) <= 0)
653                     {
654                         ftdi_usb_close_internal (ftdi);
655                         ftdi_error_return(-9, "unable to fetch serial number");
656                     }
657                     if (strncmp(string, serial, sizeof(string)) != 0)
658                     {
659                         if (ftdi_usb_close_internal (ftdi) != 0)
660                             ftdi_error_return(-10, "unable to close device");
661                         continue;
662                     }
663                 }
664
665                 if (ftdi_usb_close_internal (ftdi) != 0)
666                     ftdi_error_return(-10, "unable to close device");
667
668                 if (index > 0)
669                 {
670                     index--;
671                     continue;
672                 }
673
674                 return ftdi_usb_open_dev(ftdi, dev);
675             }
676         }
677     }
678
679     // device not found
680     ftdi_error_return(-3, "device not found");
681 }
682
683 /**
684     Opens the ftdi-device described by a description-string.
685     Intended to be used for parsing a device-description given as commandline argument.
686
687     \param ftdi pointer to ftdi_context
688     \param description NULL-terminated description-string, using this format:
689         \li <tt>d:\<devicenode></tt> path of bus and device-node (e.g. "003/001") within usb device tree (usually at /proc/bus/usb/)
690         \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")
691         \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
692         \li <tt>s:\<vendor>:\<product>:\<serial></tt> first device with given vendor id, product id and serial string
693
694     \note The description format may be extended in later versions.
695
696     \retval  0: all fine
697     \retval -1: usb_find_busses() failed
698     \retval -2: usb_find_devices() failed
699     \retval -3: usb device not found
700     \retval -4: unable to open device
701     \retval -5: unable to claim device
702     \retval -6: reset failed
703     \retval -7: set baudrate failed
704     \retval -8: get product description failed
705     \retval -9: get serial number failed
706     \retval -10: unable to close device
707     \retval -11: illegal description format
708 */
709 int ftdi_usb_open_string(struct ftdi_context *ftdi, const char* description)
710 {
711     if (description[0] == 0 || description[1] != ':')
712         ftdi_error_return(-11, "illegal description format");
713
714     if (description[0] == 'd')
715     {
716         struct usb_bus *bus;
717         struct usb_device *dev;
718
719         usb_init();
720
721         if (usb_find_busses() < 0)
722             ftdi_error_return(-1, "usb_find_busses() failed");
723         if (usb_find_devices() < 0)
724             ftdi_error_return(-2, "usb_find_devices() failed");
725
726         for (bus = usb_get_busses(); bus; bus = bus->next)
727         {
728             for (dev = bus->devices; dev; dev = dev->next)
729             {
730                 /* XXX: This doesn't handle symlinks/odd paths/etc... */
731                 const char *desc = description + 2;
732                 size_t len = strlen(bus->dirname);
733                 if (strncmp(desc, bus->dirname, len))
734                     continue;
735                 desc += len;
736                 if (desc[0] != '/')
737                     continue;
738                 ++desc;
739                 if (strcmp(desc, dev->filename))
740                     continue;
741                 return ftdi_usb_open_dev(ftdi, dev);
742             }
743         }
744
745         // device not found
746         ftdi_error_return(-3, "device not found");
747     }
748     else if (description[0] == 'i' || description[0] == 's')
749     {
750         unsigned int vendor;
751         unsigned int product;
752         unsigned int index=0;
753         const char *serial=NULL;
754         const char *startp, *endp;
755
756         errno=0;
757         startp=description+2;
758         vendor=strtoul((char*)startp,(char**)&endp,0);
759         if (*endp != ':' || endp == startp || errno != 0)
760             ftdi_error_return(-11, "illegal description format");
761
762         startp=endp+1;
763         product=strtoul((char*)startp,(char**)&endp,0);
764         if (endp == startp || errno != 0)
765             ftdi_error_return(-11, "illegal description format");
766
767         if (description[0] == 'i' && *endp != 0)
768         {
769             /* optional index field in i-mode */
770             if (*endp != ':')
771                 ftdi_error_return(-11, "illegal description format");
772
773             startp=endp+1;
774             index=strtoul((char*)startp,(char**)&endp,0);
775             if (*endp != 0 || endp == startp || errno != 0)
776                 ftdi_error_return(-11, "illegal description format");
777         }
778         if (description[0] == 's')
779         {
780             if (*endp != ':')
781                 ftdi_error_return(-11, "illegal description format");
782
783             /* rest of the description is the serial */
784             serial=endp+1;
785         }
786
787         return ftdi_usb_open_desc_index(ftdi, vendor, product, NULL, serial, index);
788     }
789     else
790     {
791         ftdi_error_return(-11, "illegal description format");
792     }
793 }
794
795 /**
796     Resets the ftdi device.
797
798     \param ftdi pointer to ftdi_context
799
800     \retval  0: all fine
801     \retval -1: FTDI reset failed
802 */
803 int ftdi_usb_reset(struct ftdi_context *ftdi)
804 {
805     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
806                         SIO_RESET_REQUEST, SIO_RESET_SIO,
807                         ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
808         ftdi_error_return(-1,"FTDI reset failed");
809
810     // Invalidate data in the readbuffer
811     ftdi->readbuffer_offset = 0;
812     ftdi->readbuffer_remaining = 0;
813
814     return 0;
815 }
816
817 /**
818     Clears the read buffer on the chip and the internal read buffer.
819
820     \param ftdi pointer to ftdi_context
821
822     \retval  0: all fine
823     \retval -1: read buffer purge failed
824 */
825 int ftdi_usb_purge_rx_buffer(struct ftdi_context *ftdi)
826 {
827     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
828                         SIO_RESET_REQUEST, SIO_RESET_PURGE_RX,
829                         ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
830         ftdi_error_return(-1, "FTDI purge of RX buffer failed");
831
832     // Invalidate data in the readbuffer
833     ftdi->readbuffer_offset = 0;
834     ftdi->readbuffer_remaining = 0;
835
836     return 0;
837 }
838
839 /**
840     Clears the write buffer on the chip.
841
842     \param ftdi pointer to ftdi_context
843
844     \retval  0: all fine
845     \retval -1: write buffer purge failed
846 */
847 int ftdi_usb_purge_tx_buffer(struct ftdi_context *ftdi)
848 {
849     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
850                         SIO_RESET_REQUEST, SIO_RESET_PURGE_TX,
851                         ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
852         ftdi_error_return(-1, "FTDI purge of TX buffer failed");
853
854     return 0;
855 }
856
857 /**
858     Clears the buffers on the chip and the internal read buffer.
859
860     \param ftdi pointer to ftdi_context
861
862     \retval  0: all fine
863     \retval -1: read buffer purge failed
864     \retval -2: write buffer purge failed
865 */
866 int ftdi_usb_purge_buffers(struct ftdi_context *ftdi)
867 {
868     int result;
869
870     result = ftdi_usb_purge_rx_buffer(ftdi);
871     if (result < 0)
872         return -1;
873
874     result = ftdi_usb_purge_tx_buffer(ftdi);
875     if (result < 0)
876         return -2;
877
878     return 0;
879 }
880
881
882
883 /**
884     Closes the ftdi device. Call ftdi_deinit() if you're cleaning up.
885
886     \param ftdi pointer to ftdi_context
887
888     \retval  0: all fine
889     \retval -1: usb_release failed
890     \retval -2: usb_close failed
891 */
892 int ftdi_usb_close(struct ftdi_context *ftdi)
893 {
894     int rtn = 0;
895
896 #ifdef LIBFTDI_LINUX_ASYNC_MODE
897     /* try to release some kernel resources */
898     ftdi_async_complete(ftdi,1);
899 #endif
900
901     if (ftdi->usb_dev != NULL)
902         if (usb_release_interface(ftdi->usb_dev, ftdi->interface) != 0)
903             rtn = -1;
904
905     if (ftdi_usb_close_internal (ftdi) != 0)
906         rtn = -2;
907
908     return rtn;
909 }
910
911 /**
912     ftdi_convert_baudrate returns nearest supported baud rate to that requested.
913     Function is only used internally
914     \internal
915 */
916 static int ftdi_convert_baudrate(int baudrate, struct ftdi_context *ftdi,
917                                  unsigned short *value, unsigned short *index)
918 {
919     static const char am_adjust_up[8] = {0, 0, 0, 1, 0, 3, 2, 1};
920     static const char am_adjust_dn[8] = {0, 0, 0, 1, 0, 1, 2, 3};
921     static const char frac_code[8] = {0, 3, 2, 4, 1, 5, 6, 7};
922     int divisor, best_divisor, best_baud, best_baud_diff;
923     unsigned long encoded_divisor;
924     int i;
925
926     if (baudrate <= 0)
927     {
928         // Return error
929         return -1;
930     }
931
932     divisor = 24000000 / baudrate;
933
934     if (ftdi->type == TYPE_AM)
935     {
936         // Round down to supported fraction (AM only)
937         divisor -= am_adjust_dn[divisor & 7];
938     }
939
940     // Try this divisor and the one above it (because division rounds down)
941     best_divisor = 0;
942     best_baud = 0;
943     best_baud_diff = 0;
944     for (i = 0; i < 2; i++)
945     {
946         int try_divisor = divisor + i;
947         int baud_estimate;
948         int baud_diff;
949
950         // Round up to supported divisor value
951         if (try_divisor <= 8)
952         {
953             // Round up to minimum supported divisor
954             try_divisor = 8;
955         }
956         else if (ftdi->type != TYPE_AM && try_divisor < 12)
957         {
958             // BM doesn't support divisors 9 through 11 inclusive
959             try_divisor = 12;
960         }
961         else if (divisor < 16)
962         {
963             // AM doesn't support divisors 9 through 15 inclusive
964             try_divisor = 16;
965         }
966         else
967         {
968             if (ftdi->type == TYPE_AM)
969             {
970                 // Round up to supported fraction (AM only)
971                 try_divisor += am_adjust_up[try_divisor & 7];
972                 if (try_divisor > 0x1FFF8)
973                 {
974                     // Round down to maximum supported divisor value (for AM)
975                     try_divisor = 0x1FFF8;
976                 }
977             }
978             else
979             {
980                 if (try_divisor > 0x1FFFF)
981                 {
982                     // Round down to maximum supported divisor value (for BM)
983                     try_divisor = 0x1FFFF;
984                 }
985             }
986         }
987         // Get estimated baud rate (to nearest integer)
988         baud_estimate = (24000000 + (try_divisor / 2)) / try_divisor;
989         // Get absolute difference from requested baud rate
990         if (baud_estimate < baudrate)
991         {
992             baud_diff = baudrate - baud_estimate;
993         }
994         else
995         {
996             baud_diff = baud_estimate - baudrate;
997         }
998         if (i == 0 || baud_diff < best_baud_diff)
999         {
1000             // Closest to requested baud rate so far
1001             best_divisor = try_divisor;
1002             best_baud = baud_estimate;
1003             best_baud_diff = baud_diff;
1004             if (baud_diff == 0)
1005             {
1006                 // Spot on! No point trying
1007                 break;
1008             }
1009         }
1010     }
1011     // Encode the best divisor value
1012     encoded_divisor = (best_divisor >> 3) | (frac_code[best_divisor & 7] << 14);
1013     // Deal with special cases for encoded value
1014     if (encoded_divisor == 1)
1015     {
1016         encoded_divisor = 0;    // 3000000 baud
1017     }
1018     else if (encoded_divisor == 0x4001)
1019     {
1020         encoded_divisor = 1;    // 2000000 baud (BM only)
1021     }
1022     // Split into "value" and "index" values
1023     *value = (unsigned short)(encoded_divisor & 0xFFFF);
1024     if (ftdi->type == TYPE_2232C || ftdi->type == TYPE_2232H || ftdi->type == TYPE_4232H)
1025     {
1026         *index = (unsigned short)(encoded_divisor >> 8);
1027         *index &= 0xFF00;
1028         *index |= ftdi->index;
1029     }
1030     else
1031         *index = (unsigned short)(encoded_divisor >> 16);
1032
1033     // Return the nearest baud rate
1034     return best_baud;
1035 }
1036
1037 /**
1038     Sets the chip baud rate
1039
1040     \param ftdi pointer to ftdi_context
1041     \param baudrate baud rate to set
1042
1043     \retval  0: all fine
1044     \retval -1: invalid baudrate
1045     \retval -2: setting baudrate failed
1046 */
1047 int ftdi_set_baudrate(struct ftdi_context *ftdi, int baudrate)
1048 {
1049     unsigned short value, index;
1050     int actual_baudrate;
1051
1052     if (ftdi->bitbang_enabled)
1053     {
1054         baudrate = baudrate*4;
1055     }
1056
1057     actual_baudrate = ftdi_convert_baudrate(baudrate, ftdi, &value, &index);
1058     if (actual_baudrate <= 0)
1059         ftdi_error_return (-1, "Silly baudrate <= 0.");
1060
1061     // Check within tolerance (about 5%)
1062     if ((actual_baudrate * 2 < baudrate /* Catch overflows */ )
1063             || ((actual_baudrate < baudrate)
1064                 ? (actual_baudrate * 21 < baudrate * 20)
1065                 : (baudrate * 21 < actual_baudrate * 20)))
1066         ftdi_error_return (-1, "Unsupported baudrate. Note: bitbang baudrates are automatically multiplied by 4");
1067
1068     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1069                         SIO_SET_BAUDRATE_REQUEST, value,
1070                         index, NULL, 0, ftdi->usb_write_timeout) != 0)
1071         ftdi_error_return (-2, "Setting new baudrate failed");
1072
1073     ftdi->baudrate = baudrate;
1074     return 0;
1075 }
1076
1077 /**
1078     Set (RS232) line characteristics.
1079     The break type can only be set via ftdi_set_line_property2()
1080     and defaults to "off".
1081
1082     \param ftdi pointer to ftdi_context
1083     \param bits Number of bits
1084     \param sbit Number of stop bits
1085     \param parity Parity mode
1086
1087     \retval  0: all fine
1088     \retval -1: Setting line property failed
1089 */
1090 int ftdi_set_line_property(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
1091                            enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity)
1092 {
1093     return ftdi_set_line_property2(ftdi, bits, sbit, parity, BREAK_OFF);
1094 }
1095
1096 /**
1097     Set (RS232) line characteristics
1098
1099     \param ftdi pointer to ftdi_context
1100     \param bits Number of bits
1101     \param sbit Number of stop bits
1102     \param parity Parity mode
1103     \param break_type Break type
1104
1105     \retval  0: all fine
1106     \retval -1: Setting line property failed
1107 */
1108 int ftdi_set_line_property2(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
1109                             enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity,
1110                             enum ftdi_break_type break_type)
1111 {
1112     unsigned short value = bits;
1113
1114     switch (parity)
1115     {
1116         case NONE:
1117             value |= (0x00 << 8);
1118             break;
1119         case ODD:
1120             value |= (0x01 << 8);
1121             break;
1122         case EVEN:
1123             value |= (0x02 << 8);
1124             break;
1125         case MARK:
1126             value |= (0x03 << 8);
1127             break;
1128         case SPACE:
1129             value |= (0x04 << 8);
1130             break;
1131     }
1132
1133     switch (sbit)
1134     {
1135         case STOP_BIT_1:
1136             value |= (0x00 << 11);
1137             break;
1138         case STOP_BIT_15:
1139             value |= (0x01 << 11);
1140             break;
1141         case STOP_BIT_2:
1142             value |= (0x02 << 11);
1143             break;
1144     }
1145
1146     switch (break_type)
1147     {
1148         case BREAK_OFF:
1149             value |= (0x00 << 14);
1150             break;
1151         case BREAK_ON:
1152             value |= (0x01 << 14);
1153             break;
1154     }
1155
1156     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1157                         SIO_SET_DATA_REQUEST, value,
1158                         ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
1159         ftdi_error_return (-1, "Setting new line property failed");
1160
1161     return 0;
1162 }
1163
1164 /**
1165     Writes data in chunks (see ftdi_write_data_set_chunksize()) to the chip
1166
1167     \param ftdi pointer to ftdi_context
1168     \param buf Buffer with the data
1169     \param size Size of the buffer
1170
1171     \retval <0: error code from usb_bulk_write()
1172     \retval >0: number of bytes written
1173 */
1174 int ftdi_write_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
1175 {
1176     int ret;
1177     int offset = 0;
1178     int total_written = 0;
1179
1180     while (offset < size)
1181     {
1182         int write_size = ftdi->writebuffer_chunksize;
1183
1184         if (offset+write_size > size)
1185             write_size = size-offset;
1186
1187         ret = usb_bulk_write(ftdi->usb_dev, ftdi->in_ep, buf+offset, write_size, ftdi->usb_write_timeout);
1188         if (ret < 0)
1189             ftdi_error_return(ret, "usb bulk write failed");
1190
1191         total_written += ret;
1192         offset += write_size;
1193     }
1194
1195     return total_written;
1196 }
1197
1198 #ifdef LIBFTDI_LINUX_ASYNC_MODE
1199 #ifdef USB_CLASS_PTP
1200 #error LIBFTDI_LINUX_ASYNC_MODE is not compatible with libusb-compat-0.1!
1201 #endif
1202 /* this is strongly dependent on libusb using the same struct layout. If libusb
1203    changes in some later version this may break horribly (this is for libusb 0.1.12) */
1204 struct usb_dev_handle
1205 {
1206     int fd;
1207     // some other stuff coming here we don't need
1208 };
1209
1210 /**
1211     Check for pending async urbs
1212     \internal
1213 */
1214 static int _usb_get_async_urbs_pending(struct ftdi_context *ftdi)
1215 {
1216     struct usbdevfs_urb *urb;
1217     int pending=0;
1218     unsigned int i;
1219
1220     for (i=0; i < ftdi->async_usb_buffer_size; i++)
1221     {
1222         urb=&((struct usbdevfs_urb *)(ftdi->async_usb_buffer))[i];
1223         if (urb->usercontext != FTDI_URB_USERCONTEXT_COOKIE)
1224             pending++;
1225     }
1226
1227     return pending;
1228 }
1229
1230 /**
1231     Wait until one or more async URBs are completed by the kernel and mark their
1232     positions in the async-buffer as unused
1233
1234     \param ftdi pointer to ftdi_context
1235     \param wait_for_more if != 0 wait for more than one write to complete
1236     \param timeout_msec max milliseconds to wait
1237
1238     \internal
1239 */
1240 static void _usb_async_cleanup(struct ftdi_context *ftdi, int wait_for_more, int timeout_msec)
1241 {
1242     struct timeval tv;
1243     struct usbdevfs_urb *urb=NULL;
1244     int ret;
1245     fd_set writefds;
1246     int keep_going=0;
1247
1248     FD_ZERO(&writefds);
1249     FD_SET(ftdi->usb_dev->fd, &writefds);
1250
1251     /* init timeout only once, select writes time left after call */
1252     tv.tv_sec = timeout_msec / 1000;
1253     tv.tv_usec = (timeout_msec % 1000) * 1000;
1254
1255     do
1256     {
1257         while (_usb_get_async_urbs_pending(ftdi)
1258                 && (ret = ioctl(ftdi->usb_dev->fd, USBDEVFS_REAPURBNDELAY, &urb)) == -1
1259                 && errno == EAGAIN)
1260         {
1261             if (keep_going && !wait_for_more)
1262             {
1263                 /* don't wait if repeating only for keep_going */
1264                 keep_going=0;
1265                 break;
1266             }
1267
1268             /* wait for timeout msec or something written ready */
1269             select(ftdi->usb_dev->fd+1, NULL, &writefds, NULL, &tv);
1270         }
1271
1272         if (ret == 0 && urb != NULL)
1273         {
1274             /* got a free urb, mark it */
1275             urb->usercontext = FTDI_URB_USERCONTEXT_COOKIE;
1276
1277             /* try to get more urbs that are ready now, but don't wait anymore */
1278             urb=NULL;
1279             keep_going=1;
1280         }
1281         else
1282         {
1283             /* no more urbs waiting */
1284             keep_going=0;
1285         }
1286     }
1287     while (keep_going);
1288 }
1289
1290 /**
1291     Wait until one or more async URBs are completed by the kernel and mark their
1292     positions in the async-buffer as unused.
1293
1294     \param ftdi pointer to ftdi_context
1295     \param wait_for_more if != 0 wait for more than one write to complete (until write timeout)
1296 */
1297 void ftdi_async_complete(struct ftdi_context *ftdi, int wait_for_more)
1298 {
1299     _usb_async_cleanup(ftdi,wait_for_more,ftdi->usb_write_timeout);
1300 }
1301
1302 /**
1303     Stupid libusb does not offer async writes nor does it allow
1304     access to its fd - so we need some hacks here.
1305     \internal
1306 */
1307 static int _usb_bulk_write_async(struct ftdi_context *ftdi, int ep, char *bytes, int size)
1308 {
1309     struct usbdevfs_urb *urb;
1310     int bytesdone = 0, requested;
1311     int ret, cleanup_count;
1312     unsigned int i;
1313
1314     do
1315     {
1316         /* find a free urb buffer we can use */
1317         urb=NULL;
1318         for (cleanup_count=0; urb==NULL && cleanup_count <= 1; cleanup_count++)
1319         {
1320             if (i==ftdi->async_usb_buffer_size)
1321             {
1322                 /* wait until some buffers are free */
1323                 _usb_async_cleanup(ftdi,0,ftdi->usb_write_timeout);
1324             }
1325
1326             for (i=0; i < ftdi->async_usb_buffer_size; i++)
1327             {
1328                 urb=&((struct usbdevfs_urb *)(ftdi->async_usb_buffer))[i];
1329                 if (urb->usercontext == FTDI_URB_USERCONTEXT_COOKIE)
1330                     break;  /* found a free urb position */
1331                 urb=NULL;
1332             }
1333         }
1334
1335         /* no free urb position found */
1336         if (urb==NULL)
1337             return -1;
1338
1339         requested = size - bytesdone;
1340         if (requested > 4096)
1341             requested = 4096;
1342
1343         memset(urb,0,sizeof(urb));
1344
1345         urb->type = USBDEVFS_URB_TYPE_BULK;
1346         urb->endpoint = ep;
1347         urb->flags = 0;
1348         urb->buffer = bytes + bytesdone;
1349         urb->buffer_length = requested;
1350         urb->signr = 0;
1351         urb->actual_length = 0;
1352         urb->number_of_packets = 0;
1353         urb->usercontext = 0;
1354
1355         do
1356         {
1357             ret = ioctl(ftdi->usb_dev->fd, USBDEVFS_SUBMITURB, urb);
1358         }
1359         while (ret < 0 && errno == EINTR);
1360         if (ret < 0)
1361             return ret;       /* the caller can read errno to get more info */
1362
1363         bytesdone += requested;
1364     }
1365     while (bytesdone < size);
1366     return bytesdone;
1367 }
1368
1369 /**
1370     Writes data in chunks (see ftdi_write_data_set_chunksize()) to the chip.
1371     Does not wait for completion of the transfer nor does it make sure that
1372     the transfer was successful.
1373
1374     This function could be extended to use signals and callbacks to inform the
1375     caller of completion or error - but this is not done yet, volunteers welcome.
1376
1377     Works around libusb and directly accesses functions only available on Linux.
1378     Only available if compiled with --with-async-mode.
1379
1380     \param ftdi pointer to ftdi_context
1381     \param buf Buffer with the data
1382     \param size Size of the buffer
1383
1384     \retval <0: error code from usb_bulk_write()
1385     \retval >0: number of bytes written
1386 */
1387 int ftdi_write_data_async(struct ftdi_context *ftdi, unsigned char *buf, int size)
1388 {
1389     int ret;
1390     int offset = 0;
1391     int total_written = 0;
1392
1393     while (offset < size)
1394     {
1395         int write_size = ftdi->writebuffer_chunksize;
1396
1397         if (offset+write_size > size)
1398             write_size = size-offset;
1399
1400         ret = _usb_bulk_write_async(ftdi, ftdi->in_ep, buf+offset, write_size);
1401         if (ret < 0)
1402             ftdi_error_return(ret, "usb bulk write async failed");
1403
1404         total_written += ret;
1405         offset += write_size;
1406     }
1407
1408     return total_written;
1409 }
1410 #endif // LIBFTDI_LINUX_ASYNC_MODE
1411
1412 /**
1413     Configure write buffer chunk size.
1414     Default is 4096.
1415
1416     \param ftdi pointer to ftdi_context
1417     \param chunksize Chunk size
1418
1419     \retval 0: all fine
1420 */
1421 int ftdi_write_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
1422 {
1423     ftdi->writebuffer_chunksize = chunksize;
1424     return 0;
1425 }
1426
1427 /**
1428     Get write buffer chunk size.
1429
1430     \param ftdi pointer to ftdi_context
1431     \param chunksize Pointer to store chunk size in
1432
1433     \retval 0: all fine
1434 */
1435 int ftdi_write_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
1436 {
1437     *chunksize = ftdi->writebuffer_chunksize;
1438     return 0;
1439 }
1440
1441 /**
1442     Reads data in chunks (see ftdi_read_data_set_chunksize()) from the chip.
1443
1444     Automatically strips the two modem status bytes transfered during every read.
1445
1446     \param ftdi pointer to ftdi_context
1447     \param buf Buffer to store data in
1448     \param size Size of the buffer
1449
1450     \retval <0: error code from usb_bulk_read()
1451     \retval  0: no data was available
1452     \retval >0: number of bytes read
1453
1454 */
1455 int ftdi_read_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
1456 {
1457     int offset = 0, ret = 1, i, num_of_chunks, chunk_remains;
1458     int packet_size = ftdi->max_packet_size;
1459
1460     // Packet size sanity check (avoid division by zero)
1461     if (packet_size == 0)
1462         ftdi_error_return(-1, "max_packet_size is bogus (zero)");
1463
1464     // everything we want is still in the readbuffer?
1465     if (size <= ftdi->readbuffer_remaining)
1466     {
1467         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);
1468
1469         // Fix offsets
1470         ftdi->readbuffer_remaining -= size;
1471         ftdi->readbuffer_offset += size;
1472
1473         /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */
1474
1475         return size;
1476     }
1477     // something still in the readbuffer, but not enough to satisfy 'size'?
1478     if (ftdi->readbuffer_remaining != 0)
1479     {
1480         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);
1481
1482         // Fix offset
1483         offset += ftdi->readbuffer_remaining;
1484     }
1485     // do the actual USB read
1486     while (offset < size && ret > 0)
1487     {
1488         ftdi->readbuffer_remaining = 0;
1489         ftdi->readbuffer_offset = 0;
1490         /* returns how much received */
1491         ret = usb_bulk_read (ftdi->usb_dev, ftdi->out_ep, ftdi->readbuffer, ftdi->readbuffer_chunksize, ftdi->usb_read_timeout);
1492         if (ret < 0)
1493             ftdi_error_return(ret, "usb bulk read failed");
1494
1495         if (ret > 2)
1496         {
1497             // skip FTDI status bytes.
1498             // Maybe stored in the future to enable modem use
1499             num_of_chunks = ret / packet_size;
1500             chunk_remains = ret % packet_size;
1501             //printf("ret = %X, num_of_chunks = %X, chunk_remains = %X, readbuffer_offset = %X\n", ret, num_of_chunks, chunk_remains, ftdi->readbuffer_offset);
1502
1503             ftdi->readbuffer_offset += 2;
1504             ret -= 2;
1505
1506             if (ret > packet_size - 2)
1507             {
1508                 for (i = 1; i < num_of_chunks; i++)
1509                     memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1510                              ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1511                              packet_size - 2);
1512                 if (chunk_remains > 2)
1513                 {
1514                     memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1515                              ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1516                              chunk_remains-2);
1517                     ret -= 2*num_of_chunks;
1518                 }
1519                 else
1520                     ret -= 2*(num_of_chunks-1)+chunk_remains;
1521             }
1522         }
1523         else if (ret <= 2)
1524         {
1525             // no more data to read?
1526             return offset;
1527         }
1528         if (ret > 0)
1529         {
1530             // data still fits in buf?
1531             if (offset+ret <= size)
1532             {
1533                 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, ret);
1534                 //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
1535                 offset += ret;
1536
1537                 /* Did we read exactly the right amount of bytes? */
1538                 if (offset == size)
1539                     //printf("read_data exact rem %d offset %d\n",
1540                     //ftdi->readbuffer_remaining, offset);
1541                     return offset;
1542             }
1543             else
1544             {
1545                 // only copy part of the data or size <= readbuffer_chunksize
1546                 int part_size = size-offset;
1547                 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, part_size);
1548
1549                 ftdi->readbuffer_offset += part_size;
1550                 ftdi->readbuffer_remaining = ret-part_size;
1551                 offset += part_size;
1552
1553                 /* printf("Returning part: %d - size: %d - offset: %d - ret: %d - remaining: %d\n",
1554                 part_size, size, offset, ret, ftdi->readbuffer_remaining); */
1555
1556                 return offset;
1557             }
1558         }
1559     }
1560     // never reached
1561     return -127;
1562 }
1563
1564 /**
1565     Configure read buffer chunk size.
1566     Default is 4096.
1567
1568     Automatically reallocates the buffer.
1569
1570     \param ftdi pointer to ftdi_context
1571     \param chunksize Chunk size
1572
1573     \retval 0: all fine
1574 */
1575 int ftdi_read_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
1576 {
1577     unsigned char *new_buf;
1578
1579     // Invalidate all remaining data
1580     ftdi->readbuffer_offset = 0;
1581     ftdi->readbuffer_remaining = 0;
1582
1583     if ((new_buf = (unsigned char *)realloc(ftdi->readbuffer, chunksize)) == NULL)
1584         ftdi_error_return(-1, "out of memory for readbuffer");
1585
1586     ftdi->readbuffer = new_buf;
1587     ftdi->readbuffer_chunksize = chunksize;
1588
1589     return 0;
1590 }
1591
1592 /**
1593     Get read buffer chunk size.
1594
1595     \param ftdi pointer to ftdi_context
1596     \param chunksize Pointer to store chunk size in
1597
1598     \retval 0: all fine
1599 */
1600 int ftdi_read_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
1601 {
1602     *chunksize = ftdi->readbuffer_chunksize;
1603     return 0;
1604 }
1605
1606
1607 /**
1608     Enable bitbang mode.
1609
1610     \deprecated use \ref ftdi_set_bitmode with mode BITMODE_BITBANG instead
1611
1612     \param ftdi pointer to ftdi_context
1613     \param bitmask Bitmask to configure lines.
1614            HIGH/ON value configures a line as output.
1615
1616     \retval  0: all fine
1617     \retval -1: can't enable bitbang mode
1618 */
1619 int ftdi_enable_bitbang(struct ftdi_context *ftdi, unsigned char bitmask)
1620 {
1621     unsigned short usb_val;
1622
1623     usb_val = bitmask; // low byte: bitmask
1624     /* FT2232C: Set bitbang_mode to 2 to enable SPI */
1625     usb_val |= (ftdi->bitbang_mode << 8);
1626
1627     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1628                         SIO_SET_BITMODE_REQUEST, usb_val, ftdi->index,
1629                         NULL, 0, ftdi->usb_write_timeout) != 0)
1630         ftdi_error_return(-1, "unable to enter bitbang mode. Perhaps not a BM type chip?");
1631
1632     ftdi->bitbang_enabled = 1;
1633     return 0;
1634 }
1635
1636 /**
1637     Disable bitbang mode.
1638
1639     \param ftdi pointer to ftdi_context
1640
1641     \retval  0: all fine
1642     \retval -1: can't disable bitbang mode
1643 */
1644 int ftdi_disable_bitbang(struct ftdi_context *ftdi)
1645 {
1646     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_SET_BITMODE_REQUEST, 0, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
1647         ftdi_error_return(-1, "unable to leave bitbang mode. Perhaps not a BM type chip?");
1648
1649     ftdi->bitbang_enabled = 0;
1650     return 0;
1651 }
1652
1653 /**
1654     Enable/disable bitbang modes.
1655
1656     \param ftdi pointer to ftdi_context
1657     \param bitmask Bitmask to configure lines.
1658            HIGH/ON value configures a line as output.
1659     \param mode Bitbang mode: use the values defined in \ref ftdi_mpsse_mode
1660
1661     \retval  0: all fine
1662     \retval -1: can't enable bitbang mode
1663 */
1664 int ftdi_set_bitmode(struct ftdi_context *ftdi, unsigned char bitmask, unsigned char mode)
1665 {
1666     unsigned short usb_val;
1667
1668     usb_val = bitmask; // low byte: bitmask
1669     usb_val |= (mode << 8);
1670     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_SET_BITMODE_REQUEST, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
1671         ftdi_error_return(-1, "unable to configure bitbang mode. Perhaps selected mode not supported on your chip?");
1672
1673     ftdi->bitbang_mode = mode;
1674     ftdi->bitbang_enabled = (mode == BITMODE_RESET) ? 0 : 1;
1675     return 0;
1676 }
1677
1678 /**
1679     Directly read pin state, circumventing the read buffer. Useful for bitbang mode.
1680
1681     \param ftdi pointer to ftdi_context
1682     \param pins Pointer to store pins into
1683
1684     \retval  0: all fine
1685     \retval -1: read pins failed
1686 */
1687 int ftdi_read_pins(struct ftdi_context *ftdi, unsigned char *pins)
1688 {
1689     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_READ_PINS_REQUEST, 0, ftdi->index, (char *)pins, 1, ftdi->usb_read_timeout) != 1)
1690         ftdi_error_return(-1, "read pins failed");
1691
1692     return 0;
1693 }
1694
1695 /**
1696     Set latency timer
1697
1698     The FTDI chip keeps data in the internal buffer for a specific
1699     amount of time if the buffer is not full yet to decrease
1700     load on the usb bus.
1701
1702     \param ftdi pointer to ftdi_context
1703     \param latency Value between 1 and 255
1704
1705     \retval  0: all fine
1706     \retval -1: latency out of range
1707     \retval -2: unable to set latency timer
1708 */
1709 int ftdi_set_latency_timer(struct ftdi_context *ftdi, unsigned char latency)
1710 {
1711     unsigned short usb_val;
1712
1713     if (latency < 1)
1714         ftdi_error_return(-1, "latency out of range. Only valid for 1-255");
1715
1716     usb_val = latency;
1717     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_SET_LATENCY_TIMER_REQUEST, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
1718         ftdi_error_return(-2, "unable to set latency timer");
1719
1720     return 0;
1721 }
1722
1723 /**
1724     Get latency timer
1725
1726     \param ftdi pointer to ftdi_context
1727     \param latency Pointer to store latency value in
1728
1729     \retval  0: all fine
1730     \retval -1: unable to get latency timer
1731 */
1732 int ftdi_get_latency_timer(struct ftdi_context *ftdi, unsigned char *latency)
1733 {
1734     unsigned short usb_val;
1735     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_GET_LATENCY_TIMER_REQUEST, 0, ftdi->index, (char *)&usb_val, 1, ftdi->usb_read_timeout) != 1)
1736         ftdi_error_return(-1, "reading latency timer failed");
1737
1738     *latency = (unsigned char)usb_val;
1739     return 0;
1740 }
1741
1742 /**
1743     Poll modem status information
1744
1745     This function allows the retrieve the two status bytes of the device.
1746     The device sends these bytes also as a header for each read access
1747     where they are discarded by ftdi_read_data(). The chip generates
1748     the two stripped status bytes in the absence of data every 40 ms.
1749
1750     Layout of the first byte:
1751     - B0..B3 - must be 0
1752     - B4       Clear to send (CTS)
1753                  0 = inactive
1754                  1 = active
1755     - B5       Data set ready (DTS)
1756                  0 = inactive
1757                  1 = active
1758     - B6       Ring indicator (RI)
1759                  0 = inactive
1760                  1 = active
1761     - B7       Receive line signal detect (RLSD)
1762                  0 = inactive
1763                  1 = active
1764
1765     Layout of the second byte:
1766     - B0       Data ready (DR)
1767     - B1       Overrun error (OE)
1768     - B2       Parity error (PE)
1769     - B3       Framing error (FE)
1770     - B4       Break interrupt (BI)
1771     - B5       Transmitter holding register (THRE)
1772     - B6       Transmitter empty (TEMT)
1773     - B7       Error in RCVR FIFO
1774
1775     \param ftdi pointer to ftdi_context
1776     \param status Pointer to store status information in. Must be two bytes.
1777
1778     \retval  0: all fine
1779     \retval -1: unable to retrieve status information
1780 */
1781 int ftdi_poll_modem_status(struct ftdi_context *ftdi, unsigned short *status)
1782 {
1783     char usb_val[2];
1784
1785     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_POLL_MODEM_STATUS_REQUEST, 0, ftdi->index, usb_val, 2, ftdi->usb_read_timeout) != 2)
1786         ftdi_error_return(-1, "getting modem status failed");
1787
1788     *status = (usb_val[1] << 8) | usb_val[0];
1789
1790     return 0;
1791 }
1792
1793 /**
1794     Set flowcontrol for ftdi chip
1795
1796     \param ftdi pointer to ftdi_context
1797     \param flowctrl flow control to use. should be
1798            SIO_DISABLE_FLOW_CTRL, SIO_RTS_CTS_HS, SIO_DTR_DSR_HS or SIO_XON_XOFF_HS
1799
1800     \retval  0: all fine
1801     \retval -1: set flow control failed
1802 */
1803 int ftdi_setflowctrl(struct ftdi_context *ftdi, int flowctrl)
1804 {
1805     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1806                         SIO_SET_FLOW_CTRL_REQUEST, 0, (flowctrl | ftdi->index),
1807                         NULL, 0, ftdi->usb_write_timeout) != 0)
1808         ftdi_error_return(-1, "set flow control failed");
1809
1810     return 0;
1811 }
1812
1813 /**
1814     Set dtr line
1815
1816     \param ftdi pointer to ftdi_context
1817     \param state state to set line to (1 or 0)
1818
1819     \retval  0: all fine
1820     \retval -1: set dtr failed
1821 */
1822 int ftdi_setdtr(struct ftdi_context *ftdi, int state)
1823 {
1824     unsigned short usb_val;
1825
1826     if (state)
1827         usb_val = SIO_SET_DTR_HIGH;
1828     else
1829         usb_val = SIO_SET_DTR_LOW;
1830
1831     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1832                         SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
1833                         NULL, 0, ftdi->usb_write_timeout) != 0)
1834         ftdi_error_return(-1, "set dtr failed");
1835
1836     return 0;
1837 }
1838
1839 /**
1840     Set rts line
1841
1842     \param ftdi pointer to ftdi_context
1843     \param state state to set line to (1 or 0)
1844
1845     \retval  0: all fine
1846     \retval -1 set rts failed
1847 */
1848 int ftdi_setrts(struct ftdi_context *ftdi, int state)
1849 {
1850     unsigned short usb_val;
1851
1852     if (state)
1853         usb_val = SIO_SET_RTS_HIGH;
1854     else
1855         usb_val = SIO_SET_RTS_LOW;
1856
1857     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1858                         SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
1859                         NULL, 0, ftdi->usb_write_timeout) != 0)
1860         ftdi_error_return(-1, "set of rts failed");
1861
1862     return 0;
1863 }
1864
1865 /**
1866  Set dtr and rts line in one pass
1867
1868  \param ftdi pointer to ftdi_context
1869  \param dtr  DTR state to set line to (1 or 0)
1870  \param rts  RTS state to set line to (1 or 0)
1871
1872  \retval  0: all fine
1873  \retval -1 set dtr/rts failed
1874  */
1875 int ftdi_setdtr_rts(struct ftdi_context *ftdi, int dtr, int rts)
1876 {
1877     unsigned short usb_val;
1878
1879     if (dtr)
1880         usb_val = SIO_SET_DTR_HIGH;
1881     else
1882         usb_val = SIO_SET_DTR_LOW;
1883
1884     if (rts)
1885         usb_val |= SIO_SET_RTS_HIGH;
1886     else
1887         usb_val |= SIO_SET_RTS_LOW;
1888
1889     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1890                         SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
1891                         NULL, 0, ftdi->usb_write_timeout) != 0)
1892         ftdi_error_return(-1, "set of rts/dtr failed");
1893
1894     return 0;
1895 }
1896
1897 /**
1898     Set the special event character
1899
1900     \param ftdi pointer to ftdi_context
1901     \param eventch Event character
1902     \param enable 0 to disable the event character, non-zero otherwise
1903
1904     \retval  0: all fine
1905     \retval -1: unable to set event character
1906 */
1907 int ftdi_set_event_char(struct ftdi_context *ftdi,
1908                         unsigned char eventch, unsigned char enable)
1909 {
1910     unsigned short usb_val;
1911
1912     usb_val = eventch;
1913     if (enable)
1914         usb_val |= 1 << 8;
1915
1916     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_SET_EVENT_CHAR_REQUEST, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
1917         ftdi_error_return(-1, "setting event character failed");
1918
1919     return 0;
1920 }
1921
1922 /**
1923     Set error character
1924
1925     \param ftdi pointer to ftdi_context
1926     \param errorch Error character
1927     \param enable 0 to disable the error character, non-zero otherwise
1928
1929     \retval  0: all fine
1930     \retval -1: unable to set error character
1931 */
1932 int ftdi_set_error_char(struct ftdi_context *ftdi,
1933                         unsigned char errorch, unsigned char enable)
1934 {
1935     unsigned short usb_val;
1936
1937     usb_val = errorch;
1938     if (enable)
1939         usb_val |= 1 << 8;
1940
1941     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_SET_ERROR_CHAR_REQUEST, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
1942         ftdi_error_return(-1, "setting error character failed");
1943
1944     return 0;
1945 }
1946
1947 /**
1948    Set the eeprom size
1949
1950    \param ftdi pointer to ftdi_context
1951    \param eeprom Pointer to ftdi_eeprom
1952    \param size
1953
1954 */
1955 void ftdi_eeprom_setsize(struct ftdi_context *ftdi, struct ftdi_eeprom *eeprom, int size)
1956 {
1957     ftdi->eeprom_size=size;
1958     eeprom->size=size;
1959 }
1960
1961 /**
1962     Init eeprom with default values.
1963
1964     \param eeprom Pointer to ftdi_eeprom
1965 */
1966 void ftdi_eeprom_initdefaults(struct ftdi_eeprom *eeprom)
1967 {
1968     eeprom->vendor_id = 0x0403;
1969     eeprom->product_id = 0x6001;
1970
1971     eeprom->self_powered = 1;
1972     eeprom->remote_wakeup = 1;
1973     eeprom->BM_type_chip = 1;
1974
1975     eeprom->in_is_isochronous = 0;
1976     eeprom->out_is_isochronous = 0;
1977     eeprom->suspend_pull_downs = 0;
1978
1979     eeprom->use_serial = 0;
1980     eeprom->change_usb_version = 0;
1981     eeprom->usb_version = 0x0200;
1982     eeprom->max_power = 0;
1983
1984     eeprom->manufacturer = NULL;
1985     eeprom->product = NULL;
1986     eeprom->serial = NULL;
1987
1988     eeprom->size = FTDI_DEFAULT_EEPROM_SIZE;
1989 }
1990
1991 /**
1992    Build binary output from ftdi_eeprom structure.
1993    Output is suitable for ftdi_write_eeprom().
1994
1995    \param eeprom Pointer to ftdi_eeprom
1996    \param output Buffer of 128 bytes to store eeprom image to
1997
1998    \retval >0: used eeprom size
1999    \retval -1: eeprom size (128 bytes) exceeded by custom strings
2000 */
2001 int ftdi_eeprom_build(struct ftdi_eeprom *eeprom, unsigned char *output)
2002 {
2003     unsigned char i, j;
2004     unsigned short checksum, value;
2005     unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
2006     int size_check;
2007
2008     if (eeprom->manufacturer != NULL)
2009         manufacturer_size = strlen(eeprom->manufacturer);
2010     if (eeprom->product != NULL)
2011         product_size = strlen(eeprom->product);
2012     if (eeprom->serial != NULL)
2013         serial_size = strlen(eeprom->serial);
2014
2015     size_check = eeprom->size;
2016     size_check -= 28; // 28 are always in use (fixed)
2017
2018     // Top half of a 256byte eeprom is used just for strings and checksum
2019     // it seems that the FTDI chip will not read these strings from the lower half
2020     // Each string starts with two bytes; offset and type (0x03 for string)
2021     // the checksum needs two bytes, so without the string data that 8 bytes from the top half
2022     if (eeprom->size>=256)size_check = 120;
2023     size_check -= manufacturer_size*2;
2024     size_check -= product_size*2;
2025     size_check -= serial_size*2;
2026
2027     // eeprom size exceeded?
2028     if (size_check < 0)
2029         return (-1);
2030
2031     // empty eeprom
2032     memset (output, 0, eeprom->size);
2033
2034     // Addr 00: Stay 00 00
2035     // Addr 02: Vendor ID
2036     output[0x02] = eeprom->vendor_id;
2037     output[0x03] = eeprom->vendor_id >> 8;
2038
2039     // Addr 04: Product ID
2040     output[0x04] = eeprom->product_id;
2041     output[0x05] = eeprom->product_id >> 8;
2042
2043     // Addr 06: Device release number (0400h for BM features)
2044     output[0x06] = 0x00;
2045
2046     if (eeprom->BM_type_chip == 1)
2047         output[0x07] = 0x04;
2048     else
2049         output[0x07] = 0x02;
2050
2051     // Addr 08: Config descriptor
2052     // Bit 7: always 1
2053     // Bit 6: 1 if this device is self powered, 0 if bus powered
2054     // Bit 5: 1 if this device uses remote wakeup
2055     // Bit 4: 1 if this device is battery powered
2056     j = 0x80;
2057     if (eeprom->self_powered == 1)
2058         j |= 0x40;
2059     if (eeprom->remote_wakeup == 1)
2060         j |= 0x20;
2061     output[0x08] = j;
2062
2063     // Addr 09: Max power consumption: max power = value * 2 mA
2064     output[0x09] = eeprom->max_power;
2065
2066     // Addr 0A: Chip configuration
2067     // Bit 7: 0 - reserved
2068     // Bit 6: 0 - reserved
2069     // Bit 5: 0 - reserved
2070     // Bit 4: 1 - Change USB version
2071     // Bit 3: 1 - Use the serial number string
2072     // Bit 2: 1 - Enable suspend pull downs for lower power
2073     // Bit 1: 1 - Out EndPoint is Isochronous
2074     // Bit 0: 1 - In EndPoint is Isochronous
2075     //
2076     j = 0;
2077     if (eeprom->in_is_isochronous == 1)
2078         j = j | 1;
2079     if (eeprom->out_is_isochronous == 1)
2080         j = j | 2;
2081     if (eeprom->suspend_pull_downs == 1)
2082         j = j | 4;
2083     if (eeprom->use_serial == 1)
2084         j = j | 8;
2085     if (eeprom->change_usb_version == 1)
2086         j = j | 16;
2087     output[0x0A] = j;
2088
2089     // Addr 0B: reserved
2090     output[0x0B] = 0x00;
2091
2092     // Addr 0C: USB version low byte when 0x0A bit 4 is set
2093     // Addr 0D: USB version high byte when 0x0A bit 4 is set
2094     if (eeprom->change_usb_version == 1)
2095     {
2096         output[0x0C] = eeprom->usb_version;
2097         output[0x0D] = eeprom->usb_version >> 8;
2098     }
2099
2100
2101     // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
2102     // Addr 0F: Length of manufacturer string
2103     output[0x0F] = manufacturer_size*2 + 2;
2104
2105     // Addr 10: Offset of the product string + 0x80, calculated later
2106     // Addr 11: Length of product string
2107     output[0x11] = product_size*2 + 2;
2108
2109     // Addr 12: Offset of the serial string + 0x80, calculated later
2110     // Addr 13: Length of serial string
2111     output[0x13] = serial_size*2 + 2;
2112
2113     // Dynamic content
2114     i=0x14;
2115     if (eeprom->size>=256) i = 0x80;
2116
2117
2118     // Output manufacturer
2119     output[0x0E] = i | 0x80;  // calculate offset
2120     output[i++] = manufacturer_size*2 + 2;
2121     output[i++] = 0x03; // type: string
2122     for (j = 0; j < manufacturer_size; j++)
2123     {
2124         output[i] = eeprom->manufacturer[j], i++;
2125         output[i] = 0x00, i++;
2126     }
2127
2128     // Output product name
2129     output[0x10] = i | 0x80;  // calculate offset
2130     output[i] = product_size*2 + 2, i++;
2131     output[i] = 0x03, i++;
2132     for (j = 0; j < product_size; j++)
2133     {
2134         output[i] = eeprom->product[j], i++;
2135         output[i] = 0x00, i++;
2136     }
2137
2138     // Output serial
2139     output[0x12] = i | 0x80; // calculate offset
2140     output[i] = serial_size*2 + 2, i++;
2141     output[i] = 0x03, i++;
2142     for (j = 0; j < serial_size; j++)
2143     {
2144         output[i] = eeprom->serial[j], i++;
2145         output[i] = 0x00, i++;
2146     }
2147
2148     // calculate checksum
2149     checksum = 0xAAAA;
2150
2151     for (i = 0; i < eeprom->size/2-1; i++)
2152     {
2153         value = output[i*2];
2154         value += output[(i*2)+1] << 8;
2155
2156         checksum = value^checksum;
2157         checksum = (checksum << 1) | (checksum >> 15);
2158     }
2159
2160     output[eeprom->size-2] = checksum;
2161     output[eeprom->size-1] = checksum >> 8;
2162
2163     return size_check;
2164 }
2165
2166 /**
2167    Decode binary EEPROM image into an ftdi_eeprom structure.
2168
2169    \param eeprom Pointer to ftdi_eeprom which will be filled in.
2170    \param buf Buffer of \a size bytes of raw eeprom data
2171    \param size size size of eeprom data in bytes
2172
2173    \retval 0: all fine
2174    \retval -1: something went wrong
2175
2176    FIXME: How to pass size? How to handle size field in ftdi_eeprom?
2177    FIXME: Strings are malloc'ed here and should be freed somewhere
2178 */
2179 int ftdi_eeprom_decode(struct ftdi_eeprom *eeprom, unsigned char *buf, int size)
2180 {
2181     unsigned char i, j;
2182     unsigned short checksum, eeprom_checksum, value;
2183     unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
2184     int size_check;
2185     int eeprom_size = 128;
2186 #if 0
2187     size_check = eeprom->size;
2188     size_check -= 28; // 28 are always in use (fixed)
2189
2190     // Top half of a 256byte eeprom is used just for strings and checksum
2191     // it seems that the FTDI chip will not read these strings from the lower half
2192     // Each string starts with two bytes; offset and type (0x03 for string)
2193     // the checksum needs two bytes, so without the string data that 8 bytes from the top half
2194     if (eeprom->size>=256)size_check = 120;
2195     size_check -= manufacturer_size*2;
2196     size_check -= product_size*2;
2197     size_check -= serial_size*2;
2198
2199     // eeprom size exceeded?
2200     if (size_check < 0)
2201         return (-1);
2202 #endif
2203
2204     // empty eeprom struct
2205     memset(eeprom, 0, sizeof(struct ftdi_eeprom));
2206
2207     // Addr 00: Stay 00 00
2208
2209     // Addr 02: Vendor ID
2210     eeprom->vendor_id = buf[0x02] + (buf[0x03] << 8);
2211
2212     // Addr 04: Product ID
2213     eeprom->product_id = buf[0x04] + (buf[0x05] << 8);
2214
2215     value = buf[0x06] + (buf[0x07]<<8);
2216     switch (value)
2217     {
2218         case 0x0400:
2219             eeprom->BM_type_chip = 1;
2220             break;
2221         case 0x0200:
2222             eeprom->BM_type_chip = 0;
2223             break;
2224         default: // Unknown device
2225             eeprom->BM_type_chip = 0;
2226             break;
2227     }
2228
2229     // Addr 08: Config descriptor
2230     // Bit 7: always 1
2231     // Bit 6: 1 if this device is self powered, 0 if bus powered
2232     // Bit 5: 1 if this device uses remote wakeup
2233     // Bit 4: 1 if this device is battery powered
2234     j = buf[0x08];
2235     if (j&0x40) eeprom->self_powered = 1;
2236     if (j&0x20) eeprom->remote_wakeup = 1;
2237
2238     // Addr 09: Max power consumption: max power = value * 2 mA
2239     eeprom->max_power = buf[0x09];
2240
2241     // Addr 0A: Chip configuration
2242     // Bit 7: 0 - reserved
2243     // Bit 6: 0 - reserved
2244     // Bit 5: 0 - reserved
2245     // Bit 4: 1 - Change USB version
2246     // Bit 3: 1 - Use the serial number string
2247     // Bit 2: 1 - Enable suspend pull downs for lower power
2248     // Bit 1: 1 - Out EndPoint is Isochronous
2249     // Bit 0: 1 - In EndPoint is Isochronous
2250     //
2251     j = buf[0x0A];
2252     if (j&0x01) eeprom->in_is_isochronous = 1;
2253     if (j&0x02) eeprom->out_is_isochronous = 1;
2254     if (j&0x04) eeprom->suspend_pull_downs = 1;
2255     if (j&0x08) eeprom->use_serial = 1;
2256     if (j&0x10) eeprom->change_usb_version = 1;
2257
2258     // Addr 0B: reserved
2259
2260     // Addr 0C: USB version low byte when 0x0A bit 4 is set
2261     // Addr 0D: USB version high byte when 0x0A bit 4 is set
2262     if (eeprom->change_usb_version == 1)
2263     {
2264         eeprom->usb_version = buf[0x0C] + (buf[0x0D] << 8);
2265     }
2266
2267     // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
2268     // Addr 0F: Length of manufacturer string
2269     manufacturer_size = buf[0x0F]/2;
2270     if (manufacturer_size > 0) eeprom->manufacturer = malloc(manufacturer_size);
2271     else eeprom->manufacturer = NULL;
2272
2273     // Addr 10: Offset of the product string + 0x80, calculated later
2274     // Addr 11: Length of product string
2275     product_size = buf[0x11]/2;
2276     if (product_size > 0) eeprom->product = malloc(product_size);
2277     else eeprom->product = NULL;
2278
2279     // Addr 12: Offset of the serial string + 0x80, calculated later
2280     // Addr 13: Length of serial string
2281     serial_size = buf[0x13]/2;
2282     if (serial_size > 0) eeprom->serial = malloc(serial_size);
2283     else eeprom->serial = NULL;
2284
2285     // Decode manufacturer
2286     i = buf[0x0E] & 0x7f; // offset
2287     for (j=0;j<manufacturer_size-1;j++)
2288     {
2289         eeprom->manufacturer[j] = buf[2*j+i+2];
2290     }
2291     eeprom->manufacturer[j] = '\0';
2292
2293     // Decode product name
2294     i = buf[0x10] & 0x7f; // offset
2295     for (j=0;j<product_size-1;j++)
2296     {
2297         eeprom->product[j] = buf[2*j+i+2];
2298     }
2299     eeprom->product[j] = '\0';
2300
2301     // Decode serial
2302     i = buf[0x12] & 0x7f; // offset
2303     for (j=0;j<serial_size-1;j++)
2304     {
2305         eeprom->serial[j] = buf[2*j+i+2];
2306     }
2307     eeprom->serial[j] = '\0';
2308
2309     // verify checksum
2310     checksum = 0xAAAA;
2311
2312     for (i = 0; i < eeprom_size/2-1; i++)
2313     {
2314         value = buf[i*2];
2315         value += buf[(i*2)+1] << 8;
2316
2317         checksum = value^checksum;
2318         checksum = (checksum << 1) | (checksum >> 15);
2319     }
2320
2321     eeprom_checksum = buf[eeprom_size-2] + (buf[eeprom_size-1] << 8);
2322
2323     if (eeprom_checksum != checksum)
2324     {
2325         fprintf(stderr, "Checksum Error: %04x %04x\n", checksum, eeprom_checksum);
2326         return -1;
2327     }
2328
2329     return 0;
2330 }
2331
2332 /**
2333     Read eeprom location
2334
2335     \param ftdi pointer to ftdi_context
2336     \param eeprom_addr Address of eeprom location to be read
2337     \param eeprom_val Pointer to store read eeprom location
2338
2339     \retval  0: all fine
2340     \retval -1: read failed
2341 */
2342 int ftdi_read_eeprom_location (struct ftdi_context *ftdi, int eeprom_addr, unsigned short *eeprom_val)
2343 {
2344     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_READ_EEPROM_REQUEST, 0, eeprom_addr, (char *)eeprom_val, 2, ftdi->usb_read_timeout) != 2)
2345         ftdi_error_return(-1, "reading eeprom failed");
2346
2347     return 0;
2348 }
2349
2350 /**
2351     Read eeprom
2352
2353     \param ftdi pointer to ftdi_context
2354     \param eeprom Pointer to store eeprom into
2355
2356     \retval  0: all fine
2357     \retval -1: read failed
2358 */
2359 int ftdi_read_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
2360 {
2361     int i;
2362
2363     for (i = 0; i < ftdi->eeprom_size/2; i++)
2364     {
2365         if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_READ_EEPROM_REQUEST, 0, i, eeprom+(i*2), 2, ftdi->usb_read_timeout) != 2)
2366             ftdi_error_return(-1, "reading eeprom failed");
2367     }
2368
2369     return 0;
2370 }
2371
2372 /*
2373     ftdi_read_chipid_shift does the bitshift operation needed for the FTDIChip-ID
2374     Function is only used internally
2375     \internal
2376 */
2377 static unsigned char ftdi_read_chipid_shift(unsigned char value)
2378 {
2379     return ((value & 1) << 1) |
2380            ((value & 2) << 5) |
2381            ((value & 4) >> 2) |
2382            ((value & 8) << 4) |
2383            ((value & 16) >> 1) |
2384            ((value & 32) >> 1) |
2385            ((value & 64) >> 4) |
2386            ((value & 128) >> 2);
2387 }
2388
2389 /**
2390     Read the FTDIChip-ID from R-type devices
2391
2392     \param ftdi pointer to ftdi_context
2393     \param chipid Pointer to store FTDIChip-ID
2394
2395     \retval  0: all fine
2396     \retval -1: read failed
2397 */
2398 int ftdi_read_chipid(struct ftdi_context *ftdi, unsigned int *chipid)
2399 {
2400     unsigned int a = 0, b = 0;
2401
2402     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_READ_EEPROM_REQUEST, 0, 0x43, (char *)&a, 2, ftdi->usb_read_timeout) == 2)
2403     {
2404         a = a << 8 | a >> 8;
2405         if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_READ_EEPROM_REQUEST, 0, 0x44, (char *)&b, 2, ftdi->usb_read_timeout) == 2)
2406         {
2407             b = b << 8 | b >> 8;
2408             a = (a << 16) | (b & 0xFFFF);
2409             a = ftdi_read_chipid_shift(a) | ftdi_read_chipid_shift(a>>8)<<8
2410                 | ftdi_read_chipid_shift(a>>16)<<16 | ftdi_read_chipid_shift(a>>24)<<24;
2411             *chipid = a ^ 0xa5f0f7d1;
2412             return 0;
2413         }
2414     }
2415
2416     ftdi_error_return(-1, "read of FTDIChip-ID failed");
2417 }
2418
2419 /**
2420    Guesses size of eeprom by reading eeprom and comparing halves - will not work with blank eeprom
2421    Call this function then do a write then call again to see if size changes, if so write again.
2422
2423    \param ftdi pointer to ftdi_context
2424    \param eeprom Pointer to store eeprom into
2425    \param maxsize the size of the buffer to read into
2426
2427    \retval size of eeprom
2428 */
2429 int ftdi_read_eeprom_getsize(struct ftdi_context *ftdi, unsigned char *eeprom, int maxsize)
2430 {
2431     int i=0,j,minsize=32;
2432     int size=minsize;
2433
2434     do
2435     {
2436         for (j = 0; i < maxsize/2 && j<size; j++)
2437         {
2438             if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE,
2439                                 SIO_READ_EEPROM_REQUEST, 0, i,
2440                                 eeprom+(i*2), 2, ftdi->usb_read_timeout) != 2)
2441                 ftdi_error_return(-1, "reading eeprom failed");
2442             i++;
2443         }
2444         size*=2;
2445     }
2446     while (size<=maxsize && memcmp(eeprom,&eeprom[size/2],size/2)!=0);
2447
2448     return size/2;
2449 }
2450
2451 /**
2452     Write eeprom location
2453
2454     \param ftdi pointer to ftdi_context
2455     \param eeprom_addr Address of eeprom location to be written
2456     \param eeprom_val Value to be written
2457
2458     \retval  0: all fine
2459     \retval -1: read failed
2460 */
2461 int ftdi_write_eeprom_location(struct ftdi_context *ftdi, int eeprom_addr, unsigned short eeprom_val)
2462 {
2463     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
2464                                     SIO_WRITE_EEPROM_REQUEST, eeprom_val, eeprom_addr,
2465                                     NULL, 0, ftdi->usb_write_timeout) != 0)
2466         ftdi_error_return(-1, "unable to write eeprom");
2467
2468     return 0;
2469 }
2470
2471 /**
2472     Write eeprom
2473
2474     \param ftdi pointer to ftdi_context
2475     \param eeprom Pointer to read eeprom from
2476
2477     \retval  0: all fine
2478     \retval -1: read failed
2479 */
2480 int ftdi_write_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
2481 {
2482     unsigned short usb_val, status;
2483     int i, ret;
2484
2485     /* These commands were traced while running MProg */
2486     if ((ret = ftdi_usb_reset(ftdi)) != 0)
2487         return ret;
2488     if ((ret = ftdi_poll_modem_status(ftdi, &status)) != 0)
2489         return ret;
2490     if ((ret = ftdi_set_latency_timer(ftdi, 0x77)) != 0)
2491         return ret;
2492
2493     for (i = 0; i < ftdi->eeprom_size/2; i++)
2494     {
2495         usb_val = eeprom[i*2];
2496         usb_val += eeprom[(i*2)+1] << 8;
2497         if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
2498                             SIO_WRITE_EEPROM_REQUEST, usb_val, i,
2499                             NULL, 0, ftdi->usb_write_timeout) != 0)
2500             ftdi_error_return(-1, "unable to write eeprom");
2501     }
2502
2503     return 0;
2504 }
2505
2506 /**
2507     Erase eeprom
2508
2509     This is not supported on FT232R/FT245R according to the MProg manual from FTDI.
2510
2511     \param ftdi pointer to ftdi_context
2512
2513     \retval  0: all fine
2514     \retval -1: erase failed
2515 */
2516 int ftdi_erase_eeprom(struct ftdi_context *ftdi)
2517 {
2518     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_ERASE_EEPROM_REQUEST, 0, 0, NULL, 0, ftdi->usb_write_timeout) != 0)
2519         ftdi_error_return(-1, "unable to erase eeprom");
2520
2521     return 0;
2522 }
2523
2524 /**
2525     Get string representation for last error code
2526
2527     \param ftdi pointer to ftdi_context
2528
2529     \retval Pointer to error string
2530 */
2531 char *ftdi_get_error_string (struct ftdi_context *ftdi)
2532 {
2533     return ftdi->error_str;
2534 }
2535
2536 /* @} end of doxygen libftdi group */