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