libftdi: (tomj) make async code optional
[libftdi] / src / ftdi.c
CommitLineData
a3da1d95
GE
1/***************************************************************************
2 ftdi.c - description
3 -------------------
4 begin : Fri Apr 4 2003
c201f80f 5 copyright : (C) 2003-2008 by Intra2net AG
5fdb1cb1 6 email : opensource@intra2net.com
a3da1d95
GE
7 ***************************************************************************/
8
9/***************************************************************************
10 * *
11 * This program is free software; you can redistribute it and/or modify *
12 * it under the terms of the GNU Lesser General Public License *
13 * version 2.1 as published by the Free Software Foundation; *
14 * *
15 ***************************************************************************/
d9f0cce7 16
b5ec1820
TJ
17/**
18 \mainpage libftdi API documentation
19
ad397a4b 20 Library to talk to FTDI chips. You find the latest versions of libftdi at
b5ec1820
TJ
21 http://www.intra2net.com/de/produkte/opensource/ftdi/
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>
0e302db6 34
98452d97 35#include "ftdi.h"
a3da1d95 36
7cc9950e 37/* stuff needed for async write */
f01d7ca6
TJ
38#ifdef LIBFTDI_LINUX_ASYNC_MODE
39 #include <sys/ioctl.h>
40 #include <sys/time.h>
41 #include <sys/select.h>
42 #include <sys/types.h>
43 #include <unistd.h>
44 #include <linux/usbdevice_fs.h>
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
TJ
51
52
1941414d
TJ
53/**
54 Initializes a ftdi_context.
4837f98a 55
1941414d 56 \param ftdi pointer to ftdi_context
4837f98a 57
1941414d
TJ
58 \retval 0: all fine
59 \retval -1: couldn't allocate read buffer
60
61 \remark This should be called before all functions
948f9ada 62*/
a8f46ddc
TJ
63int ftdi_init(struct ftdi_context *ftdi)
64{
7cc9950e
GE
65 int i;
66
98452d97 67 ftdi->usb_dev = NULL;
545820ce
TJ
68 ftdi->usb_read_timeout = 5000;
69 ftdi->usb_write_timeout = 5000;
a3da1d95 70
53ad271d 71 ftdi->type = TYPE_BM; /* chip type */
a3da1d95
GE
72 ftdi->baudrate = -1;
73 ftdi->bitbang_enabled = 0;
74
948f9ada
TJ
75 ftdi->readbuffer = NULL;
76 ftdi->readbuffer_offset = 0;
77 ftdi->readbuffer_remaining = 0;
78 ftdi->writebuffer_chunksize = 4096;
79
545820ce
TJ
80 ftdi->interface = 0;
81 ftdi->index = 0;
82 ftdi->in_ep = 0x02;
83 ftdi->out_ep = 0x81;
3119537f 84 ftdi->bitbang_mode = 1; /* 1: Normal bitbang mode, 2: SPI bitbang mode */
53ad271d 85
a3da1d95
GE
86 ftdi->error_str = NULL;
87
f01d7ca6 88#ifdef LIBFTDI_LINUX_ASYNC_MODE
7cc9950e
GE
89 ftdi->async_usb_buffer_size=10;
90 if ((ftdi->async_usb_buffer=malloc(sizeof(struct usbdevfs_urb)*ftdi->async_usb_buffer_size)) == NULL)
91 ftdi_error_return(-1, "out of memory for async usb buffer");
92
93 /* initialize async usb buffer with unused-marker */
94 for (i=0; i < ftdi->async_usb_buffer_size; i++)
95 ((struct usbdevfs_urb*)ftdi->async_usb_buffer)[i].usercontext = FTDI_URB_USERCONTEXT_COOKIE;
f01d7ca6
TJ
96#else
97 ftdi->async_usb_buffer_size=0;
98 ftdi->async_usb_buffer = NULL;
99#endif
7cc9950e 100
c201f80f
TJ
101 ftdi->eeprom_size = FTDI_DEFAULT_EEPROM_SIZE;
102
1c733d33
TJ
103 /* All fine. Now allocate the readbuffer */
104 return ftdi_read_data_set_chunksize(ftdi, 4096);
948f9ada 105}
4837f98a 106
1941414d
TJ
107/**
108 Open selected channels on a chip, otherwise use first channel.
109
110 \param ftdi pointer to ftdi_context
111 \param interface Interface to use for FT2232C chips.
112
113 \retval 0: all fine
114 \retval -1: unknown interface
c4446c36 115*/
0ce2f5fa 116int ftdi_set_interface(struct ftdi_context *ftdi, enum ftdi_interface interface)
c4446c36
TJ
117{
118 switch (interface) {
119 case INTERFACE_ANY:
120 case INTERFACE_A:
0ce2f5fa 121 /* ftdi_usb_open_desc cares to set the right index, depending on the found chip */
c4446c36
TJ
122 break;
123 case INTERFACE_B:
124 ftdi->interface = 1;
125 ftdi->index = INTERFACE_B;
126 ftdi->in_ep = 0x04;
127 ftdi->out_ep = 0x83;
128 break;
129 default:
130 ftdi_error_return(-1, "Unknown interface");
131 }
132 return 0;
133}
948f9ada 134
1941414d
TJ
135/**
136 Deinitializes a ftdi_context.
4837f98a 137
1941414d 138 \param ftdi pointer to ftdi_context
4837f98a 139*/
a8f46ddc
TJ
140void ftdi_deinit(struct ftdi_context *ftdi)
141{
7cc9950e
GE
142 if (ftdi->async_usb_buffer != NULL) {
143 free(ftdi->async_usb_buffer);
144 ftdi->async_usb_buffer = NULL;
145 }
146
948f9ada 147 if (ftdi->readbuffer != NULL) {
d9f0cce7
TJ
148 free(ftdi->readbuffer);
149 ftdi->readbuffer = NULL;
948f9ada 150 }
a3da1d95
GE
151}
152
1941414d
TJ
153/**
154 Use an already open libusb device.
155
156 \param ftdi pointer to ftdi_context
157 \param usb libusb usb_dev_handle to use
4837f98a 158*/
a8f46ddc
TJ
159void ftdi_set_usbdev (struct ftdi_context *ftdi, usb_dev_handle *usb)
160{
98452d97
TJ
161 ftdi->usb_dev = usb;
162}
163
164
1941414d
TJ
165/**
166 Finds all ftdi devices on the usb bus. Creates a new ftdi_device_list which
167 needs to be deallocated by ftdi_list_free() after use.
168
169 \param ftdi pointer to ftdi_context
170 \param devlist Pointer where to store list of found devices
171 \param vendor Vendor ID to search for
172 \param product Product ID to search for
edb82cbf 173
1941414d
TJ
174 \retval >0: number of devices found
175 \retval -1: usb_find_busses() failed
176 \retval -2: usb_find_devices() failed
177 \retval -3: out of memory
edb82cbf 178*/
d2f10023 179int ftdi_usb_find_all(struct ftdi_context *ftdi, struct ftdi_device_list **devlist, int vendor, int product)
edb82cbf
TJ
180{
181 struct ftdi_device_list **curdev;
182 struct usb_bus *bus;
183 struct usb_device *dev;
184 int count = 0;
d2f10023 185
edb82cbf
TJ
186 usb_init();
187 if (usb_find_busses() < 0)
188 ftdi_error_return(-1, "usb_find_busses() failed");
189 if (usb_find_devices() < 0)
190 ftdi_error_return(-2, "usb_find_devices() failed");
191
192 curdev = devlist;
6db32169 193 *curdev = NULL;
edb82cbf
TJ
194 for (bus = usb_busses; bus; bus = bus->next) {
195 for (dev = bus->devices; dev; dev = dev->next) {
196 if (dev->descriptor.idVendor == vendor
197 && dev->descriptor.idProduct == product)
198 {
199 *curdev = (struct ftdi_device_list*)malloc(sizeof(struct ftdi_device_list));
200 if (!*curdev)
201 ftdi_error_return(-3, "out of memory");
d2f10023 202
edb82cbf
TJ
203 (*curdev)->next = NULL;
204 (*curdev)->dev = dev;
205
206 curdev = &(*curdev)->next;
207 count++;
208 }
209 }
210 }
d2f10023 211
edb82cbf
TJ
212 return count;
213}
214
1941414d
TJ
215/**
216 Frees a usb device list.
edb82cbf 217
1941414d 218 \param devlist USB device list created by ftdi_usb_find_all()
edb82cbf 219*/
d2f10023 220void ftdi_list_free(struct ftdi_device_list **devlist)
edb82cbf 221{
6db32169
TJ
222 struct ftdi_device_list *curdev, *next;
223
224 for (curdev = *devlist; curdev != NULL;) {
225 next = curdev->next;
226 free(curdev);
227 curdev = next;
edb82cbf
TJ
228 }
229
6db32169 230 *devlist = NULL;
edb82cbf
TJ
231}
232
1941414d 233/**
474786c0
TJ
234 Return device ID strings from the usb device.
235
236 The parameters manufacturer, description and serial may be NULL
237 or pointer to buffers to store the fetched strings.
238
898c34dd
TJ
239 \note Use this function only in combination with ftdi_usb_find_all()
240 as it closes the internal "usb_dev" after use.
241
474786c0
TJ
242 \param ftdi pointer to ftdi_context
243 \param dev libusb usb_dev to use
244 \param manufacturer Store manufacturer string here if not NULL
245 \param mnf_len Buffer size of manufacturer string
246 \param description Store product description string here if not NULL
247 \param desc_len Buffer size of product description string
248 \param serial Store serial string here if not NULL
249 \param serial_len Buffer size of serial string
250
251 \retval 0: all fine
252 \retval -1: wrong arguments
253 \retval -4: unable to open device
254 \retval -7: get product manufacturer failed
255 \retval -8: get product description failed
256 \retval -9: get serial number failed
257 \retval -10: unable to close device
258*/
259int ftdi_usb_get_strings(struct ftdi_context * ftdi, struct usb_device * dev,
260 char * manufacturer, int mnf_len, char * description, int desc_len, char * serial, int serial_len)
261{
262 if ((ftdi==NULL) || (dev==NULL))
263 return -1;
264
265 if (!(ftdi->usb_dev = usb_open(dev)))
266 ftdi_error_return(-4, usb_strerror());
267
268 if (manufacturer != NULL) {
269 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iManufacturer, manufacturer, mnf_len) <= 0) {
270 usb_close (ftdi->usb_dev);
271 ftdi_error_return(-7, usb_strerror());
272 }
273 }
274
275 if (description != NULL) {
276 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iProduct, description, desc_len) <= 0) {
277 usb_close (ftdi->usb_dev);
278 ftdi_error_return(-8, usb_strerror());
279 }
280 }
281
282 if (serial != NULL) {
283 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iSerialNumber, serial, serial_len) <= 0) {
284 usb_close (ftdi->usb_dev);
285 ftdi_error_return(-9, usb_strerror());
286 }
287 }
288
289 if (usb_close (ftdi->usb_dev) != 0)
290 ftdi_error_return(-10, usb_strerror());
291
292 return 0;
293}
294
295/**
1941414d 296 Opens a ftdi device given by a usb_device.
7b18bef6 297
1941414d
TJ
298 \param ftdi pointer to ftdi_context
299 \param dev libusb usb_dev to use
300
301 \retval 0: all fine
302 \retval -4: unable to open device
303 \retval -5: unable to claim device
304 \retval -6: reset failed
305 \retval -7: set baudrate failed
7b18bef6
TJ
306*/
307int ftdi_usb_open_dev(struct ftdi_context *ftdi, struct usb_device *dev)
308{
d2f10023 309 int detach_errno = 0;
7b18bef6
TJ
310 if (!(ftdi->usb_dev = usb_open(dev)))
311 ftdi_error_return(-4, "usb_open() failed");
d2f10023
TJ
312
313#ifdef LIBUSB_HAS_GET_DRIVER_NP
314 // Try to detach ftdi_sio kernel module
315 // Returns ENODATA if driver is not loaded
316 if (usb_detach_kernel_driver_np(ftdi->usb_dev, ftdi->interface) != 0 && errno != ENODATA)
317 detach_errno = errno;
318#endif
319
7b18bef6
TJ
320 if (usb_claim_interface(ftdi->usb_dev, ftdi->interface) != 0) {
321 usb_close (ftdi->usb_dev);
d2f10023
TJ
322 if (detach_errno == EPERM) {
323 ftdi_error_return(-8, "inappropriate permissions on device!");
324 } else {
325 ftdi_error_return(-5, "unable to claim usb device. Make sure ftdi_sio is unloaded!");
326 }
7b18bef6
TJ
327 }
328
329 if (ftdi_usb_reset (ftdi) != 0) {
330 usb_close (ftdi->usb_dev);
331 ftdi_error_return(-6, "ftdi_usb_reset failed");
332 }
333
334 if (ftdi_set_baudrate (ftdi, 9600) != 0) {
335 usb_close (ftdi->usb_dev);
336 ftdi_error_return(-7, "set baudrate failed");
337 }
338
339 // Try to guess chip type
340 // Bug in the BM type chips: bcdDevice is 0x200 for serial == 0
341 if (dev->descriptor.bcdDevice == 0x400 || (dev->descriptor.bcdDevice == 0x200
342 && dev->descriptor.iSerialNumber == 0))
343 ftdi->type = TYPE_BM;
344 else if (dev->descriptor.bcdDevice == 0x200)
345 ftdi->type = TYPE_AM;
346 else if (dev->descriptor.bcdDevice == 0x500) {
347 ftdi->type = TYPE_2232C;
348 if (!ftdi->index)
349 ftdi->index = INTERFACE_A;
cb6250fa
TJ
350 } else if (dev->descriptor.bcdDevice == 0x600)
351 ftdi->type = TYPE_R;
7b18bef6
TJ
352
353 ftdi_error_return(0, "all fine");
354}
355
1941414d
TJ
356/**
357 Opens the first device with a given vendor and product ids.
358
359 \param ftdi pointer to ftdi_context
360 \param vendor Vendor ID
361 \param product Product ID
362
9bec2387 363 \retval same as ftdi_usb_open_desc()
1941414d 364*/
edb82cbf
TJ
365int ftdi_usb_open(struct ftdi_context *ftdi, int vendor, int product)
366{
367 return ftdi_usb_open_desc(ftdi, vendor, product, NULL, NULL);
368}
369
1941414d
TJ
370/**
371 Opens the first device with a given, vendor id, product id,
372 description and serial.
373
374 \param ftdi pointer to ftdi_context
375 \param vendor Vendor ID
376 \param product Product ID
377 \param description Description to search for. Use NULL if not needed.
378 \param serial Serial to search for. Use NULL if not needed.
379
380 \retval 0: all fine
381 \retval -1: usb_find_busses() failed
382 \retval -2: usb_find_devices() failed
383 \retval -3: usb device not found
384 \retval -4: unable to open device
385 \retval -5: unable to claim device
386 \retval -6: reset failed
387 \retval -7: set baudrate failed
388 \retval -8: get product description failed
389 \retval -9: get serial number failed
390 \retval -10: unable to close device
a3da1d95 391*/
04e1ea0a 392int ftdi_usb_open_desc(struct ftdi_context *ftdi, int vendor, int product,
a8f46ddc
TJ
393 const char* description, const char* serial)
394{
98452d97
TJ
395 struct usb_bus *bus;
396 struct usb_device *dev;
c3d95b87 397 char string[256];
98452d97
TJ
398
399 usb_init();
400
c3d95b87
TJ
401 if (usb_find_busses() < 0)
402 ftdi_error_return(-1, "usb_find_busses() failed");
c3d95b87 403 if (usb_find_devices() < 0)
edb82cbf 404 ftdi_error_return(-2, "usb_find_devices() failed");
a3da1d95 405
98452d97
TJ
406 for (bus = usb_busses; bus; bus = bus->next) {
407 for (dev = bus->devices; dev; dev = dev->next) {
a8f46ddc 408 if (dev->descriptor.idVendor == vendor
c3d95b87
TJ
409 && dev->descriptor.idProduct == product) {
410 if (!(ftdi->usb_dev = usb_open(dev)))
411 ftdi_error_return(-4, "usb_open() failed");
412
a8f46ddc
TJ
413 if (description != NULL) {
414 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iProduct, string, sizeof(string)) <= 0) {
c3d95b87
TJ
415 usb_close (ftdi->usb_dev);
416 ftdi_error_return(-8, "unable to fetch product description");
98452d97 417 }
a8f46ddc 418 if (strncmp(string, description, sizeof(string)) != 0) {
edb82cbf
TJ
419 if (usb_close (ftdi->usb_dev) != 0)
420 ftdi_error_return(-10, "unable to close device");
a8f46ddc
TJ
421 continue;
422 }
423 }
424 if (serial != NULL) {
425 if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iSerialNumber, string, sizeof(string)) <= 0) {
c3d95b87
TJ
426 usb_close (ftdi->usb_dev);
427 ftdi_error_return(-9, "unable to fetch serial number");
a8f46ddc
TJ
428 }
429 if (strncmp(string, serial, sizeof(string)) != 0) {
a8f46ddc 430 if (usb_close (ftdi->usb_dev) != 0)
edb82cbf 431 ftdi_error_return(-10, "unable to close device");
a8f46ddc
TJ
432 continue;
433 }
434 }
98452d97 435
edb82cbf
TJ
436 if (usb_close (ftdi->usb_dev) != 0)
437 ftdi_error_return(-10, "unable to close device");
d2f10023 438
edb82cbf 439 return ftdi_usb_open_dev(ftdi, dev);
98452d97
TJ
440 }
441 }
98452d97 442 }
a3da1d95 443
98452d97 444 // device not found
c3d95b87 445 ftdi_error_return(-3, "device not found");
a3da1d95
GE
446}
447
1941414d
TJ
448/**
449 Resets the ftdi device.
a3da1d95 450
1941414d
TJ
451 \param ftdi pointer to ftdi_context
452
453 \retval 0: all fine
454 \retval -1: FTDI reset failed
4837f98a 455*/
edb82cbf 456int ftdi_usb_reset(struct ftdi_context *ftdi)
a8f46ddc 457{
c3d95b87
TJ
458 if (usb_control_msg(ftdi->usb_dev, 0x40, 0, 0, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
459 ftdi_error_return(-1,"FTDI reset failed");
460
545820ce 461 // Invalidate data in the readbuffer
bfcee05b
TJ
462 ftdi->readbuffer_offset = 0;
463 ftdi->readbuffer_remaining = 0;
464
a3da1d95
GE
465 return 0;
466}
467
1941414d
TJ
468/**
469 Clears the buffers on the chip.
470
471 \param ftdi pointer to ftdi_context
4837f98a 472
1941414d
TJ
473 \retval 0: all fine
474 \retval -1: write buffer purge failed
475 \retval -2: read buffer purge failed
4837f98a 476*/
a8f46ddc
TJ
477int ftdi_usb_purge_buffers(struct ftdi_context *ftdi)
478{
c3d95b87
TJ
479 if (usb_control_msg(ftdi->usb_dev, 0x40, 0, 1, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
480 ftdi_error_return(-1, "FTDI purge of RX buffer failed");
481
545820ce 482 // Invalidate data in the readbuffer
bfcee05b
TJ
483 ftdi->readbuffer_offset = 0;
484 ftdi->readbuffer_remaining = 0;
a60be878 485
c3d95b87
TJ
486 if (usb_control_msg(ftdi->usb_dev, 0x40, 0, 2, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
487 ftdi_error_return(-2, "FTDI purge of TX buffer failed");
545820ce 488
a60be878
TJ
489 return 0;
490}
a3da1d95 491
1941414d
TJ
492/**
493 Closes the ftdi device. Call ftdi_deinit() if you're cleaning up.
494
495 \param ftdi pointer to ftdi_context
496
497 \retval 0: all fine
498 \retval -1: usb_release failed
499 \retval -2: usb_close failed
a3da1d95 500*/
a8f46ddc
TJ
501int ftdi_usb_close(struct ftdi_context *ftdi)
502{
a3da1d95
GE
503 int rtn = 0;
504
f01d7ca6 505#ifdef LIBFTDI_LINUX_ASYNC_MODE
7cc9950e
GE
506 /* try to release some kernel resources */
507 ftdi_async_complete(ftdi,1);
f01d7ca6 508#endif
7cc9950e 509
98452d97 510 if (usb_release_interface(ftdi->usb_dev, ftdi->interface) != 0)
a3da1d95 511 rtn = -1;
98452d97
TJ
512
513 if (usb_close (ftdi->usb_dev) != 0)
a3da1d95 514 rtn = -2;
98452d97 515
a3da1d95
GE
516 return rtn;
517}
518
a3da1d95 519/*
53ad271d
TJ
520 ftdi_convert_baudrate returns nearest supported baud rate to that requested.
521 Function is only used internally
b5ec1820 522 \internal
53ad271d 523*/
0126d22e 524static int ftdi_convert_baudrate(int baudrate, struct ftdi_context *ftdi,
a8f46ddc
TJ
525 unsigned short *value, unsigned short *index)
526{
53ad271d
TJ
527 static const char am_adjust_up[8] = {0, 0, 0, 1, 0, 3, 2, 1};
528 static const char am_adjust_dn[8] = {0, 0, 0, 1, 0, 1, 2, 3};
529 static const char frac_code[8] = {0, 3, 2, 4, 1, 5, 6, 7};
530 int divisor, best_divisor, best_baud, best_baud_diff;
531 unsigned long encoded_divisor;
532 int i;
533
534 if (baudrate <= 0) {
535 // Return error
536 return -1;
537 }
538
539 divisor = 24000000 / baudrate;
540
0126d22e 541 if (ftdi->type == TYPE_AM) {
53ad271d
TJ
542 // Round down to supported fraction (AM only)
543 divisor -= am_adjust_dn[divisor & 7];
544 }
545
546 // Try this divisor and the one above it (because division rounds down)
547 best_divisor = 0;
548 best_baud = 0;
549 best_baud_diff = 0;
550 for (i = 0; i < 2; i++) {
551 int try_divisor = divisor + i;
552 int baud_estimate;
553 int baud_diff;
554
555 // Round up to supported divisor value
df612d35 556 if (try_divisor <= 8) {
53ad271d
TJ
557 // Round up to minimum supported divisor
558 try_divisor = 8;
0126d22e 559 } else if (ftdi->type != TYPE_AM && try_divisor < 12) {
53ad271d
TJ
560 // BM doesn't support divisors 9 through 11 inclusive
561 try_divisor = 12;
562 } else if (divisor < 16) {
563 // AM doesn't support divisors 9 through 15 inclusive
564 try_divisor = 16;
565 } else {
0126d22e 566 if (ftdi->type == TYPE_AM) {
53ad271d
TJ
567 // Round up to supported fraction (AM only)
568 try_divisor += am_adjust_up[try_divisor & 7];
569 if (try_divisor > 0x1FFF8) {
570 // Round down to maximum supported divisor value (for AM)
571 try_divisor = 0x1FFF8;
572 }
573 } else {
574 if (try_divisor > 0x1FFFF) {
575 // Round down to maximum supported divisor value (for BM)
576 try_divisor = 0x1FFFF;
577 }
578 }
579 }
580 // Get estimated baud rate (to nearest integer)
581 baud_estimate = (24000000 + (try_divisor / 2)) / try_divisor;
582 // Get absolute difference from requested baud rate
583 if (baud_estimate < baudrate) {
584 baud_diff = baudrate - baud_estimate;
585 } else {
586 baud_diff = baud_estimate - baudrate;
587 }
588 if (i == 0 || baud_diff < best_baud_diff) {
589 // Closest to requested baud rate so far
590 best_divisor = try_divisor;
591 best_baud = baud_estimate;
592 best_baud_diff = baud_diff;
593 if (baud_diff == 0) {
594 // Spot on! No point trying
595 break;
596 }
597 }
598 }
599 // Encode the best divisor value
600 encoded_divisor = (best_divisor >> 3) | (frac_code[best_divisor & 7] << 14);
601 // Deal with special cases for encoded value
602 if (encoded_divisor == 1) {
4837f98a 603 encoded_divisor = 0; // 3000000 baud
53ad271d 604 } else if (encoded_divisor == 0x4001) {
4837f98a 605 encoded_divisor = 1; // 2000000 baud (BM only)
53ad271d
TJ
606 }
607 // Split into "value" and "index" values
608 *value = (unsigned short)(encoded_divisor & 0xFFFF);
de22df10 609 if(ftdi->type == TYPE_2232C) {
0126d22e
TJ
610 *index = (unsigned short)(encoded_divisor >> 8);
611 *index &= 0xFF00;
a9c57c05 612 *index |= ftdi->index;
0126d22e
TJ
613 }
614 else
615 *index = (unsigned short)(encoded_divisor >> 16);
c3d95b87 616
53ad271d
TJ
617 // Return the nearest baud rate
618 return best_baud;
619}
620
1941414d 621/**
9bec2387 622 Sets the chip baud rate
1941414d
TJ
623
624 \param ftdi pointer to ftdi_context
9bec2387 625 \param baudrate baud rate to set
1941414d
TJ
626
627 \retval 0: all fine
628 \retval -1: invalid baudrate
629 \retval -2: setting baudrate failed
a3da1d95 630*/
a8f46ddc
TJ
631int ftdi_set_baudrate(struct ftdi_context *ftdi, int baudrate)
632{
53ad271d
TJ
633 unsigned short value, index;
634 int actual_baudrate;
a3da1d95
GE
635
636 if (ftdi->bitbang_enabled) {
637 baudrate = baudrate*4;
638 }
639
25707904 640 actual_baudrate = ftdi_convert_baudrate(baudrate, ftdi, &value, &index);
c3d95b87
TJ
641 if (actual_baudrate <= 0)
642 ftdi_error_return (-1, "Silly baudrate <= 0.");
a3da1d95 643
53ad271d
TJ
644 // Check within tolerance (about 5%)
645 if ((actual_baudrate * 2 < baudrate /* Catch overflows */ )
646 || ((actual_baudrate < baudrate)
647 ? (actual_baudrate * 21 < baudrate * 20)
c3d95b87
TJ
648 : (baudrate * 21 < actual_baudrate * 20)))
649 ftdi_error_return (-1, "Unsupported baudrate. Note: bitbang baudrates are automatically multiplied by 4");
545820ce 650
c3d95b87
TJ
651 if (usb_control_msg(ftdi->usb_dev, 0x40, 3, value, index, NULL, 0, ftdi->usb_write_timeout) != 0)
652 ftdi_error_return (-2, "Setting new baudrate failed");
a3da1d95
GE
653
654 ftdi->baudrate = baudrate;
655 return 0;
656}
657
1941414d
TJ
658/**
659 Set (RS232) line characteristics by Alain Abbas
4837f98a 660
1941414d
TJ
661 \param ftdi pointer to ftdi_context
662 \param bits Number of bits
663 \param sbit Number of stop bits
664 \param parity Parity mode
665
666 \retval 0: all fine
667 \retval -1: Setting line property failed
2f73e59f
TJ
668*/
669int ftdi_set_line_property(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
d2f10023 670 enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity)
2f73e59f
TJ
671{
672 unsigned short value = bits;
673
674 switch(parity) {
675 case NONE:
676 value |= (0x00 << 8);
677 break;
678 case ODD:
679 value |= (0x01 << 8);
680 break;
681 case EVEN:
682 value |= (0x02 << 8);
683 break;
684 case MARK:
685 value |= (0x03 << 8);
686 break;
687 case SPACE:
688 value |= (0x04 << 8);
689 break;
690 }
d2f10023 691
2f73e59f
TJ
692 switch(sbit) {
693 case STOP_BIT_1:
694 value |= (0x00 << 11);
695 break;
696 case STOP_BIT_15:
697 value |= (0x01 << 11);
698 break;
699 case STOP_BIT_2:
700 value |= (0x02 << 11);
701 break;
702 }
d2f10023 703
2f73e59f
TJ
704 if (usb_control_msg(ftdi->usb_dev, 0x40, 0x04, value, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
705 ftdi_error_return (-1, "Setting new line property failed");
d2f10023 706
2f73e59f
TJ
707 return 0;
708}
a3da1d95 709
1941414d
TJ
710/**
711 Writes data in chunks (see ftdi_write_data_set_chunksize()) to the chip
712
713 \param ftdi pointer to ftdi_context
714 \param buf Buffer with the data
715 \param size Size of the buffer
716
717 \retval <0: error code from usb_bulk_write()
718 \retval >0: number of bytes written
719*/
a8f46ddc
TJ
720int ftdi_write_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
721{
a3da1d95
GE
722 int ret;
723 int offset = 0;
545820ce 724 int total_written = 0;
c3d95b87 725
a3da1d95 726 while (offset < size) {
948f9ada 727 int write_size = ftdi->writebuffer_chunksize;
a3da1d95
GE
728
729 if (offset+write_size > size)
730 write_size = size-offset;
731
98452d97 732 ret = usb_bulk_write(ftdi->usb_dev, ftdi->in_ep, buf+offset, write_size, ftdi->usb_write_timeout);
c3d95b87
TJ
733 if (ret < 0)
734 ftdi_error_return(ret, "usb bulk write failed");
a3da1d95 735
c3d95b87 736 total_written += ret;
a3da1d95
GE
737 offset += write_size;
738 }
739
545820ce 740 return total_written;
a3da1d95
GE
741}
742
f01d7ca6 743#ifdef LIBFTDI_LINUX_ASYNC_MODE
4c9e3812
GE
744/* this is strongly dependent on libusb using the same struct layout. If libusb
745 changes in some later version this may break horribly (this is for libusb 0.1.12) */
746struct usb_dev_handle {
747 int fd;
748 // some other stuff coming here we don't need
749};
750
84f85aaa 751/**
c201f80f
TJ
752 Check for pending async urbs
753 \internal
754*/
755static int _usb_get_async_urbs_pending(struct ftdi_context *ftdi)
7cc9950e
GE
756{
757 struct usbdevfs_urb *urb;
758 int pending=0;
759 int i;
760
761 for (i=0; i < ftdi->async_usb_buffer_size; i++) {
762 urb=&((struct usbdevfs_urb *)(ftdi->async_usb_buffer))[i];
763 if (urb->usercontext != FTDI_URB_USERCONTEXT_COOKIE)
764 pending++;
765 }
766
767 return pending;
768}
769
84f85aaa
GE
770/**
771 Wait until one or more async URBs are completed by the kernel and mark their
772 positions in the async-buffer as unused
773
774 \param ftdi pointer to ftdi_context
775 \param wait_for_more if != 0 wait for more than one write to complete
776 \param timeout_msec max milliseconds to wait
777
c201f80f
TJ
778 \internal
779*/
780static void _usb_async_cleanup(struct ftdi_context *ftdi, int wait_for_more, int timeout_msec)
7cc9950e
GE
781{
782 struct timeval tv;
783 struct usbdevfs_urb *urb=NULL;
784 int ret;
785 fd_set writefds;
786 int keep_going=0;
787
788 FD_ZERO(&writefds);
789 FD_SET(ftdi->usb_dev->fd, &writefds);
790
791 /* init timeout only once, select writes time left after call */
792 tv.tv_sec = timeout_msec / 1000;
793 tv.tv_usec = (timeout_msec % 1000) * 1000;
794
795 do {
c201f80f 796 while (_usb_get_async_urbs_pending(ftdi)
7cc9950e
GE
797 && (ret = ioctl(ftdi->usb_dev->fd, USBDEVFS_REAPURBNDELAY, &urb)) == -1
798 && errno == EAGAIN)
799 {
800 if (keep_going && !wait_for_more) {
801 /* don't wait if repeating only for keep_going */
802 keep_going=0;
803 break;
804 }
805
806 /* wait for timeout msec or something written ready */
807 select(ftdi->usb_dev->fd+1, NULL, &writefds, NULL, &tv);
808 }
809
810 if (ret == 0 && urb != NULL) {
811 /* got a free urb, mark it */
812 urb->usercontext = FTDI_URB_USERCONTEXT_COOKIE;
813
814 /* try to get more urbs that are ready now, but don't wait anymore */
815 urb=NULL;
816 keep_going=1;
817 } else {
818 /* no more urbs waiting */
819 keep_going=0;
820 }
821 } while (keep_going);
822}
823
824/**
84f85aaa
GE
825 Wait until one or more async URBs are completed by the kernel and mark their
826 positions in the async-buffer as unused.
7cc9950e
GE
827
828 \param ftdi pointer to ftdi_context
829 \param wait_for_more if != 0 wait for more than one write to complete (until write timeout)
830*/
831void ftdi_async_complete(struct ftdi_context *ftdi, int wait_for_more)
832{
c201f80f 833 _usb_async_cleanup(ftdi,wait_for_more,ftdi->usb_write_timeout);
7cc9950e 834}
4c9e3812
GE
835
836/**
837 Stupid libusb does not offer async writes nor does it allow
838 access to its fd - so we need some hacks here.
c201f80f 839 \internal
4c9e3812 840*/
c201f80f 841static int _usb_bulk_write_async(struct ftdi_context *ftdi, int ep, char *bytes, int size)
4c9e3812 842{
7cc9950e 843 struct usbdevfs_urb *urb;
4c9e3812 844 int bytesdone = 0, requested;
7cc9950e
GE
845 int ret, i;
846 int cleanup_count;
4c9e3812
GE
847
848 do {
7cc9950e
GE
849 /* find a free urb buffer we can use */
850 urb=NULL;
851 for (cleanup_count=0; urb==NULL && cleanup_count <= 1; cleanup_count++)
852 {
853 if (i==ftdi->async_usb_buffer_size) {
854 /* wait until some buffers are free */
c201f80f 855 _usb_async_cleanup(ftdi,0,ftdi->usb_write_timeout);
7cc9950e
GE
856 }
857
858 for (i=0; i < ftdi->async_usb_buffer_size; i++) {
859 urb=&((struct usbdevfs_urb *)(ftdi->async_usb_buffer))[i];
860 if (urb->usercontext == FTDI_URB_USERCONTEXT_COOKIE)
861 break; /* found a free urb position */
862 urb=NULL;
863 }
864 }
865
866 /* no free urb position found */
867 if (urb==NULL)
868 return -1;
4c9e3812
GE
869
870 requested = size - bytesdone;
7cc9950e
GE
871 if (requested > 4096)
872 requested = 4096;
873
874 memset(urb,0,sizeof(urb));
875
876 urb->type = USBDEVFS_URB_TYPE_BULK;
877 urb->endpoint = ep;
878 urb->flags = 0;
879 urb->buffer = bytes + bytesdone;
880 urb->buffer_length = requested;
881 urb->signr = 0;
882 urb->actual_length = 0;
883 urb->number_of_packets = 0;
884 urb->usercontext = 0;
885
886 do {
887 ret = ioctl(ftdi->usb_dev->fd, USBDEVFS_SUBMITURB, urb);
888 } while (ret < 0 && errno == EINTR);
4c9e3812
GE
889 if (ret < 0)
890 return ret; /* the caller can read errno to get more info */
891
892 bytesdone += requested;
893 } while (bytesdone < size);
894 return bytesdone;
895}
896
897/**
898 Writes data in chunks (see ftdi_write_data_set_chunksize()) to the chip.
899 Does not wait for completion of the transfer nor does it make sure that
900 the transfer was successful.
901
902 This function could be extended to use signals and callbacks to inform the
903 caller of completion or error - but this is not done yet, volunteers welcome.
904
905 Works around libusb and directly accesses functions only available on Linux.
906
907 \param ftdi pointer to ftdi_context
908 \param buf Buffer with the data
909 \param size Size of the buffer
910
911 \retval <0: error code from usb_bulk_write()
912 \retval >0: number of bytes written
913*/
914int ftdi_write_data_async(struct ftdi_context *ftdi, unsigned char *buf, int size)
915{
916 int ret;
917 int offset = 0;
918 int total_written = 0;
919
920 while (offset < size) {
921 int write_size = ftdi->writebuffer_chunksize;
922
923 if (offset+write_size > size)
924 write_size = size-offset;
925
c201f80f 926 ret = _usb_bulk_write_async(ftdi, ftdi->in_ep, buf+offset, write_size);
4c9e3812
GE
927 if (ret < 0)
928 ftdi_error_return(ret, "usb bulk write async failed");
929
930 total_written += ret;
931 offset += write_size;
932 }
933
934 return total_written;
935}
f01d7ca6 936#endif // LIBFTDI_LINUX_ASYNC_MODE
4c9e3812 937
1941414d
TJ
938/**
939 Configure write buffer chunk size.
940 Default is 4096.
941
942 \param ftdi pointer to ftdi_context
943 \param chunksize Chunk size
a3da1d95 944
1941414d
TJ
945 \retval 0: all fine
946*/
a8f46ddc
TJ
947int ftdi_write_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
948{
948f9ada
TJ
949 ftdi->writebuffer_chunksize = chunksize;
950 return 0;
951}
952
1941414d
TJ
953/**
954 Get write buffer chunk size.
955
956 \param ftdi pointer to ftdi_context
957 \param chunksize Pointer to store chunk size in
948f9ada 958
1941414d
TJ
959 \retval 0: all fine
960*/
a8f46ddc
TJ
961int ftdi_write_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
962{
948f9ada
TJ
963 *chunksize = ftdi->writebuffer_chunksize;
964 return 0;
965}
cbabb7d3 966
1941414d
TJ
967/**
968 Reads data in chunks (see ftdi_read_data_set_chunksize()) from the chip.
969
970 Automatically strips the two modem status bytes transfered during every read.
948f9ada 971
1941414d
TJ
972 \param ftdi pointer to ftdi_context
973 \param buf Buffer to store data in
974 \param size Size of the buffer
975
976 \retval <0: error code from usb_bulk_read()
d77b0e94 977 \retval 0: no data was available
1941414d
TJ
978 \retval >0: number of bytes read
979
980 \remark This function is not useful in bitbang mode.
981 Use ftdi_read_pins() to get the current state of the pins.
982*/
a8f46ddc
TJ
983int ftdi_read_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
984{
1c733d33 985 int offset = 0, ret = 1, i, num_of_chunks, chunk_remains;
d9f0cce7 986
948f9ada
TJ
987 // everything we want is still in the readbuffer?
988 if (size <= ftdi->readbuffer_remaining) {
d9f0cce7
TJ
989 memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);
990
991 // Fix offsets
992 ftdi->readbuffer_remaining -= size;
993 ftdi->readbuffer_offset += size;
994
545820ce 995 /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */
d9f0cce7
TJ
996
997 return size;
979a145c 998 }
948f9ada
TJ
999 // something still in the readbuffer, but not enough to satisfy 'size'?
1000 if (ftdi->readbuffer_remaining != 0) {
d9f0cce7 1001 memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);
979a145c 1002
d9f0cce7
TJ
1003 // Fix offset
1004 offset += ftdi->readbuffer_remaining;
948f9ada 1005 }
948f9ada 1006 // do the actual USB read
cbabb7d3 1007 while (offset < size && ret > 0) {
d9f0cce7
TJ
1008 ftdi->readbuffer_remaining = 0;
1009 ftdi->readbuffer_offset = 0;
98452d97
TJ
1010 /* returns how much received */
1011 ret = usb_bulk_read (ftdi->usb_dev, ftdi->out_ep, ftdi->readbuffer, ftdi->readbuffer_chunksize, ftdi->usb_read_timeout);
c3d95b87
TJ
1012 if (ret < 0)
1013 ftdi_error_return(ret, "usb bulk read failed");
98452d97 1014
d9f0cce7
TJ
1015 if (ret > 2) {
1016 // skip FTDI status bytes.
1017 // Maybe stored in the future to enable modem use
1c733d33
TJ
1018 num_of_chunks = ret / 64;
1019 chunk_remains = ret % 64;
1020 //printf("ret = %X, num_of_chunks = %X, chunk_remains = %X, readbuffer_offset = %X\n", ret, num_of_chunks, chunk_remains, ftdi->readbuffer_offset);
1021
d9f0cce7
TJ
1022 ftdi->readbuffer_offset += 2;
1023 ret -= 2;
1c733d33 1024
fde0a89e 1025 if (ret > 62) {
1c733d33
TJ
1026 for (i = 1; i < num_of_chunks; i++)
1027 memmove (ftdi->readbuffer+ftdi->readbuffer_offset+62*i,
1028 ftdi->readbuffer+ftdi->readbuffer_offset+64*i,
1029 62);
1030 if (chunk_remains > 2) {
1031 memmove (ftdi->readbuffer+ftdi->readbuffer_offset+62*i,
1032 ftdi->readbuffer+ftdi->readbuffer_offset+64*i,
1033 chunk_remains-2);
1034 ret -= 2*num_of_chunks;
1035 } else
1036 ret -= 2*(num_of_chunks-1)+chunk_remains;
1037 }
d9f0cce7
TJ
1038 } else if (ret <= 2) {
1039 // no more data to read?
1040 return offset;
1041 }
d9f0cce7
TJ
1042 if (ret > 0) {
1043 // data still fits in buf?
1044 if (offset+ret <= size) {
1045 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, ret);
545820ce 1046 //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
d9f0cce7
TJ
1047 offset += ret;
1048
53ad271d 1049 /* Did we read exactly the right amount of bytes? */
d9f0cce7 1050 if (offset == size)
c4446c36
TJ
1051 //printf("read_data exact rem %d offset %d\n",
1052 //ftdi->readbuffer_remaining, offset);
d9f0cce7
TJ
1053 return offset;
1054 } else {
1055 // only copy part of the data or size <= readbuffer_chunksize
1056 int part_size = size-offset;
1057 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, part_size);
98452d97 1058
d9f0cce7
TJ
1059 ftdi->readbuffer_offset += part_size;
1060 ftdi->readbuffer_remaining = ret-part_size;
1061 offset += part_size;
1062
53ad271d
TJ
1063 /* printf("Returning part: %d - size: %d - offset: %d - ret: %d - remaining: %d\n",
1064 part_size, size, offset, ret, ftdi->readbuffer_remaining); */
d9f0cce7
TJ
1065
1066 return offset;
1067 }
1068 }
cbabb7d3 1069 }
948f9ada 1070 // never reached
29c4af7f 1071 return -127;
a3da1d95
GE
1072}
1073
1941414d
TJ
1074/**
1075 Configure read buffer chunk size.
1076 Default is 4096.
1077
1078 Automatically reallocates the buffer.
a3da1d95 1079
1941414d
TJ
1080 \param ftdi pointer to ftdi_context
1081 \param chunksize Chunk size
1082
1083 \retval 0: all fine
1084*/
a8f46ddc
TJ
1085int ftdi_read_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
1086{
29c4af7f
TJ
1087 unsigned char *new_buf;
1088
948f9ada
TJ
1089 // Invalidate all remaining data
1090 ftdi->readbuffer_offset = 0;
1091 ftdi->readbuffer_remaining = 0;
1092
c3d95b87
TJ
1093 if ((new_buf = (unsigned char *)realloc(ftdi->readbuffer, chunksize)) == NULL)
1094 ftdi_error_return(-1, "out of memory for readbuffer");
d9f0cce7 1095
948f9ada
TJ
1096 ftdi->readbuffer = new_buf;
1097 ftdi->readbuffer_chunksize = chunksize;
1098
1099 return 0;
1100}
1101
1941414d
TJ
1102/**
1103 Get read buffer chunk size.
948f9ada 1104
1941414d
TJ
1105 \param ftdi pointer to ftdi_context
1106 \param chunksize Pointer to store chunk size in
1107
1108 \retval 0: all fine
1109*/
a8f46ddc
TJ
1110int ftdi_read_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
1111{
948f9ada
TJ
1112 *chunksize = ftdi->readbuffer_chunksize;
1113 return 0;
1114}
1115
1116
1941414d
TJ
1117/**
1118 Enable bitbang mode.
948f9ada 1119
1941414d
TJ
1120 For advanced bitbang modes of the FT2232C chip use ftdi_set_bitmode().
1121
1122 \param ftdi pointer to ftdi_context
1123 \param bitmask Bitmask to configure lines.
1124 HIGH/ON value configures a line as output.
1125
1126 \retval 0: all fine
1127 \retval -1: can't enable bitbang mode
1128*/
a8f46ddc
TJ
1129int ftdi_enable_bitbang(struct ftdi_context *ftdi, unsigned char bitmask)
1130{
a3da1d95
GE
1131 unsigned short usb_val;
1132
d9f0cce7 1133 usb_val = bitmask; // low byte: bitmask
3119537f
TJ
1134 /* FT2232C: Set bitbang_mode to 2 to enable SPI */
1135 usb_val |= (ftdi->bitbang_mode << 8);
1136
c3d95b87
TJ
1137 if (usb_control_msg(ftdi->usb_dev, 0x40, 0x0B, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
1138 ftdi_error_return(-1, "unable to enter bitbang mode. Perhaps not a BM type chip?");
1139
a3da1d95
GE
1140 ftdi->bitbang_enabled = 1;
1141 return 0;
1142}
1143
1941414d
TJ
1144/**
1145 Disable bitbang mode.
a3da1d95 1146
1941414d
TJ
1147 \param ftdi pointer to ftdi_context
1148
1149 \retval 0: all fine
1150 \retval -1: can't disable bitbang mode
1151*/
a8f46ddc
TJ
1152int ftdi_disable_bitbang(struct ftdi_context *ftdi)
1153{
c3d95b87
TJ
1154 if (usb_control_msg(ftdi->usb_dev, 0x40, 0x0B, 0, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
1155 ftdi_error_return(-1, "unable to leave bitbang mode. Perhaps not a BM type chip?");
a3da1d95
GE
1156
1157 ftdi->bitbang_enabled = 0;
1158 return 0;
1159}
1160
1941414d
TJ
1161/**
1162 Enable advanced bitbang mode for FT2232C chips.
a3da1d95 1163
1941414d
TJ
1164 \param ftdi pointer to ftdi_context
1165 \param bitmask Bitmask to configure lines.
1166 HIGH/ON value configures a line as output.
1167 \param mode Bitbang mode: 1 for normal mode, 2 for SPI mode
1168
1169 \retval 0: all fine
1170 \retval -1: can't enable bitbang mode
1171*/
c4446c36
TJ
1172int ftdi_set_bitmode(struct ftdi_context *ftdi, unsigned char bitmask, unsigned char mode)
1173{
1174 unsigned short usb_val;
1175
1176 usb_val = bitmask; // low byte: bitmask
1177 usb_val |= (mode << 8);
1178 if (usb_control_msg(ftdi->usb_dev, 0x40, 0x0B, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
1179 ftdi_error_return(-1, "unable to configure bitbang mode. Perhaps not a 2232C type chip?");
1180
1181 ftdi->bitbang_mode = mode;
1182 ftdi->bitbang_enabled = (mode == BITMODE_BITBANG || mode == BITMODE_SYNCBB)?1:0;
1183 return 0;
1184}
1185
1941414d
TJ
1186/**
1187 Directly read pin state. Useful for bitbang mode.
1188
1189 \param ftdi pointer to ftdi_context
1190 \param pins Pointer to store pins into
1191
1192 \retval 0: all fine
1193 \retval -1: read pins failed
1194*/
a8f46ddc
TJ
1195int ftdi_read_pins(struct ftdi_context *ftdi, unsigned char *pins)
1196{
85f3c596 1197 if (usb_control_msg(ftdi->usb_dev, 0xC0, 0x0C, 0, ftdi->index, (char *)pins, 1, ftdi->usb_read_timeout) != 1)
c3d95b87 1198 ftdi_error_return(-1, "read pins failed");
a3da1d95 1199
a3da1d95
GE
1200 return 0;
1201}
1202
1941414d
TJ
1203/**
1204 Set latency timer
1205
1206 The FTDI chip keeps data in the internal buffer for a specific
1207 amount of time if the buffer is not full yet to decrease
1208 load on the usb bus.
a3da1d95 1209
1941414d
TJ
1210 \param ftdi pointer to ftdi_context
1211 \param latency Value between 1 and 255
1212
1213 \retval 0: all fine
1214 \retval -1: latency out of range
1215 \retval -2: unable to set latency timer
1216*/
a8f46ddc
TJ
1217int ftdi_set_latency_timer(struct ftdi_context *ftdi, unsigned char latency)
1218{
a3da1d95
GE
1219 unsigned short usb_val;
1220
c3d95b87
TJ
1221 if (latency < 1)
1222 ftdi_error_return(-1, "latency out of range. Only valid for 1-255");
a3da1d95 1223
d79d2e68 1224 usb_val = latency;
c3d95b87
TJ
1225 if (usb_control_msg(ftdi->usb_dev, 0x40, 0x09, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
1226 ftdi_error_return(-2, "unable to set latency timer");
1227
a3da1d95
GE
1228 return 0;
1229}
1230
1941414d
TJ
1231/**
1232 Get latency timer
a3da1d95 1233
1941414d
TJ
1234 \param ftdi pointer to ftdi_context
1235 \param latency Pointer to store latency value in
1236
1237 \retval 0: all fine
1238 \retval -1: unable to get latency timer
1239*/
a8f46ddc
TJ
1240int ftdi_get_latency_timer(struct ftdi_context *ftdi, unsigned char *latency)
1241{
a3da1d95 1242 unsigned short usb_val;
c3d95b87
TJ
1243 if (usb_control_msg(ftdi->usb_dev, 0xC0, 0x0A, 0, ftdi->index, (char *)&usb_val, 1, ftdi->usb_read_timeout) != 1)
1244 ftdi_error_return(-1, "reading latency timer failed");
a3da1d95
GE
1245
1246 *latency = (unsigned char)usb_val;
1247 return 0;
1248}
1249
1941414d 1250/**
c201f80f
TJ
1251 Set the eeprom size
1252
1253 \param ftdi pointer to ftdi_context
1254 \param eeprom Pointer to ftdi_eeprom
1255 \param size
1256
1257*/
1258void ftdi_eeprom_setsize(struct ftdi_context *ftdi, struct ftdi_eeprom *eeprom, int size)
1259{
1260 ftdi->eeprom_size=size;
1261 eeprom->size=size;
1262}
1263
1264/**
1941414d 1265 Init eeprom with default values.
a3da1d95 1266
1941414d
TJ
1267 \param eeprom Pointer to ftdi_eeprom
1268*/
a8f46ddc
TJ
1269void ftdi_eeprom_initdefaults(struct ftdi_eeprom *eeprom)
1270{
f396dbad
TJ
1271 eeprom->vendor_id = 0x0403;
1272 eeprom->product_id = 0x6001;
d9f0cce7 1273
b8aa7b35
TJ
1274 eeprom->self_powered = 1;
1275 eeprom->remote_wakeup = 1;
1276 eeprom->BM_type_chip = 1;
d9f0cce7 1277
b8aa7b35
TJ
1278 eeprom->in_is_isochronous = 0;
1279 eeprom->out_is_isochronous = 0;
1280 eeprom->suspend_pull_downs = 0;
d9f0cce7 1281
b8aa7b35
TJ
1282 eeprom->use_serial = 0;
1283 eeprom->change_usb_version = 0;
f396dbad 1284 eeprom->usb_version = 0x0200;
b8aa7b35 1285 eeprom->max_power = 0;
d9f0cce7 1286
b8aa7b35
TJ
1287 eeprom->manufacturer = NULL;
1288 eeprom->product = NULL;
1289 eeprom->serial = NULL;
c201f80f
TJ
1290
1291 eeprom->size = FTDI_DEFAULT_EEPROM_SIZE;
b8aa7b35
TJ
1292}
1293
1941414d
TJ
1294/**
1295 Build binary output from ftdi_eeprom structure.
1296 Output is suitable for ftdi_write_eeprom().
b8aa7b35 1297
1941414d
TJ
1298 \param eeprom Pointer to ftdi_eeprom
1299 \param output Buffer of 128 bytes to store eeprom image to
1300
1301 \retval >0: used eeprom size
1302 \retval -1: eeprom size (128 bytes) exceeded by custom strings
b8aa7b35 1303*/
a8f46ddc
TJ
1304int ftdi_eeprom_build(struct ftdi_eeprom *eeprom, unsigned char *output)
1305{
b8aa7b35
TJ
1306 unsigned char i, j;
1307 unsigned short checksum, value;
1308 unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
1309 int size_check;
1310
1311 if (eeprom->manufacturer != NULL)
d9f0cce7 1312 manufacturer_size = strlen(eeprom->manufacturer);
b8aa7b35 1313 if (eeprom->product != NULL)
d9f0cce7 1314 product_size = strlen(eeprom->product);
b8aa7b35 1315 if (eeprom->serial != NULL)
d9f0cce7 1316 serial_size = strlen(eeprom->serial);
b8aa7b35 1317
c201f80f 1318 size_check = eeprom->size;
d9f0cce7 1319 size_check -= 28; // 28 are always in use (fixed)
c201f80f
TJ
1320
1321 // Top half of a 256byte eeprom is used just for strings and checksum
1322 // it seems that the FTDI chip will not read these strings from the lower half
1323 // Each string starts with two bytes; offset and type (0x03 for string)
1324 // the checksum needs two bytes, so without the string data that 8 bytes from the top half
1325 if(eeprom->size>=256)size_check = 120;
b8aa7b35
TJ
1326 size_check -= manufacturer_size*2;
1327 size_check -= product_size*2;
1328 size_check -= serial_size*2;
1329
1330 // eeprom size exceeded?
1331 if (size_check < 0)
d9f0cce7 1332 return (-1);
b8aa7b35
TJ
1333
1334 // empty eeprom
c201f80f 1335 memset (output, 0, eeprom->size);
b8aa7b35
TJ
1336
1337 // Addr 00: Stay 00 00
1338 // Addr 02: Vendor ID
1339 output[0x02] = eeprom->vendor_id;
1340 output[0x03] = eeprom->vendor_id >> 8;
1341
1342 // Addr 04: Product ID
1343 output[0x04] = eeprom->product_id;
1344 output[0x05] = eeprom->product_id >> 8;
1345
1346 // Addr 06: Device release number (0400h for BM features)
1347 output[0x06] = 0x00;
d9f0cce7 1348
b8aa7b35 1349 if (eeprom->BM_type_chip == 1)
d9f0cce7 1350 output[0x07] = 0x04;
b8aa7b35 1351 else
d9f0cce7 1352 output[0x07] = 0x02;
b8aa7b35
TJ
1353
1354 // Addr 08: Config descriptor
1355 // Bit 1: remote wakeup if 1
1356 // Bit 0: self powered if 1
1357 //
1358 j = 0;
1359 if (eeprom->self_powered == 1)
d9f0cce7 1360 j = j | 1;
b8aa7b35 1361 if (eeprom->remote_wakeup == 1)
d9f0cce7 1362 j = j | 2;
b8aa7b35
TJ
1363 output[0x08] = j;
1364
1365 // Addr 09: Max power consumption: max power = value * 2 mA
d9f0cce7
TJ
1366 output[0x09] = eeprom->max_power;
1367 ;
1368
b8aa7b35
TJ
1369 // Addr 0A: Chip configuration
1370 // Bit 7: 0 - reserved
1371 // Bit 6: 0 - reserved
1372 // Bit 5: 0 - reserved
1373 // Bit 4: 1 - Change USB version
1374 // Bit 3: 1 - Use the serial number string
1375 // Bit 2: 1 - Enable suspend pull downs for lower power
1376 // Bit 1: 1 - Out EndPoint is Isochronous
1377 // Bit 0: 1 - In EndPoint is Isochronous
1378 //
1379 j = 0;
1380 if (eeprom->in_is_isochronous == 1)
d9f0cce7 1381 j = j | 1;
b8aa7b35 1382 if (eeprom->out_is_isochronous == 1)
d9f0cce7 1383 j = j | 2;
b8aa7b35 1384 if (eeprom->suspend_pull_downs == 1)
d9f0cce7 1385 j = j | 4;
b8aa7b35 1386 if (eeprom->use_serial == 1)
d9f0cce7 1387 j = j | 8;
b8aa7b35 1388 if (eeprom->change_usb_version == 1)
d9f0cce7 1389 j = j | 16;
b8aa7b35 1390 output[0x0A] = j;
d9f0cce7 1391
b8aa7b35
TJ
1392 // Addr 0B: reserved
1393 output[0x0B] = 0x00;
d9f0cce7 1394
b8aa7b35
TJ
1395 // Addr 0C: USB version low byte when 0x0A bit 4 is set
1396 // Addr 0D: USB version high byte when 0x0A bit 4 is set
1397 if (eeprom->change_usb_version == 1) {
1398 output[0x0C] = eeprom->usb_version;
d9f0cce7 1399 output[0x0D] = eeprom->usb_version >> 8;
b8aa7b35
TJ
1400 }
1401
1402
c201f80f 1403 // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
b8aa7b35
TJ
1404 // Addr 0F: Length of manufacturer string
1405 output[0x0F] = manufacturer_size*2 + 2;
1406
1407 // Addr 10: Offset of the product string + 0x80, calculated later
1408 // Addr 11: Length of product string
1409 output[0x11] = product_size*2 + 2;
1410
1411 // Addr 12: Offset of the serial string + 0x80, calculated later
1412 // Addr 13: Length of serial string
1413 output[0x13] = serial_size*2 + 2;
1414
1415 // Dynamic content
c201f80f
TJ
1416 i=0x14;
1417 if(eeprom->size>=256) i = 0x80;
f01d7ca6 1418
c201f80f
TJ
1419
1420 // Output manufacturer
1421 output[0x0E] = i | 0x80; // calculate offset
1422 output[i++] = manufacturer_size*2 + 2;
1423 output[i++] = 0x03; // type: string
b8aa7b35 1424 for (j = 0; j < manufacturer_size; j++) {
d9f0cce7
TJ
1425 output[i] = eeprom->manufacturer[j], i++;
1426 output[i] = 0x00, i++;
b8aa7b35
TJ
1427 }
1428
1429 // Output product name
c201f80f 1430 output[0x10] = i | 0x80; // calculate offset
b8aa7b35
TJ
1431 output[i] = product_size*2 + 2, i++;
1432 output[i] = 0x03, i++;
1433 for (j = 0; j < product_size; j++) {
d9f0cce7
TJ
1434 output[i] = eeprom->product[j], i++;
1435 output[i] = 0x00, i++;
b8aa7b35 1436 }
d9f0cce7 1437
b8aa7b35 1438 // Output serial
c201f80f 1439 output[0x12] = i | 0x80; // calculate offset
b8aa7b35
TJ
1440 output[i] = serial_size*2 + 2, i++;
1441 output[i] = 0x03, i++;
1442 for (j = 0; j < serial_size; j++) {
d9f0cce7
TJ
1443 output[i] = eeprom->serial[j], i++;
1444 output[i] = 0x00, i++;
b8aa7b35
TJ
1445 }
1446
1447 // calculate checksum
1448 checksum = 0xAAAA;
d9f0cce7 1449
c201f80f 1450 for (i = 0; i < eeprom->size/2-1; i++) {
d9f0cce7
TJ
1451 value = output[i*2];
1452 value += output[(i*2)+1] << 8;
b8aa7b35 1453
d9f0cce7
TJ
1454 checksum = value^checksum;
1455 checksum = (checksum << 1) | (checksum >> 15);
b8aa7b35
TJ
1456 }
1457
c201f80f
TJ
1458 output[eeprom->size-2] = checksum;
1459 output[eeprom->size-1] = checksum >> 8;
b8aa7b35 1460
8ed61121 1461 return size_check;
b8aa7b35
TJ
1462}
1463
1941414d
TJ
1464/**
1465 Read eeprom
1466
1467 \param ftdi pointer to ftdi_context
1468 \param eeprom Pointer to store eeprom into
b8aa7b35 1469
1941414d
TJ
1470 \retval 0: all fine
1471 \retval -1: read failed
1472*/
a8f46ddc
TJ
1473int ftdi_read_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
1474{
a3da1d95
GE
1475 int i;
1476
c201f80f 1477 for (i = 0; i < ftdi->eeprom_size/2; i++) {
c3d95b87
TJ
1478 if (usb_control_msg(ftdi->usb_dev, 0xC0, 0x90, 0, i, eeprom+(i*2), 2, ftdi->usb_read_timeout) != 2)
1479 ftdi_error_return(-1, "reading eeprom failed");
a3da1d95
GE
1480 }
1481
1482 return 0;
1483}
1484
cb6250fa
TJ
1485/*
1486 ftdi_read_chipid_shift does the bitshift operation needed for the FTDIChip-ID
1487 Function is only used internally
1488 \internal
1489*/
1490static unsigned char ftdi_read_chipid_shift(unsigned char value)
1491{
1492 return ((value & 1) << 1) |
1493 ((value & 2) << 5) |
1494 ((value & 4) >> 2) |
1495 ((value & 8) << 4) |
1496 ((value & 16) >> 1) |
1497 ((value & 32) >> 1) |
1498 ((value & 64) >> 4) |
1499 ((value & 128) >> 2);
1500}
1501
1502/**
1503 Read the FTDIChip-ID from R-type devices
1504
1505 \param ftdi pointer to ftdi_context
1506 \param chipid Pointer to store FTDIChip-ID
1507
1508 \retval 0: all fine
1509 \retval -1: read failed
1510*/
1511int ftdi_read_chipid(struct ftdi_context *ftdi, unsigned int *chipid)
1512{
c7eb3112 1513 unsigned int a = 0, b = 0;
cb6250fa
TJ
1514
1515 if (usb_control_msg(ftdi->usb_dev, 0xC0, 0x90, 0, 0x43, (char *)&a, 2, ftdi->usb_read_timeout) == 2)
1516 {
1517 a = a << 8 | a >> 8;
1518 if (usb_control_msg(ftdi->usb_dev, 0xC0, 0x90, 0, 0x44, (char *)&b, 2, ftdi->usb_read_timeout) == 2)
1519 {
1520 b = b << 8 | b >> 8;
1521 a = (a << 16) | b;
912d50ca
TJ
1522 a = ftdi_read_chipid_shift(a) | ftdi_read_chipid_shift(a>>8)<<8
1523 | ftdi_read_chipid_shift(a>>16)<<16 | ftdi_read_chipid_shift(a>>24)<<24;
cb6250fa 1524 *chipid = a ^ 0xa5f0f7d1;
c7eb3112 1525 return 0;
cb6250fa
TJ
1526 }
1527 }
1528
c7eb3112 1529 ftdi_error_return(-1, "read of FTDIChip-ID failed");
cb6250fa
TJ
1530}
1531
1941414d 1532/**
c201f80f
TJ
1533 Guesses size of eeprom by reading eeprom and comparing halves - will not work with blank eeprom
1534 Call this function then do a write then call again to see if size changes, if so write again.
1535
1536 \param ftdi pointer to ftdi_context
1537 \param eeprom Pointer to store eeprom into
1538 \param maxsize the size of the buffer to read into
1539
1540 \retval size of eeprom
1541*/
1542int ftdi_read_eeprom_getsize(struct ftdi_context *ftdi, unsigned char *eeprom, int maxsize)
1543{
1544 int i=0,j,minsize=32;
1545 int size=minsize;
1546
1547 do{
1548 for (j = 0; i < maxsize/2 && j<size; j++) {
1549 if (usb_control_msg(ftdi->usb_dev, 0xC0, 0x90, 0, i, eeprom+(i*2), 2, ftdi->usb_read_timeout) != 2)
1550 ftdi_error_return(-1, "reading eeprom failed");
1551 i++;
1552 }
1553 size*=2;
1554 }while(size<=maxsize && memcmp(eeprom,&eeprom[size/2],size/2)!=0);
1555
1556 return size/2;
1557}
1558
1559/**
1941414d 1560 Write eeprom
a3da1d95 1561
1941414d
TJ
1562 \param ftdi pointer to ftdi_context
1563 \param eeprom Pointer to read eeprom from
1564
1565 \retval 0: all fine
1566 \retval -1: read failed
1567*/
a8f46ddc
TJ
1568int ftdi_write_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
1569{
a3da1d95
GE
1570 unsigned short usb_val;
1571 int i;
1572
c201f80f 1573 for (i = 0; i < ftdi->eeprom_size/2; i++) {
d9f0cce7
TJ
1574 usb_val = eeprom[i*2];
1575 usb_val += eeprom[(i*2)+1] << 8;
c3d95b87
TJ
1576 if (usb_control_msg(ftdi->usb_dev, 0x40, 0x91, usb_val, i, NULL, 0, ftdi->usb_write_timeout) != 0)
1577 ftdi_error_return(-1, "unable to write eeprom");
a3da1d95
GE
1578 }
1579
1580 return 0;
1581}
1582
1941414d
TJ
1583/**
1584 Erase eeprom
a3da1d95 1585
1941414d
TJ
1586 \param ftdi pointer to ftdi_context
1587
1588 \retval 0: all fine
1589 \retval -1: erase failed
1590*/
a8f46ddc
TJ
1591int ftdi_erase_eeprom(struct ftdi_context *ftdi)
1592{
c3d95b87
TJ
1593 if (usb_control_msg(ftdi->usb_dev, 0x40, 0x92, 0, 0, NULL, 0, ftdi->usb_write_timeout) != 0)
1594 ftdi_error_return(-1, "unable to erase eeprom");
a3da1d95
GE
1595
1596 return 0;
1597}
c3d95b87 1598
1941414d
TJ
1599/**
1600 Get string representation for last error code
c3d95b87 1601
1941414d
TJ
1602 \param ftdi pointer to ftdi_context
1603
1604 \retval Pointer to error string
1605*/
c3d95b87
TJ
1606char *ftdi_get_error_string (struct ftdi_context *ftdi)
1607{
1608 return ftdi->error_str;
1609}
a01d31e2 1610
9bec2387
TJ
1611/*
1612 Flow control code by Lorenz Moesenlechner (lorenz@hcilab.org)
1613 and Matthias Kranz (matthias@hcilab.org)
1614*/
1941414d
TJ
1615/**
1616 Set flowcontrol for ftdi chip
a01d31e2 1617
1941414d
TJ
1618 \param ftdi pointer to ftdi_context
1619 \param flowctrl flow control to use. should be
1620 SIO_DISABLE_FLOW_CTRL, SIO_RTS_CTS_HS, SIO_DTR_DSR_HS or SIO_XON_XOFF_HS
1621
1622 \retval 0: all fine
1623 \retval -1: set flow control failed
1624*/
a01d31e2
TJ
1625int ftdi_setflowctrl(struct ftdi_context *ftdi, int flowctrl)
1626{
1627 if (usb_control_msg(ftdi->usb_dev, SIO_SET_FLOW_CTRL_REQUEST_TYPE,
d2f10023
TJ
1628 SIO_SET_FLOW_CTRL_REQUEST, 0, (flowctrl | ftdi->interface),
1629 NULL, 0, ftdi->usb_write_timeout) != 0)
1630 ftdi_error_return(-1, "set flow control failed");
a01d31e2
TJ
1631
1632 return 0;
1633}
1634
1941414d
TJ
1635/**
1636 Set dtr line
1637
1638 \param ftdi pointer to ftdi_context
1639 \param state state to set line to (1 or 0)
1640
1641 \retval 0: all fine
1642 \retval -1: set dtr failed
1643*/
a01d31e2
TJ
1644int ftdi_setdtr(struct ftdi_context *ftdi, int state)
1645{
1646 unsigned short usb_val;
1647
d2f10023 1648 if (state)
a01d31e2
TJ
1649 usb_val = SIO_SET_DTR_HIGH;
1650 else
1651 usb_val = SIO_SET_DTR_LOW;
1652
1653 if (usb_control_msg(ftdi->usb_dev, SIO_SET_MODEM_CTRL_REQUEST_TYPE,
d2f10023
TJ
1654 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->interface,
1655 NULL, 0, ftdi->usb_write_timeout) != 0)
1656 ftdi_error_return(-1, "set dtr failed");
a01d31e2
TJ
1657
1658 return 0;
1659}
1660
1941414d
TJ
1661/**
1662 Set rts line
1663
1664 \param ftdi pointer to ftdi_context
1665 \param state state to set line to (1 or 0)
1666
1667 \retval 0: all fine
1668 \retval -1 set rts failed
1669*/
a01d31e2
TJ
1670int ftdi_setrts(struct ftdi_context *ftdi, int state)
1671{
1672 unsigned short usb_val;
1673
d2f10023 1674 if (state)
a01d31e2
TJ
1675 usb_val = SIO_SET_RTS_HIGH;
1676 else
1677 usb_val = SIO_SET_RTS_LOW;
1678
d2f10023
TJ
1679 if (usb_control_msg(ftdi->usb_dev, SIO_SET_MODEM_CTRL_REQUEST_TYPE,
1680 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->interface,
1681 NULL, 0, ftdi->usb_write_timeout) != 0)
1682 ftdi_error_return(-1, "set of rts failed");
a01d31e2
TJ
1683
1684 return 0;
1685}
b5ec1820
TJ
1686
1687/* @} end of doxygen libftdi group */