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