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