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