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