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