libftdi: (tomj) find all devices by vendor/product id
[libftdi] / src / ftdi.c
1 /***************************************************************************
2                           ftdi.c  -  description
3                              -------------------
4     begin                : Fri Apr 4 2003
5     copyright            : (C) 2003 by Intra2net AG
6     email                : opensource@intra2net.com
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  ***************************************************************************/
16
17 #include <usb.h>
18 #include <string.h>
19
20 #include "ftdi.h"
21
22 #define ftdi_error_return(code, str) do {  \
23         ftdi->error_str = str;             \
24         return code;                       \
25    } while(0);                 
26
27
28 /* ftdi_init
29
30   Initializes a ftdi_context.
31
32   Return codes:
33    0: All fine
34   -1: Couldn't allocate read buffer
35 */
36 int ftdi_init(struct ftdi_context *ftdi)
37 {
38     ftdi->usb_dev = NULL;
39     ftdi->usb_read_timeout = 5000;
40     ftdi->usb_write_timeout = 5000;
41
42     ftdi->type = TYPE_BM;    /* chip type */
43     ftdi->baudrate = -1;
44     ftdi->bitbang_enabled = 0;
45
46     ftdi->readbuffer = NULL;
47     ftdi->readbuffer_offset = 0;
48     ftdi->readbuffer_remaining = 0;
49     ftdi->writebuffer_chunksize = 4096;
50
51     ftdi->interface = 0;
52     ftdi->index = 0;
53     ftdi->in_ep = 0x02;
54     ftdi->out_ep = 0x81;
55     ftdi->bitbang_mode = 1; /* 1: Normal bitbang mode, 2: SPI bitbang mode */
56
57     ftdi->error_str = NULL;
58
59     /* All fine. Now allocate the readbuffer */
60     return ftdi_read_data_set_chunksize(ftdi, 4096);
61 }
62
63 /* ftdi_set_interface
64    
65    Call after ftdi_init
66    
67    Open selected channels on a chip, otherwise use first channel
68     0: all fine
69    -1: unknown interface
70 */
71 int ftdi_set_interface(struct ftdi_context *ftdi, enum ftdi_interface interface)
72 {
73     switch (interface) {
74     case INTERFACE_ANY:
75     case INTERFACE_A:
76         /* ftdi_usb_open_desc cares to set the right index, depending on the found chip */
77         break;
78     case INTERFACE_B:
79         ftdi->interface = 1;
80         ftdi->index     = INTERFACE_B;
81         ftdi->in_ep     = 0x04;
82         ftdi->out_ep    = 0x83;
83         break;
84     default:
85         ftdi_error_return(-1, "Unknown interface");
86     }
87     return 0;
88 }
89
90 /* ftdi_deinit
91
92    Deinitializes a ftdi_context.
93 */
94 void ftdi_deinit(struct ftdi_context *ftdi)
95 {
96     if (ftdi->readbuffer != NULL) {
97         free(ftdi->readbuffer);
98         ftdi->readbuffer = NULL;
99     }
100 }
101
102 /* ftdi_set_usbdev
103  
104    Use an already open device.
105 */
106 void ftdi_set_usbdev (struct ftdi_context *ftdi, usb_dev_handle *usb)
107 {
108     ftdi->usb_dev = usb;
109 }
110
111
112 /* ftdi_usb_find_all
113  
114    Finds all ftdi devices on the usb bus. Creates a new ftdi_device_list which
115    needs to be deallocated by ftdi_list_free after use.
116
117    Return codes:
118     >0: number of devices found
119     -1: usb_find_busses() failed
120     -2: usb_find_devices() failed
121     -3: out of memory
122 */
123 int ftdi_usb_find_all(struct ftdi_context *ftdi, struct ftdi_device_list **devlist, int vendor, int product) 
124 {
125     struct ftdi_device_list **curdev;
126     struct usb_bus *bus;
127     struct usb_device *dev;
128     int count = 0;
129     
130     usb_init();
131     if (usb_find_busses() < 0)
132         ftdi_error_return(-1, "usb_find_busses() failed");
133     if (usb_find_devices() < 0)
134         ftdi_error_return(-2, "usb_find_devices() failed");
135
136     curdev = devlist;
137     for (bus = usb_busses; bus; bus = bus->next) {
138         for (dev = bus->devices; dev; dev = dev->next) {
139             if (dev->descriptor.idVendor == vendor
140                     && dev->descriptor.idProduct == product)
141             {
142                 *curdev = (struct ftdi_device_list*)malloc(sizeof(struct ftdi_device_list));
143                 if (!*curdev)
144                     ftdi_error_return(-3, "out of memory");
145                 
146                 (*curdev)->next = NULL;
147                 (*curdev)->dev = dev;
148
149                 curdev = &(*curdev)->next;
150                 count++;
151             }
152         }
153     }
154     
155     return count;
156 }
157
158 /* ftdi_list_free
159
160    Frees a created device list.
161 */
162 void ftdi_list_free(struct ftdi_device_list **devlist) 
163 {
164     struct ftdi_device_list **curdev;
165     for (; *devlist == NULL; devlist = curdev) {
166         curdev = &(*devlist)->next;
167         free(*devlist);
168     }
169
170     devlist = NULL;
171 }
172
173 int ftdi_usb_open(struct ftdi_context *ftdi, int vendor, int product)
174 {
175     return ftdi_usb_open_desc(ftdi, vendor, product, NULL, NULL);
176 }
177
178 /* ftdi_usb_open_desc
179
180    Opens the first device with a given, vendor id, product id,
181    description and serial.
182    
183    Return codes:
184      0: all fine
185     -1: usb_find_busses() failed
186     -2: usb_find_devices() failed
187     -3: usb device not found
188     -4: unable to open device
189     -5: unable to claim device
190     -6: reset failed
191     -7: set baudrate failed
192     -8: get product description failed
193     -9: get serial number failed
194     -10: unable to close device
195 */
196 int ftdi_usb_open_desc(struct ftdi_context *ftdi, int vendor, int product,
197                        const char* description, const char* serial)
198 {
199     struct usb_bus *bus;
200     struct usb_device *dev;
201     char string[256];
202
203     usb_init();
204
205     if (usb_find_busses() < 0)
206         ftdi_error_return(-1, "usb_find_busses() failed");
207     if (usb_find_devices() < 0)
208         ftdi_error_return(-2, "usb_find_devices() failed");
209
210     for (bus = usb_busses; bus; bus = bus->next) {
211         for (dev = bus->devices; dev; dev = dev->next) {
212             if (dev->descriptor.idVendor == vendor
213                     && dev->descriptor.idProduct == product) {
214                 if (!(ftdi->usb_dev = usb_open(dev)))
215                     ftdi_error_return(-4, "usb_open() failed");
216
217                 if (description != NULL) {
218                     if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iProduct, string, sizeof(string)) <= 0) {
219                         usb_close (ftdi->usb_dev);
220                         ftdi_error_return(-8, "unable to fetch product description");
221                     }
222                     if (strncmp(string, description, sizeof(string)) != 0) {
223                         if (usb_close (ftdi->usb_dev) != 0)
224                             ftdi_error_return(-10, "unable to close device");
225                         continue;
226                     }
227                 }
228                 if (serial != NULL) {
229                     if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iSerialNumber, string, sizeof(string)) <= 0) {
230                         usb_close (ftdi->usb_dev);
231                         ftdi_error_return(-9, "unable to fetch serial number");
232                     }
233                     if (strncmp(string, serial, sizeof(string)) != 0) {
234                         if (usb_close (ftdi->usb_dev) != 0)
235                             ftdi_error_return(-10, "unable to close device");
236                         continue;
237                     }
238                 }
239
240                 if (usb_close (ftdi->usb_dev) != 0)
241                     ftdi_error_return(-10, "unable to close device");
242                 
243                 return ftdi_usb_open_dev(ftdi, dev);
244             }
245         }
246     }
247
248     // device not found
249     ftdi_error_return(-3, "device not found");
250 }
251
252 /* ftdi_usb_reset
253
254    Resets the ftdi device.
255    
256    Return codes:
257      0: all fine
258     -1: FTDI reset failed
259 */
260 int ftdi_usb_reset(struct ftdi_context *ftdi)
261 {
262     if (usb_control_msg(ftdi->usb_dev, 0x40, 0, 0, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
263         ftdi_error_return(-1,"FTDI reset failed");
264
265     // Invalidate data in the readbuffer
266     ftdi->readbuffer_offset = 0;
267     ftdi->readbuffer_remaining = 0;
268
269     return 0;
270 }
271
272 /* ftdi_usb_purge_buffers
273
274    Cleans the buffers of the ftdi device.
275    
276    Return codes:
277      0: all fine
278     -1: write buffer purge failed
279     -2: read buffer purge failed
280 */
281 int ftdi_usb_purge_buffers(struct ftdi_context *ftdi)
282 {
283     if (usb_control_msg(ftdi->usb_dev, 0x40, 0, 1, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
284         ftdi_error_return(-1, "FTDI purge of RX buffer failed");
285
286     // Invalidate data in the readbuffer
287     ftdi->readbuffer_offset = 0;
288     ftdi->readbuffer_remaining = 0;
289
290     if (usb_control_msg(ftdi->usb_dev, 0x40, 0, 2, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
291         ftdi_error_return(-2, "FTDI purge of TX buffer failed");
292
293     return 0;
294 }
295
296 /* ftdi_usb_close
297    
298    Closes the ftdi device.
299    
300    Return codes:
301      0: all fine
302     -1: usb_release failed
303     -2: usb_close failed
304 */
305 int ftdi_usb_close(struct ftdi_context *ftdi)
306 {
307     int rtn = 0;
308
309     if (usb_release_interface(ftdi->usb_dev, ftdi->interface) != 0)
310         rtn = -1;
311
312     if (usb_close (ftdi->usb_dev) != 0)
313         rtn = -2;
314
315     return rtn;
316 }
317
318
319 /*
320     ftdi_convert_baudrate returns nearest supported baud rate to that requested.
321     Function is only used internally
322 */
323 static int ftdi_convert_baudrate(int baudrate, struct ftdi_context *ftdi,
324                                  unsigned short *value, unsigned short *index)
325 {
326     static const char am_adjust_up[8] = {0, 0, 0, 1, 0, 3, 2, 1};
327     static const char am_adjust_dn[8] = {0, 0, 0, 1, 0, 1, 2, 3};
328     static const char frac_code[8] = {0, 3, 2, 4, 1, 5, 6, 7};
329     int divisor, best_divisor, best_baud, best_baud_diff;
330     unsigned long encoded_divisor;
331     int i;
332
333     if (baudrate <= 0) {
334         // Return error
335         return -1;
336     }
337
338     divisor = 24000000 / baudrate;
339
340     if (ftdi->type == TYPE_AM) {
341         // Round down to supported fraction (AM only)
342         divisor -= am_adjust_dn[divisor & 7];
343     }
344
345     // Try this divisor and the one above it (because division rounds down)
346     best_divisor = 0;
347     best_baud = 0;
348     best_baud_diff = 0;
349     for (i = 0; i < 2; i++) {
350         int try_divisor = divisor + i;
351         int baud_estimate;
352         int baud_diff;
353
354         // Round up to supported divisor value
355         if (try_divisor <= 8) {
356             // Round up to minimum supported divisor
357             try_divisor = 8;
358         } else if (ftdi->type != TYPE_AM && try_divisor < 12) {
359             // BM doesn't support divisors 9 through 11 inclusive
360             try_divisor = 12;
361         } else if (divisor < 16) {
362             // AM doesn't support divisors 9 through 15 inclusive
363             try_divisor = 16;
364         } else {
365             if (ftdi->type == TYPE_AM) {
366                 // Round up to supported fraction (AM only)
367                 try_divisor += am_adjust_up[try_divisor & 7];
368                 if (try_divisor > 0x1FFF8) {
369                     // Round down to maximum supported divisor value (for AM)
370                     try_divisor = 0x1FFF8;
371                 }
372             } else {
373                 if (try_divisor > 0x1FFFF) {
374                     // Round down to maximum supported divisor value (for BM)
375                     try_divisor = 0x1FFFF;
376                 }
377             }
378         }
379         // Get estimated baud rate (to nearest integer)
380         baud_estimate = (24000000 + (try_divisor / 2)) / try_divisor;
381         // Get absolute difference from requested baud rate
382         if (baud_estimate < baudrate) {
383             baud_diff = baudrate - baud_estimate;
384         } else {
385             baud_diff = baud_estimate - baudrate;
386         }
387         if (i == 0 || baud_diff < best_baud_diff) {
388             // Closest to requested baud rate so far
389             best_divisor = try_divisor;
390             best_baud = baud_estimate;
391             best_baud_diff = baud_diff;
392             if (baud_diff == 0) {
393                 // Spot on! No point trying
394                 break;
395             }
396         }
397     }
398     // Encode the best divisor value
399     encoded_divisor = (best_divisor >> 3) | (frac_code[best_divisor & 7] << 14);
400     // Deal with special cases for encoded value
401     if (encoded_divisor == 1) {
402         encoded_divisor = 0;    // 3000000 baud
403     } else if (encoded_divisor == 0x4001) {
404         encoded_divisor = 1;    // 2000000 baud (BM only)
405     }
406     // Split into "value" and "index" values
407     *value = (unsigned short)(encoded_divisor & 0xFFFF);
408     if(ftdi->type == TYPE_2232C) {
409         *index = (unsigned short)(encoded_divisor >> 8);
410         *index &= 0xFF00;
411         *index |= ftdi->interface;
412     }
413     else
414         *index = (unsigned short)(encoded_divisor >> 16);
415
416     // Return the nearest baud rate
417     return best_baud;
418 }
419
420 /*
421     ftdi_set_baudrate
422     
423     Sets the chip baudrate
424     
425     Return codes:
426      0: all fine
427     -1: invalid baudrate
428     -2: setting baudrate failed
429 */
430 int ftdi_set_baudrate(struct ftdi_context *ftdi, int baudrate)
431 {
432     unsigned short value, index;
433     int actual_baudrate;
434
435     if (ftdi->bitbang_enabled) {
436         baudrate = baudrate*4;
437     }
438
439     actual_baudrate = ftdi_convert_baudrate(baudrate, ftdi, &value, &index);
440     if (actual_baudrate <= 0)
441         ftdi_error_return (-1, "Silly baudrate <= 0.");
442
443     // Check within tolerance (about 5%)
444     if ((actual_baudrate * 2 < baudrate /* Catch overflows */ )
445             || ((actual_baudrate < baudrate)
446                 ? (actual_baudrate * 21 < baudrate * 20)
447                 : (baudrate * 21 < actual_baudrate * 20)))
448         ftdi_error_return (-1, "Unsupported baudrate. Note: bitbang baudrates are automatically multiplied by 4");
449
450     if (usb_control_msg(ftdi->usb_dev, 0x40, 3, value, index, NULL, 0, ftdi->usb_write_timeout) != 0)
451         ftdi_error_return (-2, "Setting new baudrate failed");
452
453     ftdi->baudrate = baudrate;
454     return 0;
455 }
456
457 /*
458     ftdi_set_line_property
459
460     set (RS232) line characteristics by Alain Abbas
461     
462     Return codes:
463      0: all fine
464     -1: Setting line property failed
465 */
466 int ftdi_set_line_property(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
467                     enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity)
468 {
469     unsigned short value = bits;
470
471     switch(parity) {
472     case NONE:
473         value |= (0x00 << 8);
474         break;
475     case ODD:
476         value |= (0x01 << 8);
477         break;
478     case EVEN:
479         value |= (0x02 << 8);
480         break;
481     case MARK:
482         value |= (0x03 << 8);
483         break;
484     case SPACE:
485         value |= (0x04 << 8);
486         break;
487     }
488     
489     switch(sbit) {
490     case STOP_BIT_1:
491         value |= (0x00 << 11);
492         break;
493     case STOP_BIT_15:
494         value |= (0x01 << 11);
495         break;
496     case STOP_BIT_2:
497         value |= (0x02 << 11);
498         break;
499     }
500     
501     if (usb_control_msg(ftdi->usb_dev, 0x40, 0x04, value, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
502         ftdi_error_return (-1, "Setting new line property failed");
503     
504     return 0;
505 }
506
507 int ftdi_write_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
508 {
509     int ret;
510     int offset = 0;
511     int total_written = 0;
512
513     while (offset < size) {
514         int write_size = ftdi->writebuffer_chunksize;
515
516         if (offset+write_size > size)
517             write_size = size-offset;
518
519         ret = usb_bulk_write(ftdi->usb_dev, ftdi->in_ep, buf+offset, write_size, ftdi->usb_write_timeout);
520         if (ret < 0)
521             ftdi_error_return(ret, "usb bulk write failed");
522
523         total_written += ret;
524         offset += write_size;
525     }
526
527     return total_written;
528 }
529
530
531 int ftdi_write_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
532 {
533     ftdi->writebuffer_chunksize = chunksize;
534     return 0;
535 }
536
537
538 int ftdi_write_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
539 {
540     *chunksize = ftdi->writebuffer_chunksize;
541     return 0;
542 }
543
544
545 int ftdi_read_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
546 {
547     int offset = 0, ret = 1, i, num_of_chunks, chunk_remains;
548
549     // everything we want is still in the readbuffer?
550     if (size <= ftdi->readbuffer_remaining) {
551         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);
552
553         // Fix offsets
554         ftdi->readbuffer_remaining -= size;
555         ftdi->readbuffer_offset += size;
556
557         /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */
558
559         return size;
560     }
561     // something still in the readbuffer, but not enough to satisfy 'size'?
562     if (ftdi->readbuffer_remaining != 0) {
563         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);
564
565         // Fix offset
566         offset += ftdi->readbuffer_remaining;
567     }
568     // do the actual USB read
569     while (offset < size && ret > 0) {
570         ftdi->readbuffer_remaining = 0;
571         ftdi->readbuffer_offset = 0;
572         /* returns how much received */
573         ret = usb_bulk_read (ftdi->usb_dev, ftdi->out_ep, ftdi->readbuffer, ftdi->readbuffer_chunksize, ftdi->usb_read_timeout);
574         if (ret < 0)
575             ftdi_error_return(ret, "usb bulk read failed");
576
577         if (ret > 2) {
578             // skip FTDI status bytes.
579             // Maybe stored in the future to enable modem use
580             num_of_chunks = ret / 64;
581             chunk_remains = ret % 64;
582             //printf("ret = %X, num_of_chunks = %X, chunk_remains = %X, readbuffer_offset = %X\n", ret, num_of_chunks, chunk_remains, ftdi->readbuffer_offset);
583
584             ftdi->readbuffer_offset += 2;
585             ret -= 2;
586
587             if (ret > 62) {
588                 for (i = 1; i < num_of_chunks; i++)
589                     memmove (ftdi->readbuffer+ftdi->readbuffer_offset+62*i,
590                              ftdi->readbuffer+ftdi->readbuffer_offset+64*i,
591                              62);
592                 if (chunk_remains > 2) {
593                     memmove (ftdi->readbuffer+ftdi->readbuffer_offset+62*i,
594                              ftdi->readbuffer+ftdi->readbuffer_offset+64*i,
595                              chunk_remains-2);
596                     ret -= 2*num_of_chunks;
597                 } else
598                     ret -= 2*(num_of_chunks-1)+chunk_remains;
599             }
600         } else if (ret <= 2) {
601             // no more data to read?
602             return offset;
603         }
604         if (ret > 0) {
605             // data still fits in buf?
606             if (offset+ret <= size) {
607                 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, ret);
608                 //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
609                 offset += ret;
610
611                 /* Did we read exactly the right amount of bytes? */
612                 if (offset == size)
613                     //printf("read_data exact rem %d offset %d\n",
614                     //ftdi->readbuffer_remaining, offset);
615                     return offset;
616             } else {
617                 // only copy part of the data or size <= readbuffer_chunksize
618                 int part_size = size-offset;
619                 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, part_size);
620
621                 ftdi->readbuffer_offset += part_size;
622                 ftdi->readbuffer_remaining = ret-part_size;
623                 offset += part_size;
624
625                 /* printf("Returning part: %d - size: %d - offset: %d - ret: %d - remaining: %d\n",
626                 part_size, size, offset, ret, ftdi->readbuffer_remaining); */
627
628                 return offset;
629             }
630         }
631     }
632     // never reached
633     return -127;
634 }
635
636
637 int ftdi_read_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
638 {
639     unsigned char *new_buf;
640
641     // Invalidate all remaining data
642     ftdi->readbuffer_offset = 0;
643     ftdi->readbuffer_remaining = 0;
644
645     if ((new_buf = (unsigned char *)realloc(ftdi->readbuffer, chunksize)) == NULL)
646         ftdi_error_return(-1, "out of memory for readbuffer");
647
648     ftdi->readbuffer = new_buf;
649     ftdi->readbuffer_chunksize = chunksize;
650
651     return 0;
652 }
653
654
655 int ftdi_read_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
656 {
657     *chunksize = ftdi->readbuffer_chunksize;
658     return 0;
659 }
660
661
662
663 int ftdi_enable_bitbang(struct ftdi_context *ftdi, unsigned char bitmask)
664 {
665     unsigned short usb_val;
666
667     usb_val = bitmask; // low byte: bitmask
668     /* FT2232C: Set bitbang_mode to 2 to enable SPI */
669     usb_val |= (ftdi->bitbang_mode << 8);
670
671     if (usb_control_msg(ftdi->usb_dev, 0x40, 0x0B, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
672         ftdi_error_return(-1, "unable to enter bitbang mode. Perhaps not a BM type chip?");
673
674     ftdi->bitbang_enabled = 1;
675     return 0;
676 }
677
678
679 int ftdi_disable_bitbang(struct ftdi_context *ftdi)
680 {
681     if (usb_control_msg(ftdi->usb_dev, 0x40, 0x0B, 0, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
682         ftdi_error_return(-1, "unable to leave bitbang mode. Perhaps not a BM type chip?");
683
684     ftdi->bitbang_enabled = 0;
685     return 0;
686 }
687
688
689 int ftdi_set_bitmode(struct ftdi_context *ftdi, unsigned char bitmask, unsigned char mode)
690 {
691     unsigned short usb_val;
692
693     usb_val = bitmask; // low byte: bitmask
694     usb_val |= (mode << 8);
695     if (usb_control_msg(ftdi->usb_dev, 0x40, 0x0B, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
696         ftdi_error_return(-1, "unable to configure bitbang mode. Perhaps not a 2232C type chip?");
697
698     ftdi->bitbang_mode = mode;
699     ftdi->bitbang_enabled = (mode == BITMODE_BITBANG || mode == BITMODE_SYNCBB)?1:0;
700     return 0;
701 }
702
703 int ftdi_read_pins(struct ftdi_context *ftdi, unsigned char *pins)
704 {
705     unsigned short usb_val;
706     if (usb_control_msg(ftdi->usb_dev, 0xC0, 0x0C, 0, ftdi->index, (char *)&usb_val, 1, ftdi->usb_read_timeout) != 1)
707         ftdi_error_return(-1, "read pins failed");
708
709     *pins = (unsigned char)usb_val;
710     return 0;
711 }
712
713
714 int ftdi_set_latency_timer(struct ftdi_context *ftdi, unsigned char latency)
715 {
716     unsigned short usb_val;
717
718     if (latency < 1)
719         ftdi_error_return(-1, "latency out of range. Only valid for 1-255");
720
721     usb_val = latency;
722     if (usb_control_msg(ftdi->usb_dev, 0x40, 0x09, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
723         ftdi_error_return(-2, "unable to set latency timer");
724
725     return 0;
726 }
727
728
729 int ftdi_get_latency_timer(struct ftdi_context *ftdi, unsigned char *latency)
730 {
731     unsigned short usb_val;
732     if (usb_control_msg(ftdi->usb_dev, 0xC0, 0x0A, 0, ftdi->index, (char *)&usb_val, 1, ftdi->usb_read_timeout) != 1)
733         ftdi_error_return(-1, "reading latency timer failed");
734
735     *latency = (unsigned char)usb_val;
736     return 0;
737 }
738
739
740 void ftdi_eeprom_initdefaults(struct ftdi_eeprom *eeprom)
741 {
742     eeprom->vendor_id = 0x0403;
743     eeprom->product_id = 0x6001;
744
745     eeprom->self_powered = 1;
746     eeprom->remote_wakeup = 1;
747     eeprom->BM_type_chip = 1;
748
749     eeprom->in_is_isochronous = 0;
750     eeprom->out_is_isochronous = 0;
751     eeprom->suspend_pull_downs = 0;
752
753     eeprom->use_serial = 0;
754     eeprom->change_usb_version = 0;
755     eeprom->usb_version = 0x0200;
756     eeprom->max_power = 0;
757
758     eeprom->manufacturer = NULL;
759     eeprom->product = NULL;
760     eeprom->serial = NULL;
761 }
762
763
764 /*
765     ftdi_eeprom_build
766     
767     Build binary output from ftdi_eeprom structure.
768     Output is suitable for ftdi_write_eeprom.
769     
770     Return codes:
771     positive value: used eeprom size
772     -1: eeprom size (128 bytes) exceeded by custom strings
773 */
774 int ftdi_eeprom_build(struct ftdi_eeprom *eeprom, unsigned char *output)
775 {
776     unsigned char i, j;
777     unsigned short checksum, value;
778     unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
779     int size_check;
780
781     if (eeprom->manufacturer != NULL)
782         manufacturer_size = strlen(eeprom->manufacturer);
783     if (eeprom->product != NULL)
784         product_size = strlen(eeprom->product);
785     if (eeprom->serial != NULL)
786         serial_size = strlen(eeprom->serial);
787
788     size_check = 128; // eeprom is 128 bytes
789     size_check -= 28; // 28 are always in use (fixed)
790     size_check -= manufacturer_size*2;
791     size_check -= product_size*2;
792     size_check -= serial_size*2;
793
794     // eeprom size exceeded?
795     if (size_check < 0)
796         return (-1);
797
798     // empty eeprom
799     memset (output, 0, 128);
800
801     // Addr 00: Stay 00 00
802     // Addr 02: Vendor ID
803     output[0x02] = eeprom->vendor_id;
804     output[0x03] = eeprom->vendor_id >> 8;
805
806     // Addr 04: Product ID
807     output[0x04] = eeprom->product_id;
808     output[0x05] = eeprom->product_id >> 8;
809
810     // Addr 06: Device release number (0400h for BM features)
811     output[0x06] = 0x00;
812
813     if (eeprom->BM_type_chip == 1)
814         output[0x07] = 0x04;
815     else
816         output[0x07] = 0x02;
817
818     // Addr 08: Config descriptor
819     // Bit 1: remote wakeup if 1
820     // Bit 0: self powered if 1
821     //
822     j = 0;
823     if (eeprom->self_powered == 1)
824         j = j | 1;
825     if (eeprom->remote_wakeup == 1)
826         j = j | 2;
827     output[0x08] = j;
828
829     // Addr 09: Max power consumption: max power = value * 2 mA
830     output[0x09] = eeprom->max_power;
831     ;
832
833     // Addr 0A: Chip configuration
834     // Bit 7: 0 - reserved
835     // Bit 6: 0 - reserved
836     // Bit 5: 0 - reserved
837     // Bit 4: 1 - Change USB version
838     // Bit 3: 1 - Use the serial number string
839     // Bit 2: 1 - Enable suspend pull downs for lower power
840     // Bit 1: 1 - Out EndPoint is Isochronous
841     // Bit 0: 1 - In EndPoint is Isochronous
842     //
843     j = 0;
844     if (eeprom->in_is_isochronous == 1)
845         j = j | 1;
846     if (eeprom->out_is_isochronous == 1)
847         j = j | 2;
848     if (eeprom->suspend_pull_downs == 1)
849         j = j | 4;
850     if (eeprom->use_serial == 1)
851         j = j | 8;
852     if (eeprom->change_usb_version == 1)
853         j = j | 16;
854     output[0x0A] = j;
855
856     // Addr 0B: reserved
857     output[0x0B] = 0x00;
858
859     // Addr 0C: USB version low byte when 0x0A bit 4 is set
860     // Addr 0D: USB version high byte when 0x0A bit 4 is set
861     if (eeprom->change_usb_version == 1) {
862         output[0x0C] = eeprom->usb_version;
863         output[0x0D] = eeprom->usb_version >> 8;
864     }
865
866
867     // Addr 0E: Offset of the manufacturer string + 0x80
868     output[0x0E] = 0x14 + 0x80;
869
870     // Addr 0F: Length of manufacturer string
871     output[0x0F] = manufacturer_size*2 + 2;
872
873     // Addr 10: Offset of the product string + 0x80, calculated later
874     // Addr 11: Length of product string
875     output[0x11] = product_size*2 + 2;
876
877     // Addr 12: Offset of the serial string + 0x80, calculated later
878     // Addr 13: Length of serial string
879     output[0x13] = serial_size*2 + 2;
880
881     // Dynamic content
882     output[0x14] = manufacturer_size*2 + 2;
883     output[0x15] = 0x03; // type: string
884
885     i = 0x16, j = 0;
886
887     // Output manufacturer
888     for (j = 0; j < manufacturer_size; j++) {
889         output[i] = eeprom->manufacturer[j], i++;
890         output[i] = 0x00, i++;
891     }
892
893     // Output product name
894     output[0x10] = i + 0x80;  // calculate offset
895     output[i] = product_size*2 + 2, i++;
896     output[i] = 0x03, i++;
897     for (j = 0; j < product_size; j++) {
898         output[i] = eeprom->product[j], i++;
899         output[i] = 0x00, i++;
900     }
901
902     // Output serial
903     output[0x12] = i + 0x80; // calculate offset
904     output[i] = serial_size*2 + 2, i++;
905     output[i] = 0x03, i++;
906     for (j = 0; j < serial_size; j++) {
907         output[i] = eeprom->serial[j], i++;
908         output[i] = 0x00, i++;
909     }
910
911     // calculate checksum
912     checksum = 0xAAAA;
913
914     for (i = 0; i < 63; i++) {
915         value = output[i*2];
916         value += output[(i*2)+1] << 8;
917
918         checksum = value^checksum;
919         checksum = (checksum << 1) | (checksum >> 15);
920     }
921
922     output[0x7E] = checksum;
923     output[0x7F] = checksum >> 8;
924
925     return size_check;
926 }
927
928
929 int ftdi_read_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
930 {
931     int i;
932
933     for (i = 0; i < 64; i++) {
934         if (usb_control_msg(ftdi->usb_dev, 0xC0, 0x90, 0, i, eeprom+(i*2), 2, ftdi->usb_read_timeout) != 2)
935             ftdi_error_return(-1, "reading eeprom failed");
936     }
937
938     return 0;
939 }
940
941
942 int ftdi_write_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
943 {
944     unsigned short usb_val;
945     int i;
946
947     for (i = 0; i < 64; i++) {
948         usb_val = eeprom[i*2];
949         usb_val += eeprom[(i*2)+1] << 8;
950         if (usb_control_msg(ftdi->usb_dev, 0x40, 0x91, usb_val, i, NULL, 0, ftdi->usb_write_timeout) != 0)
951             ftdi_error_return(-1, "unable to write eeprom");
952     }
953
954     return 0;
955 }
956
957
958 int ftdi_erase_eeprom(struct ftdi_context *ftdi)
959 {
960     if (usb_control_msg(ftdi->usb_dev, 0x40, 0x92, 0, 0, NULL, 0, ftdi->usb_write_timeout) != 0)
961         ftdi_error_return(-1, "unable to erase eeprom");
962
963     return 0;
964 }
965
966
967 char *ftdi_get_error_string (struct ftdi_context *ftdi)
968 {
969     return ftdi->error_str;
970 }