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