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