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