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