Fix for double-free and segfault after close
[libftdi] / src / ftdi.c
CommitLineData
a3da1d95
GE
1/***************************************************************************
2 ftdi.c - description
3 -------------------
4 begin : Fri Apr 4 2003
c201f80f 5 copyright : (C) 2003-2008 by Intra2net AG
5fdb1cb1 6 email : opensource@intra2net.com
a3da1d95
GE
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 ***************************************************************************/
d9f0cce7 16
b5ec1820
TJ
17/**
18 \mainpage libftdi API documentation
19
ad397a4b 20 Library to talk to FTDI chips. You find the latest versions of libftdi at
1bfc403c 21 http://www.intra2net.com/en/developer/libftdi/
b5ec1820 22
ad397a4b
TJ
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.
b5ec1820
TJ
27*/
28/** \addtogroup libftdi */
29/* @{ */
30
98452d97 31#include <usb.h>
a8f46ddc 32#include <string.h>
d2f10023 33#include <errno.h>
b56d5a64 34#include <stdio.h>
0e302db6 35
98452d97 36#include "ftdi.h"
a3da1d95 37
7cc9950e 38/* stuff needed for async write */
f01d7ca6 39#ifdef LIBFTDI_LINUX_ASYNC_MODE
22d12cda
TJ
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>
f01d7ca6 46#endif
7cc9950e 47
21abaf2e 48#define ftdi_error_return(code, str) do { \
2f73e59f 49 ftdi->error_str = str; \
21abaf2e 50 return code; \
d2f10023 51 } while(0);
c3d95b87 52
dff4fdb0
NF
53/* internal usb_close wrapper -> sets usb dev handle to NULL */
54int 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}
c3d95b87 65
1941414d
TJ
66/**
67 Initializes a ftdi_context.
4837f98a 68
1941414d 69 \param ftdi pointer to ftdi_context
4837f98a 70
1941414d
TJ
71 \retval 0: all fine
72 \retval -1: couldn't allocate read buffer
73
74 \remark This should be called before all functions
948f9ada 75*/
a8f46ddc
TJ
76int ftdi_init(struct ftdi_context *ftdi)
77{
bf35baa0 78 unsigned int i;
7cc9950e 79
98452d97 80 ftdi->usb_dev = NULL;
545820ce
TJ
81 ftdi->usb_read_timeout = 5000;
82 ftdi->usb_write_timeout = 5000;
a3da1d95 83
53ad271d 84 ftdi->type = TYPE_BM; /* chip type */
a3da1d95
GE
85 ftdi->baudrate = -1;
86 ftdi->bitbang_enabled = 0;
87
948f9ada
TJ
88 ftdi->readbuffer = NULL;
89 ftdi->readbuffer_offset = 0;
90 ftdi->readbuffer_remaining = 0;
91 ftdi->writebuffer_chunksize = 4096;
92
545820ce
TJ
93 ftdi->interface = 0;
94 ftdi->index = 0;
95 ftdi->in_ep = 0x02;
96 ftdi->out_ep = 0x81;
3119537f 97 ftdi->bitbang_mode = 1; /* 1: Normal bitbang mode, 2: SPI bitbang mode */
53ad271d 98
a3da1d95
GE
99 ftdi->error_str = NULL;
100
f01d7ca6 101#ifdef LIBFTDI_LINUX_ASYNC_MODE
7cc9950e
GE
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;
f01d7ca6
TJ
109#else
110 ftdi->async_usb_buffer_size=0;
111 ftdi->async_usb_buffer = NULL;
112#endif
7cc9950e 113
c201f80f
TJ
114 ftdi->eeprom_size = FTDI_DEFAULT_EEPROM_SIZE;
115
1c733d33
TJ
116 /* All fine. Now allocate the readbuffer */
117 return ftdi_read_data_set_chunksize(ftdi, 4096);
948f9ada 118}
4837f98a 119
1941414d 120/**
cef378aa
TJ
121 Allocate and initialize a new ftdi_context
122
123 \return a pointer to a new ftdi_context, or NULL on failure
124*/
672ac008 125struct ftdi_context *ftdi_new(void)
cef378aa
TJ
126{
127 struct ftdi_context * ftdi = (struct ftdi_context *)malloc(sizeof(struct ftdi_context));
128
22d12cda
TJ
129 if (ftdi == NULL)
130 {
cef378aa
TJ
131 return NULL;
132 }
133
22d12cda
TJ
134 if (ftdi_init(ftdi) != 0)
135 {
cef378aa 136 free(ftdi);
cdf448f6 137 return NULL;
cef378aa
TJ
138 }
139
140 return ftdi;
141}
142
143/**
1941414d
TJ
144 Open selected channels on a chip, otherwise use first channel.
145
146 \param ftdi pointer to ftdi_context
f9d69895 147 \param interface Interface to use for FT2232C/2232H/4232H chips.
1941414d
TJ
148
149 \retval 0: all fine
150 \retval -1: unknown interface
c4446c36 151*/
0ce2f5fa 152int ftdi_set_interface(struct ftdi_context *ftdi, enum ftdi_interface interface)
c4446c36 153{
22d12cda
TJ
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;
f9d69895
AH
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;
22d12cda
TJ
178 default:
179 ftdi_error_return(-1, "Unknown interface");
c4446c36
TJ
180 }
181 return 0;
182}
948f9ada 183
1941414d
TJ
184/**
185 Deinitializes a ftdi_context.
4837f98a 186
1941414d 187 \param ftdi pointer to ftdi_context
4837f98a 188*/
a8f46ddc
TJ
189void ftdi_deinit(struct ftdi_context *ftdi)
190{
dff4fdb0
NF
191 usb_close_intl (ftdi);
192
22d12cda
TJ
193 if (ftdi->async_usb_buffer != NULL)
194 {
7cc9950e
GE
195 free(ftdi->async_usb_buffer);
196 ftdi->async_usb_buffer = NULL;
197 }
198
22d12cda
TJ
199 if (ftdi->readbuffer != NULL)
200 {
d9f0cce7
TJ
201 free(ftdi->readbuffer);
202 ftdi->readbuffer = NULL;
948f9ada 203 }
a3da1d95
GE
204}
205
1941414d 206/**
cef378aa
TJ
207 Deinitialize and free an ftdi_context.
208
209 \param ftdi pointer to ftdi_context
210*/
211void ftdi_free(struct ftdi_context *ftdi)
212{
213 ftdi_deinit(ftdi);
214 free(ftdi);
215}
216
217/**
1941414d
TJ
218 Use an already open libusb device.
219
220 \param ftdi pointer to ftdi_context
221 \param usb libusb usb_dev_handle to use
4837f98a 222*/
a8f46ddc
TJ
223void ftdi_set_usbdev (struct ftdi_context *ftdi, usb_dev_handle *usb)
224{
98452d97
TJ
225 ftdi->usb_dev = usb;
226}
227
228
1941414d
TJ
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
edb82cbf 237
1941414d
TJ
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
edb82cbf 242*/
d2f10023 243int ftdi_usb_find_all(struct ftdi_context *ftdi, struct ftdi_device_list **devlist, int vendor, int product)
edb82cbf
TJ
244{
245 struct ftdi_device_list **curdev;
246 struct usb_bus *bus;
247 struct usb_device *dev;
248 int count = 0;
d2f10023 249
edb82cbf
TJ
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;
6db32169 257 *curdev = NULL;
22d12cda
TJ
258 for (bus = usb_get_busses(); bus; bus = bus->next)
259 {
260 for (dev = bus->devices; dev; dev = dev->next)
261 {
edb82cbf
TJ
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");
d2f10023 268
edb82cbf
TJ
269 (*curdev)->next = NULL;
270 (*curdev)->dev = dev;
271
272 curdev = &(*curdev)->next;
273 count++;
274 }
275 }
276 }
d2f10023 277
edb82cbf
TJ
278 return count;
279}
280
1941414d
TJ
281/**
282 Frees a usb device list.
edb82cbf 283
1941414d 284 \param devlist USB device list created by ftdi_usb_find_all()
edb82cbf 285*/
d2f10023 286void ftdi_list_free(struct ftdi_device_list **devlist)
edb82cbf 287{
6db32169
TJ
288 struct ftdi_device_list *curdev, *next;
289
22d12cda
TJ
290 for (curdev = *devlist; curdev != NULL;)
291 {
6db32169
TJ
292 next = curdev->next;
293 free(curdev);
294 curdev = next;
edb82cbf
TJ
295 }
296
6db32169 297 *devlist = NULL;
edb82cbf
TJ
298}
299
1941414d 300/**
cef378aa
TJ
301 Frees a usb device list.
302
303 \param devlist USB device list created by ftdi_usb_find_all()
304*/
305void ftdi_list_free2(struct ftdi_device_list *devlist)
306{
307 ftdi_list_free(&devlist);
308}
309
310/**
474786c0
TJ
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
898c34dd
TJ
316 \note Use this function only in combination with ftdi_usb_find_all()
317 as it closes the internal "usb_dev" after use.
318
474786c0
TJ
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*/
336int ftdi_usb_get_strings(struct ftdi_context * ftdi, struct usb_device * dev,
22d12cda 337 char * manufacturer, int mnf_len, char * description, int desc_len, char * serial, int serial_len)
474786c0
TJ
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
22d12cda
TJ
345 if (manufacturer != NULL)
346 {
347 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iManufacturer, manufacturer, mnf_len) <= 0)
348 {
dff4fdb0 349 usb_close_intl (ftdi);
474786c0
TJ
350 ftdi_error_return(-7, usb_strerror());
351 }
352 }
353
22d12cda
TJ
354 if (description != NULL)
355 {
356 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iProduct, description, desc_len) <= 0)
357 {
dff4fdb0 358 usb_close_intl (ftdi);
474786c0
TJ
359 ftdi_error_return(-8, usb_strerror());
360 }
361 }
362
22d12cda
TJ
363 if (serial != NULL)
364 {
365 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iSerialNumber, serial, serial_len) <= 0)
366 {
dff4fdb0 367 usb_close_intl (ftdi);
474786c0
TJ
368 ftdi_error_return(-9, usb_strerror());
369 }
370 }
371
dff4fdb0 372 if (usb_close_intl (ftdi) != 0)
474786c0
TJ
373 ftdi_error_return(-10, usb_strerror());
374
375 return 0;
376}
377
378/**
1941414d 379 Opens a ftdi device given by a usb_device.
7b18bef6 380
1941414d
TJ
381 \param ftdi pointer to ftdi_context
382 \param dev libusb usb_dev to use
383
384 \retval 0: all fine
23b1798d 385 \retval -3: unable to config device
1941414d
TJ
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
7b18bef6
TJ
390*/
391int ftdi_usb_open_dev(struct ftdi_context *ftdi, struct usb_device *dev)
392{
d2f10023 393 int detach_errno = 0;
7b18bef6
TJ
394 if (!(ftdi->usb_dev = usb_open(dev)))
395 ftdi_error_return(-4, "usb_open() failed");
d2f10023
TJ
396
397#ifdef LIBUSB_HAS_GET_DRIVER_NP
22592e17
TJ
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.
d2f10023
TJ
405 if (usb_detach_kernel_driver_np(ftdi->usb_dev, ftdi->interface) != 0 && errno != ENODATA)
406 detach_errno = errno;
407#endif
408
b57aedfd
GE
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)
22d12cda
TJ
412 if (dev->descriptor.bNumConfigurations > 0 &&
413 usb_set_configuration(ftdi->usb_dev, dev->config[0].bConfigurationValue) &&
414 errno != EBUSY)
b57aedfd 415 {
dff4fdb0 416 usb_close_intl (ftdi);
22d12cda
TJ
417 if (detach_errno == EPERM)
418 {
23b1798d 419 ftdi_error_return(-8, "inappropriate permissions on device!");
22d12cda
TJ
420 }
421 else
422 {
23b1798d
TJ
423 ftdi_error_return(-3, "unable to set usb configuration. Make sure ftdi_sio is unloaded!");
424 }
425 }
426
22d12cda
TJ
427 if (usb_claim_interface(ftdi->usb_dev, ftdi->interface) != 0)
428 {
dff4fdb0 429 usb_close_intl (ftdi);
22d12cda
TJ
430 if (detach_errno == EPERM)
431 {
d2f10023 432 ftdi_error_return(-8, "inappropriate permissions on device!");
22d12cda
TJ
433 }
434 else
435 {
d2f10023
TJ
436 ftdi_error_return(-5, "unable to claim usb device. Make sure ftdi_sio is unloaded!");
437 }
7b18bef6
TJ
438 }
439
22d12cda
TJ
440 if (ftdi_usb_reset (ftdi) != 0)
441 {
dff4fdb0 442 usb_close_intl (ftdi);
7b18bef6
TJ
443 ftdi_error_return(-6, "ftdi_usb_reset failed");
444 }
445
22d12cda
TJ
446 if (ftdi_set_baudrate (ftdi, 9600) != 0)
447 {
dff4fdb0 448 usb_close_intl (ftdi);
7b18bef6
TJ
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;
22d12cda 459 else if (dev->descriptor.bcdDevice == 0x500)
7b18bef6 460 ftdi->type = TYPE_2232C;
22d12cda 461 else if (dev->descriptor.bcdDevice == 0x600)
cb6250fa 462 ftdi->type = TYPE_R;
0beb9686
TJ
463 else if (dev->descriptor.bcdDevice == 0x700)
464 ftdi->type = TYPE_2232H;
465 else if (dev->descriptor.bcdDevice == 0x800)
466 ftdi->type = TYPE_4232H;
7b18bef6 467
f9d69895
AH
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
7b18bef6
TJ
481 ftdi_error_return(0, "all fine");
482}
483
1941414d
TJ
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
9bec2387 491 \retval same as ftdi_usb_open_desc()
1941414d 492*/
edb82cbf
TJ
493int 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
1941414d
TJ
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
a3da1d95 519*/
04e1ea0a 520int ftdi_usb_open_desc(struct ftdi_context *ftdi, int vendor, int product,
a8f46ddc
TJ
521 const char* description, const char* serial)
522{
98452d97
TJ
523 struct usb_bus *bus;
524 struct usb_device *dev;
c3d95b87 525 char string[256];
98452d97
TJ
526
527 usb_init();
528
c3d95b87
TJ
529 if (usb_find_busses() < 0)
530 ftdi_error_return(-1, "usb_find_busses() failed");
c3d95b87 531 if (usb_find_devices() < 0)
edb82cbf 532 ftdi_error_return(-2, "usb_find_devices() failed");
a3da1d95 533
22d12cda
TJ
534 for (bus = usb_get_busses(); bus; bus = bus->next)
535 {
536 for (dev = bus->devices; dev; dev = dev->next)
537 {
a8f46ddc 538 if (dev->descriptor.idVendor == vendor
22d12cda
TJ
539 && dev->descriptor.idProduct == product)
540 {
c3d95b87
TJ
541 if (!(ftdi->usb_dev = usb_open(dev)))
542 ftdi_error_return(-4, "usb_open() failed");
543
22d12cda
TJ
544 if (description != NULL)
545 {
546 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iProduct, string, sizeof(string)) <= 0)
547 {
dff4fdb0 548 usb_close_intl (ftdi);
c3d95b87 549 ftdi_error_return(-8, "unable to fetch product description");
98452d97 550 }
22d12cda
TJ
551 if (strncmp(string, description, sizeof(string)) != 0)
552 {
dff4fdb0 553 if (usb_close_intl (ftdi) != 0)
edb82cbf 554 ftdi_error_return(-10, "unable to close device");
a8f46ddc
TJ
555 continue;
556 }
557 }
22d12cda
TJ
558 if (serial != NULL)
559 {
560 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iSerialNumber, string, sizeof(string)) <= 0)
561 {
dff4fdb0 562 usb_close_intl (ftdi);
c3d95b87 563 ftdi_error_return(-9, "unable to fetch serial number");
a8f46ddc 564 }
22d12cda
TJ
565 if (strncmp(string, serial, sizeof(string)) != 0)
566 {
dff4fdb0 567 if (usb_close_intl (ftdi) != 0)
edb82cbf 568 ftdi_error_return(-10, "unable to close device");
a8f46ddc
TJ
569 continue;
570 }
571 }
98452d97 572
dff4fdb0 573 if (usb_close_intl (ftdi) != 0)
edb82cbf 574 ftdi_error_return(-10, "unable to close device");
d2f10023 575
edb82cbf 576 return ftdi_usb_open_dev(ftdi, dev);
98452d97
TJ
577 }
578 }
98452d97 579 }
a3da1d95 580
98452d97 581 // device not found
c3d95b87 582 ftdi_error_return(-3, "device not found");
a3da1d95
GE
583}
584
1941414d
TJ
585/**
586 Resets the ftdi device.
a3da1d95 587
1941414d
TJ
588 \param ftdi pointer to ftdi_context
589
590 \retval 0: all fine
591 \retval -1: FTDI reset failed
4837f98a 592*/
edb82cbf 593int ftdi_usb_reset(struct ftdi_context *ftdi)
a8f46ddc 594{
a5e1bd8c
MK
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)
22d12cda 598 ftdi_error_return(-1,"FTDI reset failed");
c3d95b87 599
545820ce 600 // Invalidate data in the readbuffer
bfcee05b
TJ
601 ftdi->readbuffer_offset = 0;
602 ftdi->readbuffer_remaining = 0;
603
a3da1d95
GE
604 return 0;
605}
606
1941414d 607/**
1189b11a 608 Clears the read buffer on the chip and the internal read buffer.
1941414d
TJ
609
610 \param ftdi pointer to ftdi_context
4837f98a 611
1941414d 612 \retval 0: all fine
1189b11a 613 \retval -1: read buffer purge failed
4837f98a 614*/
1189b11a 615int ftdi_usb_purge_rx_buffer(struct ftdi_context *ftdi)
a8f46ddc 616{
22d12cda
TJ
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)
c3d95b87
TJ
620 ftdi_error_return(-1, "FTDI purge of RX buffer failed");
621
545820ce 622 // Invalidate data in the readbuffer
bfcee05b
TJ
623 ftdi->readbuffer_offset = 0;
624 ftdi->readbuffer_remaining = 0;
a60be878 625
1189b11a
TJ
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*/
637int ftdi_usb_purge_tx_buffer(struct ftdi_context *ftdi)
638{
22d12cda
TJ
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)
1189b11a
TJ
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*/
656int ftdi_usb_purge_buffers(struct ftdi_context *ftdi)
657{
658 int result;
659
660 result = ftdi_usb_purge_rx_buffer(ftdi);
5a2b51cb 661 if (result < 0)
1189b11a
TJ
662 return -1;
663
664 result = ftdi_usb_purge_tx_buffer(ftdi);
5a2b51cb 665 if (result < 0)
1189b11a 666 return -2;
545820ce 667
a60be878
TJ
668 return 0;
669}
a3da1d95 670
1941414d
TJ
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
a3da1d95 679*/
a8f46ddc
TJ
680int ftdi_usb_close(struct ftdi_context *ftdi)
681{
a3da1d95
GE
682 int rtn = 0;
683
f01d7ca6 684#ifdef LIBFTDI_LINUX_ASYNC_MODE
7cc9950e
GE
685 /* try to release some kernel resources */
686 ftdi_async_complete(ftdi,1);
f01d7ca6 687#endif
7cc9950e 688
dff4fdb0
NF
689 if (ftdi->usb_dev != NULL)
690 if (usb_release_interface(ftdi->usb_dev, ftdi->interface) != 0)
691 rtn = -1;
98452d97 692
dff4fdb0 693 if (usb_close_intl (ftdi)!= 0)
a3da1d95 694 rtn = -2;
98452d97 695
a3da1d95
GE
696 return rtn;
697}
698
a3da1d95 699/*
53ad271d
TJ
700 ftdi_convert_baudrate returns nearest supported baud rate to that requested.
701 Function is only used internally
b5ec1820 702 \internal
53ad271d 703*/
0126d22e 704static int ftdi_convert_baudrate(int baudrate, struct ftdi_context *ftdi,
a8f46ddc
TJ
705 unsigned short *value, unsigned short *index)
706{
53ad271d
TJ
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
22d12cda
TJ
714 if (baudrate <= 0)
715 {
53ad271d
TJ
716 // Return error
717 return -1;
718 }
719
720 divisor = 24000000 / baudrate;
721
22d12cda
TJ
722 if (ftdi->type == TYPE_AM)
723 {
53ad271d
TJ
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;
22d12cda
TJ
732 for (i = 0; i < 2; i++)
733 {
53ad271d
TJ
734 int try_divisor = divisor + i;
735 int baud_estimate;
736 int baud_diff;
737
738 // Round up to supported divisor value
22d12cda
TJ
739 if (try_divisor <= 8)
740 {
53ad271d
TJ
741 // Round up to minimum supported divisor
742 try_divisor = 8;
22d12cda
TJ
743 }
744 else if (ftdi->type != TYPE_AM && try_divisor < 12)
745 {
53ad271d
TJ
746 // BM doesn't support divisors 9 through 11 inclusive
747 try_divisor = 12;
22d12cda
TJ
748 }
749 else if (divisor < 16)
750 {
53ad271d
TJ
751 // AM doesn't support divisors 9 through 15 inclusive
752 try_divisor = 16;
22d12cda
TJ
753 }
754 else
755 {
756 if (ftdi->type == TYPE_AM)
757 {
53ad271d
TJ
758 // Round up to supported fraction (AM only)
759 try_divisor += am_adjust_up[try_divisor & 7];
22d12cda
TJ
760 if (try_divisor > 0x1FFF8)
761 {
53ad271d
TJ
762 // Round down to maximum supported divisor value (for AM)
763 try_divisor = 0x1FFF8;
764 }
22d12cda
TJ
765 }
766 else
767 {
768 if (try_divisor > 0x1FFFF)
769 {
53ad271d
TJ
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
22d12cda
TJ
778 if (baud_estimate < baudrate)
779 {
53ad271d 780 baud_diff = baudrate - baud_estimate;
22d12cda
TJ
781 }
782 else
783 {
53ad271d
TJ
784 baud_diff = baud_estimate - baudrate;
785 }
22d12cda
TJ
786 if (i == 0 || baud_diff < best_baud_diff)
787 {
53ad271d
TJ
788 // Closest to requested baud rate so far
789 best_divisor = try_divisor;
790 best_baud = baud_estimate;
791 best_baud_diff = baud_diff;
22d12cda
TJ
792 if (baud_diff == 0)
793 {
53ad271d
TJ
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
22d12cda
TJ
802 if (encoded_divisor == 1)
803 {
4837f98a 804 encoded_divisor = 0; // 3000000 baud
22d12cda
TJ
805 }
806 else if (encoded_divisor == 0x4001)
807 {
4837f98a 808 encoded_divisor = 1; // 2000000 baud (BM only)
53ad271d
TJ
809 }
810 // Split into "value" and "index" values
811 *value = (unsigned short)(encoded_divisor & 0xFFFF);
22d12cda
TJ
812 if (ftdi->type == TYPE_2232C)
813 {
0126d22e
TJ
814 *index = (unsigned short)(encoded_divisor >> 8);
815 *index &= 0xFF00;
a9c57c05 816 *index |= ftdi->index;
0126d22e
TJ
817 }
818 else
819 *index = (unsigned short)(encoded_divisor >> 16);
c3d95b87 820
53ad271d
TJ
821 // Return the nearest baud rate
822 return best_baud;
823}
824
1941414d 825/**
9bec2387 826 Sets the chip baud rate
1941414d
TJ
827
828 \param ftdi pointer to ftdi_context
9bec2387 829 \param baudrate baud rate to set
1941414d
TJ
830
831 \retval 0: all fine
832 \retval -1: invalid baudrate
833 \retval -2: setting baudrate failed
a3da1d95 834*/
a8f46ddc
TJ
835int ftdi_set_baudrate(struct ftdi_context *ftdi, int baudrate)
836{
53ad271d
TJ
837 unsigned short value, index;
838 int actual_baudrate;
a3da1d95 839
22d12cda
TJ
840 if (ftdi->bitbang_enabled)
841 {
a3da1d95
GE
842 baudrate = baudrate*4;
843 }
844
25707904 845 actual_baudrate = ftdi_convert_baudrate(baudrate, ftdi, &value, &index);
c3d95b87
TJ
846 if (actual_baudrate <= 0)
847 ftdi_error_return (-1, "Silly baudrate <= 0.");
a3da1d95 848
53ad271d
TJ
849 // Check within tolerance (about 5%)
850 if ((actual_baudrate * 2 < baudrate /* Catch overflows */ )
851 || ((actual_baudrate < baudrate)
852 ? (actual_baudrate * 21 < baudrate * 20)
c3d95b87
TJ
853 : (baudrate * 21 < actual_baudrate * 20)))
854 ftdi_error_return (-1, "Unsupported baudrate. Note: bitbang baudrates are automatically multiplied by 4");
545820ce 855
a5e1bd8c 856 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
9ecfef2a
TJ
857 SIO_SET_BAUDRATE_REQUEST, value,
858 index, NULL, 0, ftdi->usb_write_timeout) != 0)
c3d95b87 859 ftdi_error_return (-2, "Setting new baudrate failed");
a3da1d95
GE
860
861 ftdi->baudrate = baudrate;
862 return 0;
863}
864
1941414d 865/**
6c32e222
TJ
866 Set (RS232) line characteristics.
867 The break type can only be set via ftdi_set_line_property2()
868 and defaults to "off".
4837f98a 869
1941414d
TJ
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
2f73e59f
TJ
877*/
878int ftdi_set_line_property(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
d2f10023 879 enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity)
2f73e59f 880{
6c32e222
TJ
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*/
896int ftdi_set_line_property2(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
22d12cda
TJ
897 enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity,
898 enum ftdi_break_type break_type)
6c32e222 899{
2f73e59f
TJ
900 unsigned short value = bits;
901
22d12cda
TJ
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;
2f73e59f 919 }
d2f10023 920
22d12cda
TJ
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;
2f73e59f 932 }
d2f10023 933
22d12cda
TJ
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;
6c32e222
TJ
942 }
943
a5e1bd8c 944 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
9ecfef2a
TJ
945 SIO_SET_DATA_REQUEST, value,
946 ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
2f73e59f 947 ftdi_error_return (-1, "Setting new line property failed");
d2f10023 948
2f73e59f
TJ
949 return 0;
950}
a3da1d95 951
1941414d
TJ
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*/
a8f46ddc
TJ
962int ftdi_write_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
963{
a3da1d95
GE
964 int ret;
965 int offset = 0;
545820ce 966 int total_written = 0;
c3d95b87 967
22d12cda
TJ
968 while (offset < size)
969 {
948f9ada 970 int write_size = ftdi->writebuffer_chunksize;
a3da1d95
GE
971
972 if (offset+write_size > size)
973 write_size = size-offset;
974
98452d97 975 ret = usb_bulk_write(ftdi->usb_dev, ftdi->in_ep, buf+offset, write_size, ftdi->usb_write_timeout);
c3d95b87
TJ
976 if (ret < 0)
977 ftdi_error_return(ret, "usb bulk write failed");
a3da1d95 978
c3d95b87 979 total_written += ret;
a3da1d95
GE
980 offset += write_size;
981 }
982
545820ce 983 return total_written;
a3da1d95
GE
984}
985
f01d7ca6 986#ifdef LIBFTDI_LINUX_ASYNC_MODE
4c9e3812
GE
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) */
22d12cda
TJ
989struct usb_dev_handle
990{
991 int fd;
992 // some other stuff coming here we don't need
4c9e3812
GE
993};
994
84f85aaa 995/**
c201f80f
TJ
996 Check for pending async urbs
997 \internal
998*/
999static int _usb_get_async_urbs_pending(struct ftdi_context *ftdi)
7cc9950e
GE
1000{
1001 struct usbdevfs_urb *urb;
1002 int pending=0;
bf35baa0 1003 unsigned int i;
7cc9950e 1004
22d12cda
TJ
1005 for (i=0; i < ftdi->async_usb_buffer_size; i++)
1006 {
7cc9950e
GE
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
84f85aaa
GE
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
c201f80f
TJ
1023 \internal
1024*/
1025static void _usb_async_cleanup(struct ftdi_context *ftdi, int wait_for_more, int timeout_msec)
7cc9950e 1026{
22d12cda
TJ
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
7cc9950e 1041 {
22d12cda
TJ
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 }
7cc9950e 1052
22d12cda
TJ
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;
7cc9950e 1061
22d12cda
TJ
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 }
7cc9950e 1071 }
22d12cda 1072 while (keep_going);
7cc9950e
GE
1073}
1074
1075/**
84f85aaa
GE
1076 Wait until one or more async URBs are completed by the kernel and mark their
1077 positions in the async-buffer as unused.
7cc9950e
GE
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*/
1082void ftdi_async_complete(struct ftdi_context *ftdi, int wait_for_more)
1083{
22d12cda 1084 _usb_async_cleanup(ftdi,wait_for_more,ftdi->usb_write_timeout);
7cc9950e 1085}
4c9e3812
GE
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.
c201f80f 1090 \internal
4c9e3812 1091*/
c201f80f 1092static int _usb_bulk_write_async(struct ftdi_context *ftdi, int ep, char *bytes, int size)
4c9e3812 1093{
22d12cda
TJ
1094 struct usbdevfs_urb *urb;
1095 int bytesdone = 0, requested;
bf35baa0
TJ
1096 int ret, cleanup_count;
1097 unsigned int i;
22d12cda
TJ
1098
1099 do
7cc9950e 1100 {
22d12cda
TJ
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 }
7cc9950e 1110
22d12cda
TJ
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 }
7cc9950e 1118 }
7cc9950e 1119
22d12cda
TJ
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;
4c9e3812 1127
22d12cda
TJ
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;
4c9e3812
GE
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.
cef378aa 1163 Only available if compiled with --with-async-mode.
4c9e3812
GE
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*/
1172int 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
22d12cda
TJ
1178 while (offset < size)
1179 {
4c9e3812
GE
1180 int write_size = ftdi->writebuffer_chunksize;
1181
1182 if (offset+write_size > size)
1183 write_size = size-offset;
1184
c201f80f 1185 ret = _usb_bulk_write_async(ftdi, ftdi->in_ep, buf+offset, write_size);
4c9e3812
GE
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}
f01d7ca6 1195#endif // LIBFTDI_LINUX_ASYNC_MODE
4c9e3812 1196
1941414d
TJ
1197/**
1198 Configure write buffer chunk size.
1199 Default is 4096.
1200
1201 \param ftdi pointer to ftdi_context
1202 \param chunksize Chunk size
a3da1d95 1203
1941414d
TJ
1204 \retval 0: all fine
1205*/
a8f46ddc
TJ
1206int ftdi_write_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
1207{
948f9ada
TJ
1208 ftdi->writebuffer_chunksize = chunksize;
1209 return 0;
1210}
1211
1941414d
TJ
1212/**
1213 Get write buffer chunk size.
1214
1215 \param ftdi pointer to ftdi_context
1216 \param chunksize Pointer to store chunk size in
948f9ada 1217
1941414d
TJ
1218 \retval 0: all fine
1219*/
a8f46ddc
TJ
1220int ftdi_write_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
1221{
948f9ada
TJ
1222 *chunksize = ftdi->writebuffer_chunksize;
1223 return 0;
1224}
cbabb7d3 1225
1941414d
TJ
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.
948f9ada 1230
1941414d
TJ
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()
d77b0e94 1236 \retval 0: no data was available
1941414d
TJ
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*/
a8f46ddc
TJ
1242int ftdi_read_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
1243{
1c733d33 1244 int offset = 0, ret = 1, i, num_of_chunks, chunk_remains;
f2f00cb5
DC
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;
d9f0cce7 1252
948f9ada 1253 // everything we want is still in the readbuffer?
22d12cda
TJ
1254 if (size <= ftdi->readbuffer_remaining)
1255 {
d9f0cce7
TJ
1256 memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);
1257
1258 // Fix offsets
1259 ftdi->readbuffer_remaining -= size;
1260 ftdi->readbuffer_offset += size;
1261
545820ce 1262 /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */
d9f0cce7
TJ
1263
1264 return size;
979a145c 1265 }
948f9ada 1266 // something still in the readbuffer, but not enough to satisfy 'size'?
22d12cda
TJ
1267 if (ftdi->readbuffer_remaining != 0)
1268 {
d9f0cce7 1269 memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);
979a145c 1270
d9f0cce7
TJ
1271 // Fix offset
1272 offset += ftdi->readbuffer_remaining;
948f9ada 1273 }
948f9ada 1274 // do the actual USB read
22d12cda
TJ
1275 while (offset < size && ret > 0)
1276 {
d9f0cce7
TJ
1277 ftdi->readbuffer_remaining = 0;
1278 ftdi->readbuffer_offset = 0;
98452d97
TJ
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);
c3d95b87
TJ
1281 if (ret < 0)
1282 ftdi_error_return(ret, "usb bulk read failed");
98452d97 1283
22d12cda
TJ
1284 if (ret > 2)
1285 {
d9f0cce7
TJ
1286 // skip FTDI status bytes.
1287 // Maybe stored in the future to enable modem use
f2f00cb5
DC
1288 num_of_chunks = ret / packet_size;
1289 chunk_remains = ret % packet_size;
1c733d33
TJ
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
d9f0cce7
TJ
1292 ftdi->readbuffer_offset += 2;
1293 ret -= 2;
1c733d33 1294
f2f00cb5 1295 if (ret > packet_size - 2)
22d12cda 1296 {
1c733d33 1297 for (i = 1; i < num_of_chunks; i++)
f2f00cb5
DC
1298 memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1299 ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1300 packet_size - 2);
22d12cda
TJ
1301 if (chunk_remains > 2)
1302 {
f2f00cb5
DC
1303 memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1304 ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1c733d33
TJ
1305 chunk_remains-2);
1306 ret -= 2*num_of_chunks;
22d12cda
TJ
1307 }
1308 else
1c733d33
TJ
1309 ret -= 2*(num_of_chunks-1)+chunk_remains;
1310 }
22d12cda
TJ
1311 }
1312 else if (ret <= 2)
1313 {
d9f0cce7
TJ
1314 // no more data to read?
1315 return offset;
1316 }
22d12cda
TJ
1317 if (ret > 0)
1318 {
d9f0cce7 1319 // data still fits in buf?
22d12cda
TJ
1320 if (offset+ret <= size)
1321 {
d9f0cce7 1322 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, ret);
545820ce 1323 //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
d9f0cce7
TJ
1324 offset += ret;
1325
53ad271d 1326 /* Did we read exactly the right amount of bytes? */
d9f0cce7 1327 if (offset == size)
c4446c36
TJ
1328 //printf("read_data exact rem %d offset %d\n",
1329 //ftdi->readbuffer_remaining, offset);
d9f0cce7 1330 return offset;
22d12cda
TJ
1331 }
1332 else
1333 {
d9f0cce7
TJ
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);
98452d97 1337
d9f0cce7
TJ
1338 ftdi->readbuffer_offset += part_size;
1339 ftdi->readbuffer_remaining = ret-part_size;
1340 offset += part_size;
1341
53ad271d
TJ
1342 /* printf("Returning part: %d - size: %d - offset: %d - ret: %d - remaining: %d\n",
1343 part_size, size, offset, ret, ftdi->readbuffer_remaining); */
d9f0cce7
TJ
1344
1345 return offset;
1346 }
1347 }
cbabb7d3 1348 }
948f9ada 1349 // never reached
29c4af7f 1350 return -127;
a3da1d95
GE
1351}
1352
1941414d
TJ
1353/**
1354 Configure read buffer chunk size.
1355 Default is 4096.
1356
1357 Automatically reallocates the buffer.
a3da1d95 1358
1941414d
TJ
1359 \param ftdi pointer to ftdi_context
1360 \param chunksize Chunk size
1361
1362 \retval 0: all fine
1363*/
a8f46ddc
TJ
1364int ftdi_read_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
1365{
29c4af7f
TJ
1366 unsigned char *new_buf;
1367
948f9ada
TJ
1368 // Invalidate all remaining data
1369 ftdi->readbuffer_offset = 0;
1370 ftdi->readbuffer_remaining = 0;
1371
c3d95b87
TJ
1372 if ((new_buf = (unsigned char *)realloc(ftdi->readbuffer, chunksize)) == NULL)
1373 ftdi_error_return(-1, "out of memory for readbuffer");
d9f0cce7 1374
948f9ada
TJ
1375 ftdi->readbuffer = new_buf;
1376 ftdi->readbuffer_chunksize = chunksize;
1377
1378 return 0;
1379}
1380
1941414d
TJ
1381/**
1382 Get read buffer chunk size.
948f9ada 1383
1941414d
TJ
1384 \param ftdi pointer to ftdi_context
1385 \param chunksize Pointer to store chunk size in
1386
1387 \retval 0: all fine
1388*/
a8f46ddc
TJ
1389int ftdi_read_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
1390{
948f9ada
TJ
1391 *chunksize = ftdi->readbuffer_chunksize;
1392 return 0;
1393}
1394
1395
1941414d
TJ
1396/**
1397 Enable bitbang mode.
948f9ada 1398
1941414d
TJ
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*/
a8f46ddc
TJ
1408int ftdi_enable_bitbang(struct ftdi_context *ftdi, unsigned char bitmask)
1409{
a3da1d95
GE
1410 unsigned short usb_val;
1411
d9f0cce7 1412 usb_val = bitmask; // low byte: bitmask
3119537f
TJ
1413 /* FT2232C: Set bitbang_mode to 2 to enable SPI */
1414 usb_val |= (ftdi->bitbang_mode << 8);
1415
22d12cda
TJ
1416 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1417 SIO_SET_BITMODE_REQUEST, usb_val, ftdi->index,
a5e1bd8c 1418 NULL, 0, ftdi->usb_write_timeout) != 0)
c3d95b87
TJ
1419 ftdi_error_return(-1, "unable to enter bitbang mode. Perhaps not a BM type chip?");
1420
a3da1d95
GE
1421 ftdi->bitbang_enabled = 1;
1422 return 0;
1423}
1424
1941414d
TJ
1425/**
1426 Disable bitbang mode.
a3da1d95 1427
1941414d
TJ
1428 \param ftdi pointer to ftdi_context
1429
1430 \retval 0: all fine
1431 \retval -1: can't disable bitbang mode
1432*/
a8f46ddc
TJ
1433int ftdi_disable_bitbang(struct ftdi_context *ftdi)
1434{
a5e1bd8c 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)
c3d95b87 1436 ftdi_error_return(-1, "unable to leave bitbang mode. Perhaps not a BM type chip?");
a3da1d95
GE
1437
1438 ftdi->bitbang_enabled = 0;
1439 return 0;
1440}
1441
1941414d
TJ
1442/**
1443 Enable advanced bitbang mode for FT2232C chips.
a3da1d95 1444
1941414d
TJ
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*/
c4446c36
TJ
1453int 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);
a5e1bd8c 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)
c4446c36
TJ
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
1941414d
TJ
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*/
a8f46ddc
TJ
1476int ftdi_read_pins(struct ftdi_context *ftdi, unsigned char *pins)
1477{
a5e1bd8c 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)
c3d95b87 1479 ftdi_error_return(-1, "read pins failed");
a3da1d95 1480
a3da1d95
GE
1481 return 0;
1482}
1483
1941414d
TJ
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.
a3da1d95 1490
1941414d
TJ
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*/
a8f46ddc
TJ
1498int ftdi_set_latency_timer(struct ftdi_context *ftdi, unsigned char latency)
1499{
a3da1d95
GE
1500 unsigned short usb_val;
1501
c3d95b87
TJ
1502 if (latency < 1)
1503 ftdi_error_return(-1, "latency out of range. Only valid for 1-255");
a3da1d95 1504
d79d2e68 1505 usb_val = latency;
a5e1bd8c 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)
c3d95b87
TJ
1507 ftdi_error_return(-2, "unable to set latency timer");
1508
a3da1d95
GE
1509 return 0;
1510}
1511
1941414d
TJ
1512/**
1513 Get latency timer
a3da1d95 1514
1941414d
TJ
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*/
a8f46ddc
TJ
1521int ftdi_get_latency_timer(struct ftdi_context *ftdi, unsigned char *latency)
1522{
a3da1d95 1523 unsigned short usb_val;
a5e1bd8c 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)
c3d95b87 1525 ftdi_error_return(-1, "reading latency timer failed");
a3da1d95
GE
1526
1527 *latency = (unsigned char)usb_val;
1528 return 0;
1529}
1530
1941414d 1531/**
1189b11a
TJ
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*/
1570int ftdi_poll_modem_status(struct ftdi_context *ftdi, unsigned short *status)
1571{
1572 char usb_val[2];
1573
a5e1bd8c 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)
1189b11a
TJ
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
a7fb8440
TJ
1582/**
1583 Set flowcontrol for ftdi chip
1584
1585 \param ftdi pointer to ftdi_context
22d12cda
TJ
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
a7fb8440
TJ
1588
1589 \retval 0: all fine
1590 \retval -1: set flow control failed
1591*/
1592int ftdi_setflowctrl(struct ftdi_context *ftdi, int flowctrl)
1593{
a5e1bd8c 1594 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
9ecfef2a 1595 SIO_SET_FLOW_CTRL_REQUEST, 0, (flowctrl | ftdi->index),
a7fb8440
TJ
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*/
1611int 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
a5e1bd8c 1620 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
9ecfef2a 1621 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
a7fb8440
TJ
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*/
1637int 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
a5e1bd8c 1646 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
9ecfef2a 1647 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
a7fb8440
TJ
1648 NULL, 0, ftdi->usb_write_timeout) != 0)
1649 ftdi_error_return(-1, "set of rts failed");
1650
1651 return 0;
1652}
1653
1189b11a 1654/**
9ecfef2a
TJ
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 */
1664int ftdi_setdtr_rts(struct ftdi_context *ftdi, int dtr, int rts)
1665{
1666 unsigned short usb_val;
1667
1668 if (dtr)
22d12cda 1669 usb_val = SIO_SET_DTR_HIGH;
9ecfef2a 1670 else
22d12cda 1671 usb_val = SIO_SET_DTR_LOW;
9ecfef2a
TJ
1672
1673 if (rts)
22d12cda 1674 usb_val |= SIO_SET_RTS_HIGH;
9ecfef2a 1675 else
22d12cda 1676 usb_val |= SIO_SET_RTS_LOW;
9ecfef2a 1677
a5e1bd8c 1678 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
9ecfef2a
TJ
1679 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
1680 NULL, 0, ftdi->usb_write_timeout) != 0)
22d12cda 1681 ftdi_error_return(-1, "set of rts/dtr failed");
9ecfef2a
TJ
1682
1683 return 0;
1684}
1685
1686/**
1189b11a
TJ
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*/
1696int ftdi_set_event_char(struct ftdi_context *ftdi,
22d12cda 1697 unsigned char eventch, unsigned char enable)
1189b11a
TJ
1698{
1699 unsigned short usb_val;
1700
1701 usb_val = eventch;
1702 if (enable)
1703 usb_val |= 1 << 8;
1704
a5e1bd8c 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)
1189b11a
TJ
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*/
1721int ftdi_set_error_char(struct ftdi_context *ftdi,
22d12cda 1722 unsigned char errorch, unsigned char enable)
1189b11a
TJ
1723{
1724 unsigned short usb_val;
1725
1726 usb_val = errorch;
1727 if (enable)
1728 usb_val |= 1 << 8;
1729
a5e1bd8c 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)
1189b11a
TJ
1731 ftdi_error_return(-1, "setting error character failed");
1732
1733 return 0;
1734}
1735
1736/**
c201f80f
TJ
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*/
1744void ftdi_eeprom_setsize(struct ftdi_context *ftdi, struct ftdi_eeprom *eeprom, int size)
1745{
22d12cda
TJ
1746 ftdi->eeprom_size=size;
1747 eeprom->size=size;
c201f80f
TJ
1748}
1749
1750/**
1941414d 1751 Init eeprom with default values.
a3da1d95 1752
1941414d
TJ
1753 \param eeprom Pointer to ftdi_eeprom
1754*/
a8f46ddc
TJ
1755void ftdi_eeprom_initdefaults(struct ftdi_eeprom *eeprom)
1756{
f396dbad
TJ
1757 eeprom->vendor_id = 0x0403;
1758 eeprom->product_id = 0x6001;
d9f0cce7 1759
b8aa7b35
TJ
1760 eeprom->self_powered = 1;
1761 eeprom->remote_wakeup = 1;
1762 eeprom->BM_type_chip = 1;
d9f0cce7 1763
b8aa7b35
TJ
1764 eeprom->in_is_isochronous = 0;
1765 eeprom->out_is_isochronous = 0;
1766 eeprom->suspend_pull_downs = 0;
d9f0cce7 1767
b8aa7b35
TJ
1768 eeprom->use_serial = 0;
1769 eeprom->change_usb_version = 0;
f396dbad 1770 eeprom->usb_version = 0x0200;
b8aa7b35 1771 eeprom->max_power = 0;
d9f0cce7 1772
b8aa7b35
TJ
1773 eeprom->manufacturer = NULL;
1774 eeprom->product = NULL;
1775 eeprom->serial = NULL;
c201f80f
TJ
1776
1777 eeprom->size = FTDI_DEFAULT_EEPROM_SIZE;
b8aa7b35
TJ
1778}
1779
1941414d
TJ
1780/**
1781 Build binary output from ftdi_eeprom structure.
1782 Output is suitable for ftdi_write_eeprom().
b8aa7b35 1783
1941414d
TJ
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
b8aa7b35 1789*/
a8f46ddc
TJ
1790int ftdi_eeprom_build(struct ftdi_eeprom *eeprom, unsigned char *output)
1791{
b8aa7b35
TJ
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)
d9f0cce7 1798 manufacturer_size = strlen(eeprom->manufacturer);
b8aa7b35 1799 if (eeprom->product != NULL)
d9f0cce7 1800 product_size = strlen(eeprom->product);
b8aa7b35 1801 if (eeprom->serial != NULL)
d9f0cce7 1802 serial_size = strlen(eeprom->serial);
b8aa7b35 1803
c201f80f 1804 size_check = eeprom->size;
d9f0cce7 1805 size_check -= 28; // 28 are always in use (fixed)
c201f80f 1806
22d12cda 1807 // Top half of a 256byte eeprom is used just for strings and checksum
c201f80f
TJ
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
22d12cda 1811 if (eeprom->size>=256)size_check = 120;
b8aa7b35
TJ
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)
d9f0cce7 1818 return (-1);
b8aa7b35
TJ
1819
1820 // empty eeprom
c201f80f 1821 memset (output, 0, eeprom->size);
b8aa7b35
TJ
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;
d9f0cce7 1834
b8aa7b35 1835 if (eeprom->BM_type_chip == 1)
d9f0cce7 1836 output[0x07] = 0x04;
b8aa7b35 1837 else
d9f0cce7 1838 output[0x07] = 0x02;
b8aa7b35
TJ
1839
1840 // Addr 08: Config descriptor
8fae3e8e
TJ
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
5a1dcd55 1845 j = 0x80;
b8aa7b35 1846 if (eeprom->self_powered == 1)
5a1dcd55 1847 j |= 0x40;
b8aa7b35 1848 if (eeprom->remote_wakeup == 1)
5a1dcd55 1849 j |= 0x20;
b8aa7b35
TJ
1850 output[0x08] = j;
1851
1852 // Addr 09: Max power consumption: max power = value * 2 mA
d9f0cce7 1853 output[0x09] = eeprom->max_power;
d9f0cce7 1854
b8aa7b35
TJ
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)
d9f0cce7 1867 j = j | 1;
b8aa7b35 1868 if (eeprom->out_is_isochronous == 1)
d9f0cce7 1869 j = j | 2;
b8aa7b35 1870 if (eeprom->suspend_pull_downs == 1)
d9f0cce7 1871 j = j | 4;
b8aa7b35 1872 if (eeprom->use_serial == 1)
d9f0cce7 1873 j = j | 8;
b8aa7b35 1874 if (eeprom->change_usb_version == 1)
d9f0cce7 1875 j = j | 16;
b8aa7b35 1876 output[0x0A] = j;
d9f0cce7 1877
b8aa7b35
TJ
1878 // Addr 0B: reserved
1879 output[0x0B] = 0x00;
d9f0cce7 1880
b8aa7b35
TJ
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
22d12cda
TJ
1883 if (eeprom->change_usb_version == 1)
1884 {
b8aa7b35 1885 output[0x0C] = eeprom->usb_version;
d9f0cce7 1886 output[0x0D] = eeprom->usb_version >> 8;
b8aa7b35
TJ
1887 }
1888
1889
c201f80f 1890 // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
b8aa7b35
TJ
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
c201f80f 1903 i=0x14;
22d12cda 1904 if (eeprom->size>=256) i = 0x80;
f01d7ca6 1905
c201f80f 1906
22d12cda 1907 // Output manufacturer
c201f80f
TJ
1908 output[0x0E] = i | 0x80; // calculate offset
1909 output[i++] = manufacturer_size*2 + 2;
1910 output[i++] = 0x03; // type: string
22d12cda
TJ
1911 for (j = 0; j < manufacturer_size; j++)
1912 {
d9f0cce7
TJ
1913 output[i] = eeprom->manufacturer[j], i++;
1914 output[i] = 0x00, i++;
b8aa7b35
TJ
1915 }
1916
1917 // Output product name
c201f80f 1918 output[0x10] = i | 0x80; // calculate offset
b8aa7b35
TJ
1919 output[i] = product_size*2 + 2, i++;
1920 output[i] = 0x03, i++;
22d12cda
TJ
1921 for (j = 0; j < product_size; j++)
1922 {
d9f0cce7
TJ
1923 output[i] = eeprom->product[j], i++;
1924 output[i] = 0x00, i++;
b8aa7b35 1925 }
d9f0cce7 1926
b8aa7b35 1927 // Output serial
c201f80f 1928 output[0x12] = i | 0x80; // calculate offset
b8aa7b35
TJ
1929 output[i] = serial_size*2 + 2, i++;
1930 output[i] = 0x03, i++;
22d12cda
TJ
1931 for (j = 0; j < serial_size; j++)
1932 {
d9f0cce7
TJ
1933 output[i] = eeprom->serial[j], i++;
1934 output[i] = 0x00, i++;
b8aa7b35
TJ
1935 }
1936
1937 // calculate checksum
1938 checksum = 0xAAAA;
d9f0cce7 1939
22d12cda
TJ
1940 for (i = 0; i < eeprom->size/2-1; i++)
1941 {
d9f0cce7
TJ
1942 value = output[i*2];
1943 value += output[(i*2)+1] << 8;
b8aa7b35 1944
d9f0cce7
TJ
1945 checksum = value^checksum;
1946 checksum = (checksum << 1) | (checksum >> 15);
b8aa7b35
TJ
1947 }
1948
c201f80f
TJ
1949 output[eeprom->size-2] = checksum;
1950 output[eeprom->size-1] = checksum >> 8;
b8aa7b35 1951
8ed61121 1952 return size_check;
b8aa7b35
TJ
1953}
1954
4af1d1bb
MK
1955/**
1956 Decode binary EEPROM image into an ftdi_eeprom structure.
1957
1958 \param eeprom Pointer to ftdi_eeprom which will be filled in.
1bbaf1ce 1959 \param buf Buffer of \a size bytes of raw eeprom data
4af1d1bb
MK
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*/
49c5ac72 1968int ftdi_eeprom_decode(struct ftdi_eeprom *eeprom, unsigned char *buf, int size)
b56d5a64
MK
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
22d12cda 1979 // Top half of a 256byte eeprom is used just for strings and checksum
b56d5a64
MK
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
22d12cda 1983 if (eeprom->size>=256)size_check = 120;
b56d5a64
MK
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
4af1d1bb 1994 memset(eeprom, 0, sizeof(struct ftdi_eeprom));
b56d5a64
MK
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);
22d12cda 2003
6335545d
TJ
2004 value = buf[0x06] + (buf[0x07]<<8);
2005 switch (value)
22d12cda
TJ
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;
4af1d1bb 2016 }
b56d5a64
MK
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];
b56d5a64
MK
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];
4af1d1bb
MK
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;
b56d5a64 2046
4af1d1bb 2047 // Addr 0B: reserved
b56d5a64
MK
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
22d12cda
TJ
2051 if (eeprom->change_usb_version == 1)
2052 {
2053 eeprom->usb_version = buf[0x0C] + (buf[0x0D] << 8);
b56d5a64
MK
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
22d12cda 2074 // Decode manufacturer
b56d5a64 2075 i = buf[0x0E] & 0x7f; // offset
22d12cda
TJ
2076 for (j=0;j<manufacturer_size-1;j++)
2077 {
2078 eeprom->manufacturer[j] = buf[2*j+i+2];
b56d5a64
MK
2079 }
2080 eeprom->manufacturer[j] = '\0';
2081
2082 // Decode product name
2083 i = buf[0x10] & 0x7f; // offset
22d12cda
TJ
2084 for (j=0;j<product_size-1;j++)
2085 {
2086 eeprom->product[j] = buf[2*j+i+2];
b56d5a64
MK
2087 }
2088 eeprom->product[j] = '\0';
2089
2090 // Decode serial
2091 i = buf[0x12] & 0x7f; // offset
22d12cda
TJ
2092 for (j=0;j<serial_size-1;j++)
2093 {
2094 eeprom->serial[j] = buf[2*j+i+2];
b56d5a64
MK
2095 }
2096 eeprom->serial[j] = '\0';
2097
2098 // verify checksum
2099 checksum = 0xAAAA;
2100
22d12cda
TJ
2101 for (i = 0; i < eeprom_size/2-1; i++)
2102 {
b56d5a64
MK
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
22d12cda
TJ
2112 if (eeprom_checksum != checksum)
2113 {
2114 fprintf(stderr, "Checksum Error: %04x %04x\n", checksum, eeprom_checksum);
2115 return -1;
4af1d1bb
MK
2116 }
2117
2118 return 0;
b56d5a64
MK
2119}
2120
1941414d
TJ
2121/**
2122 Read eeprom
2123
2124 \param ftdi pointer to ftdi_context
2125 \param eeprom Pointer to store eeprom into
b8aa7b35 2126
1941414d
TJ
2127 \retval 0: all fine
2128 \retval -1: read failed
2129*/
a8f46ddc
TJ
2130int ftdi_read_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
2131{
a3da1d95
GE
2132 int i;
2133
22d12cda
TJ
2134 for (i = 0; i < ftdi->eeprom_size/2; i++)
2135 {
a5e1bd8c 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)
c3d95b87 2137 ftdi_error_return(-1, "reading eeprom failed");
a3da1d95
GE
2138 }
2139
2140 return 0;
2141}
2142
cb6250fa
TJ
2143/*
2144 ftdi_read_chipid_shift does the bitshift operation needed for the FTDIChip-ID
2145 Function is only used internally
2146 \internal
2147*/
2148static unsigned char ftdi_read_chipid_shift(unsigned char value)
2149{
2150 return ((value & 1) << 1) |
22d12cda
TJ
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);
cb6250fa
TJ
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*/
2169int ftdi_read_chipid(struct ftdi_context *ftdi, unsigned int *chipid)
2170{
c7eb3112 2171 unsigned int a = 0, b = 0;
cb6250fa 2172
a5e1bd8c 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)
cb6250fa
TJ
2174 {
2175 a = a << 8 | a >> 8;
a5e1bd8c 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)
cb6250fa
TJ
2177 {
2178 b = b << 8 | b >> 8;
5230676f 2179 a = (a << 16) | (b & 0xFFFF);
912d50ca
TJ
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;
cb6250fa 2182 *chipid = a ^ 0xa5f0f7d1;
c7eb3112 2183 return 0;
cb6250fa
TJ
2184 }
2185 }
2186
c7eb3112 2187 ftdi_error_return(-1, "read of FTDIChip-ID failed");
cb6250fa
TJ
2188}
2189
1941414d 2190/**
c201f80f
TJ
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*/
2200int 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
22d12cda
TJ
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);
c201f80f
TJ
2218
2219 return size/2;
2220}
2221
2222/**
1941414d 2223 Write eeprom
a3da1d95 2224
1941414d
TJ
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*/
a8f46ddc
TJ
2231int ftdi_write_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
2232{
ba5329be 2233 unsigned short usb_val, status;
e30da501 2234 int i, ret;
a3da1d95 2235
ba5329be 2236 /* These commands were traced while running MProg */
e30da501
TJ
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;
ba5329be 2243
22d12cda
TJ
2244 for (i = 0; i < ftdi->eeprom_size/2; i++)
2245 {
d9f0cce7
TJ
2246 usb_val = eeprom[i*2];
2247 usb_val += eeprom[(i*2)+1] << 8;
a5e1bd8c 2248 if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
22d12cda 2249 SIO_WRITE_EEPROM_REQUEST, usb_val, i,
a5e1bd8c 2250 NULL, 0, ftdi->usb_write_timeout) != 0)
c3d95b87 2251 ftdi_error_return(-1, "unable to write eeprom");
a3da1d95
GE
2252 }
2253
2254 return 0;
2255}
2256
1941414d
TJ
2257/**
2258 Erase eeprom
a3da1d95 2259
a5e1bd8c
MK
2260 This is not supported on FT232R/FT245R according to the MProg manual from FTDI.
2261
1941414d
TJ
2262 \param ftdi pointer to ftdi_context
2263
2264 \retval 0: all fine
2265 \retval -1: erase failed
2266*/
a8f46ddc
TJ
2267int ftdi_erase_eeprom(struct ftdi_context *ftdi)
2268{
a5e1bd8c 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)
c3d95b87 2270 ftdi_error_return(-1, "unable to erase eeprom");
a3da1d95
GE
2271
2272 return 0;
2273}
c3d95b87 2274
1941414d
TJ
2275/**
2276 Get string representation for last error code
c3d95b87 2277
1941414d
TJ
2278 \param ftdi pointer to ftdi_context
2279
2280 \retval Pointer to error string
2281*/
c3d95b87
TJ
2282char *ftdi_get_error_string (struct ftdi_context *ftdi)
2283{
2284 return ftdi->error_str;
2285}
a01d31e2 2286
b5ec1820 2287/* @} end of doxygen libftdi group */