libftdi: (tomj) refactored USB part of libftdi, doesn't depend
[libftdi] / ftdi / ftdi.c
CommitLineData
a3da1d95
GE
1/***************************************************************************
2 ftdi.c - description
3 -------------------
4 begin : Fri Apr 4 2003
5 copyright : (C) 2003 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 ***************************************************************************/
0e302db6 16#define _GNU_SOURCE
d9f0cce7 17
a3da1d95 18#include "ftdi.h"
0e302db6
TJ
19#include <sys/ioctl.h>
20#include <sys/time.h>
0e302db6 21#include <sys/stat.h>
a97980ad
TJ
22#include <fcntl.h>
23#include <dirent.h>
0e302db6
TJ
24
25/* Internal USB devfs functions. Do not use outside libftdi */
a97980ad
TJ
26
27/* Those two functions are borrowed from "usbstress" */
28static int ftdi_usbdev_parsedev(int fd, unsigned int *bus, unsigned int *dev, int vendorid, int productid);
29int ftdi_usbdev_open(int vendorid, int productid);
30
31int ftdi_usbdev_claim_interface(int fd, unsigned int interface);
32int ftdi_usbdev_release_interface(int fd, int interface);
33int ftdi_usbdev_bulk_write(int fd, unsigned int endpoint, const void *data,
34 unsigned int size, unsigned int timeout);
35int ftdi_usbdev_control_msg(int fd, unsigned int requesttype, unsigned int request,
36 unsigned int value, unsigned int index,
37 void *data, unsigned int size, unsigned int timeout);
38struct usbdevfs_urb * ftdi_usbdev_alloc_urb(int iso_packets);
39int ftdi_usbdev_submit_urb(int fd, struct usbdevfs_urb *urb);
40int ftdi_usbdev_reap_urb_ndelay(int fd, struct usbdevfs_urb **urb_return);
0e302db6 41
a3da1d95 42
948f9ada
TJ
43/* ftdi_init return codes:
44 0: all fine
6d9aa99f 45 -1: couldn't allocate read buffer
948f9ada 46*/
0e302db6
TJ
47int ftdi_init(struct ftdi_context *ftdi)
48{
a97980ad 49 ftdi->usb_fd = -1;
545820ce
TJ
50 ftdi->usb_read_timeout = 5000;
51 ftdi->usb_write_timeout = 5000;
a3da1d95 52
53ad271d 53 ftdi->type = TYPE_BM; /* chip type */
a3da1d95
GE
54 ftdi->baudrate = -1;
55 ftdi->bitbang_enabled = 0;
56
948f9ada
TJ
57 ftdi->readbuffer = NULL;
58 ftdi->readbuffer_offset = 0;
59 ftdi->readbuffer_remaining = 0;
60 ftdi->writebuffer_chunksize = 4096;
61
545820ce
TJ
62 ftdi->interface = 0;
63 ftdi->index = 0;
64 ftdi->in_ep = 0x02;
65 ftdi->out_ep = 0x81;
3119537f 66 ftdi->bitbang_mode = 1; /* 1: Normal bitbang mode, 2: SPI bitbang mode */
53ad271d 67
a3da1d95
GE
68 ftdi->error_str = NULL;
69
0e302db6
TJ
70 ftdi->urb = ftdi_usbdev_alloc_urb(0);
71 if (!ftdi->urb) {
72 ftdi->error_str = "out of memory for read URB";
73 return -1;
74 }
75
948f9ada
TJ
76 // all fine. Now allocate the readbuffer
77 return ftdi_read_data_set_chunksize(ftdi, 4096);
78}
79
80
0e302db6
TJ
81void ftdi_deinit(struct ftdi_context *ftdi)
82{
948f9ada 83 if (ftdi->readbuffer != NULL) {
d9f0cce7
TJ
84 free(ftdi->readbuffer);
85 ftdi->readbuffer = NULL;
948f9ada 86 }
0e302db6
TJ
87
88 if (ftdi->urb != NULL) {
89 free (ftdi->urb);
90 ftdi->urb = NULL;
91 }
a3da1d95
GE
92}
93
a3da1d95
GE
94/* ftdi_usb_open return codes:
95 0: all fine
a97980ad
TJ
96 -1: usb device not found or unable to open
97 -2: unable to claim device
98 -3: reset failed
99 -4: set baudrate failed
a3da1d95
GE
100*/
101int ftdi_usb_open(struct ftdi_context *ftdi, int vendor, int product) {
a97980ad
TJ
102 if ((ftdi->usb_fd = ftdi_usbdev_open(vendor, product)) < 0) {
103 ftdi->error_str = "Device not found or unable to open it (permission problem?)";
104 ftdi->usb_fd = -1;
105 return -1;
106 }
107
108 if (ftdi_usbdev_claim_interface(ftdi->usb_fd, ftdi->interface) != 0) {
109 ftdi->error_str = "unable to claim usb device. Make sure ftdi_sio is unloaded!";
110 close (ftdi->usb_fd);
111 ftdi->usb_fd = -1;
a3da1d95
GE
112 return -2;
113 }
114
a97980ad
TJ
115 if (ftdi_usb_reset (ftdi) != 0)
116 return -6;
a3da1d95 117
a97980ad
TJ
118 if (ftdi_set_baudrate (ftdi, 9600) != 0)
119 return -7;
a3da1d95 120
a97980ad
TJ
121/*
122 // Try to guess chip type
123 // Bug in the BM type chips: bcdDevice is 0x200 for serial == 0
124 if (dev->descriptor.bcdDevice == 0x400 || (dev->descriptor.bcdDevice == 0x200
125 && dev->descriptor.iSerialNumber == 0))
126 ftdi->type = TYPE_BM;
127 else if (dev->descriptor.bcdDevice == 0x200)
128 ftdi->type = TYPE_AM;
129 else if (dev->descriptor.bcdDevice == 0x500)
130 ftdi->type = TYPE_2232C;
131*/
132 return 0;
a3da1d95
GE
133}
134
135
136int ftdi_usb_reset(struct ftdi_context *ftdi) {
a97980ad 137 if (ftdi_usbdev_control_msg(ftdi->usb_fd, 0x40, 0, 0, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0) {
a3da1d95
GE
138 ftdi->error_str = "FTDI reset failed";
139 return -1;
140 }
545820ce 141 // Invalidate data in the readbuffer
bfcee05b
TJ
142 ftdi->readbuffer_offset = 0;
143 ftdi->readbuffer_remaining = 0;
144
a3da1d95
GE
145 return 0;
146}
147
a60be878 148int ftdi_usb_purge_buffers(struct ftdi_context *ftdi) {
a97980ad 149 if (ftdi_usbdev_control_msg(ftdi->usb_fd, 0x40, 0, 1, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0) {
a60be878
TJ
150 ftdi->error_str = "FTDI purge of RX buffer failed";
151 return -1;
152 }
545820ce 153 // Invalidate data in the readbuffer
bfcee05b
TJ
154 ftdi->readbuffer_offset = 0;
155 ftdi->readbuffer_remaining = 0;
a60be878 156
a97980ad 157 if (ftdi_usbdev_control_msg(ftdi->usb_fd, 0x40, 0, 2, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0) {
a60be878
TJ
158 ftdi->error_str = "FTDI purge of TX buffer failed";
159 return -1;
160 }
161
545820ce 162
a60be878
TJ
163 return 0;
164}
a3da1d95
GE
165
166/* ftdi_usb_close return codes
167 0: all fine
a97980ad
TJ
168 -1: ftdi_usb_release failed
169 -2: close failed
a3da1d95
GE
170*/
171int ftdi_usb_close(struct ftdi_context *ftdi) {
172 int rtn = 0;
173
a97980ad
TJ
174 if (ftdi_usbdev_release_interface(ftdi->usb_fd, ftdi->interface) != 0) {
175 ftdi->error_str = "Unable to release interface";
a3da1d95 176 rtn = -1;
a97980ad
TJ
177 }
178
179
180 if (close (ftdi->usb_fd) != 0) {
181 ftdi->error_str = "Unable to close file descriptor";
a3da1d95 182 rtn = -2;
a97980ad
TJ
183 }
184
a3da1d95
GE
185 return rtn;
186}
187
188
189/*
53ad271d
TJ
190 ftdi_convert_baudrate returns nearest supported baud rate to that requested.
191 Function is only used internally
192*/
0126d22e 193static int ftdi_convert_baudrate(int baudrate, struct ftdi_context *ftdi,
53ad271d
TJ
194 unsigned short *value, unsigned short *index) {
195 static const char am_adjust_up[8] = {0, 0, 0, 1, 0, 3, 2, 1};
196 static const char am_adjust_dn[8] = {0, 0, 0, 1, 0, 1, 2, 3};
197 static const char frac_code[8] = {0, 3, 2, 4, 1, 5, 6, 7};
198 int divisor, best_divisor, best_baud, best_baud_diff;
199 unsigned long encoded_divisor;
200 int i;
201
202 if (baudrate <= 0) {
203 // Return error
204 return -1;
205 }
206
207 divisor = 24000000 / baudrate;
208
0126d22e 209 if (ftdi->type == TYPE_AM) {
53ad271d
TJ
210 // Round down to supported fraction (AM only)
211 divisor -= am_adjust_dn[divisor & 7];
212 }
213
214 // Try this divisor and the one above it (because division rounds down)
215 best_divisor = 0;
216 best_baud = 0;
217 best_baud_diff = 0;
218 for (i = 0; i < 2; i++) {
219 int try_divisor = divisor + i;
220 int baud_estimate;
221 int baud_diff;
222
223 // Round up to supported divisor value
224 if (try_divisor < 8) {
225 // Round up to minimum supported divisor
226 try_divisor = 8;
0126d22e 227 } else if (ftdi->type != TYPE_AM && try_divisor < 12) {
53ad271d
TJ
228 // BM doesn't support divisors 9 through 11 inclusive
229 try_divisor = 12;
230 } else if (divisor < 16) {
231 // AM doesn't support divisors 9 through 15 inclusive
232 try_divisor = 16;
233 } else {
0126d22e 234 if (ftdi->type == TYPE_AM) {
53ad271d
TJ
235 // Round up to supported fraction (AM only)
236 try_divisor += am_adjust_up[try_divisor & 7];
237 if (try_divisor > 0x1FFF8) {
238 // Round down to maximum supported divisor value (for AM)
239 try_divisor = 0x1FFF8;
240 }
241 } else {
242 if (try_divisor > 0x1FFFF) {
243 // Round down to maximum supported divisor value (for BM)
244 try_divisor = 0x1FFFF;
245 }
246 }
247 }
248 // Get estimated baud rate (to nearest integer)
249 baud_estimate = (24000000 + (try_divisor / 2)) / try_divisor;
250 // Get absolute difference from requested baud rate
251 if (baud_estimate < baudrate) {
252 baud_diff = baudrate - baud_estimate;
253 } else {
254 baud_diff = baud_estimate - baudrate;
255 }
256 if (i == 0 || baud_diff < best_baud_diff) {
257 // Closest to requested baud rate so far
258 best_divisor = try_divisor;
259 best_baud = baud_estimate;
260 best_baud_diff = baud_diff;
261 if (baud_diff == 0) {
262 // Spot on! No point trying
263 break;
264 }
265 }
266 }
267 // Encode the best divisor value
268 encoded_divisor = (best_divisor >> 3) | (frac_code[best_divisor & 7] << 14);
269 // Deal with special cases for encoded value
270 if (encoded_divisor == 1) {
271 encoded_divisor = 0; // 3000000 baud
272 } else if (encoded_divisor == 0x4001) {
273 encoded_divisor = 1; // 2000000 baud (BM only)
274 }
275 // Split into "value" and "index" values
276 *value = (unsigned short)(encoded_divisor & 0xFFFF);
de22df10 277 if(ftdi->type == TYPE_2232C) {
0126d22e
TJ
278 *index = (unsigned short)(encoded_divisor >> 8);
279 *index &= 0xFF00;
280 *index |= ftdi->interface;
281 }
282 else
283 *index = (unsigned short)(encoded_divisor >> 16);
284
53ad271d
TJ
285 // Return the nearest baud rate
286 return best_baud;
287}
288
289/*
a3da1d95
GE
290 ftdi_set_baudrate return codes:
291 0: all fine
292 -1: invalid baudrate
293 -2: setting baudrate failed
294*/
295int ftdi_set_baudrate(struct ftdi_context *ftdi, int baudrate) {
53ad271d
TJ
296 unsigned short value, index;
297 int actual_baudrate;
a3da1d95
GE
298
299 if (ftdi->bitbang_enabled) {
300 baudrate = baudrate*4;
301 }
302
25707904 303 actual_baudrate = ftdi_convert_baudrate(baudrate, ftdi, &value, &index);
53ad271d
TJ
304 if (actual_baudrate <= 0) {
305 ftdi->error_str = "Silly baudrate <= 0.";
a3da1d95
GE
306 return -1;
307 }
308
53ad271d
TJ
309 // Check within tolerance (about 5%)
310 if ((actual_baudrate * 2 < baudrate /* Catch overflows */ )
311 || ((actual_baudrate < baudrate)
312 ? (actual_baudrate * 21 < baudrate * 20)
313 : (baudrate * 21 < actual_baudrate * 20))) {
314 ftdi->error_str = "Unsupported baudrate. Note: bitbang baudrates are automatically multiplied by 4";
315 return -1;
316 }
545820ce 317
a97980ad 318 if (ftdi_usbdev_control_msg(ftdi->usb_fd, 0x40, 3, value, index, NULL, 0, ftdi->usb_write_timeout) != 0) {
a3da1d95
GE
319 ftdi->error_str = "Setting new baudrate failed";
320 return -2;
321 }
322
323 ftdi->baudrate = baudrate;
324 return 0;
325}
326
327
be5d7eec 328int ftdi_write_data(struct ftdi_context *ftdi, unsigned char *buf, int size) {
a3da1d95
GE
329 int ret;
330 int offset = 0;
545820ce 331 int total_written = 0;
a3da1d95 332 while (offset < size) {
948f9ada 333 int write_size = ftdi->writebuffer_chunksize;
a3da1d95
GE
334
335 if (offset+write_size > size)
336 write_size = size-offset;
337
a97980ad 338 ret = ftdi_usbdev_bulk_write(ftdi->usb_fd, ftdi->in_ep, buf+offset, write_size, ftdi->usb_write_timeout);
cbabb7d3 339 if (ret == -1) {
d9f0cce7 340 ftdi->error_str = "bulk write failed";
a3da1d95 341 return -1;
d9f0cce7 342 }
545820ce 343 total_written += ret;
a3da1d95
GE
344
345 offset += write_size;
346 }
347
545820ce 348 return total_written;
a3da1d95
GE
349}
350
351
948f9ada
TJ
352int ftdi_write_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize) {
353 ftdi->writebuffer_chunksize = chunksize;
354 return 0;
355}
356
357
358int ftdi_write_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize) {
359 *chunksize = ftdi->writebuffer_chunksize;
360 return 0;
361}
cbabb7d3 362
948f9ada
TJ
363
364int ftdi_read_data(struct ftdi_context *ftdi, unsigned char *buf, int size) {
0e302db6
TJ
365 struct timeval tv, tv_ref, tv_now;
366 struct usbdevfs_urb *returned_urb;
367 int offset = 0, ret = 1, waiting;
d9f0cce7 368
948f9ada
TJ
369 // everything we want is still in the readbuffer?
370 if (size <= ftdi->readbuffer_remaining) {
d9f0cce7
TJ
371 memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);
372
373 // Fix offsets
374 ftdi->readbuffer_remaining -= size;
375 ftdi->readbuffer_offset += size;
376
545820ce 377 /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */
d9f0cce7
TJ
378
379 return size;
979a145c 380 }
948f9ada
TJ
381 // something still in the readbuffer, but not enough to satisfy 'size'?
382 if (ftdi->readbuffer_remaining != 0) {
d9f0cce7 383 memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);
979a145c 384
d9f0cce7
TJ
385 // Fix offset
386 offset += ftdi->readbuffer_remaining;
948f9ada 387 }
0e302db6 388
948f9ada 389 // do the actual USB read
cbabb7d3 390 while (offset < size && ret > 0) {
d9f0cce7
TJ
391 ftdi->readbuffer_remaining = 0;
392 ftdi->readbuffer_offset = 0;
0e302db6 393
0e302db6
TJ
394 /* Real userspace URB processing to cope with
395 a race condition where two or more status bytes
396 could already be in the kernel USB buffer */
397 memset(ftdi->urb, 0, sizeof(struct usbdevfs_urb));
398
399 ftdi->urb->type = USBDEVFS_URB_TYPE_BULK;
400 ftdi->urb->endpoint = ftdi->out_ep | USB_DIR_IN;
401 ftdi->urb->buffer = ftdi->readbuffer;
402 ftdi->urb->buffer_length = ftdi->readbuffer_chunksize;
403
404 /* Submit URB to USB layer */
a97980ad 405 if (ftdi_usbdev_submit_urb(ftdi->usb_fd, ftdi->urb) == -1) {
0e302db6 406 ftdi->error_str = "ftdi_usbdev_submit_urb for bulk read failed";
cbabb7d3 407 return -1;
d9f0cce7 408 }
0e302db6
TJ
409
410 /* Wait for the result to come in.
411 Timer stuff is borrowed from libusb's interrupt transfer */
412 gettimeofday(&tv_ref, NULL);
413 tv_ref.tv_sec = tv_ref.tv_sec + ftdi->usb_read_timeout / 1000;
414 tv_ref.tv_usec = tv_ref.tv_usec + (ftdi->usb_read_timeout % 1000) * 1000;
415
416 if (tv_ref.tv_usec > 1e6) {
417 tv_ref.tv_usec -= 1e6;
418 tv_ref.tv_sec++;
419 }
420
421 waiting = 1;
422 memset (&tv, 0, sizeof (struct timeval));
a97980ad 423 while (((ret = ftdi_usbdev_reap_urb_ndelay(ftdi->usb_fd, &returned_urb)) == -1) && waiting) {
0e302db6
TJ
424 tv.tv_sec = 0;
425 tv.tv_usec = 1000; // 1 msec
426 select(0, NULL, NULL, NULL, &tv); //sub second wait
427
428 /* compare with actual time, as the select timeout is not that precise */
429 gettimeofday(&tv_now, NULL);
430
431 if ((tv_now.tv_sec > tv_ref.tv_sec) ||
432 ((tv_now.tv_sec == tv_ref.tv_sec) && (tv_now.tv_usec >= tv_ref.tv_usec)))
433 waiting = 0;
434 }
435
436 if (!waiting) {
437 ftdi->error_str = "timeout during ftdi_read_data";
438 return -1;
439 }
440
441 if (ret < 0) {
442 ftdi->error_str = "ftdi_usbdev_reap_urb for bulk read failed";
443 return -1;
444 }
445
446 if (returned_urb->status) {
447 ftdi->error_str = "URB return status not OK";
448 return -1;
449 }
450
451 /* Paranoia check */
452 if (returned_urb->buffer != ftdi->readbuffer) {
453 ftdi->error_str = "buffer paranoia check failed";
454 return -1;
455 }
456
457 ret = returned_urb->actual_length;
d9f0cce7
TJ
458 if (ret > 2) {
459 // skip FTDI status bytes.
460 // Maybe stored in the future to enable modem use
461 ftdi->readbuffer_offset += 2;
462 ret -= 2;
463 } else if (ret <= 2) {
464 // no more data to read?
465 return offset;
466 }
d9f0cce7
TJ
467 if (ret > 0) {
468 // data still fits in buf?
469 if (offset+ret <= size) {
470 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, ret);
545820ce 471 //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
d9f0cce7
TJ
472 offset += ret;
473
53ad271d 474 /* Did we read exactly the right amount of bytes? */
d9f0cce7
TJ
475 if (offset == size)
476 return offset;
477 } else {
478 // only copy part of the data or size <= readbuffer_chunksize
479 int part_size = size-offset;
480 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, part_size);
0e302db6 481
d9f0cce7
TJ
482 ftdi->readbuffer_offset += part_size;
483 ftdi->readbuffer_remaining = ret-part_size;
484 offset += part_size;
485
53ad271d
TJ
486 /* printf("Returning part: %d - size: %d - offset: %d - ret: %d - remaining: %d\n",
487 part_size, size, offset, ret, ftdi->readbuffer_remaining); */
d9f0cce7
TJ
488
489 return offset;
490 }
491 }
cbabb7d3 492 }
948f9ada
TJ
493 // never reached
494 return -2;
a3da1d95
GE
495}
496
497
948f9ada
TJ
498int ftdi_read_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize) {
499 // Invalidate all remaining data
500 ftdi->readbuffer_offset = 0;
501 ftdi->readbuffer_remaining = 0;
502
503 unsigned char *new_buf;
504 if ((new_buf = (unsigned char *)realloc(ftdi->readbuffer, chunksize)) == NULL) {
d9f0cce7
TJ
505 ftdi->error_str = "out of memory for readbuffer";
506 return -1;
948f9ada 507 }
d9f0cce7 508
948f9ada
TJ
509 ftdi->readbuffer = new_buf;
510 ftdi->readbuffer_chunksize = chunksize;
511
512 return 0;
513}
514
515
25707904 516int ftdi_read_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize) {
948f9ada
TJ
517 *chunksize = ftdi->readbuffer_chunksize;
518 return 0;
519}
520
521
522
a3da1d95
GE
523int ftdi_enable_bitbang(struct ftdi_context *ftdi, unsigned char bitmask) {
524 unsigned short usb_val;
525
d9f0cce7 526 usb_val = bitmask; // low byte: bitmask
3119537f
TJ
527 /* FT2232C: Set bitbang_mode to 2 to enable SPI */
528 usb_val |= (ftdi->bitbang_mode << 8);
529
a97980ad 530 if (ftdi_usbdev_control_msg(ftdi->usb_fd, 0x40, 0x0B, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0) {
a3da1d95
GE
531 ftdi->error_str = "Unable to enter bitbang mode. Perhaps not a BM type chip?";
532 return -1;
533 }
a3da1d95
GE
534 ftdi->bitbang_enabled = 1;
535 return 0;
536}
537
538
539int ftdi_disable_bitbang(struct ftdi_context *ftdi) {
a97980ad 540 if (ftdi_usbdev_control_msg(ftdi->usb_fd, 0x40, 0x0B, 0, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0) {
a3da1d95
GE
541 ftdi->error_str = "Unable to leave bitbang mode. Perhaps not a BM type chip?";
542 return -1;
543 }
544
545 ftdi->bitbang_enabled = 0;
546 return 0;
547}
548
549
550int ftdi_read_pins(struct ftdi_context *ftdi, unsigned char *pins) {
551 unsigned short usb_val;
a97980ad 552 if (ftdi_usbdev_control_msg(ftdi->usb_fd, 0xC0, 0x0C, 0, ftdi->index, (char *)&usb_val, 1, ftdi->usb_read_timeout) != 1) {
a3da1d95
GE
553 ftdi->error_str = "Read pins failed";
554 return -1;
555 }
556
557 *pins = (unsigned char)usb_val;
558 return 0;
559}
560
561
562int ftdi_set_latency_timer(struct ftdi_context *ftdi, unsigned char latency) {
563 unsigned short usb_val;
564
565 if (latency < 1) {
d9f0cce7
TJ
566 ftdi->error_str = "Latency out of range. Only valid for 1-255";
567 return -1;
a3da1d95
GE
568 }
569
d79d2e68 570 usb_val = latency;
a97980ad 571 if (ftdi_usbdev_control_msg(ftdi->usb_fd, 0x40, 0x09, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0) {
d9f0cce7
TJ
572 ftdi->error_str = "Unable to set latency timer";
573 return -2;
a3da1d95
GE
574 }
575 return 0;
576}
577
578
579int ftdi_get_latency_timer(struct ftdi_context *ftdi, unsigned char *latency) {
580 unsigned short usb_val;
a97980ad 581 if (ftdi_usbdev_control_msg(ftdi->usb_fd, 0xC0, 0x0A, 0, ftdi->index, (char *)&usb_val, 1, ftdi->usb_read_timeout) != 1) {
a3da1d95
GE
582 ftdi->error_str = "Reading latency timer failed";
583 return -1;
584 }
585
586 *latency = (unsigned char)usb_val;
587 return 0;
588}
589
590
b8aa7b35 591void ftdi_eeprom_initdefaults(struct ftdi_eeprom *eeprom) {
f396dbad
TJ
592 eeprom->vendor_id = 0x0403;
593 eeprom->product_id = 0x6001;
d9f0cce7 594
b8aa7b35
TJ
595 eeprom->self_powered = 1;
596 eeprom->remote_wakeup = 1;
597 eeprom->BM_type_chip = 1;
d9f0cce7 598
b8aa7b35
TJ
599 eeprom->in_is_isochronous = 0;
600 eeprom->out_is_isochronous = 0;
601 eeprom->suspend_pull_downs = 0;
d9f0cce7 602
b8aa7b35
TJ
603 eeprom->use_serial = 0;
604 eeprom->change_usb_version = 0;
f396dbad 605 eeprom->usb_version = 0x0200;
b8aa7b35 606 eeprom->max_power = 0;
d9f0cce7 607
b8aa7b35
TJ
608 eeprom->manufacturer = NULL;
609 eeprom->product = NULL;
610 eeprom->serial = NULL;
611}
612
613
614/*
615 ftdi_eeprom_build return codes:
8ed61121 616 positive value: used eeprom size
b8aa7b35
TJ
617 -1: eeprom size (128 bytes) exceeded by custom strings
618*/
619int ftdi_eeprom_build(struct ftdi_eeprom *eeprom, unsigned char *output) {
620 unsigned char i, j;
621 unsigned short checksum, value;
622 unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
623 int size_check;
624
625 if (eeprom->manufacturer != NULL)
d9f0cce7 626 manufacturer_size = strlen(eeprom->manufacturer);
b8aa7b35 627 if (eeprom->product != NULL)
d9f0cce7 628 product_size = strlen(eeprom->product);
b8aa7b35 629 if (eeprom->serial != NULL)
d9f0cce7 630 serial_size = strlen(eeprom->serial);
b8aa7b35 631
d9f0cce7
TJ
632 size_check = 128; // eeprom is 128 bytes
633 size_check -= 28; // 28 are always in use (fixed)
b8aa7b35
TJ
634 size_check -= manufacturer_size*2;
635 size_check -= product_size*2;
636 size_check -= serial_size*2;
637
638 // eeprom size exceeded?
639 if (size_check < 0)
d9f0cce7 640 return (-1);
b8aa7b35
TJ
641
642 // empty eeprom
643 memset (output, 0, 128);
644
645 // Addr 00: Stay 00 00
646 // Addr 02: Vendor ID
647 output[0x02] = eeprom->vendor_id;
648 output[0x03] = eeprom->vendor_id >> 8;
649
650 // Addr 04: Product ID
651 output[0x04] = eeprom->product_id;
652 output[0x05] = eeprom->product_id >> 8;
653
654 // Addr 06: Device release number (0400h for BM features)
655 output[0x06] = 0x00;
d9f0cce7 656
b8aa7b35 657 if (eeprom->BM_type_chip == 1)
d9f0cce7 658 output[0x07] = 0x04;
b8aa7b35 659 else
d9f0cce7 660 output[0x07] = 0x02;
b8aa7b35
TJ
661
662 // Addr 08: Config descriptor
663 // Bit 1: remote wakeup if 1
664 // Bit 0: self powered if 1
665 //
666 j = 0;
667 if (eeprom->self_powered == 1)
d9f0cce7 668 j = j | 1;
b8aa7b35 669 if (eeprom->remote_wakeup == 1)
d9f0cce7 670 j = j | 2;
b8aa7b35
TJ
671 output[0x08] = j;
672
673 // Addr 09: Max power consumption: max power = value * 2 mA
d9f0cce7
TJ
674 output[0x09] = eeprom->max_power;
675 ;
676
b8aa7b35
TJ
677 // Addr 0A: Chip configuration
678 // Bit 7: 0 - reserved
679 // Bit 6: 0 - reserved
680 // Bit 5: 0 - reserved
681 // Bit 4: 1 - Change USB version
682 // Bit 3: 1 - Use the serial number string
683 // Bit 2: 1 - Enable suspend pull downs for lower power
684 // Bit 1: 1 - Out EndPoint is Isochronous
685 // Bit 0: 1 - In EndPoint is Isochronous
686 //
687 j = 0;
688 if (eeprom->in_is_isochronous == 1)
d9f0cce7 689 j = j | 1;
b8aa7b35 690 if (eeprom->out_is_isochronous == 1)
d9f0cce7 691 j = j | 2;
b8aa7b35 692 if (eeprom->suspend_pull_downs == 1)
d9f0cce7 693 j = j | 4;
b8aa7b35 694 if (eeprom->use_serial == 1)
d9f0cce7 695 j = j | 8;
b8aa7b35 696 if (eeprom->change_usb_version == 1)
d9f0cce7 697 j = j | 16;
b8aa7b35 698 output[0x0A] = j;
d9f0cce7 699
b8aa7b35
TJ
700 // Addr 0B: reserved
701 output[0x0B] = 0x00;
d9f0cce7 702
b8aa7b35
TJ
703 // Addr 0C: USB version low byte when 0x0A bit 4 is set
704 // Addr 0D: USB version high byte when 0x0A bit 4 is set
705 if (eeprom->change_usb_version == 1) {
706 output[0x0C] = eeprom->usb_version;
d9f0cce7 707 output[0x0D] = eeprom->usb_version >> 8;
b8aa7b35
TJ
708 }
709
710
711 // Addr 0E: Offset of the manufacturer string + 0x80
712 output[0x0E] = 0x14 + 0x80;
713
714 // Addr 0F: Length of manufacturer string
715 output[0x0F] = manufacturer_size*2 + 2;
716
717 // Addr 10: Offset of the product string + 0x80, calculated later
718 // Addr 11: Length of product string
719 output[0x11] = product_size*2 + 2;
720
721 // Addr 12: Offset of the serial string + 0x80, calculated later
722 // Addr 13: Length of serial string
723 output[0x13] = serial_size*2 + 2;
724
725 // Dynamic content
a862ddcf 726 output[0x14] = manufacturer_size*2 + 2;
d9f0cce7
TJ
727 output[0x15] = 0x03; // type: string
728
b8aa7b35 729 i = 0x16, j = 0;
d9f0cce7 730
b8aa7b35
TJ
731 // Output manufacturer
732 for (j = 0; j < manufacturer_size; j++) {
d9f0cce7
TJ
733 output[i] = eeprom->manufacturer[j], i++;
734 output[i] = 0x00, i++;
b8aa7b35
TJ
735 }
736
737 // Output product name
d9f0cce7 738 output[0x10] = i + 0x80; // calculate offset
b8aa7b35
TJ
739 output[i] = product_size*2 + 2, i++;
740 output[i] = 0x03, i++;
741 for (j = 0; j < product_size; j++) {
d9f0cce7
TJ
742 output[i] = eeprom->product[j], i++;
743 output[i] = 0x00, i++;
b8aa7b35 744 }
d9f0cce7 745
b8aa7b35 746 // Output serial
d9f0cce7 747 output[0x12] = i + 0x80; // calculate offset
b8aa7b35
TJ
748 output[i] = serial_size*2 + 2, i++;
749 output[i] = 0x03, i++;
750 for (j = 0; j < serial_size; j++) {
d9f0cce7
TJ
751 output[i] = eeprom->serial[j], i++;
752 output[i] = 0x00, i++;
b8aa7b35
TJ
753 }
754
755 // calculate checksum
756 checksum = 0xAAAA;
d9f0cce7 757
b8aa7b35 758 for (i = 0; i < 63; i++) {
d9f0cce7
TJ
759 value = output[i*2];
760 value += output[(i*2)+1] << 8;
b8aa7b35 761
d9f0cce7
TJ
762 checksum = value^checksum;
763 checksum = (checksum << 1) | (checksum >> 15);
b8aa7b35
TJ
764 }
765
766 output[0x7E] = checksum;
d9f0cce7 767 output[0x7F] = checksum >> 8;
b8aa7b35 768
8ed61121 769 return size_check;
b8aa7b35
TJ
770}
771
772
be5d7eec 773int ftdi_read_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom) {
a3da1d95
GE
774 int i;
775
776 for (i = 0; i < 64; i++) {
a97980ad 777 if (ftdi_usbdev_control_msg(ftdi->usb_fd, 0xC0, 0x90, 0, i, eeprom+(i*2), 2, ftdi->usb_read_timeout) != 2) {
d9f0cce7
TJ
778 ftdi->error_str = "Reading eeprom failed";
779 return -1;
a3da1d95
GE
780 }
781 }
782
783 return 0;
784}
785
786
be5d7eec 787int ftdi_write_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom) {
a3da1d95
GE
788 unsigned short usb_val;
789 int i;
790
791 for (i = 0; i < 64; i++) {
d9f0cce7
TJ
792 usb_val = eeprom[i*2];
793 usb_val += eeprom[(i*2)+1] << 8;
a97980ad 794 if (ftdi_usbdev_control_msg(ftdi->usb_fd, 0x40, 0x91, usb_val, i, NULL, 0, ftdi->usb_write_timeout) != 0) {
d9f0cce7
TJ
795 ftdi->error_str = "Unable to write eeprom";
796 return -1;
797 }
a3da1d95
GE
798 }
799
800 return 0;
801}
802
803
804int ftdi_erase_eeprom(struct ftdi_context *ftdi) {
a97980ad 805 if (ftdi_usbdev_control_msg(ftdi->usb_fd, 0x40, 0x92, 0, 0, NULL, 0, ftdi->usb_write_timeout) != 0) {
a3da1d95
GE
806 ftdi->error_str = "Unable to erase eeprom";
807 return -1;
808 }
809
810 return 0;
811}
0e302db6
TJ
812
813
a97980ad
TJ
814/* libusb like functions - currently linux only */
815static int check_usb_vfs(const unsigned char *dirname)
816{
817 DIR *dir;
818 struct dirent *entry;
819 int found = 0;
820
821 dir = opendir(dirname);
822 if (!dir)
823 return 0;
824
825 while ((entry = readdir(dir)) != NULL) {
826 /* Skip anything starting with a . */
827 if (entry->d_name[0] == '.')
828 continue;
829
830 /* We assume if we find any files that it must be the right place */
831 found = 1;
832 break;
833 }
834
835 closedir(dir);
836
837 return found;
838}
839
840static int ftdi_usbdev_parsedev(int fd, unsigned int *bus, unsigned int *dev, int vendorid, int productid)
841{
842 char buf[16384];
843 char *start, *end, *lineend, *cp;
844 int devnum = -1, busnum = -1, vendor = -1, product = -1;
845 int ret;
846
847 if (lseek(fd, 0, SEEK_SET) == (off_t)-1)
848 return -1;
849 ret = read(fd, buf, sizeof(buf)-1);
850 if (ret == -1)
851 return -1;
852 end = buf + ret;
853 *end = 0;
854 start = buf;
855 ret = 0;
856 while (start < end) {
857 lineend = strchr(start, '\n');
858 if (!lineend)
859 break;
860 *lineend = 0;
861 switch (start[0]) {
862 case 'T': /* topology line */
863 if ((cp = strstr(start, "Dev#="))) {
864 devnum = strtoul(cp + 5, NULL, 0);
865 } else
866 devnum = -1;
867 if ((cp = strstr(start, "Bus="))) {
868 busnum = strtoul(cp + 4, NULL, 0);
869 } else
870 busnum = -1;
871 break;
872
873 case 'P':
874 if ((cp = strstr(start, "Vendor="))) {
875 vendor = strtoul(cp + 7, NULL, 16);
876 } else
877 vendor = -1;
878 if ((cp = strstr(start, "ProdID="))) {
879 product = strtoul(cp + 7, NULL, 16);
880 } else
881 product = -1;
882 if (vendor != -1 && product != -1 && devnum >= 1 && devnum <= 127 &&
883 busnum >= 0 && busnum <= 999 &&
884 (vendorid == vendor || vendorid == -1) &&
885 (productid == product || productid == -1)) {
886 if (bus)
887 *bus = busnum;
888 if (dev)
889 *dev = devnum;
890 ret++;
891 }
892 break;
893 }
894 start = lineend + 1;
895 }
896 return ret;
897}
898
899int ftdi_usbdev_open(int vendorid, int productid)
900{
901 unsigned int busnum, devnum, fd, ret;
902 char usb_path[PATH_MAX+1] = "";
903 char usb_devices_path[PATH_MAX*2];
904
905 /* Find the path to the virtual filesystem */
906 if (getenv("USB_DEVFS_PATH")) {
907 if (check_usb_vfs((char*)getenv("USB_DEVFS_PATH"))) {
908 strncpy(usb_path, (char*)getenv("USB_DEVFS_PATH"), sizeof(usb_path) - 1);
909 usb_path[sizeof(usb_path) - 1] = 0;
910 }
911 }
912
913 if (!usb_path[0]) {
914 if (check_usb_vfs("/proc/bus/usb")) {
915 strncpy(usb_path, "/proc/bus/usb", sizeof(usb_path) - 1);
916 usb_path[sizeof(usb_path) - 1] = 0;
917 } else if (check_usb_vfs("/sys/bus/usb")) { /* 2.6 Kernel with sysfs */
918 strncpy(usb_path, "/sys/bus/usb", sizeof(usb_path) -1);
919 usb_path[sizeof(usb_path) - 1] = 0;
920 } else if (check_usb_vfs("/dev/usb")) {
921 strncpy(usb_path, "/dev/usb", sizeof(usb_path) - 1);
922 usb_path[sizeof(usb_path) - 1] = 0;
923 } else
924 usb_path[0] = 0;
925 }
926
927 /* No path, no USB support */
928 if (!usb_path[0])
929 return -1;
930
931 /* Parse device list */
932 snprintf(usb_devices_path, sizeof(usb_devices_path), "%s/devices", usb_path);
933 if ((fd = open(usb_devices_path, O_RDONLY)) == -1)
934 return -2;
935
936 ret = ftdi_usbdev_parsedev(fd, &busnum, &devnum, vendorid, productid);
937 close (fd);
938
939 // Device not found
940 if (ret != 1)
941 return -3;
942
943 snprintf(usb_devices_path, sizeof(usb_devices_path), "%s/%03u/%03u", usb_path, busnum, devnum);
944 if ((fd = open(usb_devices_path, O_RDWR)) == -1)
945 return -4;
946
947 return fd;
948}
949
950int ftdi_usbdev_claim_interface(int fd, unsigned int interface)
951{
952 return ioctl(fd, USBDEVFS_CLAIMINTERFACE, &interface);
953}
954
955int ftdi_usbdev_release_interface(int fd, int interface)
956{
957 return ioctl(fd, USBDEVFS_RELEASEINTERFACE, &interface);
958}
959
960
961int ftdi_usbdev_bulk_write(int fd, unsigned int endpoint, const void *data,
962 unsigned int size, unsigned int timeout)
963{
964 struct usbdevfs_bulktransfer arg;
965
966 arg.ep = endpoint & ~USB_DIR_IN;
967 arg.len = size;
968 arg.timeout = timeout;
969 arg.data = (void *) data;
970
971 return ioctl(fd, USBDEVFS_BULK, &arg);
972}
973
974int ftdi_usbdev_control_msg(int fd, unsigned int requesttype,
975 unsigned int request, unsigned int value, unsigned int index,
976 void *data, unsigned int size, unsigned int timeout)
977{
978 struct usbdevfs_ctrltransfer arg;
979
980 arg.requesttype = requesttype;
981 arg.request = request;
982 arg.value = value;
983 arg.index = index;
984 arg.length = size;
985 arg.timeout = timeout;
986 arg.data = data;
987
988 return ioctl(fd, USBDEVFS_CONTROL, &arg);
989}
990
0e302db6 991/* Functions needed for userspace URB processing */
a97980ad 992struct usbdevfs_urb * ftdi_usbdev_alloc_urb(int iso_packets)
0e302db6 993{
a97980ad 994 return (struct usbdevfs_urb *)calloc(sizeof(struct usbdevfs_urb)
0e302db6
TJ
995 + iso_packets * sizeof(struct usbdevfs_iso_packet_desc),
996 1);
997}
998
999
a97980ad 1000int ftdi_usbdev_submit_urb(int fd, struct usbdevfs_urb *urb)
0e302db6
TJ
1001{
1002 return ioctl(fd, USBDEVFS_SUBMITURB, urb);
1003}
1004
1005
a97980ad 1006int ftdi_usbdev_reap_urb_ndelay(int fd, struct usbdevfs_urb **urb_return)
0e302db6
TJ
1007{
1008 return ioctl(fd, USBDEVFS_REAPURBNDELAY, urb_return);
1009}