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