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