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