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