libftdi: (tomj) refactored USB part of libftdi, doesn't depend
[libftdi] / ftdi / 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 #define _GNU_SOURCE
17
18 #include "ftdi.h"
19 #include <sys/ioctl.h>
20 #include <sys/time.h>
21 #include <sys/stat.h>
22 #include <fcntl.h>
23 #include <dirent.h>
24
25 /* Internal USB devfs functions. Do not use outside libftdi */
26
27 /* Those two functions are borrowed from "usbstress" */
28 static int ftdi_usbdev_parsedev(int fd, unsigned int *bus, unsigned int *dev, int vendorid, int productid);
29 int ftdi_usbdev_open(int vendorid, int productid);
30
31 int ftdi_usbdev_claim_interface(int fd, unsigned int interface);
32 int ftdi_usbdev_release_interface(int fd, int interface);
33 int ftdi_usbdev_bulk_write(int fd, unsigned int endpoint, const void *data,
34                     unsigned int size, unsigned int timeout);
35 int ftdi_usbdev_control_msg(int fd, unsigned int requesttype, unsigned int request,
36                     unsigned int value, unsigned int index,
37                     void *data, unsigned int size, unsigned int timeout);
38 struct usbdevfs_urb * ftdi_usbdev_alloc_urb(int iso_packets);
39 int ftdi_usbdev_submit_urb(int fd, struct usbdevfs_urb *urb);
40 int ftdi_usbdev_reap_urb_ndelay(int fd, struct usbdevfs_urb **urb_return);
41
42
43 /* ftdi_init return codes:
44    0: all fine
45   -1: couldn't allocate read buffer
46 */
47 int ftdi_init(struct ftdi_context *ftdi)
48 {
49     ftdi->usb_fd = -1;
50     ftdi->usb_read_timeout = 5000;
51     ftdi->usb_write_timeout = 5000;
52
53     ftdi->type = TYPE_BM;    /* chip type */
54     ftdi->baudrate = -1;
55     ftdi->bitbang_enabled = 0;
56
57     ftdi->readbuffer = NULL;
58     ftdi->readbuffer_offset = 0;
59     ftdi->readbuffer_remaining = 0;
60     ftdi->writebuffer_chunksize = 4096;
61
62     ftdi->interface = 0;
63     ftdi->index = 0;
64     ftdi->in_ep = 0x02;
65     ftdi->out_ep = 0x81;
66     ftdi->bitbang_mode = 1; /* 1: Normal bitbang mode, 2: SPI bitbang mode */
67
68     ftdi->error_str = NULL;
69
70     ftdi->urb = ftdi_usbdev_alloc_urb(0);
71     if (!ftdi->urb) {
72         ftdi->error_str = "out of memory for read URB";
73         return -1;
74     }
75           
76     // all fine. Now allocate the readbuffer
77     return ftdi_read_data_set_chunksize(ftdi, 4096);
78 }
79
80
81 void ftdi_deinit(struct ftdi_context *ftdi)
82 {
83     if (ftdi->readbuffer != NULL) {
84         free(ftdi->readbuffer);
85         ftdi->readbuffer = NULL;
86     }
87     
88     if (ftdi->urb != NULL) {
89         free (ftdi->urb);
90         ftdi->urb = NULL;
91     }
92 }
93
94 /* ftdi_usb_open return codes:
95    0: all fine
96   -1: usb device not found or unable to open
97   -2: unable to claim device
98   -3: reset failed
99   -4: set baudrate failed
100 */
101 int ftdi_usb_open(struct ftdi_context *ftdi, int vendor, int product) {
102     if ((ftdi->usb_fd = ftdi_usbdev_open(vendor, product)) < 0) {
103         ftdi->error_str = "Device not found or unable to open it (permission problem?)";
104         ftdi->usb_fd = -1;
105         return -1;                    
106     }             
107            
108     if (ftdi_usbdev_claim_interface(ftdi->usb_fd, ftdi->interface) != 0) {
109         ftdi->error_str = "unable to claim usb device. Make sure ftdi_sio is unloaded!";
110         close (ftdi->usb_fd);
111         ftdi->usb_fd = -1;
112         return -2;
113     }
114
115     if (ftdi_usb_reset (ftdi) != 0)
116         return -6;
117
118     if (ftdi_set_baudrate (ftdi, 9600) != 0)
119         return -7;
120
121 /*    
122     // Try to guess chip type
123     // Bug in the BM type chips: bcdDevice is 0x200 for serial == 0
124     if (dev->descriptor.bcdDevice == 0x400 || (dev->descriptor.bcdDevice == 0x200
125                 && dev->descriptor.iSerialNumber == 0))
126         ftdi->type = TYPE_BM;
127     else if (dev->descriptor.bcdDevice == 0x200)
128         ftdi->type = TYPE_AM;
129     else if (dev->descriptor.bcdDevice == 0x500)
130         ftdi->type = TYPE_2232C;
131 */
132     return 0;
133 }
134
135
136 int ftdi_usb_reset(struct ftdi_context *ftdi) {
137     if (ftdi_usbdev_control_msg(ftdi->usb_fd, 0x40, 0, 0, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0) {
138         ftdi->error_str = "FTDI reset failed";
139         return -1;
140     }
141     // Invalidate data in the readbuffer
142     ftdi->readbuffer_offset = 0;
143     ftdi->readbuffer_remaining = 0;
144
145     return 0;
146 }
147
148 int ftdi_usb_purge_buffers(struct ftdi_context *ftdi) {
149     if (ftdi_usbdev_control_msg(ftdi->usb_fd, 0x40, 0, 1, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0) {
150         ftdi->error_str = "FTDI purge of RX buffer failed";
151         return -1;
152     }
153     // Invalidate data in the readbuffer
154     ftdi->readbuffer_offset = 0;
155     ftdi->readbuffer_remaining = 0;
156
157     if (ftdi_usbdev_control_msg(ftdi->usb_fd, 0x40, 0, 2, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0) {
158         ftdi->error_str = "FTDI purge of TX buffer failed";
159         return -1;
160     }
161
162
163     return 0;
164 }
165
166 /* ftdi_usb_close return codes
167     0: all fine
168    -1: ftdi_usb_release failed
169    -2: close failed
170 */
171 int ftdi_usb_close(struct ftdi_context *ftdi) {
172     int rtn = 0;
173
174     if (ftdi_usbdev_release_interface(ftdi->usb_fd, ftdi->interface) != 0) {
175         ftdi->error_str = "Unable to release interface";
176         rtn = -1;
177     }
178         
179         
180     if (close (ftdi->usb_fd) != 0) {
181         ftdi->error_str = "Unable to close file descriptor";
182         rtn = -2;
183     }
184     
185     return rtn;
186 }
187
188
189 /*
190     ftdi_convert_baudrate returns nearest supported baud rate to that requested.
191     Function is only used internally
192 */
193 static int ftdi_convert_baudrate(int baudrate, struct ftdi_context *ftdi,
194                                  unsigned short *value, unsigned short *index) {
195     static const char am_adjust_up[8] = {0, 0, 0, 1, 0, 3, 2, 1};
196     static const char am_adjust_dn[8] = {0, 0, 0, 1, 0, 1, 2, 3};
197     static const char frac_code[8] = {0, 3, 2, 4, 1, 5, 6, 7};
198     int divisor, best_divisor, best_baud, best_baud_diff;
199     unsigned long encoded_divisor;
200     int i;
201
202     if (baudrate <= 0) {
203         // Return error
204         return -1;
205     }
206
207     divisor = 24000000 / baudrate;
208
209     if (ftdi->type == TYPE_AM) {
210         // Round down to supported fraction (AM only)
211         divisor -= am_adjust_dn[divisor & 7];
212     }
213
214     // Try this divisor and the one above it (because division rounds down)
215     best_divisor = 0;
216     best_baud = 0;
217     best_baud_diff = 0;
218     for (i = 0; i < 2; i++) {
219         int try_divisor = divisor + i;
220         int baud_estimate;
221         int baud_diff;
222
223         // Round up to supported divisor value
224         if (try_divisor < 8) {
225             // Round up to minimum supported divisor
226             try_divisor = 8;
227         } else if (ftdi->type != TYPE_AM && try_divisor < 12) {
228             // BM doesn't support divisors 9 through 11 inclusive
229             try_divisor = 12;
230         } else if (divisor < 16) {
231             // AM doesn't support divisors 9 through 15 inclusive
232             try_divisor = 16;
233         } else {
234             if (ftdi->type == TYPE_AM) {
235                 // Round up to supported fraction (AM only)
236                 try_divisor += am_adjust_up[try_divisor & 7];
237                 if (try_divisor > 0x1FFF8) {
238                     // Round down to maximum supported divisor value (for AM)
239                     try_divisor = 0x1FFF8;
240                 }
241             } else {
242                 if (try_divisor > 0x1FFFF) {
243                     // Round down to maximum supported divisor value (for BM)
244                     try_divisor = 0x1FFFF;
245                 }
246             }
247         }
248         // Get estimated baud rate (to nearest integer)
249         baud_estimate = (24000000 + (try_divisor / 2)) / try_divisor;
250         // Get absolute difference from requested baud rate
251         if (baud_estimate < baudrate) {
252             baud_diff = baudrate - baud_estimate;
253         } else {
254             baud_diff = baud_estimate - baudrate;
255         }
256         if (i == 0 || baud_diff < best_baud_diff) {
257             // Closest to requested baud rate so far
258             best_divisor = try_divisor;
259             best_baud = baud_estimate;
260             best_baud_diff = baud_diff;
261             if (baud_diff == 0) {
262                 // Spot on! No point trying
263                 break;
264             }
265         }
266     }
267     // Encode the best divisor value
268     encoded_divisor = (best_divisor >> 3) | (frac_code[best_divisor & 7] << 14);
269     // Deal with special cases for encoded value
270     if (encoded_divisor == 1) {
271         encoded_divisor = 0;    // 3000000 baud
272     } else if (encoded_divisor == 0x4001) {
273         encoded_divisor = 1;    // 2000000 baud (BM only)
274     }
275     // Split into "value" and "index" values
276     *value = (unsigned short)(encoded_divisor & 0xFFFF);
277     if(ftdi->type == TYPE_2232C) {
278         *index = (unsigned short)(encoded_divisor >> 8);
279         *index &= 0xFF00;
280         *index |= ftdi->interface;
281     }
282     else
283         *index = (unsigned short)(encoded_divisor >> 16);
284     
285     // Return the nearest baud rate
286     return best_baud;
287 }
288
289 /*
290     ftdi_set_baudrate return codes:
291      0: all fine
292     -1: invalid baudrate
293     -2: setting baudrate failed
294 */
295 int ftdi_set_baudrate(struct ftdi_context *ftdi, int baudrate) {
296     unsigned short value, index;
297     int actual_baudrate;
298
299     if (ftdi->bitbang_enabled) {
300         baudrate = baudrate*4;
301     }
302
303     actual_baudrate = ftdi_convert_baudrate(baudrate, ftdi, &value, &index);
304     if (actual_baudrate <= 0) {
305         ftdi->error_str = "Silly baudrate <= 0.";
306         return -1;
307     }
308
309     // Check within tolerance (about 5%)
310     if ((actual_baudrate * 2 < baudrate /* Catch overflows */ )
311             || ((actual_baudrate < baudrate)
312                 ? (actual_baudrate * 21 < baudrate * 20)
313                 : (baudrate * 21 < actual_baudrate * 20))) {
314         ftdi->error_str = "Unsupported baudrate. Note: bitbang baudrates are automatically multiplied by 4";
315         return -1;
316     }
317
318     if (ftdi_usbdev_control_msg(ftdi->usb_fd, 0x40, 3, value, index, NULL, 0, ftdi->usb_write_timeout) != 0) {
319         ftdi->error_str = "Setting new baudrate failed";
320         return -2;
321     }
322
323     ftdi->baudrate = baudrate;
324     return 0;
325 }
326
327
328 int ftdi_write_data(struct ftdi_context *ftdi, unsigned char *buf, int size) {
329     int ret;
330     int offset = 0;
331     int total_written = 0;
332     while (offset < size) {
333         int write_size = ftdi->writebuffer_chunksize;
334
335         if (offset+write_size > size)
336             write_size = size-offset;
337
338         ret = ftdi_usbdev_bulk_write(ftdi->usb_fd, ftdi->in_ep, buf+offset, write_size, ftdi->usb_write_timeout);
339         if (ret == -1) {
340             ftdi->error_str = "bulk write failed";
341             return -1;
342         }
343         total_written += ret;
344
345         offset += write_size;
346     }
347
348     return total_written;
349 }
350
351
352 int ftdi_write_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize) {
353     ftdi->writebuffer_chunksize = chunksize;
354     return 0;
355 }
356
357
358 int ftdi_write_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize) {
359     *chunksize = ftdi->writebuffer_chunksize;
360     return 0;
361 }
362
363
364 int ftdi_read_data(struct ftdi_context *ftdi, unsigned char *buf, int size) {
365     struct timeval tv, tv_ref, tv_now;
366     struct usbdevfs_urb *returned_urb;
367     int offset = 0, ret = 1, waiting;
368
369     // everything we want is still in the readbuffer?
370     if (size <= ftdi->readbuffer_remaining) {
371         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);
372
373         // Fix offsets
374         ftdi->readbuffer_remaining -= size;
375         ftdi->readbuffer_offset += size;
376
377         /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */
378
379         return size;
380     }
381     // something still in the readbuffer, but not enough to satisfy 'size'?
382     if (ftdi->readbuffer_remaining != 0) {
383         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);
384
385         // Fix offset
386         offset += ftdi->readbuffer_remaining;
387     }
388     
389     // do the actual USB read
390     while (offset < size && ret > 0) {
391         ftdi->readbuffer_remaining = 0;
392         ftdi->readbuffer_offset = 0;
393         
394         /* Real userspace URB processing to cope with
395            a race condition where two or more status bytes
396            could already be in the kernel USB buffer */
397         memset(ftdi->urb, 0, sizeof(struct usbdevfs_urb));
398         
399         ftdi->urb->type = USBDEVFS_URB_TYPE_BULK;
400         ftdi->urb->endpoint = ftdi->out_ep | USB_DIR_IN;
401         ftdi->urb->buffer = ftdi->readbuffer;
402         ftdi->urb->buffer_length = ftdi->readbuffer_chunksize;
403     
404         /* Submit URB to USB layer */
405         if (ftdi_usbdev_submit_urb(ftdi->usb_fd, ftdi->urb) == -1) {
406             ftdi->error_str = "ftdi_usbdev_submit_urb for bulk read failed";
407             return -1;
408         }
409         
410         /* Wait for the result to come in.
411            Timer stuff is borrowed from libusb's interrupt transfer */
412         gettimeofday(&tv_ref, NULL);
413         tv_ref.tv_sec = tv_ref.tv_sec + ftdi->usb_read_timeout / 1000;
414         tv_ref.tv_usec = tv_ref.tv_usec + (ftdi->usb_read_timeout % 1000) * 1000;
415         
416         if (tv_ref.tv_usec > 1e6) {
417             tv_ref.tv_usec -= 1e6;
418             tv_ref.tv_sec++;
419         }
420         
421         waiting = 1;
422         memset (&tv, 0, sizeof (struct timeval));
423         while (((ret = ftdi_usbdev_reap_urb_ndelay(ftdi->usb_fd, &returned_urb)) == -1) && waiting) {
424             tv.tv_sec = 0;
425             tv.tv_usec = 1000; // 1 msec
426             select(0, NULL, NULL, NULL, &tv); //sub second wait
427         
428             /* compare with actual time, as the select timeout is not that precise */
429             gettimeofday(&tv_now, NULL);
430         
431             if ((tv_now.tv_sec > tv_ref.tv_sec) ||
432                 ((tv_now.tv_sec == tv_ref.tv_sec) && (tv_now.tv_usec >= tv_ref.tv_usec)))
433             waiting = 0;
434         }        
435         
436         if (!waiting) {
437             ftdi->error_str = "timeout during ftdi_read_data";
438             return -1;
439         }
440         
441         if (ret < 0) {
442             ftdi->error_str = "ftdi_usbdev_reap_urb for bulk read failed";
443             return -1;
444         }
445         
446         if (returned_urb->status) {
447             ftdi->error_str = "URB return status not OK";
448             return -1;
449         }
450         
451         /* Paranoia check */
452         if (returned_urb->buffer != ftdi->readbuffer) {
453             ftdi->error_str = "buffer paranoia check failed";
454             return -1;
455         }
456         
457         ret = returned_urb->actual_length;
458         if (ret > 2) {
459             // skip FTDI status bytes.
460             // Maybe stored in the future to enable modem use
461             ftdi->readbuffer_offset += 2;
462             ret -= 2;
463         } else if (ret <= 2) {
464             // no more data to read?
465             return offset;
466         }
467         if (ret > 0) {
468             // data still fits in buf?
469             if (offset+ret <= size) {
470                 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, ret);
471                 //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
472                 offset += ret;
473
474                 /* Did we read exactly the right amount of bytes? */
475                 if (offset == size)
476                     return offset;
477             } else {
478                 // only copy part of the data or size <= readbuffer_chunksize
479                 int part_size = size-offset;
480                 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, part_size);
481                 
482                 ftdi->readbuffer_offset += part_size;
483                 ftdi->readbuffer_remaining = ret-part_size;
484                 offset += part_size;
485
486                 /* printf("Returning part: %d - size: %d - offset: %d - ret: %d - remaining: %d\n",
487                 part_size, size, offset, ret, ftdi->readbuffer_remaining); */
488
489                 return offset;
490             }
491         }
492     }
493     // never reached
494     return -2;
495 }
496
497
498 int ftdi_read_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize) {
499     // Invalidate all remaining data
500     ftdi->readbuffer_offset = 0;
501     ftdi->readbuffer_remaining = 0;
502
503     unsigned char *new_buf;
504     if ((new_buf = (unsigned char *)realloc(ftdi->readbuffer, chunksize)) == NULL) {
505         ftdi->error_str = "out of memory for readbuffer";
506         return -1;
507     }
508
509     ftdi->readbuffer = new_buf;
510     ftdi->readbuffer_chunksize = chunksize;
511
512     return 0;
513 }
514
515
516 int ftdi_read_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize) {
517     *chunksize = ftdi->readbuffer_chunksize;
518     return 0;
519 }
520
521
522
523 int ftdi_enable_bitbang(struct ftdi_context *ftdi, unsigned char bitmask) {
524     unsigned short usb_val;
525
526     usb_val = bitmask; // low byte: bitmask
527     /* FT2232C: Set bitbang_mode to 2 to enable SPI */
528     usb_val |= (ftdi->bitbang_mode << 8);
529
530     if (ftdi_usbdev_control_msg(ftdi->usb_fd, 0x40, 0x0B, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0) {
531         ftdi->error_str = "Unable to enter bitbang mode. Perhaps not a BM type chip?";
532         return -1;
533     }
534     ftdi->bitbang_enabled = 1;
535     return 0;
536 }
537
538
539 int ftdi_disable_bitbang(struct ftdi_context *ftdi) {
540     if (ftdi_usbdev_control_msg(ftdi->usb_fd, 0x40, 0x0B, 0, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0) {
541         ftdi->error_str = "Unable to leave bitbang mode. Perhaps not a BM type chip?";
542         return -1;
543     }
544
545     ftdi->bitbang_enabled = 0;
546     return 0;
547 }
548
549
550 int ftdi_read_pins(struct ftdi_context *ftdi, unsigned char *pins) {
551     unsigned short usb_val;
552     if (ftdi_usbdev_control_msg(ftdi->usb_fd, 0xC0, 0x0C, 0, ftdi->index, (char *)&usb_val, 1, ftdi->usb_read_timeout) != 1) {
553         ftdi->error_str = "Read pins failed";
554         return -1;
555     }
556
557     *pins = (unsigned char)usb_val;
558     return 0;
559 }
560
561
562 int ftdi_set_latency_timer(struct ftdi_context *ftdi, unsigned char latency) {
563     unsigned short usb_val;
564
565     if (latency < 1) {
566         ftdi->error_str = "Latency out of range. Only valid for 1-255";
567         return -1;
568     }
569
570     usb_val = latency;
571     if (ftdi_usbdev_control_msg(ftdi->usb_fd, 0x40, 0x09, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0) {
572         ftdi->error_str = "Unable to set latency timer";
573         return -2;
574     }
575     return 0;
576 }
577
578
579 int ftdi_get_latency_timer(struct ftdi_context *ftdi, unsigned char *latency) {
580     unsigned short usb_val;
581     if (ftdi_usbdev_control_msg(ftdi->usb_fd, 0xC0, 0x0A, 0, ftdi->index, (char *)&usb_val, 1, ftdi->usb_read_timeout) != 1) {
582         ftdi->error_str = "Reading latency timer failed";
583         return -1;
584     }
585
586     *latency = (unsigned char)usb_val;
587     return 0;
588 }
589
590
591 void ftdi_eeprom_initdefaults(struct ftdi_eeprom *eeprom) {
592     eeprom->vendor_id = 0x0403;
593     eeprom->product_id = 0x6001;
594
595     eeprom->self_powered = 1;
596     eeprom->remote_wakeup = 1;
597     eeprom->BM_type_chip = 1;
598
599     eeprom->in_is_isochronous = 0;
600     eeprom->out_is_isochronous = 0;
601     eeprom->suspend_pull_downs = 0;
602
603     eeprom->use_serial = 0;
604     eeprom->change_usb_version = 0;
605     eeprom->usb_version = 0x0200;
606     eeprom->max_power = 0;
607
608     eeprom->manufacturer = NULL;
609     eeprom->product = NULL;
610     eeprom->serial = NULL;
611 }
612
613
614 /*
615     ftdi_eeprom_build return codes:
616     positive value: used eeprom size
617     -1: eeprom size (128 bytes) exceeded by custom strings
618 */
619 int ftdi_eeprom_build(struct ftdi_eeprom *eeprom, unsigned char *output) {
620     unsigned char i, j;
621     unsigned short checksum, value;
622     unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
623     int size_check;
624
625     if (eeprom->manufacturer != NULL)
626         manufacturer_size = strlen(eeprom->manufacturer);
627     if (eeprom->product != NULL)
628         product_size = strlen(eeprom->product);
629     if (eeprom->serial != NULL)
630         serial_size = strlen(eeprom->serial);
631
632     size_check = 128; // eeprom is 128 bytes
633     size_check -= 28; // 28 are always in use (fixed)
634     size_check -= manufacturer_size*2;
635     size_check -= product_size*2;
636     size_check -= serial_size*2;
637
638     // eeprom size exceeded?
639     if (size_check < 0)
640         return (-1);
641
642     // empty eeprom
643     memset (output, 0, 128);
644
645     // Addr 00: Stay 00 00
646     // Addr 02: Vendor ID
647     output[0x02] = eeprom->vendor_id;
648     output[0x03] = eeprom->vendor_id >> 8;
649
650     // Addr 04: Product ID
651     output[0x04] = eeprom->product_id;
652     output[0x05] = eeprom->product_id >> 8;
653
654     // Addr 06: Device release number (0400h for BM features)
655     output[0x06] = 0x00;
656
657     if (eeprom->BM_type_chip == 1)
658         output[0x07] = 0x04;
659     else
660         output[0x07] = 0x02;
661
662     // Addr 08: Config descriptor
663     // Bit 1: remote wakeup if 1
664     // Bit 0: self powered if 1
665     //
666     j = 0;
667     if (eeprom->self_powered == 1)
668         j = j | 1;
669     if (eeprom->remote_wakeup == 1)
670         j = j | 2;
671     output[0x08] = j;
672
673     // Addr 09: Max power consumption: max power = value * 2 mA
674     output[0x09] = eeprom->max_power;
675     ;
676
677     // Addr 0A: Chip configuration
678     // Bit 7: 0 - reserved
679     // Bit 6: 0 - reserved
680     // Bit 5: 0 - reserved
681     // Bit 4: 1 - Change USB version
682     // Bit 3: 1 - Use the serial number string
683     // Bit 2: 1 - Enable suspend pull downs for lower power
684     // Bit 1: 1 - Out EndPoint is Isochronous
685     // Bit 0: 1 - In EndPoint is Isochronous
686     //
687     j = 0;
688     if (eeprom->in_is_isochronous == 1)
689         j = j | 1;
690     if (eeprom->out_is_isochronous == 1)
691         j = j | 2;
692     if (eeprom->suspend_pull_downs == 1)
693         j = j | 4;
694     if (eeprom->use_serial == 1)
695         j = j | 8;
696     if (eeprom->change_usb_version == 1)
697         j = j | 16;
698     output[0x0A] = j;
699
700     // Addr 0B: reserved
701     output[0x0B] = 0x00;
702
703     // Addr 0C: USB version low byte when 0x0A bit 4 is set
704     // Addr 0D: USB version high byte when 0x0A bit 4 is set
705     if (eeprom->change_usb_version == 1) {
706         output[0x0C] = eeprom->usb_version;
707         output[0x0D] = eeprom->usb_version >> 8;
708     }
709
710
711     // Addr 0E: Offset of the manufacturer string + 0x80
712     output[0x0E] = 0x14 + 0x80;
713
714     // Addr 0F: Length of manufacturer string
715     output[0x0F] = manufacturer_size*2 + 2;
716
717     // Addr 10: Offset of the product string + 0x80, calculated later
718     // Addr 11: Length of product string
719     output[0x11] = product_size*2 + 2;
720
721     // Addr 12: Offset of the serial string + 0x80, calculated later
722     // Addr 13: Length of serial string
723     output[0x13] = serial_size*2 + 2;
724
725     // Dynamic content
726     output[0x14] = manufacturer_size*2 + 2;
727     output[0x15] = 0x03; // type: string
728
729     i = 0x16, j = 0;
730
731     // Output manufacturer
732     for (j = 0; j < manufacturer_size; j++) {
733         output[i] = eeprom->manufacturer[j], i++;
734         output[i] = 0x00, i++;
735     }
736
737     // Output product name
738     output[0x10] = i + 0x80;  // calculate offset
739     output[i] = product_size*2 + 2, i++;
740     output[i] = 0x03, i++;
741     for (j = 0; j < product_size; j++) {
742         output[i] = eeprom->product[j], i++;
743         output[i] = 0x00, i++;
744     }
745
746     // Output serial
747     output[0x12] = i + 0x80; // calculate offset
748     output[i] = serial_size*2 + 2, i++;
749     output[i] = 0x03, i++;
750     for (j = 0; j < serial_size; j++) {
751         output[i] = eeprom->serial[j], i++;
752         output[i] = 0x00, i++;
753     }
754
755     // calculate checksum
756     checksum = 0xAAAA;
757
758     for (i = 0; i < 63; i++) {
759         value = output[i*2];
760         value += output[(i*2)+1] << 8;
761
762         checksum = value^checksum;
763         checksum = (checksum << 1) | (checksum >> 15);
764     }
765
766     output[0x7E] = checksum;
767     output[0x7F] = checksum >> 8;
768
769     return size_check;
770 }
771
772
773 int ftdi_read_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom) {
774     int i;
775
776     for (i = 0; i < 64; i++) {
777         if (ftdi_usbdev_control_msg(ftdi->usb_fd, 0xC0, 0x90, 0, i, eeprom+(i*2), 2, ftdi->usb_read_timeout) != 2) {
778             ftdi->error_str = "Reading eeprom failed";
779             return -1;
780         }
781     }
782
783     return 0;
784 }
785
786
787 int ftdi_write_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom) {
788     unsigned short usb_val;
789     int i;
790
791     for (i = 0; i < 64; i++) {
792         usb_val = eeprom[i*2];
793         usb_val += eeprom[(i*2)+1] << 8;
794         if (ftdi_usbdev_control_msg(ftdi->usb_fd, 0x40, 0x91, usb_val, i, NULL, 0, ftdi->usb_write_timeout) != 0) {
795             ftdi->error_str = "Unable to write eeprom";
796             return -1;
797         }
798     }
799
800     return 0;
801 }
802
803
804 int ftdi_erase_eeprom(struct ftdi_context *ftdi) {
805     if (ftdi_usbdev_control_msg(ftdi->usb_fd, 0x40, 0x92, 0, 0, NULL, 0, ftdi->usb_write_timeout) != 0) {
806         ftdi->error_str = "Unable to erase eeprom";
807         return -1;
808     }
809
810     return 0;
811 }
812
813
814 /* libusb like functions - currently linux only */
815 static int check_usb_vfs(const unsigned char *dirname)
816 {
817   DIR *dir;
818   struct dirent *entry;
819   int found = 0;
820
821   dir = opendir(dirname);
822   if (!dir)
823     return 0;
824
825   while ((entry = readdir(dir)) != NULL) {
826     /* Skip anything starting with a . */
827     if (entry->d_name[0] == '.')
828       continue;
829
830     /* We assume if we find any files that it must be the right place */
831     found = 1;
832     break;
833   }
834
835   closedir(dir);
836
837   return found;
838 }
839
840 static int ftdi_usbdev_parsedev(int fd, unsigned int *bus, unsigned int *dev, int vendorid, int productid)
841 {
842         char buf[16384];
843         char *start, *end, *lineend, *cp;
844         int devnum = -1, busnum = -1, vendor = -1, product = -1;
845         int ret;
846
847         if (lseek(fd, 0, SEEK_SET) == (off_t)-1)
848                 return -1;
849         ret = read(fd, buf, sizeof(buf)-1);
850         if (ret == -1)
851                 return -1;
852         end = buf + ret;
853         *end = 0;
854         start = buf;
855         ret = 0;
856         while (start < end) {
857                 lineend = strchr(start, '\n');
858                 if (!lineend)
859                         break;
860                 *lineend = 0;
861                 switch (start[0]) {
862                 case 'T':  /* topology line */
863                         if ((cp = strstr(start, "Dev#="))) {
864                                 devnum = strtoul(cp + 5, NULL, 0);
865                         } else
866                                 devnum = -1;
867                         if ((cp = strstr(start, "Bus="))) {
868                                 busnum = strtoul(cp + 4, NULL, 0);
869                         } else
870                                 busnum = -1;
871                         break;
872
873                 case 'P':
874                         if ((cp = strstr(start, "Vendor="))) {
875                                 vendor = strtoul(cp + 7, NULL, 16);
876                         } else
877                                 vendor = -1;
878                         if ((cp = strstr(start, "ProdID="))) {
879                                 product = strtoul(cp + 7, NULL, 16);
880                         } else
881                                 product = -1;
882                         if (vendor != -1 && product != -1 && devnum >= 1 && devnum <= 127 &&
883                             busnum >= 0 && busnum <= 999 &&
884                             (vendorid == vendor || vendorid == -1) &&
885                             (productid == product || productid == -1)) {
886                                 if (bus)
887                                         *bus = busnum;
888                                 if (dev)
889                                         *dev = devnum;
890                                 ret++;
891                         }
892                         break;
893                 }
894                 start = lineend + 1;
895         }
896         return ret;
897 }
898
899 int ftdi_usbdev_open(int vendorid, int productid)
900 {
901     unsigned int busnum, devnum, fd, ret;
902     char usb_path[PATH_MAX+1] = "";
903     char usb_devices_path[PATH_MAX*2];
904     
905     /* Find the path to the virtual filesystem */
906     if (getenv("USB_DEVFS_PATH")) {
907             if (check_usb_vfs((char*)getenv("USB_DEVFS_PATH"))) {
908                 strncpy(usb_path, (char*)getenv("USB_DEVFS_PATH"), sizeof(usb_path) - 1);
909                 usb_path[sizeof(usb_path) - 1] = 0;
910             }
911     }
912
913     if (!usb_path[0]) {
914         if (check_usb_vfs("/proc/bus/usb")) {
915             strncpy(usb_path, "/proc/bus/usb", sizeof(usb_path) - 1);
916             usb_path[sizeof(usb_path) - 1] = 0;
917         } else if (check_usb_vfs("/sys/bus/usb")) { /* 2.6 Kernel with sysfs */
918             strncpy(usb_path, "/sys/bus/usb", sizeof(usb_path) -1);
919             usb_path[sizeof(usb_path) - 1] = 0;
920         } else if (check_usb_vfs("/dev/usb")) {
921             strncpy(usb_path, "/dev/usb", sizeof(usb_path) - 1);
922             usb_path[sizeof(usb_path) - 1] = 0;
923         } else
924             usb_path[0] = 0;    
925     }
926     
927     /* No path, no USB support */
928     if (!usb_path[0])
929         return -1;
930     
931     /* Parse device list */    
932     snprintf(usb_devices_path, sizeof(usb_devices_path), "%s/devices", usb_path);
933     if ((fd = open(usb_devices_path, O_RDONLY)) == -1)
934         return -2;
935     
936     ret = ftdi_usbdev_parsedev(fd, &busnum, &devnum, vendorid, productid);
937     close (fd);
938     
939     // Device not found
940     if (ret != 1)
941         return -3;
942
943     snprintf(usb_devices_path, sizeof(usb_devices_path), "%s/%03u/%03u", usb_path, busnum, devnum);
944     if ((fd = open(usb_devices_path, O_RDWR)) == -1)
945         return -4;
946         
947     return fd;
948 }
949
950 int ftdi_usbdev_claim_interface(int fd, unsigned int interface)
951 {
952     return ioctl(fd, USBDEVFS_CLAIMINTERFACE, &interface);
953 }
954
955 int ftdi_usbdev_release_interface(int fd, int interface)
956 {
957     return ioctl(fd, USBDEVFS_RELEASEINTERFACE, &interface);
958 }
959
960
961 int ftdi_usbdev_bulk_write(int fd, unsigned int endpoint, const void *data,
962                     unsigned int size, unsigned int timeout)
963 {
964     struct usbdevfs_bulktransfer arg;
965
966     arg.ep = endpoint & ~USB_DIR_IN;
967     arg.len = size;
968     arg.timeout = timeout;
969     arg.data = (void *) data;
970
971     return ioctl(fd, USBDEVFS_BULK, &arg);
972 }
973
974 int ftdi_usbdev_control_msg(int fd, unsigned int requesttype,
975                  unsigned int request, unsigned int value, unsigned int index,
976                  void *data, unsigned int size, unsigned int timeout)
977 {
978     struct usbdevfs_ctrltransfer arg;
979
980     arg.requesttype = requesttype;
981     arg.request = request;
982     arg.value = value;
983     arg.index = index;
984     arg.length = size;
985     arg.timeout = timeout;
986     arg.data = data;
987
988     return ioctl(fd, USBDEVFS_CONTROL, &arg);
989 }
990
991 /* Functions needed for userspace URB processing */
992 struct usbdevfs_urb * ftdi_usbdev_alloc_urb(int iso_packets)
993 {
994     return (struct usbdevfs_urb *)calloc(sizeof(struct usbdevfs_urb)
995                     + iso_packets * sizeof(struct usbdevfs_iso_packet_desc),
996                     1);
997 }
998
999
1000 int ftdi_usbdev_submit_urb(int fd, struct usbdevfs_urb *urb)
1001 {
1002     return ioctl(fd, USBDEVFS_SUBMITURB, urb);
1003 }
1004
1005
1006 int ftdi_usbdev_reap_urb_ndelay(int fd, struct usbdevfs_urb **urb_return)
1007 {
1008     return ioctl(fd, USBDEVFS_REAPURBNDELAY, urb_return);
1009 }