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