Protect against segfault if device is closed or ftdi context is invalid
[libftdi] / src / ftdi.c
CommitLineData
a3da1d95
GE
1/***************************************************************************
2 ftdi.c - description
3 -------------------
4 begin : Fri Apr 4 2003
22a1b5c1 5 copyright : (C) 2003-2010 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
579b006f 31#include <libusb.h>
a8f46ddc 32#include <string.h>
d2f10023 33#include <errno.h>
b56d5a64 34#include <stdio.h>
579b006f 35#include <stdlib.h>
0e302db6 36
98452d97 37#include "ftdi.h"
a3da1d95 38
21abaf2e 39#define ftdi_error_return(code, str) do { \
2f73e59f 40 ftdi->error_str = str; \
21abaf2e 41 return code; \
d2f10023 42 } while(0);
c3d95b87 43
418aaa72 44
f3f81007
TJ
45/**
46 Internal function to close usb device pointer.
47 Sets ftdi->usb_dev to NULL.
48 \internal
49
50 \param ftdi pointer to ftdi_context
51
579b006f 52 \retval none
f3f81007 53*/
579b006f 54static void ftdi_usb_close_internal (struct ftdi_context *ftdi)
dff4fdb0 55{
22a1b5c1 56 if (ftdi && ftdi->usb_dev)
dff4fdb0 57 {
579b006f 58 libusb_close (ftdi->usb_dev);
dff4fdb0
NF
59 ftdi->usb_dev = NULL;
60 }
dff4fdb0 61}
c3d95b87 62
1941414d
TJ
63/**
64 Initializes a ftdi_context.
4837f98a 65
1941414d 66 \param ftdi pointer to ftdi_context
4837f98a 67
1941414d
TJ
68 \retval 0: all fine
69 \retval -1: couldn't allocate read buffer
70
71 \remark This should be called before all functions
948f9ada 72*/
a8f46ddc
TJ
73int ftdi_init(struct ftdi_context *ftdi)
74{
98452d97 75 ftdi->usb_dev = NULL;
545820ce
TJ
76 ftdi->usb_read_timeout = 5000;
77 ftdi->usb_write_timeout = 5000;
a3da1d95 78
53ad271d 79 ftdi->type = TYPE_BM; /* chip type */
a3da1d95 80 ftdi->baudrate = -1;
418aaa72 81 ftdi->bitbang_enabled = 0; /* 0: normal mode 1: any of the bitbang modes enabled */
a3da1d95 82
948f9ada
TJ
83 ftdi->readbuffer = NULL;
84 ftdi->readbuffer_offset = 0;
85 ftdi->readbuffer_remaining = 0;
86 ftdi->writebuffer_chunksize = 4096;
e2f12a4f 87 ftdi->max_packet_size = 0;
948f9ada 88
545820ce
TJ
89 ftdi->interface = 0;
90 ftdi->index = 0;
91 ftdi->in_ep = 0x02;
92 ftdi->out_ep = 0x81;
418aaa72 93 ftdi->bitbang_mode = 1; /* when bitbang is enabled this holds the number of the mode */
53ad271d 94
a3da1d95
GE
95 ftdi->error_str = NULL;
96
c201f80f
TJ
97 ftdi->eeprom_size = FTDI_DEFAULT_EEPROM_SIZE;
98
1c733d33
TJ
99 /* All fine. Now allocate the readbuffer */
100 return ftdi_read_data_set_chunksize(ftdi, 4096);
948f9ada 101}
4837f98a 102
1941414d 103/**
cef378aa
TJ
104 Allocate and initialize a new ftdi_context
105
106 \return a pointer to a new ftdi_context, or NULL on failure
107*/
672ac008 108struct ftdi_context *ftdi_new(void)
cef378aa
TJ
109{
110 struct ftdi_context * ftdi = (struct ftdi_context *)malloc(sizeof(struct ftdi_context));
111
22d12cda
TJ
112 if (ftdi == NULL)
113 {
cef378aa
TJ
114 return NULL;
115 }
116
22d12cda
TJ
117 if (ftdi_init(ftdi) != 0)
118 {
cef378aa 119 free(ftdi);
cdf448f6 120 return NULL;
cef378aa
TJ
121 }
122
123 return ftdi;
124}
125
126/**
1941414d
TJ
127 Open selected channels on a chip, otherwise use first channel.
128
129 \param ftdi pointer to ftdi_context
f9d69895 130 \param interface Interface to use for FT2232C/2232H/4232H chips.
1941414d
TJ
131
132 \retval 0: all fine
133 \retval -1: unknown interface
22a1b5c1 134 \retval -2: USB device unavailable
c4446c36 135*/
0ce2f5fa 136int ftdi_set_interface(struct ftdi_context *ftdi, enum ftdi_interface interface)
c4446c36 137{
22a1b5c1
TJ
138 if (ftdi == NULL || ftdi->usb_dev == NULL)
139 ftdi_error_return(-2, "USB device unavailable");
140
22d12cda
TJ
141 switch (interface)
142 {
143 case INTERFACE_ANY:
144 case INTERFACE_A:
145 /* ftdi_usb_open_desc cares to set the right index, depending on the found chip */
146 break;
147 case INTERFACE_B:
148 ftdi->interface = 1;
149 ftdi->index = INTERFACE_B;
150 ftdi->in_ep = 0x04;
151 ftdi->out_ep = 0x83;
152 break;
f9d69895
AH
153 case INTERFACE_C:
154 ftdi->interface = 2;
155 ftdi->index = INTERFACE_C;
156 ftdi->in_ep = 0x06;
157 ftdi->out_ep = 0x85;
158 break;
159 case INTERFACE_D:
160 ftdi->interface = 3;
161 ftdi->index = INTERFACE_D;
162 ftdi->in_ep = 0x08;
163 ftdi->out_ep = 0x87;
164 break;
22d12cda
TJ
165 default:
166 ftdi_error_return(-1, "Unknown interface");
c4446c36
TJ
167 }
168 return 0;
169}
948f9ada 170
1941414d
TJ
171/**
172 Deinitializes a ftdi_context.
4837f98a 173
1941414d 174 \param ftdi pointer to ftdi_context
4837f98a 175*/
a8f46ddc
TJ
176void ftdi_deinit(struct ftdi_context *ftdi)
177{
22a1b5c1
TJ
178 if (ftdi == NULL)
179 return;
180
f3f81007 181 ftdi_usb_close_internal (ftdi);
dff4fdb0 182
22d12cda
TJ
183 if (ftdi->readbuffer != NULL)
184 {
d9f0cce7
TJ
185 free(ftdi->readbuffer);
186 ftdi->readbuffer = NULL;
948f9ada 187 }
a3da1d95
GE
188}
189
1941414d 190/**
cef378aa
TJ
191 Deinitialize and free an ftdi_context.
192
193 \param ftdi pointer to ftdi_context
194*/
195void ftdi_free(struct ftdi_context *ftdi)
196{
197 ftdi_deinit(ftdi);
198 free(ftdi);
199}
200
201/**
1941414d
TJ
202 Use an already open libusb device.
203
204 \param ftdi pointer to ftdi_context
579b006f 205 \param usb libusb libusb_device_handle to use
4837f98a 206*/
579b006f 207void ftdi_set_usbdev (struct ftdi_context *ftdi, libusb_device_handle *usb)
a8f46ddc 208{
22a1b5c1
TJ
209 if (ftdi == NULL)
210 return;
211
98452d97
TJ
212 ftdi->usb_dev = usb;
213}
214
215
1941414d
TJ
216/**
217 Finds all ftdi devices on the usb bus. Creates a new ftdi_device_list which
218 needs to be deallocated by ftdi_list_free() after use.
219
220 \param ftdi pointer to ftdi_context
221 \param devlist Pointer where to store list of found devices
222 \param vendor Vendor ID to search for
223 \param product Product ID to search for
edb82cbf 224
1941414d 225 \retval >0: number of devices found
1941414d 226 \retval -3: out of memory
579b006f
JZ
227 \retval -4: libusb_init() failed
228 \retval -5: libusb_get_device_list() failed
229 \retval -6: libusb_get_device_descriptor() failed
edb82cbf 230*/
d2f10023 231int ftdi_usb_find_all(struct ftdi_context *ftdi, struct ftdi_device_list **devlist, int vendor, int product)
edb82cbf
TJ
232{
233 struct ftdi_device_list **curdev;
579b006f
JZ
234 libusb_device *dev;
235 libusb_device **devs;
edb82cbf 236 int count = 0;
579b006f
JZ
237 int i = 0;
238
239 if (libusb_init(NULL) < 0)
240 ftdi_error_return(-4, "libusb_init() failed");
d2f10023 241
579b006f
JZ
242 if (libusb_get_device_list(NULL, &devs) < 0)
243 ftdi_error_return(-5, "libusb_get_device_list() failed");
edb82cbf
TJ
244
245 curdev = devlist;
6db32169 246 *curdev = NULL;
579b006f
JZ
247
248 while ((dev = devs[i++]) != NULL)
22d12cda 249 {
579b006f 250 struct libusb_device_descriptor desc;
d2f10023 251
579b006f
JZ
252 if (libusb_get_device_descriptor(dev, &desc) < 0)
253 ftdi_error_return(-6, "libusb_get_device_descriptor() failed");
edb82cbf 254
579b006f
JZ
255 if (desc.idVendor == vendor && desc.idProduct == product)
256 {
257 *curdev = (struct ftdi_device_list*)malloc(sizeof(struct ftdi_device_list));
258 if (!*curdev)
259 ftdi_error_return(-3, "out of memory");
260
261 (*curdev)->next = NULL;
262 (*curdev)->dev = dev;
263
264 curdev = &(*curdev)->next;
265 count++;
edb82cbf
TJ
266 }
267 }
d2f10023 268
edb82cbf
TJ
269 return count;
270}
271
1941414d
TJ
272/**
273 Frees a usb device list.
edb82cbf 274
1941414d 275 \param devlist USB device list created by ftdi_usb_find_all()
edb82cbf 276*/
d2f10023 277void ftdi_list_free(struct ftdi_device_list **devlist)
edb82cbf 278{
6db32169
TJ
279 struct ftdi_device_list *curdev, *next;
280
22d12cda
TJ
281 for (curdev = *devlist; curdev != NULL;)
282 {
6db32169
TJ
283 next = curdev->next;
284 free(curdev);
285 curdev = next;
edb82cbf
TJ
286 }
287
6db32169 288 *devlist = NULL;
edb82cbf
TJ
289}
290
1941414d 291/**
cef378aa
TJ
292 Frees a usb device list.
293
294 \param devlist USB device list created by ftdi_usb_find_all()
295*/
296void ftdi_list_free2(struct ftdi_device_list *devlist)
297{
298 ftdi_list_free(&devlist);
299}
300
301/**
474786c0
TJ
302 Return device ID strings from the usb device.
303
304 The parameters manufacturer, description and serial may be NULL
305 or pointer to buffers to store the fetched strings.
306
898c34dd
TJ
307 \note Use this function only in combination with ftdi_usb_find_all()
308 as it closes the internal "usb_dev" after use.
309
474786c0
TJ
310 \param ftdi pointer to ftdi_context
311 \param dev libusb usb_dev to use
312 \param manufacturer Store manufacturer string here if not NULL
313 \param mnf_len Buffer size of manufacturer string
314 \param description Store product description string here if not NULL
315 \param desc_len Buffer size of product description string
316 \param serial Store serial string here if not NULL
317 \param serial_len Buffer size of serial string
318
319 \retval 0: all fine
320 \retval -1: wrong arguments
321 \retval -4: unable to open device
322 \retval -7: get product manufacturer failed
323 \retval -8: get product description failed
324 \retval -9: get serial number failed
579b006f 325 \retval -11: libusb_get_device_descriptor() failed
474786c0 326*/
579b006f 327int ftdi_usb_get_strings(struct ftdi_context * ftdi, struct libusb_device * dev,
22d12cda 328 char * manufacturer, int mnf_len, char * description, int desc_len, char * serial, int serial_len)
474786c0 329{
579b006f
JZ
330 struct libusb_device_descriptor desc;
331
474786c0
TJ
332 if ((ftdi==NULL) || (dev==NULL))
333 return -1;
334
579b006f
JZ
335 if (libusb_open(dev, &ftdi->usb_dev) < 0)
336 ftdi_error_return(-4, "libusb_open() failed");
337
338 if (libusb_get_device_descriptor(dev, &desc) < 0)
339 ftdi_error_return(-11, "libusb_get_device_descriptor() failed");
474786c0 340
22d12cda
TJ
341 if (manufacturer != NULL)
342 {
579b006f 343 if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iManufacturer, (unsigned char *)manufacturer, mnf_len) < 0)
22d12cda 344 {
f3f81007 345 ftdi_usb_close_internal (ftdi);
579b006f 346 ftdi_error_return(-7, "libusb_get_string_descriptor_ascii() failed");
474786c0
TJ
347 }
348 }
349
22d12cda
TJ
350 if (description != NULL)
351 {
579b006f 352 if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iProduct, (unsigned char *)description, desc_len) < 0)
22d12cda 353 {
f3f81007 354 ftdi_usb_close_internal (ftdi);
579b006f 355 ftdi_error_return(-8, "libusb_get_string_descriptor_ascii() failed");
474786c0
TJ
356 }
357 }
358
22d12cda
TJ
359 if (serial != NULL)
360 {
579b006f 361 if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iSerialNumber, (unsigned char *)serial, serial_len) < 0)
22d12cda 362 {
f3f81007 363 ftdi_usb_close_internal (ftdi);
579b006f 364 ftdi_error_return(-9, "libusb_get_string_descriptor_ascii() failed");
474786c0
TJ
365 }
366 }
367
579b006f 368 ftdi_usb_close_internal (ftdi);
474786c0
TJ
369
370 return 0;
371}
372
373/**
e2f12a4f
TJ
374 * Internal function to determine the maximum packet size.
375 * \param ftdi pointer to ftdi_context
376 * \param dev libusb usb_dev to use
377 * \retval Maximum packet size for this device
378 */
579b006f 379static unsigned int _ftdi_determine_max_packet_size(struct ftdi_context *ftdi, libusb_device *dev)
e2f12a4f 380{
579b006f
JZ
381 struct libusb_device_descriptor desc;
382 struct libusb_config_descriptor *config0;
e2f12a4f
TJ
383 unsigned int packet_size;
384
22a1b5c1
TJ
385 // Sanity check
386 if (ftdi == NULL || dev == NULL)
387 return 64;
388
e2f12a4f
TJ
389 // Determine maximum packet size. Init with default value.
390 // New hi-speed devices from FTDI use a packet size of 512 bytes
391 // but could be connected to a normal speed USB hub -> 64 bytes packet size.
392 if (ftdi->type == TYPE_2232H || ftdi->type == TYPE_4232H)
393 packet_size = 512;
394 else
395 packet_size = 64;
396
579b006f
JZ
397 if (libusb_get_device_descriptor(dev, &desc) < 0)
398 return packet_size;
399
400 if (libusb_get_config_descriptor(dev, 0, &config0) < 0)
401 return packet_size;
e2f12a4f 402
579b006f
JZ
403 if (desc.bNumConfigurations > 0)
404 {
405 if (ftdi->interface < config0->bNumInterfaces)
e2f12a4f 406 {
579b006f 407 struct libusb_interface interface = config0->interface[ftdi->interface];
e2f12a4f
TJ
408 if (interface.num_altsetting > 0)
409 {
579b006f 410 struct libusb_interface_descriptor descriptor = interface.altsetting[0];
e2f12a4f
TJ
411 if (descriptor.bNumEndpoints > 0)
412 {
413 packet_size = descriptor.endpoint[0].wMaxPacketSize;
414 }
415 }
416 }
417 }
418
579b006f 419 libusb_free_config_descriptor (config0);
e2f12a4f
TJ
420 return packet_size;
421}
422
423/**
418aaa72 424 Opens a ftdi device given by an usb_device.
7b18bef6 425
1941414d
TJ
426 \param ftdi pointer to ftdi_context
427 \param dev libusb usb_dev to use
428
429 \retval 0: all fine
23b1798d 430 \retval -3: unable to config device
1941414d
TJ
431 \retval -4: unable to open device
432 \retval -5: unable to claim device
433 \retval -6: reset failed
434 \retval -7: set baudrate failed
22a1b5c1 435 \retval -8: ftdi context invalid
579b006f
JZ
436 \retval -9: libusb_get_device_descriptor() failed
437 \retval -10: libusb_get_config_descriptor() failed
438 \retval -11: libusb_etach_kernel_driver() failed
439 \retval -12: libusb_get_configuration() failed
7b18bef6 440*/
579b006f 441int ftdi_usb_open_dev(struct ftdi_context *ftdi, libusb_device *dev)
7b18bef6 442{
579b006f
JZ
443 struct libusb_device_descriptor desc;
444 struct libusb_config_descriptor *config0;
445 int cfg, cfg0;
446
22a1b5c1
TJ
447 if (ftdi == NULL)
448 ftdi_error_return(-8, "ftdi context invalid");
449
579b006f
JZ
450 if (libusb_open(dev, &ftdi->usb_dev) < 0)
451 ftdi_error_return(-4, "libusb_open() failed");
452
453 if (libusb_get_device_descriptor(dev, &desc) < 0)
454 ftdi_error_return(-9, "libusb_get_device_descriptor() failed");
455
456 if (libusb_get_config_descriptor(dev, 0, &config0) < 0)
457 ftdi_error_return(-10, "libusb_get_config_descriptor() failed");
458 cfg0 = config0->bConfigurationValue;
459 libusb_free_config_descriptor (config0);
d2f10023
TJ
460
461#ifdef LIBUSB_HAS_GET_DRIVER_NP
22592e17
TJ
462 // Try to detach ftdi_sio kernel module.
463 // Returns ENODATA if driver is not loaded.
464 //
465 // The return code is kept in a separate variable and only parsed
466 // if usb_set_configuration() or usb_claim_interface() fails as the
467 // detach operation might be denied and everything still works fine.
468 // Likely scenario is a static ftdi_sio kernel module.
579b006f
JZ
469 ret = libusb_detach_kernel_driver(ftdi->usb_dev, ftdi->interface);
470 if (ret < 0 && ret != LIBUSB_ERROR_NOT_FOUND)
471 ftdi_error_return(-11, "libusb_detach_kernel_driver () failed");
d2f10023
TJ
472#endif
473
579b006f
JZ
474 if (libusb_get_configuration (ftdi->usb_dev, &cfg) < 0)
475 ftdi_error_return(-12, "libusb_get_configuration () failed");
476
b57aedfd
GE
477 // set configuration (needed especially for windows)
478 // tolerate EBUSY: one device with one configuration, but two interfaces
479 // and libftdi sessions to both interfaces (e.g. FT2232)
579b006f 480 if (desc.bNumConfigurations > 0 && cfg != cfg0)
b57aedfd 481 {
579b006f 482 if (libusb_set_configuration(ftdi->usb_dev, cfg0) < 0)
22d12cda 483 {
a56ba2bd 484 ftdi_usb_close_internal (ftdi);
579b006f 485 ftdi_error_return(-3, "unable to set usb configuration. Make sure ftdi_sio is unloaded!");
23b1798d
TJ
486 }
487 }
488
579b006f 489 if (libusb_claim_interface(ftdi->usb_dev, ftdi->interface) < 0)
22d12cda 490 {
f3f81007 491 ftdi_usb_close_internal (ftdi);
579b006f 492 ftdi_error_return(-5, "unable to claim usb device. Make sure ftdi_sio is unloaded!");
7b18bef6
TJ
493 }
494
22d12cda
TJ
495 if (ftdi_usb_reset (ftdi) != 0)
496 {
f3f81007 497 ftdi_usb_close_internal (ftdi);
7b18bef6
TJ
498 ftdi_error_return(-6, "ftdi_usb_reset failed");
499 }
500
7b18bef6
TJ
501 // Try to guess chip type
502 // Bug in the BM type chips: bcdDevice is 0x200 for serial == 0
579b006f
JZ
503 if (desc.bcdDevice == 0x400 || (desc.bcdDevice == 0x200
504 && desc.iSerialNumber == 0))
7b18bef6 505 ftdi->type = TYPE_BM;
579b006f 506 else if (desc.bcdDevice == 0x200)
7b18bef6 507 ftdi->type = TYPE_AM;
579b006f 508 else if (desc.bcdDevice == 0x500)
7b18bef6 509 ftdi->type = TYPE_2232C;
579b006f 510 else if (desc.bcdDevice == 0x600)
cb6250fa 511 ftdi->type = TYPE_R;
579b006f 512 else if (desc.bcdDevice == 0x700)
0beb9686 513 ftdi->type = TYPE_2232H;
579b006f 514 else if (desc.bcdDevice == 0x800)
0beb9686 515 ftdi->type = TYPE_4232H;
7b18bef6 516
f9d69895
AH
517 // Set default interface on dual/quad type chips
518 switch(ftdi->type)
519 {
520 case TYPE_2232C:
521 case TYPE_2232H:
522 case TYPE_4232H:
523 if (!ftdi->index)
524 ftdi->index = INTERFACE_A;
525 break;
526 default:
527 break;
528 }
529
e2f12a4f
TJ
530 // Determine maximum packet size
531 ftdi->max_packet_size = _ftdi_determine_max_packet_size(ftdi, dev);
532
ef6f4838
TE
533 if (ftdi_set_baudrate (ftdi, 9600) != 0)
534 {
535 ftdi_usb_close_internal (ftdi);
536 ftdi_error_return(-7, "set baudrate failed");
537 }
538
7b18bef6
TJ
539 ftdi_error_return(0, "all fine");
540}
541
1941414d
TJ
542/**
543 Opens the first device with a given vendor and product ids.
544
545 \param ftdi pointer to ftdi_context
546 \param vendor Vendor ID
547 \param product Product ID
548
9bec2387 549 \retval same as ftdi_usb_open_desc()
1941414d 550*/
edb82cbf
TJ
551int ftdi_usb_open(struct ftdi_context *ftdi, int vendor, int product)
552{
553 return ftdi_usb_open_desc(ftdi, vendor, product, NULL, NULL);
554}
555
1941414d
TJ
556/**
557 Opens the first device with a given, vendor id, product id,
558 description and serial.
559
560 \param ftdi pointer to ftdi_context
561 \param vendor Vendor ID
562 \param product Product ID
563 \param description Description to search for. Use NULL if not needed.
564 \param serial Serial to search for. Use NULL if not needed.
565
566 \retval 0: all fine
1941414d
TJ
567 \retval -3: usb device not found
568 \retval -4: unable to open device
569 \retval -5: unable to claim device
570 \retval -6: reset failed
571 \retval -7: set baudrate failed
572 \retval -8: get product description failed
573 \retval -9: get serial number failed
579b006f
JZ
574 \retval -11: libusb_init() failed
575 \retval -12: libusb_get_device_list() failed
576 \retval -13: libusb_get_device_descriptor() failed
a3da1d95 577*/
04e1ea0a 578int ftdi_usb_open_desc(struct ftdi_context *ftdi, int vendor, int product,
a8f46ddc
TJ
579 const char* description, const char* serial)
580{
5ebbdab9
GE
581 return ftdi_usb_open_desc_index(ftdi,vendor,product,description,serial,0);
582}
583
584/**
585 Opens the index-th device with a given, vendor id, product id,
586 description and serial.
587
588 \param ftdi pointer to ftdi_context
589 \param vendor Vendor ID
590 \param product Product ID
591 \param description Description to search for. Use NULL if not needed.
592 \param serial Serial to search for. Use NULL if not needed.
593 \param index Number of matching device to open if there are more than one, starts with 0.
594
595 \retval 0: all fine
596 \retval -1: usb_find_busses() failed
597 \retval -2: usb_find_devices() failed
598 \retval -3: usb device not found
599 \retval -4: unable to open device
600 \retval -5: unable to claim device
601 \retval -6: reset failed
602 \retval -7: set baudrate failed
603 \retval -8: get product description failed
604 \retval -9: get serial number failed
605 \retval -10: unable to close device
22a1b5c1 606 \retval -11: ftdi context invalid
5ebbdab9
GE
607*/
608int ftdi_usb_open_desc_index(struct ftdi_context *ftdi, int vendor, int product,
609 const char* description, const char* serial, unsigned int index)
610{
579b006f
JZ
611 libusb_device *dev;
612 libusb_device **devs;
c3d95b87 613 char string[256];
579b006f 614 int i = 0;
98452d97 615
579b006f
JZ
616 if (libusb_init(NULL) < 0)
617 ftdi_error_return(-11, "libusb_init() failed");
98452d97 618
579b006f
JZ
619 if (libusb_get_device_list(NULL, &devs) < 0)
620 ftdi_error_return(-12, "libusb_get_device_list() failed");
a3da1d95 621
22a1b5c1
TJ
622 if (ftdi == NULL)
623 ftdi_error_return(-11, "ftdi context invalid");
624
579b006f 625 while ((dev = devs[i++]) != NULL)
22d12cda 626 {
579b006f
JZ
627 struct libusb_device_descriptor desc;
628
629 if (libusb_get_device_descriptor(dev, &desc) < 0)
630 ftdi_error_return(-13, "libusb_get_device_descriptor() failed");
631
632 if (desc.idVendor == vendor && desc.idProduct == product)
22d12cda 633 {
579b006f
JZ
634 if (libusb_open(dev, &ftdi->usb_dev) < 0)
635 ftdi_error_return(-4, "usb_open() failed");
c3d95b87 636
579b006f
JZ
637 if (description != NULL)
638 {
639 if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iProduct, (unsigned char *)string, sizeof(string)) < 0)
22d12cda 640 {
579b006f
JZ
641 libusb_close (ftdi->usb_dev);
642 ftdi_error_return(-8, "unable to fetch product description");
a8f46ddc 643 }
579b006f 644 if (strncmp(string, description, sizeof(string)) != 0)
22d12cda 645 {
579b006f
JZ
646 libusb_close (ftdi->usb_dev);
647 continue;
a8f46ddc 648 }
579b006f
JZ
649 }
650 if (serial != NULL)
651 {
652 if (libusb_get_string_descriptor_ascii(ftdi->usb_dev, desc.iSerialNumber, (unsigned char *)string, sizeof(string)) < 0)
653 {
654 ftdi_usb_close_internal (ftdi);
655 ftdi_error_return(-9, "unable to fetch serial number");
656 }
657 if (strncmp(string, serial, sizeof(string)) != 0)
658 {
659 ftdi_usb_close_internal (ftdi);
660 continue;
661 }
662 }
98452d97 663
579b006f 664 ftdi_usb_close_internal (ftdi);
d2f10023 665
5ebbdab9
GE
666 if (index > 0)
667 {
668 index--;
669 continue;
670 }
671
579b006f 672 return ftdi_usb_open_dev(ftdi, dev);
98452d97 673 }
98452d97 674 }
a3da1d95 675
98452d97 676 // device not found
c3d95b87 677 ftdi_error_return(-3, "device not found");
a3da1d95
GE
678}
679
1941414d 680/**
5ebbdab9
GE
681 Opens the ftdi-device described by a description-string.
682 Intended to be used for parsing a device-description given as commandline argument.
683
684 \param ftdi pointer to ftdi_context
685 \param description NULL-terminated description-string, using this format:
686 \li <tt>d:\<devicenode></tt> path of bus and device-node (e.g. "003/001") within usb device tree (usually at /proc/bus/usb/)
687 \li <tt>i:\<vendor>:\<product></tt> first device with given vendor and product id, ids can be decimal, octal (preceded by "0") or hex (preceded by "0x")
688 \li <tt>i:\<vendor>:\<product>:\<index></tt> as above with index being the number of the device (starting with 0) if there are more than one
689 \li <tt>s:\<vendor>:\<product>:\<serial></tt> first device with given vendor id, product id and serial string
690
691 \note The description format may be extended in later versions.
692
693 \retval 0: all fine
579b006f
JZ
694 \retval -1: libusb_init() failed
695 \retval -2: libusb_get_device_list() failed
5ebbdab9
GE
696 \retval -3: usb device not found
697 \retval -4: unable to open device
698 \retval -5: unable to claim device
699 \retval -6: reset failed
700 \retval -7: set baudrate failed
701 \retval -8: get product description failed
702 \retval -9: get serial number failed
703 \retval -10: unable to close device
704 \retval -11: illegal description format
22a1b5c1 705 \retval -12: ftdi context invalid
5ebbdab9
GE
706*/
707int ftdi_usb_open_string(struct ftdi_context *ftdi, const char* description)
708{
22a1b5c1
TJ
709 if (ftdi == NULL)
710 ftdi_error_return(-12, "ftdi context invalid");
711
5ebbdab9
GE
712 if (description[0] == 0 || description[1] != ':')
713 ftdi_error_return(-11, "illegal description format");
714
715 if (description[0] == 'd')
716 {
579b006f
JZ
717 libusb_device *dev;
718 libusb_device **devs;
719 unsigned int bus_number, device_address;
720 int i = 0;
721
722 if (libusb_init (NULL) < 0)
723 ftdi_error_return(-1, "libusb_init() failed");
5ebbdab9 724
579b006f
JZ
725 if (libusb_get_device_list(NULL, &devs) < 0)
726 ftdi_error_return(-2, "libusb_get_device_list() failed");
5ebbdab9 727
579b006f
JZ
728 /* XXX: This doesn't handle symlinks/odd paths/etc... */
729 if (sscanf (description + 2, "%u/%u", &bus_number, &device_address) != 2)
730 ftdi_error_return(-11, "illegal description format");
5ebbdab9 731
579b006f 732 while ((dev = devs[i++]) != NULL)
5ebbdab9 733 {
579b006f
JZ
734 if (bus_number == libusb_get_bus_number (dev)
735 && device_address == libusb_get_device_address (dev))
3d0099ee 736 return ftdi_usb_open_dev(ftdi, dev);
5ebbdab9
GE
737 }
738
739 // device not found
740 ftdi_error_return(-3, "device not found");
741 }
742 else if (description[0] == 'i' || description[0] == 's')
743 {
744 unsigned int vendor;
745 unsigned int product;
746 unsigned int index=0;
0e6cf62b 747 const char *serial=NULL;
5ebbdab9
GE
748 const char *startp, *endp;
749
750 errno=0;
751 startp=description+2;
752 vendor=strtoul((char*)startp,(char**)&endp,0);
753 if (*endp != ':' || endp == startp || errno != 0)
754 ftdi_error_return(-11, "illegal description format");
755
756 startp=endp+1;
757 product=strtoul((char*)startp,(char**)&endp,0);
758 if (endp == startp || errno != 0)
759 ftdi_error_return(-11, "illegal description format");
760
761 if (description[0] == 'i' && *endp != 0)
762 {
763 /* optional index field in i-mode */
764 if (*endp != ':')
765 ftdi_error_return(-11, "illegal description format");
766
767 startp=endp+1;
768 index=strtoul((char*)startp,(char**)&endp,0);
769 if (*endp != 0 || endp == startp || errno != 0)
770 ftdi_error_return(-11, "illegal description format");
771 }
772 if (description[0] == 's')
773 {
774 if (*endp != ':')
775 ftdi_error_return(-11, "illegal description format");
776
777 /* rest of the description is the serial */
778 serial=endp+1;
779 }
780
781 return ftdi_usb_open_desc_index(ftdi, vendor, product, NULL, serial, index);
782 }
783 else
784 {
785 ftdi_error_return(-11, "illegal description format");
786 }
787}
788
789/**
1941414d 790 Resets the ftdi device.
a3da1d95 791
1941414d
TJ
792 \param ftdi pointer to ftdi_context
793
794 \retval 0: all fine
795 \retval -1: FTDI reset failed
22a1b5c1 796 \retval -2: USB device unavailable
4837f98a 797*/
edb82cbf 798int ftdi_usb_reset(struct ftdi_context *ftdi)
a8f46ddc 799{
22a1b5c1
TJ
800 if (ftdi == NULL || ftdi->usb_dev == NULL)
801 ftdi_error_return(-2, "USB device unavailable");
802
579b006f
JZ
803 if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
804 SIO_RESET_REQUEST, SIO_RESET_SIO,
805 ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
22d12cda 806 ftdi_error_return(-1,"FTDI reset failed");
c3d95b87 807
545820ce 808 // Invalidate data in the readbuffer
bfcee05b
TJ
809 ftdi->readbuffer_offset = 0;
810 ftdi->readbuffer_remaining = 0;
811
a3da1d95
GE
812 return 0;
813}
814
1941414d 815/**
1189b11a 816 Clears the read buffer on the chip and the internal read buffer.
1941414d
TJ
817
818 \param ftdi pointer to ftdi_context
4837f98a 819
1941414d 820 \retval 0: all fine
1189b11a 821 \retval -1: read buffer purge failed
22a1b5c1 822 \retval -2: USB device unavailable
4837f98a 823*/
1189b11a 824int ftdi_usb_purge_rx_buffer(struct ftdi_context *ftdi)
a8f46ddc 825{
22a1b5c1
TJ
826 if (ftdi == NULL || ftdi->usb_dev == NULL)
827 ftdi_error_return(-2, "USB device unavailable");
828
579b006f
JZ
829 if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
830 SIO_RESET_REQUEST, SIO_RESET_PURGE_RX,
831 ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
c3d95b87
TJ
832 ftdi_error_return(-1, "FTDI purge of RX buffer failed");
833
545820ce 834 // Invalidate data in the readbuffer
bfcee05b
TJ
835 ftdi->readbuffer_offset = 0;
836 ftdi->readbuffer_remaining = 0;
a60be878 837
1189b11a
TJ
838 return 0;
839}
840
841/**
842 Clears the write buffer on the chip.
843
844 \param ftdi pointer to ftdi_context
845
846 \retval 0: all fine
847 \retval -1: write buffer purge failed
22a1b5c1 848 \retval -2: USB device unavailable
1189b11a
TJ
849*/
850int ftdi_usb_purge_tx_buffer(struct ftdi_context *ftdi)
851{
22a1b5c1
TJ
852 if (ftdi == NULL || ftdi->usb_dev == NULL)
853 ftdi_error_return(-2, "USB device unavailable");
854
579b006f
JZ
855 if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
856 SIO_RESET_REQUEST, SIO_RESET_PURGE_TX,
857 ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
1189b11a
TJ
858 ftdi_error_return(-1, "FTDI purge of TX buffer failed");
859
860 return 0;
861}
862
863/**
864 Clears the buffers on the chip and the internal read buffer.
865
866 \param ftdi pointer to ftdi_context
867
868 \retval 0: all fine
869 \retval -1: read buffer purge failed
870 \retval -2: write buffer purge failed
22a1b5c1 871 \retval -3: USB device unavailable
1189b11a
TJ
872*/
873int ftdi_usb_purge_buffers(struct ftdi_context *ftdi)
874{
875 int result;
876
22a1b5c1
TJ
877 if (ftdi == NULL || ftdi->usb_dev == NULL)
878 ftdi_error_return(-3, "USB device unavailable");
879
1189b11a 880 result = ftdi_usb_purge_rx_buffer(ftdi);
5a2b51cb 881 if (result < 0)
1189b11a
TJ
882 return -1;
883
884 result = ftdi_usb_purge_tx_buffer(ftdi);
5a2b51cb 885 if (result < 0)
1189b11a 886 return -2;
545820ce 887
a60be878
TJ
888 return 0;
889}
a3da1d95 890
f3f81007
TJ
891
892
1941414d
TJ
893/**
894 Closes the ftdi device. Call ftdi_deinit() if you're cleaning up.
895
896 \param ftdi pointer to ftdi_context
897
898 \retval 0: all fine
899 \retval -1: usb_release failed
22a1b5c1 900 \retval -3: ftdi context invalid
a3da1d95 901*/
a8f46ddc
TJ
902int ftdi_usb_close(struct ftdi_context *ftdi)
903{
a3da1d95
GE
904 int rtn = 0;
905
22a1b5c1
TJ
906 if (ftdi == NULL)
907 ftdi_error_return(-3, "ftdi context invalid");
908
dff4fdb0 909 if (ftdi->usb_dev != NULL)
579b006f 910 if (libusb_release_interface(ftdi->usb_dev, ftdi->interface) < 0)
dff4fdb0 911 rtn = -1;
98452d97 912
579b006f 913 ftdi_usb_close_internal (ftdi);
98452d97 914
a3da1d95
GE
915 return rtn;
916}
917
418aaa72 918/**
53ad271d
TJ
919 ftdi_convert_baudrate returns nearest supported baud rate to that requested.
920 Function is only used internally
b5ec1820 921 \internal
53ad271d 922*/
0126d22e 923static int ftdi_convert_baudrate(int baudrate, struct ftdi_context *ftdi,
a8f46ddc
TJ
924 unsigned short *value, unsigned short *index)
925{
53ad271d
TJ
926 static const char am_adjust_up[8] = {0, 0, 0, 1, 0, 3, 2, 1};
927 static const char am_adjust_dn[8] = {0, 0, 0, 1, 0, 1, 2, 3};
928 static const char frac_code[8] = {0, 3, 2, 4, 1, 5, 6, 7};
929 int divisor, best_divisor, best_baud, best_baud_diff;
930 unsigned long encoded_divisor;
931 int i;
932
22d12cda
TJ
933 if (baudrate <= 0)
934 {
53ad271d
TJ
935 // Return error
936 return -1;
937 }
938
939 divisor = 24000000 / baudrate;
940
22d12cda
TJ
941 if (ftdi->type == TYPE_AM)
942 {
53ad271d
TJ
943 // Round down to supported fraction (AM only)
944 divisor -= am_adjust_dn[divisor & 7];
945 }
946
947 // Try this divisor and the one above it (because division rounds down)
948 best_divisor = 0;
949 best_baud = 0;
950 best_baud_diff = 0;
22d12cda
TJ
951 for (i = 0; i < 2; i++)
952 {
53ad271d
TJ
953 int try_divisor = divisor + i;
954 int baud_estimate;
955 int baud_diff;
956
957 // Round up to supported divisor value
22d12cda
TJ
958 if (try_divisor <= 8)
959 {
53ad271d
TJ
960 // Round up to minimum supported divisor
961 try_divisor = 8;
22d12cda
TJ
962 }
963 else if (ftdi->type != TYPE_AM && try_divisor < 12)
964 {
53ad271d
TJ
965 // BM doesn't support divisors 9 through 11 inclusive
966 try_divisor = 12;
22d12cda
TJ
967 }
968 else if (divisor < 16)
969 {
53ad271d
TJ
970 // AM doesn't support divisors 9 through 15 inclusive
971 try_divisor = 16;
22d12cda
TJ
972 }
973 else
974 {
975 if (ftdi->type == TYPE_AM)
976 {
53ad271d
TJ
977 // Round up to supported fraction (AM only)
978 try_divisor += am_adjust_up[try_divisor & 7];
22d12cda
TJ
979 if (try_divisor > 0x1FFF8)
980 {
53ad271d
TJ
981 // Round down to maximum supported divisor value (for AM)
982 try_divisor = 0x1FFF8;
983 }
22d12cda
TJ
984 }
985 else
986 {
987 if (try_divisor > 0x1FFFF)
988 {
53ad271d
TJ
989 // Round down to maximum supported divisor value (for BM)
990 try_divisor = 0x1FFFF;
991 }
992 }
993 }
994 // Get estimated baud rate (to nearest integer)
995 baud_estimate = (24000000 + (try_divisor / 2)) / try_divisor;
996 // Get absolute difference from requested baud rate
22d12cda
TJ
997 if (baud_estimate < baudrate)
998 {
53ad271d 999 baud_diff = baudrate - baud_estimate;
22d12cda
TJ
1000 }
1001 else
1002 {
53ad271d
TJ
1003 baud_diff = baud_estimate - baudrate;
1004 }
22d12cda
TJ
1005 if (i == 0 || baud_diff < best_baud_diff)
1006 {
53ad271d
TJ
1007 // Closest to requested baud rate so far
1008 best_divisor = try_divisor;
1009 best_baud = baud_estimate;
1010 best_baud_diff = baud_diff;
22d12cda
TJ
1011 if (baud_diff == 0)
1012 {
53ad271d
TJ
1013 // Spot on! No point trying
1014 break;
1015 }
1016 }
1017 }
1018 // Encode the best divisor value
1019 encoded_divisor = (best_divisor >> 3) | (frac_code[best_divisor & 7] << 14);
1020 // Deal with special cases for encoded value
22d12cda
TJ
1021 if (encoded_divisor == 1)
1022 {
4837f98a 1023 encoded_divisor = 0; // 3000000 baud
22d12cda
TJ
1024 }
1025 else if (encoded_divisor == 0x4001)
1026 {
4837f98a 1027 encoded_divisor = 1; // 2000000 baud (BM only)
53ad271d
TJ
1028 }
1029 // Split into "value" and "index" values
1030 *value = (unsigned short)(encoded_divisor & 0xFFFF);
1416eb14 1031 if (ftdi->type == TYPE_2232C || ftdi->type == TYPE_2232H || ftdi->type == TYPE_4232H)
22d12cda 1032 {
0126d22e
TJ
1033 *index = (unsigned short)(encoded_divisor >> 8);
1034 *index &= 0xFF00;
a9c57c05 1035 *index |= ftdi->index;
0126d22e
TJ
1036 }
1037 else
1038 *index = (unsigned short)(encoded_divisor >> 16);
c3d95b87 1039
53ad271d
TJ
1040 // Return the nearest baud rate
1041 return best_baud;
1042}
1043
1941414d 1044/**
9bec2387 1045 Sets the chip baud rate
1941414d
TJ
1046
1047 \param ftdi pointer to ftdi_context
9bec2387 1048 \param baudrate baud rate to set
1941414d
TJ
1049
1050 \retval 0: all fine
1051 \retval -1: invalid baudrate
1052 \retval -2: setting baudrate failed
22a1b5c1 1053 \retval -3: USB device unavailable
a3da1d95 1054*/
a8f46ddc
TJ
1055int ftdi_set_baudrate(struct ftdi_context *ftdi, int baudrate)
1056{
53ad271d
TJ
1057 unsigned short value, index;
1058 int actual_baudrate;
a3da1d95 1059
22a1b5c1
TJ
1060 if (ftdi == NULL || ftdi->usb_dev == NULL)
1061 ftdi_error_return(-3, "USB device unavailable");
1062
22d12cda
TJ
1063 if (ftdi->bitbang_enabled)
1064 {
a3da1d95
GE
1065 baudrate = baudrate*4;
1066 }
1067
25707904 1068 actual_baudrate = ftdi_convert_baudrate(baudrate, ftdi, &value, &index);
c3d95b87
TJ
1069 if (actual_baudrate <= 0)
1070 ftdi_error_return (-1, "Silly baudrate <= 0.");
a3da1d95 1071
53ad271d
TJ
1072 // Check within tolerance (about 5%)
1073 if ((actual_baudrate * 2 < baudrate /* Catch overflows */ )
1074 || ((actual_baudrate < baudrate)
1075 ? (actual_baudrate * 21 < baudrate * 20)
c3d95b87
TJ
1076 : (baudrate * 21 < actual_baudrate * 20)))
1077 ftdi_error_return (-1, "Unsupported baudrate. Note: bitbang baudrates are automatically multiplied by 4");
545820ce 1078
579b006f
JZ
1079 if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1080 SIO_SET_BAUDRATE_REQUEST, value,
1081 index, NULL, 0, ftdi->usb_write_timeout) < 0)
c3d95b87 1082 ftdi_error_return (-2, "Setting new baudrate failed");
a3da1d95
GE
1083
1084 ftdi->baudrate = baudrate;
1085 return 0;
1086}
1087
1941414d 1088/**
6c32e222
TJ
1089 Set (RS232) line characteristics.
1090 The break type can only be set via ftdi_set_line_property2()
1091 and defaults to "off".
4837f98a 1092
1941414d
TJ
1093 \param ftdi pointer to ftdi_context
1094 \param bits Number of bits
1095 \param sbit Number of stop bits
1096 \param parity Parity mode
1097
1098 \retval 0: all fine
1099 \retval -1: Setting line property failed
2f73e59f
TJ
1100*/
1101int ftdi_set_line_property(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
d2f10023 1102 enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity)
2f73e59f 1103{
6c32e222
TJ
1104 return ftdi_set_line_property2(ftdi, bits, sbit, parity, BREAK_OFF);
1105}
1106
1107/**
1108 Set (RS232) line characteristics
1109
1110 \param ftdi pointer to ftdi_context
1111 \param bits Number of bits
1112 \param sbit Number of stop bits
1113 \param parity Parity mode
1114 \param break_type Break type
1115
1116 \retval 0: all fine
1117 \retval -1: Setting line property failed
22a1b5c1 1118 \retval -2: USB device unavailable
6c32e222
TJ
1119*/
1120int ftdi_set_line_property2(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
22d12cda
TJ
1121 enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity,
1122 enum ftdi_break_type break_type)
6c32e222 1123{
2f73e59f
TJ
1124 unsigned short value = bits;
1125
22a1b5c1
TJ
1126 if (ftdi == NULL || ftdi->usb_dev == NULL)
1127 ftdi_error_return(-2, "USB device unavailable");
1128
22d12cda
TJ
1129 switch (parity)
1130 {
1131 case NONE:
1132 value |= (0x00 << 8);
1133 break;
1134 case ODD:
1135 value |= (0x01 << 8);
1136 break;
1137 case EVEN:
1138 value |= (0x02 << 8);
1139 break;
1140 case MARK:
1141 value |= (0x03 << 8);
1142 break;
1143 case SPACE:
1144 value |= (0x04 << 8);
1145 break;
2f73e59f 1146 }
d2f10023 1147
22d12cda
TJ
1148 switch (sbit)
1149 {
1150 case STOP_BIT_1:
1151 value |= (0x00 << 11);
1152 break;
1153 case STOP_BIT_15:
1154 value |= (0x01 << 11);
1155 break;
1156 case STOP_BIT_2:
1157 value |= (0x02 << 11);
1158 break;
2f73e59f 1159 }
d2f10023 1160
22d12cda
TJ
1161 switch (break_type)
1162 {
1163 case BREAK_OFF:
1164 value |= (0x00 << 14);
1165 break;
1166 case BREAK_ON:
1167 value |= (0x01 << 14);
1168 break;
6c32e222
TJ
1169 }
1170
579b006f
JZ
1171 if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1172 SIO_SET_DATA_REQUEST, value,
1173 ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
2f73e59f 1174 ftdi_error_return (-1, "Setting new line property failed");
d2f10023 1175
2f73e59f
TJ
1176 return 0;
1177}
a3da1d95 1178
1941414d
TJ
1179/**
1180 Writes data in chunks (see ftdi_write_data_set_chunksize()) to the chip
1181
1182 \param ftdi pointer to ftdi_context
1183 \param buf Buffer with the data
1184 \param size Size of the buffer
1185
22a1b5c1 1186 \retval -666: USB device unavailable
1941414d
TJ
1187 \retval <0: error code from usb_bulk_write()
1188 \retval >0: number of bytes written
1189*/
a8f46ddc
TJ
1190int ftdi_write_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
1191{
a3da1d95 1192 int offset = 0;
579b006f 1193 int actual_length;
c3d95b87 1194
22a1b5c1
TJ
1195 if (ftdi == NULL || ftdi->usb_dev == NULL)
1196 ftdi_error_return(-666, "USB device unavailable");
1197
22d12cda
TJ
1198 while (offset < size)
1199 {
948f9ada 1200 int write_size = ftdi->writebuffer_chunksize;
a3da1d95
GE
1201
1202 if (offset+write_size > size)
1203 write_size = size-offset;
1204
579b006f
JZ
1205 if (libusb_bulk_transfer(ftdi->usb_dev, ftdi->in_ep, buf+offset, write_size, &actual_length, ftdi->usb_write_timeout) < 0)
1206 ftdi_error_return(-1, "usb bulk write failed");
a3da1d95 1207
579b006f 1208 offset += actual_length;
a3da1d95
GE
1209 }
1210
579b006f 1211 return offset;
a3da1d95
GE
1212}
1213
f01d7ca6 1214#ifdef LIBFTDI_LINUX_ASYNC_MODE
e59bc450
CW
1215#ifdef USB_CLASS_PTP
1216#error LIBFTDI_LINUX_ASYNC_MODE is not compatible with libusb-compat-0.1!
1217#endif
579b006f 1218static void ftdi_read_data_cb(struct libusb_transfer *transfer)
22d12cda 1219{
579b006f
JZ
1220 struct ftdi_transfer_control *tc = (struct ftdi_transfer_control *) transfer->user_data;
1221 struct ftdi_context *ftdi = tc->ftdi;
1222 int packet_size, actual_length, num_of_chunks, chunk_remains, i, ret;
4c9e3812 1223
b1139150 1224 packet_size = ftdi->max_packet_size;
579b006f
JZ
1225
1226 actual_length = transfer->actual_length;
1227
1228 if (actual_length > 2)
1229 {
1230 // skip FTDI status bytes.
1231 // Maybe stored in the future to enable modem use
1232 num_of_chunks = actual_length / packet_size;
1233 chunk_remains = actual_length % packet_size;
1234 //printf("actual_length = %X, num_of_chunks = %X, chunk_remains = %X, readbuffer_offset = %X\n", actual_length, num_of_chunks, chunk_remains, ftdi->readbuffer_offset);
1235
1236 ftdi->readbuffer_offset += 2;
1237 actual_length -= 2;
1238
1239 if (actual_length > packet_size - 2)
1240 {
1241 for (i = 1; i < num_of_chunks; i++)
1242 memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1243 ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1244 packet_size - 2);
1245 if (chunk_remains > 2)
1246 {
1247 memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1248 ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1249 chunk_remains-2);
1250 actual_length -= 2*num_of_chunks;
1251 }
1252 else
1253 actual_length -= 2*(num_of_chunks-1)+chunk_remains;
1254 }
1255
1256 if (actual_length > 0)
1257 {
1258 // data still fits in buf?
1259 if (tc->offset + actual_length <= tc->size)
1260 {
1261 memcpy (tc->buf + tc->offset, ftdi->readbuffer + ftdi->readbuffer_offset, actual_length);
1262 //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
1263 tc->offset += actual_length;
1264
1265 ftdi->readbuffer_offset = 0;
1266 ftdi->readbuffer_remaining = 0;
1267
1268 /* Did we read exactly the right amount of bytes? */
1269 if (tc->offset == tc->size)
1270 {
1271 //printf("read_data exact rem %d offset %d\n",
1272 //ftdi->readbuffer_remaining, offset);
1273 tc->completed = 1;
1274 return;
1275 }
1276 }
1277 else
1278 {
1279 // only copy part of the data or size <= readbuffer_chunksize
1280 int part_size = tc->size - tc->offset;
1281 memcpy (tc->buf + tc->offset, ftdi->readbuffer + ftdi->readbuffer_offset, part_size);
1282 tc->offset += part_size;
1283
1284 ftdi->readbuffer_offset += part_size;
1285 ftdi->readbuffer_remaining = actual_length - part_size;
1286
1287 /* printf("Returning part: %d - size: %d - offset: %d - actual_length: %d - remaining: %d\n",
1288 part_size, size, offset, actual_length, ftdi->readbuffer_remaining); */
1289 tc->completed = 1;
1290 return;
1291 }
1292 }
1293 }
1294 ret = libusb_submit_transfer (transfer);
1295 if (ret < 0)
1296 tc->completed = 1;
1297}
1298
1299
1300static void ftdi_write_data_cb(struct libusb_transfer *transfer)
7cc9950e 1301{
579b006f
JZ
1302 struct ftdi_transfer_control *tc = (struct ftdi_transfer_control *) transfer->user_data;
1303 struct ftdi_context *ftdi = tc->ftdi;
1304
1305 tc->offset = transfer->actual_length;
7cc9950e 1306
579b006f 1307 if (tc->offset == tc->size)
22d12cda 1308 {
579b006f 1309 tc->completed = 1;
7cc9950e 1310 }
579b006f
JZ
1311 else
1312 {
1313 int write_size = ftdi->writebuffer_chunksize;
1314 int ret;
7cc9950e 1315
579b006f
JZ
1316 if (tc->offset + write_size > tc->size)
1317 write_size = tc->size - tc->offset;
1318
1319 transfer->length = write_size;
1320 transfer->buffer = tc->buf + tc->offset;
1321 ret = libusb_submit_transfer (transfer);
1322 if (ret < 0)
1323 tc->completed = 1;
1324 }
7cc9950e
GE
1325}
1326
579b006f 1327
84f85aaa 1328/**
579b006f
JZ
1329 Writes data to the chip. Does not wait for completion of the transfer
1330 nor does it make sure that the transfer was successful.
1331
1332 Use libusb 1.0 Asynchronous API.
1333 Only available if compiled with --with-async-mode.
84f85aaa
GE
1334
1335 \param ftdi pointer to ftdi_context
579b006f
JZ
1336 \param buf Buffer with the data
1337 \param size Size of the buffer
84f85aaa 1338
579b006f
JZ
1339 \retval NULL: Some error happens when submit transfer
1340 \retval !NULL: Pointer to a ftdi_transfer_control
c201f80f 1341*/
579b006f
JZ
1342
1343struct ftdi_transfer_control *ftdi_write_data_submit(struct ftdi_context *ftdi, unsigned char *buf, int size)
7cc9950e 1344{
579b006f
JZ
1345 struct ftdi_transfer_control *tc;
1346 struct libusb_transfer *transfer = libusb_alloc_transfer(0);
1347 int write_size, ret;
22d12cda 1348
22a1b5c1
TJ
1349 if (ftdi == NULL || ftdi->usb_dev == NULL)
1350 {
1351 libusb_free_transfer(transfer);
1352 return NULL;
1353 }
1354
579b006f 1355 tc = (struct ftdi_transfer_control *) malloc (sizeof (*tc));
22d12cda 1356
579b006f
JZ
1357 if (!tc || !transfer)
1358 return NULL;
22d12cda 1359
579b006f
JZ
1360 tc->ftdi = ftdi;
1361 tc->completed = 0;
1362 tc->buf = buf;
1363 tc->size = size;
1364 tc->offset = 0;
7cc9950e 1365
579b006f
JZ
1366 if (size < ftdi->writebuffer_chunksize)
1367 write_size = size;
1368 else
1369 write_size = ftdi->writebuffer_chunksize;
22d12cda 1370
579b006f
JZ
1371 libusb_fill_bulk_transfer(transfer, ftdi->usb_dev, ftdi->in_ep, buf, write_size, ftdi_write_data_cb, tc, ftdi->usb_write_timeout);
1372 transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
7cc9950e 1373
579b006f
JZ
1374 ret = libusb_submit_transfer(transfer);
1375 if (ret < 0)
1376 {
1377 libusb_free_transfer(transfer);
1378 tc->completed = 1;
1379 tc->transfer = NULL;
1380 return NULL;
7cc9950e 1381 }
579b006f
JZ
1382 tc->transfer = transfer;
1383
1384 return tc;
7cc9950e
GE
1385}
1386
1387/**
579b006f
JZ
1388 Reads data from the chip. Does not wait for completion of the transfer
1389 nor does it make sure that the transfer was successful.
1390
1391 Use libusb 1.0 Asynchronous API.
1392 Only available if compiled with --with-async-mode.
7cc9950e
GE
1393
1394 \param ftdi pointer to ftdi_context
579b006f
JZ
1395 \param buf Buffer with the data
1396 \param size Size of the buffer
4c9e3812 1397
579b006f
JZ
1398 \retval NULL: Some error happens when submit transfer
1399 \retval !NULL: Pointer to a ftdi_transfer_control
4c9e3812 1400*/
579b006f
JZ
1401
1402struct ftdi_transfer_control *ftdi_read_data_submit(struct ftdi_context *ftdi, unsigned char *buf, int size)
4c9e3812 1403{
579b006f
JZ
1404 struct ftdi_transfer_control *tc;
1405 struct libusb_transfer *transfer;
1406 int ret;
22d12cda 1407
22a1b5c1
TJ
1408 if (ftdi == NULL || ftdi->usb_dev == NULL)
1409 return NULL;
1410
579b006f
JZ
1411 tc = (struct ftdi_transfer_control *) malloc (sizeof (*tc));
1412 if (!tc)
1413 return NULL;
1414
1415 tc->ftdi = ftdi;
1416 tc->buf = buf;
1417 tc->size = size;
1418
1419 if (size <= ftdi->readbuffer_remaining)
7cc9950e 1420 {
579b006f 1421 memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);
7cc9950e 1422
579b006f
JZ
1423 // Fix offsets
1424 ftdi->readbuffer_remaining -= size;
1425 ftdi->readbuffer_offset += size;
7cc9950e 1426
579b006f 1427 /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */
22d12cda 1428
579b006f
JZ
1429 tc->completed = 1;
1430 tc->offset = size;
1431 tc->transfer = NULL;
1432 return tc;
1433 }
4c9e3812 1434
579b006f
JZ
1435 tc->completed = 0;
1436 if (ftdi->readbuffer_remaining != 0)
1437 {
1438 memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);
22d12cda 1439
579b006f
JZ
1440 tc->offset = ftdi->readbuffer_remaining;
1441 }
1442 else
1443 tc->offset = 0;
22d12cda 1444
579b006f
JZ
1445 transfer = libusb_alloc_transfer(0);
1446 if (!transfer)
1447 {
1448 free (tc);
1449 return NULL;
1450 }
22d12cda 1451
579b006f
JZ
1452 ftdi->readbuffer_remaining = 0;
1453 ftdi->readbuffer_offset = 0;
1454
1455 libusb_fill_bulk_transfer(transfer, ftdi->usb_dev, ftdi->out_ep, ftdi->readbuffer, ftdi->readbuffer_chunksize, ftdi_read_data_cb, tc, ftdi->usb_read_timeout);
1456 transfer->type = LIBUSB_TRANSFER_TYPE_BULK;
1457
1458 ret = libusb_submit_transfer(transfer);
1459 if (ret < 0)
1460 {
1461 libusb_free_transfer(transfer);
1462 free (tc);
1463 return NULL;
22d12cda 1464 }
579b006f
JZ
1465 tc->transfer = transfer;
1466
1467 return tc;
4c9e3812
GE
1468}
1469
1470/**
579b006f 1471 Wait for completion of the transfer.
4c9e3812 1472
579b006f 1473 Use libusb 1.0 Asynchronous API.
cef378aa 1474 Only available if compiled with --with-async-mode.
4c9e3812 1475
579b006f 1476 \param tc pointer to ftdi_transfer_control
4c9e3812 1477
579b006f
JZ
1478 \retval < 0: Some error happens
1479 \retval >= 0: Data size transferred
4c9e3812 1480*/
579b006f
JZ
1481
1482int ftdi_transfer_data_done(struct ftdi_transfer_control *tc)
4c9e3812
GE
1483{
1484 int ret;
4c9e3812 1485
579b006f 1486 while (!tc->completed)
22d12cda 1487 {
579b006f 1488 ret = libusb_handle_events(NULL);
4c9e3812 1489 if (ret < 0)
579b006f
JZ
1490 {
1491 if (ret == LIBUSB_ERROR_INTERRUPTED)
1492 continue;
1493 libusb_cancel_transfer(tc->transfer);
1494 while (!tc->completed)
1495 if (libusb_handle_events(NULL) < 0)
1496 break;
1497 libusb_free_transfer(tc->transfer);
1498 free (tc);
1499 tc = NULL;
1500 return ret;
1501 }
4c9e3812
GE
1502 }
1503
579b006f
JZ
1504 if (tc->transfer->status == LIBUSB_TRANSFER_COMPLETED)
1505 ret = tc->offset;
1506 else
1507 ret = -1;
1508
1509 libusb_free_transfer(tc->transfer);
1510 free(tc);
1511 return ret;
4c9e3812 1512}
579b006f 1513
f01d7ca6 1514#endif // LIBFTDI_LINUX_ASYNC_MODE
4c9e3812 1515
1941414d
TJ
1516/**
1517 Configure write buffer chunk size.
1518 Default is 4096.
1519
1520 \param ftdi pointer to ftdi_context
1521 \param chunksize Chunk size
a3da1d95 1522
1941414d 1523 \retval 0: all fine
22a1b5c1 1524 \retval -1: ftdi context invalid
1941414d 1525*/
a8f46ddc
TJ
1526int ftdi_write_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
1527{
22a1b5c1
TJ
1528 if (ftdi == NULL)
1529 ftdi_error_return(-1, "ftdi context invalid");
1530
948f9ada
TJ
1531 ftdi->writebuffer_chunksize = chunksize;
1532 return 0;
1533}
1534
1941414d
TJ
1535/**
1536 Get write buffer chunk size.
1537
1538 \param ftdi pointer to ftdi_context
1539 \param chunksize Pointer to store chunk size in
948f9ada 1540
1941414d 1541 \retval 0: all fine
22a1b5c1 1542 \retval -1: ftdi context invalid
1941414d 1543*/
a8f46ddc
TJ
1544int ftdi_write_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
1545{
22a1b5c1
TJ
1546 if (ftdi == NULL)
1547 ftdi_error_return(-1, "ftdi context invalid");
1548
948f9ada
TJ
1549 *chunksize = ftdi->writebuffer_chunksize;
1550 return 0;
1551}
cbabb7d3 1552
1941414d
TJ
1553/**
1554 Reads data in chunks (see ftdi_read_data_set_chunksize()) from the chip.
1555
1556 Automatically strips the two modem status bytes transfered during every read.
948f9ada 1557
1941414d
TJ
1558 \param ftdi pointer to ftdi_context
1559 \param buf Buffer to store data in
1560 \param size Size of the buffer
1561
22a1b5c1 1562 \retval -666: USB device unavailable
579b006f 1563 \retval <0: error code from libusb_bulk_transfer()
d77b0e94 1564 \retval 0: no data was available
1941414d
TJ
1565 \retval >0: number of bytes read
1566
1941414d 1567*/
a8f46ddc
TJ
1568int ftdi_read_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
1569{
579b006f 1570 int offset = 0, ret, i, num_of_chunks, chunk_remains;
e2f12a4f 1571 int packet_size = ftdi->max_packet_size;
579b006f 1572 int actual_length = 1;
f2f00cb5 1573
22a1b5c1
TJ
1574 if (ftdi == NULL || ftdi->usb_dev == NULL)
1575 ftdi_error_return(-666, "USB device unavailable");
1576
e2f12a4f
TJ
1577 // Packet size sanity check (avoid division by zero)
1578 if (packet_size == 0)
1579 ftdi_error_return(-1, "max_packet_size is bogus (zero)");
d9f0cce7 1580
948f9ada 1581 // everything we want is still in the readbuffer?
22d12cda
TJ
1582 if (size <= ftdi->readbuffer_remaining)
1583 {
d9f0cce7
TJ
1584 memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);
1585
1586 // Fix offsets
1587 ftdi->readbuffer_remaining -= size;
1588 ftdi->readbuffer_offset += size;
1589
545820ce 1590 /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */
d9f0cce7
TJ
1591
1592 return size;
979a145c 1593 }
948f9ada 1594 // something still in the readbuffer, but not enough to satisfy 'size'?
22d12cda
TJ
1595 if (ftdi->readbuffer_remaining != 0)
1596 {
d9f0cce7 1597 memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);
979a145c 1598
d9f0cce7
TJ
1599 // Fix offset
1600 offset += ftdi->readbuffer_remaining;
948f9ada 1601 }
948f9ada 1602 // do the actual USB read
579b006f 1603 while (offset < size && actual_length > 0)
22d12cda 1604 {
d9f0cce7
TJ
1605 ftdi->readbuffer_remaining = 0;
1606 ftdi->readbuffer_offset = 0;
98452d97 1607 /* returns how much received */
579b006f 1608 ret = libusb_bulk_transfer (ftdi->usb_dev, ftdi->out_ep, ftdi->readbuffer, ftdi->readbuffer_chunksize, &actual_length, ftdi->usb_read_timeout);
c3d95b87
TJ
1609 if (ret < 0)
1610 ftdi_error_return(ret, "usb bulk read failed");
98452d97 1611
579b006f 1612 if (actual_length > 2)
22d12cda 1613 {
d9f0cce7
TJ
1614 // skip FTDI status bytes.
1615 // Maybe stored in the future to enable modem use
579b006f
JZ
1616 num_of_chunks = actual_length / packet_size;
1617 chunk_remains = actual_length % packet_size;
1618 //printf("actual_length = %X, num_of_chunks = %X, chunk_remains = %X, readbuffer_offset = %X\n", actual_length, num_of_chunks, chunk_remains, ftdi->readbuffer_offset);
1c733d33 1619
d9f0cce7 1620 ftdi->readbuffer_offset += 2;
579b006f 1621 actual_length -= 2;
1c733d33 1622
579b006f 1623 if (actual_length > packet_size - 2)
22d12cda 1624 {
1c733d33 1625 for (i = 1; i < num_of_chunks; i++)
f2f00cb5
DC
1626 memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1627 ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1628 packet_size - 2);
22d12cda
TJ
1629 if (chunk_remains > 2)
1630 {
f2f00cb5
DC
1631 memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
1632 ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
1c733d33 1633 chunk_remains-2);
579b006f 1634 actual_length -= 2*num_of_chunks;
22d12cda
TJ
1635 }
1636 else
579b006f 1637 actual_length -= 2*(num_of_chunks-1)+chunk_remains;
1c733d33 1638 }
22d12cda 1639 }
579b006f 1640 else if (actual_length <= 2)
22d12cda 1641 {
d9f0cce7
TJ
1642 // no more data to read?
1643 return offset;
1644 }
579b006f 1645 if (actual_length > 0)
22d12cda 1646 {
d9f0cce7 1647 // data still fits in buf?
579b006f 1648 if (offset+actual_length <= size)
22d12cda 1649 {
579b006f 1650 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, actual_length);
545820ce 1651 //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
579b006f 1652 offset += actual_length;
d9f0cce7 1653
53ad271d 1654 /* Did we read exactly the right amount of bytes? */
d9f0cce7 1655 if (offset == size)
c4446c36
TJ
1656 //printf("read_data exact rem %d offset %d\n",
1657 //ftdi->readbuffer_remaining, offset);
d9f0cce7 1658 return offset;
22d12cda
TJ
1659 }
1660 else
1661 {
d9f0cce7
TJ
1662 // only copy part of the data or size <= readbuffer_chunksize
1663 int part_size = size-offset;
1664 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, part_size);
98452d97 1665
d9f0cce7 1666 ftdi->readbuffer_offset += part_size;
579b006f 1667 ftdi->readbuffer_remaining = actual_length-part_size;
d9f0cce7
TJ
1668 offset += part_size;
1669
579b006f
JZ
1670 /* printf("Returning part: %d - size: %d - offset: %d - actual_length: %d - remaining: %d\n",
1671 part_size, size, offset, actual_length, ftdi->readbuffer_remaining); */
d9f0cce7
TJ
1672
1673 return offset;
1674 }
1675 }
cbabb7d3 1676 }
948f9ada 1677 // never reached
29c4af7f 1678 return -127;
a3da1d95
GE
1679}
1680
1941414d
TJ
1681/**
1682 Configure read buffer chunk size.
1683 Default is 4096.
1684
1685 Automatically reallocates the buffer.
a3da1d95 1686
1941414d
TJ
1687 \param ftdi pointer to ftdi_context
1688 \param chunksize Chunk size
1689
1690 \retval 0: all fine
22a1b5c1 1691 \retval -1: ftdi context invalid
1941414d 1692*/
a8f46ddc
TJ
1693int ftdi_read_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
1694{
29c4af7f
TJ
1695 unsigned char *new_buf;
1696
22a1b5c1
TJ
1697 if (ftdi == NULL)
1698 ftdi_error_return(-1, "ftdi context invalid");
1699
948f9ada
TJ
1700 // Invalidate all remaining data
1701 ftdi->readbuffer_offset = 0;
1702 ftdi->readbuffer_remaining = 0;
8de6eea4
JZ
1703#ifdef __linux__
1704 /* We can't set readbuffer_chunksize larger than MAX_BULK_BUFFER_LENGTH,
1705 which is defined in libusb-1.0. Otherwise, each USB read request will
2e685a1f 1706 be divided into multiple URBs. This will cause issues on Linux kernel
8de6eea4
JZ
1707 older than 2.6.32. */
1708 if (chunksize > 16384)
1709 chunksize = 16384;
1710#endif
948f9ada 1711
c3d95b87
TJ
1712 if ((new_buf = (unsigned char *)realloc(ftdi->readbuffer, chunksize)) == NULL)
1713 ftdi_error_return(-1, "out of memory for readbuffer");
d9f0cce7 1714
948f9ada
TJ
1715 ftdi->readbuffer = new_buf;
1716 ftdi->readbuffer_chunksize = chunksize;
1717
1718 return 0;
1719}
1720
1941414d
TJ
1721/**
1722 Get read buffer chunk size.
948f9ada 1723
1941414d
TJ
1724 \param ftdi pointer to ftdi_context
1725 \param chunksize Pointer to store chunk size in
1726
1727 \retval 0: all fine
22a1b5c1 1728 \retval -1: FTDI context invalid
1941414d 1729*/
a8f46ddc
TJ
1730int ftdi_read_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
1731{
22a1b5c1
TJ
1732 if (ftdi == NULL)
1733 ftdi_error_return(-1, "FTDI context invalid");
1734
948f9ada
TJ
1735 *chunksize = ftdi->readbuffer_chunksize;
1736 return 0;
1737}
1738
1739
1941414d
TJ
1740/**
1741 Enable bitbang mode.
948f9ada 1742
fd282db3 1743 \deprecated use \ref ftdi_set_bitmode with mode BITMODE_BITBANG instead
1941414d
TJ
1744
1745 \param ftdi pointer to ftdi_context
1746 \param bitmask Bitmask to configure lines.
1747 HIGH/ON value configures a line as output.
1748
1749 \retval 0: all fine
1750 \retval -1: can't enable bitbang mode
22a1b5c1 1751 \retval -2: USB device unavailable
1941414d 1752*/
a8f46ddc
TJ
1753int ftdi_enable_bitbang(struct ftdi_context *ftdi, unsigned char bitmask)
1754{
a3da1d95
GE
1755 unsigned short usb_val;
1756
22a1b5c1
TJ
1757 if (ftdi == NULL || ftdi->usb_dev == NULL)
1758 ftdi_error_return(-2, "USB device unavailable");
1759
d9f0cce7 1760 usb_val = bitmask; // low byte: bitmask
3119537f
TJ
1761 /* FT2232C: Set bitbang_mode to 2 to enable SPI */
1762 usb_val |= (ftdi->bitbang_mode << 8);
1763
579b006f
JZ
1764 if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1765 SIO_SET_BITMODE_REQUEST, usb_val, ftdi->index,
1766 NULL, 0, ftdi->usb_write_timeout) < 0)
c3d95b87
TJ
1767 ftdi_error_return(-1, "unable to enter bitbang mode. Perhaps not a BM type chip?");
1768
a3da1d95
GE
1769 ftdi->bitbang_enabled = 1;
1770 return 0;
1771}
1772
1941414d
TJ
1773/**
1774 Disable bitbang mode.
a3da1d95 1775
1941414d
TJ
1776 \param ftdi pointer to ftdi_context
1777
1778 \retval 0: all fine
1779 \retval -1: can't disable bitbang mode
22a1b5c1 1780 \retval -2: USB device unavailable
1941414d 1781*/
a8f46ddc
TJ
1782int ftdi_disable_bitbang(struct ftdi_context *ftdi)
1783{
22a1b5c1
TJ
1784 if (ftdi == NULL || ftdi->usb_dev == NULL)
1785 ftdi_error_return(-2, "USB device unavailable");
1786
579b006f 1787 if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_SET_BITMODE_REQUEST, 0, ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
c3d95b87 1788 ftdi_error_return(-1, "unable to leave bitbang mode. Perhaps not a BM type chip?");
a3da1d95
GE
1789
1790 ftdi->bitbang_enabled = 0;
1791 return 0;
1792}
1793
1941414d 1794/**
418aaa72 1795 Enable/disable bitbang modes.
a3da1d95 1796
1941414d
TJ
1797 \param ftdi pointer to ftdi_context
1798 \param bitmask Bitmask to configure lines.
1799 HIGH/ON value configures a line as output.
fd282db3 1800 \param mode Bitbang mode: use the values defined in \ref ftdi_mpsse_mode
1941414d
TJ
1801
1802 \retval 0: all fine
1803 \retval -1: can't enable bitbang mode
22a1b5c1 1804 \retval -2: USB device unavailable
1941414d 1805*/
c4446c36
TJ
1806int ftdi_set_bitmode(struct ftdi_context *ftdi, unsigned char bitmask, unsigned char mode)
1807{
1808 unsigned short usb_val;
1809
22a1b5c1
TJ
1810 if (ftdi == NULL || ftdi->usb_dev == NULL)
1811 ftdi_error_return(-2, "USB device unavailable");
1812
c4446c36
TJ
1813 usb_val = bitmask; // low byte: bitmask
1814 usb_val |= (mode << 8);
579b006f
JZ
1815 if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_SET_BITMODE_REQUEST, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) < 0)
1816 ftdi_error_return(-1, "unable to configure bitbang mode. Perhaps not a 2232C type chip?");
c4446c36
TJ
1817
1818 ftdi->bitbang_mode = mode;
418aaa72 1819 ftdi->bitbang_enabled = (mode == BITMODE_RESET) ? 0 : 1;
c4446c36
TJ
1820 return 0;
1821}
1822
1941414d 1823/**
418aaa72 1824 Directly read pin state, circumventing the read buffer. Useful for bitbang mode.
1941414d
TJ
1825
1826 \param ftdi pointer to ftdi_context
1827 \param pins Pointer to store pins into
1828
1829 \retval 0: all fine
1830 \retval -1: read pins failed
22a1b5c1 1831 \retval -2: USB device unavailable
1941414d 1832*/
a8f46ddc
TJ
1833int ftdi_read_pins(struct ftdi_context *ftdi, unsigned char *pins)
1834{
22a1b5c1
TJ
1835 if (ftdi == NULL || ftdi->usb_dev == NULL)
1836 ftdi_error_return(-2, "USB device unavailable");
1837
579b006f 1838 if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_READ_PINS_REQUEST, 0, ftdi->index, (unsigned char *)pins, 1, ftdi->usb_read_timeout) != 1)
c3d95b87 1839 ftdi_error_return(-1, "read pins failed");
a3da1d95 1840
a3da1d95
GE
1841 return 0;
1842}
1843
1941414d
TJ
1844/**
1845 Set latency timer
1846
1847 The FTDI chip keeps data in the internal buffer for a specific
1848 amount of time if the buffer is not full yet to decrease
1849 load on the usb bus.
a3da1d95 1850
1941414d
TJ
1851 \param ftdi pointer to ftdi_context
1852 \param latency Value between 1 and 255
1853
1854 \retval 0: all fine
1855 \retval -1: latency out of range
1856 \retval -2: unable to set latency timer
22a1b5c1 1857 \retval -3: USB device unavailable
1941414d 1858*/
a8f46ddc
TJ
1859int ftdi_set_latency_timer(struct ftdi_context *ftdi, unsigned char latency)
1860{
a3da1d95
GE
1861 unsigned short usb_val;
1862
c3d95b87
TJ
1863 if (latency < 1)
1864 ftdi_error_return(-1, "latency out of range. Only valid for 1-255");
a3da1d95 1865
22a1b5c1
TJ
1866 if (ftdi == NULL || ftdi->usb_dev == NULL)
1867 ftdi_error_return(-3, "USB device unavailable");
1868
d79d2e68 1869 usb_val = latency;
579b006f 1870 if (libusb_control_transfer(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
1871 ftdi_error_return(-2, "unable to set latency timer");
1872
a3da1d95
GE
1873 return 0;
1874}
1875
1941414d
TJ
1876/**
1877 Get latency timer
a3da1d95 1878
1941414d
TJ
1879 \param ftdi pointer to ftdi_context
1880 \param latency Pointer to store latency value in
1881
1882 \retval 0: all fine
1883 \retval -1: unable to get latency timer
22a1b5c1 1884 \retval -2: USB device unavailable
1941414d 1885*/
a8f46ddc
TJ
1886int ftdi_get_latency_timer(struct ftdi_context *ftdi, unsigned char *latency)
1887{
a3da1d95 1888 unsigned short usb_val;
22a1b5c1
TJ
1889
1890 if (ftdi == NULL || ftdi->usb_dev == NULL)
1891 ftdi_error_return(-2, "USB device unavailable");
1892
579b006f 1893 if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_GET_LATENCY_TIMER_REQUEST, 0, ftdi->index, (unsigned char *)&usb_val, 1, ftdi->usb_read_timeout) != 1)
c3d95b87 1894 ftdi_error_return(-1, "reading latency timer failed");
a3da1d95
GE
1895
1896 *latency = (unsigned char)usb_val;
1897 return 0;
1898}
1899
1941414d 1900/**
1189b11a
TJ
1901 Poll modem status information
1902
1903 This function allows the retrieve the two status bytes of the device.
1904 The device sends these bytes also as a header for each read access
1905 where they are discarded by ftdi_read_data(). The chip generates
1906 the two stripped status bytes in the absence of data every 40 ms.
1907
1908 Layout of the first byte:
1909 - B0..B3 - must be 0
1910 - B4 Clear to send (CTS)
1911 0 = inactive
1912 1 = active
1913 - B5 Data set ready (DTS)
1914 0 = inactive
1915 1 = active
1916 - B6 Ring indicator (RI)
1917 0 = inactive
1918 1 = active
1919 - B7 Receive line signal detect (RLSD)
1920 0 = inactive
1921 1 = active
1922
1923 Layout of the second byte:
1924 - B0 Data ready (DR)
1925 - B1 Overrun error (OE)
1926 - B2 Parity error (PE)
1927 - B3 Framing error (FE)
1928 - B4 Break interrupt (BI)
1929 - B5 Transmitter holding register (THRE)
1930 - B6 Transmitter empty (TEMT)
1931 - B7 Error in RCVR FIFO
1932
1933 \param ftdi pointer to ftdi_context
1934 \param status Pointer to store status information in. Must be two bytes.
1935
1936 \retval 0: all fine
1937 \retval -1: unable to retrieve status information
22a1b5c1 1938 \retval -2: USB device unavailable
1189b11a
TJ
1939*/
1940int ftdi_poll_modem_status(struct ftdi_context *ftdi, unsigned short *status)
1941{
1942 char usb_val[2];
1943
22a1b5c1
TJ
1944 if (ftdi == NULL || ftdi->usb_dev == NULL)
1945 ftdi_error_return(-2, "USB device unavailable");
1946
579b006f 1947 if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_POLL_MODEM_STATUS_REQUEST, 0, ftdi->index, (unsigned char *)usb_val, 2, ftdi->usb_read_timeout) != 2)
1189b11a
TJ
1948 ftdi_error_return(-1, "getting modem status failed");
1949
1950 *status = (usb_val[1] << 8) | usb_val[0];
1951
1952 return 0;
1953}
1954
a7fb8440
TJ
1955/**
1956 Set flowcontrol for ftdi chip
1957
1958 \param ftdi pointer to ftdi_context
22d12cda
TJ
1959 \param flowctrl flow control to use. should be
1960 SIO_DISABLE_FLOW_CTRL, SIO_RTS_CTS_HS, SIO_DTR_DSR_HS or SIO_XON_XOFF_HS
a7fb8440
TJ
1961
1962 \retval 0: all fine
1963 \retval -1: set flow control failed
22a1b5c1 1964 \retval -2: USB device unavailable
a7fb8440
TJ
1965*/
1966int ftdi_setflowctrl(struct ftdi_context *ftdi, int flowctrl)
1967{
22a1b5c1
TJ
1968 if (ftdi == NULL || ftdi->usb_dev == NULL)
1969 ftdi_error_return(-2, "USB device unavailable");
1970
579b006f
JZ
1971 if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
1972 SIO_SET_FLOW_CTRL_REQUEST, 0, (flowctrl | ftdi->index),
1973 NULL, 0, ftdi->usb_write_timeout) < 0)
a7fb8440
TJ
1974 ftdi_error_return(-1, "set flow control failed");
1975
1976 return 0;
1977}
1978
1979/**
1980 Set dtr line
1981
1982 \param ftdi pointer to ftdi_context
1983 \param state state to set line to (1 or 0)
1984
1985 \retval 0: all fine
1986 \retval -1: set dtr failed
22a1b5c1 1987 \retval -2: USB device unavailable
a7fb8440
TJ
1988*/
1989int ftdi_setdtr(struct ftdi_context *ftdi, int state)
1990{
1991 unsigned short usb_val;
1992
22a1b5c1
TJ
1993 if (ftdi == NULL || ftdi->usb_dev == NULL)
1994 ftdi_error_return(-2, "USB device unavailable");
1995
a7fb8440
TJ
1996 if (state)
1997 usb_val = SIO_SET_DTR_HIGH;
1998 else
1999 usb_val = SIO_SET_DTR_LOW;
2000
579b006f
JZ
2001 if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
2002 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
2003 NULL, 0, ftdi->usb_write_timeout) < 0)
a7fb8440
TJ
2004 ftdi_error_return(-1, "set dtr failed");
2005
2006 return 0;
2007}
2008
2009/**
2010 Set rts line
2011
2012 \param ftdi pointer to ftdi_context
2013 \param state state to set line to (1 or 0)
2014
2015 \retval 0: all fine
22a1b5c1
TJ
2016 \retval -1: set rts failed
2017 \retval -2: USB device unavailable
a7fb8440
TJ
2018*/
2019int ftdi_setrts(struct ftdi_context *ftdi, int state)
2020{
2021 unsigned short usb_val;
2022
22a1b5c1
TJ
2023 if (ftdi == NULL || ftdi->usb_dev == NULL)
2024 ftdi_error_return(-2, "USB device unavailable");
2025
a7fb8440
TJ
2026 if (state)
2027 usb_val = SIO_SET_RTS_HIGH;
2028 else
2029 usb_val = SIO_SET_RTS_LOW;
2030
579b006f
JZ
2031 if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
2032 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
2033 NULL, 0, ftdi->usb_write_timeout) < 0)
a7fb8440
TJ
2034 ftdi_error_return(-1, "set of rts failed");
2035
2036 return 0;
2037}
2038
1189b11a 2039/**
22a1b5c1 2040 Set dtr and rts line in one pass
9ecfef2a 2041
22a1b5c1
TJ
2042 \param ftdi pointer to ftdi_context
2043 \param dtr DTR state to set line to (1 or 0)
2044 \param rts RTS state to set line to (1 or 0)
9ecfef2a 2045
22a1b5c1
TJ
2046 \retval 0: all fine
2047 \retval -1: set dtr/rts failed
2048 \retval -2: USB device unavailable
9ecfef2a
TJ
2049 */
2050int ftdi_setdtr_rts(struct ftdi_context *ftdi, int dtr, int rts)
2051{
2052 unsigned short usb_val;
2053
22a1b5c1
TJ
2054 if (ftdi == NULL || ftdi->usb_dev == NULL)
2055 ftdi_error_return(-2, "USB device unavailable");
2056
9ecfef2a 2057 if (dtr)
22d12cda 2058 usb_val = SIO_SET_DTR_HIGH;
9ecfef2a 2059 else
22d12cda 2060 usb_val = SIO_SET_DTR_LOW;
9ecfef2a
TJ
2061
2062 if (rts)
22d12cda 2063 usb_val |= SIO_SET_RTS_HIGH;
9ecfef2a 2064 else
22d12cda 2065 usb_val |= SIO_SET_RTS_LOW;
9ecfef2a 2066
579b006f
JZ
2067 if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
2068 SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
2069 NULL, 0, ftdi->usb_write_timeout) < 0)
22d12cda 2070 ftdi_error_return(-1, "set of rts/dtr failed");
9ecfef2a
TJ
2071
2072 return 0;
2073}
2074
2075/**
1189b11a
TJ
2076 Set the special event character
2077
2078 \param ftdi pointer to ftdi_context
2079 \param eventch Event character
2080 \param enable 0 to disable the event character, non-zero otherwise
2081
2082 \retval 0: all fine
2083 \retval -1: unable to set event character
22a1b5c1 2084 \retval -2: USB device unavailable
1189b11a
TJ
2085*/
2086int ftdi_set_event_char(struct ftdi_context *ftdi,
22d12cda 2087 unsigned char eventch, unsigned char enable)
1189b11a
TJ
2088{
2089 unsigned short usb_val;
2090
22a1b5c1
TJ
2091 if (ftdi == NULL || ftdi->usb_dev == NULL)
2092 ftdi_error_return(-2, "USB device unavailable");
2093
1189b11a
TJ
2094 usb_val = eventch;
2095 if (enable)
2096 usb_val |= 1 << 8;
2097
579b006f 2098 if (libusb_control_transfer(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
2099 ftdi_error_return(-1, "setting event character failed");
2100
2101 return 0;
2102}
2103
2104/**
2105 Set error character
2106
2107 \param ftdi pointer to ftdi_context
2108 \param errorch Error character
2109 \param enable 0 to disable the error character, non-zero otherwise
2110
2111 \retval 0: all fine
2112 \retval -1: unable to set error character
22a1b5c1 2113 \retval -2: USB device unavailable
1189b11a
TJ
2114*/
2115int ftdi_set_error_char(struct ftdi_context *ftdi,
22d12cda 2116 unsigned char errorch, unsigned char enable)
1189b11a
TJ
2117{
2118 unsigned short usb_val;
2119
22a1b5c1
TJ
2120 if (ftdi == NULL || ftdi->usb_dev == NULL)
2121 ftdi_error_return(-2, "USB device unavailable");
2122
1189b11a
TJ
2123 usb_val = errorch;
2124 if (enable)
2125 usb_val |= 1 << 8;
2126
579b006f 2127 if (libusb_control_transfer(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
2128 ftdi_error_return(-1, "setting error character failed");
2129
2130 return 0;
2131}
2132
2133/**
c201f80f
TJ
2134 Set the eeprom size
2135
2136 \param ftdi pointer to ftdi_context
2137 \param eeprom Pointer to ftdi_eeprom
2138 \param size
2139
2140*/
2141void ftdi_eeprom_setsize(struct ftdi_context *ftdi, struct ftdi_eeprom *eeprom, int size)
2142{
22a1b5c1
TJ
2143 if (ftdi == NULL)
2144 return;
2145
22d12cda
TJ
2146 ftdi->eeprom_size=size;
2147 eeprom->size=size;
c201f80f
TJ
2148}
2149
2150/**
1941414d 2151 Init eeprom with default values.
a3da1d95 2152
1941414d
TJ
2153 \param eeprom Pointer to ftdi_eeprom
2154*/
a8f46ddc
TJ
2155void ftdi_eeprom_initdefaults(struct ftdi_eeprom *eeprom)
2156{
22a1b5c1
TJ
2157 if (eeprom == NULL)
2158 return;
2159
f396dbad
TJ
2160 eeprom->vendor_id = 0x0403;
2161 eeprom->product_id = 0x6001;
d9f0cce7 2162
b8aa7b35
TJ
2163 eeprom->self_powered = 1;
2164 eeprom->remote_wakeup = 1;
2165 eeprom->BM_type_chip = 1;
d9f0cce7 2166
b8aa7b35
TJ
2167 eeprom->in_is_isochronous = 0;
2168 eeprom->out_is_isochronous = 0;
2169 eeprom->suspend_pull_downs = 0;
d9f0cce7 2170
b8aa7b35
TJ
2171 eeprom->use_serial = 0;
2172 eeprom->change_usb_version = 0;
f396dbad 2173 eeprom->usb_version = 0x0200;
b8aa7b35 2174 eeprom->max_power = 0;
d9f0cce7 2175
b8aa7b35
TJ
2176 eeprom->manufacturer = NULL;
2177 eeprom->product = NULL;
2178 eeprom->serial = NULL;
c201f80f
TJ
2179
2180 eeprom->size = FTDI_DEFAULT_EEPROM_SIZE;
b8aa7b35
TJ
2181}
2182
1941414d 2183/**
22a1b5c1
TJ
2184 Build binary output from ftdi_eeprom structure.
2185 Output is suitable for ftdi_write_eeprom().
b8aa7b35 2186
22a1b5c1
TJ
2187 \param eeprom Pointer to ftdi_eeprom
2188 \param output Buffer of 128 bytes to store eeprom image to
1941414d 2189
22a1b5c1
TJ
2190 \retval >0: used eeprom size
2191 \retval -1: eeprom size (128 bytes) exceeded by custom strings
2192 \retval -2: Invalid eeprom pointer
b8aa7b35 2193*/
a8f46ddc
TJ
2194int ftdi_eeprom_build(struct ftdi_eeprom *eeprom, unsigned char *output)
2195{
b8aa7b35
TJ
2196 unsigned char i, j;
2197 unsigned short checksum, value;
2198 unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
2199 int size_check;
2200
22a1b5c1
TJ
2201 if (eeprom == NULL)
2202 return -2;
2203
b8aa7b35 2204 if (eeprom->manufacturer != NULL)
d9f0cce7 2205 manufacturer_size = strlen(eeprom->manufacturer);
b8aa7b35 2206 if (eeprom->product != NULL)
d9f0cce7 2207 product_size = strlen(eeprom->product);
b8aa7b35 2208 if (eeprom->serial != NULL)
d9f0cce7 2209 serial_size = strlen(eeprom->serial);
b8aa7b35 2210
c201f80f 2211 size_check = eeprom->size;
d9f0cce7 2212 size_check -= 28; // 28 are always in use (fixed)
c201f80f 2213
22d12cda 2214 // Top half of a 256byte eeprom is used just for strings and checksum
c201f80f
TJ
2215 // it seems that the FTDI chip will not read these strings from the lower half
2216 // Each string starts with two bytes; offset and type (0x03 for string)
2217 // the checksum needs two bytes, so without the string data that 8 bytes from the top half
22d12cda 2218 if (eeprom->size>=256)size_check = 120;
b8aa7b35
TJ
2219 size_check -= manufacturer_size*2;
2220 size_check -= product_size*2;
2221 size_check -= serial_size*2;
2222
2223 // eeprom size exceeded?
2224 if (size_check < 0)
d9f0cce7 2225 return (-1);
b8aa7b35
TJ
2226
2227 // empty eeprom
c201f80f 2228 memset (output, 0, eeprom->size);
b8aa7b35
TJ
2229
2230 // Addr 00: Stay 00 00
2231 // Addr 02: Vendor ID
2232 output[0x02] = eeprom->vendor_id;
2233 output[0x03] = eeprom->vendor_id >> 8;
2234
2235 // Addr 04: Product ID
2236 output[0x04] = eeprom->product_id;
2237 output[0x05] = eeprom->product_id >> 8;
2238
2239 // Addr 06: Device release number (0400h for BM features)
2240 output[0x06] = 0x00;
d9f0cce7 2241
b8aa7b35 2242 if (eeprom->BM_type_chip == 1)
d9f0cce7 2243 output[0x07] = 0x04;
b8aa7b35 2244 else
d9f0cce7 2245 output[0x07] = 0x02;
b8aa7b35
TJ
2246
2247 // Addr 08: Config descriptor
8fae3e8e
TJ
2248 // Bit 7: always 1
2249 // Bit 6: 1 if this device is self powered, 0 if bus powered
2250 // Bit 5: 1 if this device uses remote wakeup
2251 // Bit 4: 1 if this device is battery powered
5a1dcd55 2252 j = 0x80;
b8aa7b35 2253 if (eeprom->self_powered == 1)
5a1dcd55 2254 j |= 0x40;
b8aa7b35 2255 if (eeprom->remote_wakeup == 1)
5a1dcd55 2256 j |= 0x20;
b8aa7b35
TJ
2257 output[0x08] = j;
2258
2259 // Addr 09: Max power consumption: max power = value * 2 mA
d9f0cce7 2260 output[0x09] = eeprom->max_power;
d9f0cce7 2261
b8aa7b35
TJ
2262 // Addr 0A: Chip configuration
2263 // Bit 7: 0 - reserved
2264 // Bit 6: 0 - reserved
2265 // Bit 5: 0 - reserved
2266 // Bit 4: 1 - Change USB version
2267 // Bit 3: 1 - Use the serial number string
2268 // Bit 2: 1 - Enable suspend pull downs for lower power
2269 // Bit 1: 1 - Out EndPoint is Isochronous
2270 // Bit 0: 1 - In EndPoint is Isochronous
2271 //
2272 j = 0;
2273 if (eeprom->in_is_isochronous == 1)
d9f0cce7 2274 j = j | 1;
b8aa7b35 2275 if (eeprom->out_is_isochronous == 1)
d9f0cce7 2276 j = j | 2;
b8aa7b35 2277 if (eeprom->suspend_pull_downs == 1)
d9f0cce7 2278 j = j | 4;
b8aa7b35 2279 if (eeprom->use_serial == 1)
d9f0cce7 2280 j = j | 8;
b8aa7b35 2281 if (eeprom->change_usb_version == 1)
d9f0cce7 2282 j = j | 16;
b8aa7b35 2283 output[0x0A] = j;
d9f0cce7 2284
b8aa7b35
TJ
2285 // Addr 0B: reserved
2286 output[0x0B] = 0x00;
d9f0cce7 2287
b8aa7b35
TJ
2288 // Addr 0C: USB version low byte when 0x0A bit 4 is set
2289 // Addr 0D: USB version high byte when 0x0A bit 4 is set
22d12cda
TJ
2290 if (eeprom->change_usb_version == 1)
2291 {
b8aa7b35 2292 output[0x0C] = eeprom->usb_version;
d9f0cce7 2293 output[0x0D] = eeprom->usb_version >> 8;
b8aa7b35
TJ
2294 }
2295
2296
c201f80f 2297 // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
b8aa7b35
TJ
2298 // Addr 0F: Length of manufacturer string
2299 output[0x0F] = manufacturer_size*2 + 2;
2300
2301 // Addr 10: Offset of the product string + 0x80, calculated later
2302 // Addr 11: Length of product string
2303 output[0x11] = product_size*2 + 2;
2304
2305 // Addr 12: Offset of the serial string + 0x80, calculated later
2306 // Addr 13: Length of serial string
2307 output[0x13] = serial_size*2 + 2;
2308
2309 // Dynamic content
c201f80f 2310 i=0x14;
22d12cda 2311 if (eeprom->size>=256) i = 0x80;
f01d7ca6 2312
c201f80f 2313
22d12cda 2314 // Output manufacturer
c201f80f
TJ
2315 output[0x0E] = i | 0x80; // calculate offset
2316 output[i++] = manufacturer_size*2 + 2;
2317 output[i++] = 0x03; // type: string
22d12cda
TJ
2318 for (j = 0; j < manufacturer_size; j++)
2319 {
d9f0cce7
TJ
2320 output[i] = eeprom->manufacturer[j], i++;
2321 output[i] = 0x00, i++;
b8aa7b35
TJ
2322 }
2323
2324 // Output product name
c201f80f 2325 output[0x10] = i | 0x80; // calculate offset
b8aa7b35
TJ
2326 output[i] = product_size*2 + 2, i++;
2327 output[i] = 0x03, i++;
22d12cda
TJ
2328 for (j = 0; j < product_size; j++)
2329 {
d9f0cce7
TJ
2330 output[i] = eeprom->product[j], i++;
2331 output[i] = 0x00, i++;
b8aa7b35 2332 }
d9f0cce7 2333
b8aa7b35 2334 // Output serial
c201f80f 2335 output[0x12] = i | 0x80; // calculate offset
b8aa7b35
TJ
2336 output[i] = serial_size*2 + 2, i++;
2337 output[i] = 0x03, i++;
22d12cda
TJ
2338 for (j = 0; j < serial_size; j++)
2339 {
d9f0cce7
TJ
2340 output[i] = eeprom->serial[j], i++;
2341 output[i] = 0x00, i++;
b8aa7b35
TJ
2342 }
2343
2344 // calculate checksum
2345 checksum = 0xAAAA;
d9f0cce7 2346
22d12cda
TJ
2347 for (i = 0; i < eeprom->size/2-1; i++)
2348 {
d9f0cce7
TJ
2349 value = output[i*2];
2350 value += output[(i*2)+1] << 8;
b8aa7b35 2351
d9f0cce7
TJ
2352 checksum = value^checksum;
2353 checksum = (checksum << 1) | (checksum >> 15);
b8aa7b35
TJ
2354 }
2355
c201f80f
TJ
2356 output[eeprom->size-2] = checksum;
2357 output[eeprom->size-1] = checksum >> 8;
b8aa7b35 2358
8ed61121 2359 return size_check;
b8aa7b35
TJ
2360}
2361
4af1d1bb
MK
2362/**
2363 Decode binary EEPROM image into an ftdi_eeprom structure.
2364
2365 \param eeprom Pointer to ftdi_eeprom which will be filled in.
1bbaf1ce 2366 \param buf Buffer of \a size bytes of raw eeprom data
4af1d1bb
MK
2367 \param size size size of eeprom data in bytes
2368
2369 \retval 0: all fine
2370 \retval -1: something went wrong
2371
2372 FIXME: How to pass size? How to handle size field in ftdi_eeprom?
2373 FIXME: Strings are malloc'ed here and should be freed somewhere
2374*/
49c5ac72 2375int ftdi_eeprom_decode(struct ftdi_eeprom *eeprom, unsigned char *buf, int size)
b56d5a64
MK
2376{
2377 unsigned char i, j;
2378 unsigned short checksum, eeprom_checksum, value;
2379 unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
b56d5a64 2380 int eeprom_size = 128;
22a1b5c1
TJ
2381
2382 if (eeprom == NULL)
2383 return -1;
b56d5a64
MK
2384#if 0
2385 size_check = eeprom->size;
2386 size_check -= 28; // 28 are always in use (fixed)
2387
22d12cda 2388 // Top half of a 256byte eeprom is used just for strings and checksum
b56d5a64
MK
2389 // it seems that the FTDI chip will not read these strings from the lower half
2390 // Each string starts with two bytes; offset and type (0x03 for string)
2391 // the checksum needs two bytes, so without the string data that 8 bytes from the top half
22d12cda 2392 if (eeprom->size>=256)size_check = 120;
b56d5a64
MK
2393 size_check -= manufacturer_size*2;
2394 size_check -= product_size*2;
2395 size_check -= serial_size*2;
2396
2397 // eeprom size exceeded?
2398 if (size_check < 0)
2399 return (-1);
2400#endif
2401
2402 // empty eeprom struct
4af1d1bb 2403 memset(eeprom, 0, sizeof(struct ftdi_eeprom));
b56d5a64
MK
2404
2405 // Addr 00: Stay 00 00
2406
2407 // Addr 02: Vendor ID
2408 eeprom->vendor_id = buf[0x02] + (buf[0x03] << 8);
2409
2410 // Addr 04: Product ID
2411 eeprom->product_id = buf[0x04] + (buf[0x05] << 8);
22d12cda 2412
6335545d
TJ
2413 value = buf[0x06] + (buf[0x07]<<8);
2414 switch (value)
22d12cda
TJ
2415 {
2416 case 0x0400:
2417 eeprom->BM_type_chip = 1;
2418 break;
2419 case 0x0200:
2420 eeprom->BM_type_chip = 0;
2421 break;
2422 default: // Unknown device
2423 eeprom->BM_type_chip = 0;
2424 break;
4af1d1bb 2425 }
b56d5a64
MK
2426
2427 // Addr 08: Config descriptor
2428 // Bit 7: always 1
2429 // Bit 6: 1 if this device is self powered, 0 if bus powered
2430 // Bit 5: 1 if this device uses remote wakeup
2431 // Bit 4: 1 if this device is battery powered
2432 j = buf[0x08];
b56d5a64
MK
2433 if (j&0x40) eeprom->self_powered = 1;
2434 if (j&0x20) eeprom->remote_wakeup = 1;
2435
2436 // Addr 09: Max power consumption: max power = value * 2 mA
2437 eeprom->max_power = buf[0x09];
2438
2439 // Addr 0A: Chip configuration
2440 // Bit 7: 0 - reserved
2441 // Bit 6: 0 - reserved
2442 // Bit 5: 0 - reserved
2443 // Bit 4: 1 - Change USB version
2444 // Bit 3: 1 - Use the serial number string
2445 // Bit 2: 1 - Enable suspend pull downs for lower power
2446 // Bit 1: 1 - Out EndPoint is Isochronous
2447 // Bit 0: 1 - In EndPoint is Isochronous
2448 //
2449 j = buf[0x0A];
4af1d1bb
MK
2450 if (j&0x01) eeprom->in_is_isochronous = 1;
2451 if (j&0x02) eeprom->out_is_isochronous = 1;
2452 if (j&0x04) eeprom->suspend_pull_downs = 1;
2453 if (j&0x08) eeprom->use_serial = 1;
2454 if (j&0x10) eeprom->change_usb_version = 1;
b56d5a64 2455
4af1d1bb 2456 // Addr 0B: reserved
b56d5a64
MK
2457
2458 // Addr 0C: USB version low byte when 0x0A bit 4 is set
2459 // Addr 0D: USB version high byte when 0x0A bit 4 is set
22d12cda
TJ
2460 if (eeprom->change_usb_version == 1)
2461 {
2462 eeprom->usb_version = buf[0x0C] + (buf[0x0D] << 8);
b56d5a64
MK
2463 }
2464
2465 // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
2466 // Addr 0F: Length of manufacturer string
2467 manufacturer_size = buf[0x0F]/2;
2468 if (manufacturer_size > 0) eeprom->manufacturer = malloc(manufacturer_size);
2469 else eeprom->manufacturer = NULL;
2470
2471 // Addr 10: Offset of the product string + 0x80, calculated later
2472 // Addr 11: Length of product string
2473 product_size = buf[0x11]/2;
2474 if (product_size > 0) eeprom->product = malloc(product_size);
2475 else eeprom->product = NULL;
2476
2477 // Addr 12: Offset of the serial string + 0x80, calculated later
2478 // Addr 13: Length of serial string
2479 serial_size = buf[0x13]/2;
2480 if (serial_size > 0) eeprom->serial = malloc(serial_size);
2481 else eeprom->serial = NULL;
2482
22d12cda 2483 // Decode manufacturer
b56d5a64 2484 i = buf[0x0E] & 0x7f; // offset
22d12cda
TJ
2485 for (j=0;j<manufacturer_size-1;j++)
2486 {
2487 eeprom->manufacturer[j] = buf[2*j+i+2];
b56d5a64
MK
2488 }
2489 eeprom->manufacturer[j] = '\0';
2490
2491 // Decode product name
2492 i = buf[0x10] & 0x7f; // offset
22d12cda
TJ
2493 for (j=0;j<product_size-1;j++)
2494 {
2495 eeprom->product[j] = buf[2*j+i+2];
b56d5a64
MK
2496 }
2497 eeprom->product[j] = '\0';
2498
2499 // Decode serial
2500 i = buf[0x12] & 0x7f; // offset
22d12cda
TJ
2501 for (j=0;j<serial_size-1;j++)
2502 {
2503 eeprom->serial[j] = buf[2*j+i+2];
b56d5a64
MK
2504 }
2505 eeprom->serial[j] = '\0';
2506
2507 // verify checksum
2508 checksum = 0xAAAA;
2509
22d12cda
TJ
2510 for (i = 0; i < eeprom_size/2-1; i++)
2511 {
b56d5a64
MK
2512 value = buf[i*2];
2513 value += buf[(i*2)+1] << 8;
2514
2515 checksum = value^checksum;
2516 checksum = (checksum << 1) | (checksum >> 15);
2517 }
2518
2519 eeprom_checksum = buf[eeprom_size-2] + (buf[eeprom_size-1] << 8);
2520
22d12cda
TJ
2521 if (eeprom_checksum != checksum)
2522 {
2523 fprintf(stderr, "Checksum Error: %04x %04x\n", checksum, eeprom_checksum);
2524 return -1;
4af1d1bb
MK
2525 }
2526
2527 return 0;
b56d5a64
MK
2528}
2529
1941414d 2530/**
c1c70e13
OS
2531 Read eeprom location
2532
2533 \param ftdi pointer to ftdi_context
2534 \param eeprom_addr Address of eeprom location to be read
2535 \param eeprom_val Pointer to store read eeprom location
2536
2537 \retval 0: all fine
2538 \retval -1: read failed
22a1b5c1 2539 \retval -2: USB device unavailable
c1c70e13
OS
2540*/
2541int ftdi_read_eeprom_location (struct ftdi_context *ftdi, int eeprom_addr, unsigned short *eeprom_val)
2542{
22a1b5c1
TJ
2543 if (ftdi == NULL || ftdi->usb_dev == NULL)
2544 ftdi_error_return(-2, "USB device unavailable");
2545
579b006f 2546 if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_READ_EEPROM_REQUEST, 0, eeprom_addr, (char *)eeprom_val, 2, ftdi->usb_read_timeout) != 2)
c1c70e13
OS
2547 ftdi_error_return(-1, "reading eeprom failed");
2548
2549 return 0;
2550}
2551
2552/**
1941414d
TJ
2553 Read eeprom
2554
2555 \param ftdi pointer to ftdi_context
2556 \param eeprom Pointer to store eeprom into
b8aa7b35 2557
1941414d
TJ
2558 \retval 0: all fine
2559 \retval -1: read failed
22a1b5c1 2560 \retval -2: USB device unavailable
1941414d 2561*/
a8f46ddc
TJ
2562int ftdi_read_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
2563{
a3da1d95
GE
2564 int i;
2565
22a1b5c1
TJ
2566 if (ftdi == NULL || ftdi->usb_dev == NULL)
2567 ftdi_error_return(-2, "USB device unavailable");
2568
22d12cda
TJ
2569 for (i = 0; i < ftdi->eeprom_size/2; i++)
2570 {
579b006f 2571 if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_READ_EEPROM_REQUEST, 0, i, eeprom+(i*2), 2, ftdi->usb_read_timeout) != 2)
c3d95b87 2572 ftdi_error_return(-1, "reading eeprom failed");
a3da1d95
GE
2573 }
2574
2575 return 0;
2576}
2577
cb6250fa
TJ
2578/*
2579 ftdi_read_chipid_shift does the bitshift operation needed for the FTDIChip-ID
2580 Function is only used internally
2581 \internal
2582*/
2583static unsigned char ftdi_read_chipid_shift(unsigned char value)
2584{
2585 return ((value & 1) << 1) |
22d12cda
TJ
2586 ((value & 2) << 5) |
2587 ((value & 4) >> 2) |
2588 ((value & 8) << 4) |
2589 ((value & 16) >> 1) |
2590 ((value & 32) >> 1) |
2591 ((value & 64) >> 4) |
2592 ((value & 128) >> 2);
cb6250fa
TJ
2593}
2594
2595/**
2596 Read the FTDIChip-ID from R-type devices
2597
2598 \param ftdi pointer to ftdi_context
2599 \param chipid Pointer to store FTDIChip-ID
2600
2601 \retval 0: all fine
2602 \retval -1: read failed
22a1b5c1 2603 \retval -2: USB device unavailable
cb6250fa
TJ
2604*/
2605int ftdi_read_chipid(struct ftdi_context *ftdi, unsigned int *chipid)
2606{
c7eb3112 2607 unsigned int a = 0, b = 0;
cb6250fa 2608
22a1b5c1
TJ
2609 if (ftdi == NULL || ftdi->usb_dev == NULL)
2610 ftdi_error_return(-2, "USB device unavailable");
2611
579b006f 2612 if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_READ_EEPROM_REQUEST, 0, 0x43, (unsigned char *)&a, 2, ftdi->usb_read_timeout) == 2)
cb6250fa
TJ
2613 {
2614 a = a << 8 | a >> 8;
579b006f 2615 if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_READ_EEPROM_REQUEST, 0, 0x44, (unsigned char *)&b, 2, ftdi->usb_read_timeout) == 2)
cb6250fa
TJ
2616 {
2617 b = b << 8 | b >> 8;
5230676f 2618 a = (a << 16) | (b & 0xFFFF);
912d50ca
TJ
2619 a = ftdi_read_chipid_shift(a) | ftdi_read_chipid_shift(a>>8)<<8
2620 | ftdi_read_chipid_shift(a>>16)<<16 | ftdi_read_chipid_shift(a>>24)<<24;
cb6250fa 2621 *chipid = a ^ 0xa5f0f7d1;
c7eb3112 2622 return 0;
cb6250fa
TJ
2623 }
2624 }
2625
c7eb3112 2626 ftdi_error_return(-1, "read of FTDIChip-ID failed");
cb6250fa
TJ
2627}
2628
1941414d 2629/**
22a1b5c1
TJ
2630 Guesses size of eeprom by reading eeprom and comparing halves - will not work with blank eeprom
2631 Call this function then do a write then call again to see if size changes, if so write again.
c201f80f 2632
22a1b5c1
TJ
2633 \param ftdi pointer to ftdi_context
2634 \param eeprom Pointer to store eeprom into
2635 \param maxsize the size of the buffer to read into
c201f80f 2636
22a1b5c1
TJ
2637 \retval -1: eeprom read failed
2638 \retval -2: USB device unavailable
2639 \retval >=0: size of eeprom
c201f80f
TJ
2640*/
2641int ftdi_read_eeprom_getsize(struct ftdi_context *ftdi, unsigned char *eeprom, int maxsize)
2642{
2643 int i=0,j,minsize=32;
2644 int size=minsize;
2645
22a1b5c1
TJ
2646 if (ftdi == NULL || ftdi->usb_dev == NULL)
2647 ftdi_error_return(-2, "USB device unavailable");
2648
22d12cda
TJ
2649 do
2650 {
2651 for (j = 0; i < maxsize/2 && j<size; j++)
2652 {
579b006f
JZ
2653 if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE,
2654 SIO_READ_EEPROM_REQUEST, 0, i,
2655 eeprom+(i*2), 2, ftdi->usb_read_timeout) != 2)
22a1b5c1 2656 ftdi_error_return(-1, "eeprom read failed");
22d12cda
TJ
2657 i++;
2658 }
2659 size*=2;
2660 }
2661 while (size<=maxsize && memcmp(eeprom,&eeprom[size/2],size/2)!=0);
c201f80f
TJ
2662
2663 return size/2;
2664}
2665
2666/**
c1c70e13
OS
2667 Write eeprom location
2668
2669 \param ftdi pointer to ftdi_context
2670 \param eeprom_addr Address of eeprom location to be written
2671 \param eeprom_val Value to be written
2672
2673 \retval 0: all fine
2674 \retval -1: read failed
22a1b5c1 2675 \retval -2: USB device unavailable
c1c70e13
OS
2676*/
2677int ftdi_write_eeprom_location(struct ftdi_context *ftdi, int eeprom_addr, unsigned short eeprom_val)
2678{
22a1b5c1
TJ
2679 if (ftdi == NULL || ftdi->usb_dev == NULL)
2680 ftdi_error_return(-2, "USB device unavailable");
2681
579b006f 2682 if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
c1c70e13
OS
2683 SIO_WRITE_EEPROM_REQUEST, eeprom_val, eeprom_addr,
2684 NULL, 0, ftdi->usb_write_timeout) != 0)
2685 ftdi_error_return(-1, "unable to write eeprom");
2686
2687 return 0;
2688}
2689
2690/**
1941414d 2691 Write eeprom
a3da1d95 2692
1941414d
TJ
2693 \param ftdi pointer to ftdi_context
2694 \param eeprom Pointer to read eeprom from
2695
2696 \retval 0: all fine
2697 \retval -1: read failed
22a1b5c1 2698 \retval -2: USB device unavailable
1941414d 2699*/
a8f46ddc
TJ
2700int ftdi_write_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
2701{
ba5329be 2702 unsigned short usb_val, status;
e30da501 2703 int i, ret;
a3da1d95 2704
22a1b5c1
TJ
2705 if (ftdi == NULL || ftdi->usb_dev == NULL)
2706 ftdi_error_return(-2, "USB device unavailable");
2707
ba5329be 2708 /* These commands were traced while running MProg */
e30da501
TJ
2709 if ((ret = ftdi_usb_reset(ftdi)) != 0)
2710 return ret;
2711 if ((ret = ftdi_poll_modem_status(ftdi, &status)) != 0)
2712 return ret;
2713 if ((ret = ftdi_set_latency_timer(ftdi, 0x77)) != 0)
2714 return ret;
ba5329be 2715
22d12cda
TJ
2716 for (i = 0; i < ftdi->eeprom_size/2; i++)
2717 {
d9f0cce7
TJ
2718 usb_val = eeprom[i*2];
2719 usb_val += eeprom[(i*2)+1] << 8;
579b006f
JZ
2720 if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
2721 SIO_WRITE_EEPROM_REQUEST, usb_val, i,
2722 NULL, 0, ftdi->usb_write_timeout) < 0)
c3d95b87 2723 ftdi_error_return(-1, "unable to write eeprom");
a3da1d95
GE
2724 }
2725
2726 return 0;
2727}
2728
1941414d
TJ
2729/**
2730 Erase eeprom
a3da1d95 2731
a5e1bd8c
MK
2732 This is not supported on FT232R/FT245R according to the MProg manual from FTDI.
2733
1941414d
TJ
2734 \param ftdi pointer to ftdi_context
2735
2736 \retval 0: all fine
2737 \retval -1: erase failed
22a1b5c1 2738 \retval -2: USB device unavailable
1941414d 2739*/
a8f46ddc
TJ
2740int ftdi_erase_eeprom(struct ftdi_context *ftdi)
2741{
22a1b5c1
TJ
2742 if (ftdi == NULL || ftdi->usb_dev == NULL)
2743 ftdi_error_return(-2, "USB device unavailable");
2744
579b006f 2745 if (libusb_control_transfer(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_ERASE_EEPROM_REQUEST, 0, 0, NULL, 0, ftdi->usb_write_timeout) < 0)
c3d95b87 2746 ftdi_error_return(-1, "unable to erase eeprom");
a3da1d95
GE
2747
2748 return 0;
2749}
c3d95b87 2750
1941414d
TJ
2751/**
2752 Get string representation for last error code
c3d95b87 2753
1941414d
TJ
2754 \param ftdi pointer to ftdi_context
2755
2756 \retval Pointer to error string
2757*/
c3d95b87
TJ
2758char *ftdi_get_error_string (struct ftdi_context *ftdi)
2759{
22a1b5c1
TJ
2760 if (ftdi == NULL)
2761 return "";
2762
c3d95b87
TJ
2763 return ftdi->error_str;
2764}
a01d31e2 2765
b5ec1820 2766/* @} end of doxygen libftdi group */