ftdi.c

Go to the documentation of this file.
00001 /***************************************************************************
00002                           ftdi.c  -  description
00003                              -------------------
00004     begin                : Fri Apr 4 2003
00005     copyright            : (C) 2003-2008 by Intra2net AG
00006     email                : opensource@intra2net.com
00007  ***************************************************************************/
00008 
00009 /***************************************************************************
00010  *                                                                         *
00011  *   This program is free software; you can redistribute it and/or modify  *
00012  *   it under the terms of the GNU Lesser General Public License           *
00013  *   version 2.1 as published by the Free Software Foundation;             *
00014  *                                                                         *
00015  ***************************************************************************/
00016 
00029 /* @{ */
00030 
00031 #include <usb.h>
00032 #include <string.h>
00033 #include <errno.h>
00034 #include <stdio.h>
00035 
00036 #include "ftdi.h"
00037 
00038 /* stuff needed for async write */
00039 #ifdef LIBFTDI_LINUX_ASYNC_MODE
00040 #include <sys/ioctl.h>
00041 #include <sys/time.h>
00042 #include <sys/select.h>
00043 #include <sys/types.h>
00044 #include <unistd.h>
00045 #include <linux/usbdevice_fs.h>
00046 #endif
00047 
00048 #define ftdi_error_return(code, str) do {  \
00049         ftdi->error_str = str;             \
00050         return code;                       \
00051    } while(0);
00052 
00053 
00064 int ftdi_init(struct ftdi_context *ftdi)
00065 {
00066     unsigned int i;
00067 
00068     ftdi->usb_dev = NULL;
00069     ftdi->usb_read_timeout = 5000;
00070     ftdi->usb_write_timeout = 5000;
00071 
00072     ftdi->type = TYPE_BM;    /* chip type */
00073     ftdi->baudrate = -1;
00074     ftdi->bitbang_enabled = 0;
00075 
00076     ftdi->readbuffer = NULL;
00077     ftdi->readbuffer_offset = 0;
00078     ftdi->readbuffer_remaining = 0;
00079     ftdi->writebuffer_chunksize = 4096;
00080 
00081     ftdi->interface = 0;
00082     ftdi->index = 0;
00083     ftdi->in_ep = 0x02;
00084     ftdi->out_ep = 0x81;
00085     ftdi->bitbang_mode = 1; /* 1: Normal bitbang mode, 2: SPI bitbang mode */
00086 
00087     ftdi->error_str = NULL;
00088 
00089 #ifdef LIBFTDI_LINUX_ASYNC_MODE
00090     ftdi->async_usb_buffer_size=10;
00091     if ((ftdi->async_usb_buffer=malloc(sizeof(struct usbdevfs_urb)*ftdi->async_usb_buffer_size)) == NULL)
00092         ftdi_error_return(-1, "out of memory for async usb buffer");
00093 
00094     /* initialize async usb buffer with unused-marker */
00095     for (i=0; i < ftdi->async_usb_buffer_size; i++)
00096         ((struct usbdevfs_urb*)ftdi->async_usb_buffer)[i].usercontext = FTDI_URB_USERCONTEXT_COOKIE;
00097 #else
00098     ftdi->async_usb_buffer_size=0;
00099     ftdi->async_usb_buffer = NULL;
00100 #endif
00101 
00102     ftdi->eeprom_size = FTDI_DEFAULT_EEPROM_SIZE;
00103 
00104     /* All fine. Now allocate the readbuffer */
00105     return ftdi_read_data_set_chunksize(ftdi, 4096);
00106 }
00107 
00113 struct ftdi_context *ftdi_new()
00114 {
00115     struct ftdi_context * ftdi = (struct ftdi_context *)malloc(sizeof(struct ftdi_context));
00116 
00117     if (ftdi == NULL)
00118     {
00119         return NULL;
00120     }
00121 
00122     if (ftdi_init(ftdi) != 0)
00123     {
00124         free(ftdi);
00125         return NULL;
00126     }
00127 
00128     return ftdi;
00129 }
00130 
00140 int ftdi_set_interface(struct ftdi_context *ftdi, enum ftdi_interface interface)
00141 {
00142     switch (interface)
00143     {
00144         case INTERFACE_ANY:
00145         case INTERFACE_A:
00146             /* ftdi_usb_open_desc cares to set the right index, depending on the found chip */
00147             break;
00148         case INTERFACE_B:
00149             ftdi->interface = 1;
00150             ftdi->index     = INTERFACE_B;
00151             ftdi->in_ep     = 0x04;
00152             ftdi->out_ep    = 0x83;
00153             break;
00154         case INTERFACE_C:
00155             ftdi->interface = 2;
00156             ftdi->index     = INTERFACE_C;
00157             ftdi->in_ep     = 0x06;
00158             ftdi->out_ep    = 0x85;
00159             break;
00160         case INTERFACE_D:
00161             ftdi->interface = 3;
00162             ftdi->index     = INTERFACE_D;
00163             ftdi->in_ep     = 0x08;
00164             ftdi->out_ep    = 0x87;
00165             break;
00166         default:
00167             ftdi_error_return(-1, "Unknown interface");
00168     }
00169     return 0;
00170 }
00171 
00177 void ftdi_deinit(struct ftdi_context *ftdi)
00178 {
00179     if (ftdi->async_usb_buffer != NULL)
00180     {
00181         free(ftdi->async_usb_buffer);
00182         ftdi->async_usb_buffer = NULL;
00183     }
00184 
00185     if (ftdi->readbuffer != NULL)
00186     {
00187         free(ftdi->readbuffer);
00188         ftdi->readbuffer = NULL;
00189     }
00190 }
00191 
00197 void ftdi_free(struct ftdi_context *ftdi)
00198 {
00199     ftdi_deinit(ftdi);
00200     free(ftdi);
00201 }
00202 
00209 void ftdi_set_usbdev (struct ftdi_context *ftdi, usb_dev_handle *usb)
00210 {
00211     ftdi->usb_dev = usb;
00212 }
00213 
00214 
00229 int ftdi_usb_find_all(struct ftdi_context *ftdi, struct ftdi_device_list **devlist, int vendor, int product)
00230 {
00231     struct ftdi_device_list **curdev;
00232     struct usb_bus *bus;
00233     struct usb_device *dev;
00234     int count = 0;
00235 
00236     usb_init();
00237     if (usb_find_busses() < 0)
00238         ftdi_error_return(-1, "usb_find_busses() failed");
00239     if (usb_find_devices() < 0)
00240         ftdi_error_return(-2, "usb_find_devices() failed");
00241 
00242     curdev = devlist;
00243     *curdev = NULL;
00244     for (bus = usb_get_busses(); bus; bus = bus->next)
00245     {
00246         for (dev = bus->devices; dev; dev = dev->next)
00247         {
00248             if (dev->descriptor.idVendor == vendor
00249                     && dev->descriptor.idProduct == product)
00250             {
00251                 *curdev = (struct ftdi_device_list*)malloc(sizeof(struct ftdi_device_list));
00252                 if (!*curdev)
00253                     ftdi_error_return(-3, "out of memory");
00254 
00255                 (*curdev)->next = NULL;
00256                 (*curdev)->dev = dev;
00257 
00258                 curdev = &(*curdev)->next;
00259                 count++;
00260             }
00261         }
00262     }
00263 
00264     return count;
00265 }
00266 
00272 void ftdi_list_free(struct ftdi_device_list **devlist)
00273 {
00274     struct ftdi_device_list *curdev, *next;
00275 
00276     for (curdev = *devlist; curdev != NULL;)
00277     {
00278         next = curdev->next;
00279         free(curdev);
00280         curdev = next;
00281     }
00282 
00283     *devlist = NULL;
00284 }
00285 
00291 void ftdi_list_free2(struct ftdi_device_list *devlist)
00292 {
00293     ftdi_list_free(&devlist);
00294 }
00295 
00322 int ftdi_usb_get_strings(struct ftdi_context * ftdi, struct usb_device * dev,
00323                          char * manufacturer, int mnf_len, char * description, int desc_len, char * serial, int serial_len)
00324 {
00325     if ((ftdi==NULL) || (dev==NULL))
00326         return -1;
00327 
00328     if (!(ftdi->usb_dev = usb_open(dev)))
00329         ftdi_error_return(-4, usb_strerror());
00330 
00331     if (manufacturer != NULL)
00332     {
00333         if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iManufacturer, manufacturer, mnf_len) <= 0)
00334         {
00335             usb_close (ftdi->usb_dev);
00336             ftdi_error_return(-7, usb_strerror());
00337         }
00338     }
00339 
00340     if (description != NULL)
00341     {
00342         if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iProduct, description, desc_len) <= 0)
00343         {
00344             usb_close (ftdi->usb_dev);
00345             ftdi_error_return(-8, usb_strerror());
00346         }
00347     }
00348 
00349     if (serial != NULL)
00350     {
00351         if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iSerialNumber, serial, serial_len) <= 0)
00352         {
00353             usb_close (ftdi->usb_dev);
00354             ftdi_error_return(-9, usb_strerror());
00355         }
00356     }
00357 
00358     if (usb_close (ftdi->usb_dev) != 0)
00359         ftdi_error_return(-10, usb_strerror());
00360 
00361     return 0;
00362 }
00363 
00377 int ftdi_usb_open_dev(struct ftdi_context *ftdi, struct usb_device *dev)
00378 {
00379     int detach_errno = 0;
00380     if (!(ftdi->usb_dev = usb_open(dev)))
00381         ftdi_error_return(-4, "usb_open() failed");
00382 
00383 #ifdef LIBUSB_HAS_GET_DRIVER_NP
00384     // Try to detach ftdi_sio kernel module.
00385     // Returns ENODATA if driver is not loaded.
00386     //
00387     // The return code is kept in a separate variable and only parsed
00388     // if usb_set_configuration() or usb_claim_interface() fails as the
00389     // detach operation might be denied and everything still works fine.
00390     // Likely scenario is a static ftdi_sio kernel module.
00391     if (usb_detach_kernel_driver_np(ftdi->usb_dev, ftdi->interface) != 0 && errno != ENODATA)
00392         detach_errno = errno;
00393 #endif
00394 
00395     // set configuration (needed especially for windows)
00396     // tolerate EBUSY: one device with one configuration, but two interfaces
00397     //    and libftdi sessions to both interfaces (e.g. FT2232)
00398     if (dev->descriptor.bNumConfigurations > 0 &&
00399             usb_set_configuration(ftdi->usb_dev, dev->config[0].bConfigurationValue) &&
00400             errno != EBUSY)
00401     {
00402         usb_close (ftdi->usb_dev);
00403         if (detach_errno == EPERM)
00404         {
00405             ftdi_error_return(-8, "inappropriate permissions on device!");
00406         }
00407         else
00408         {
00409             ftdi_error_return(-3, "unable to set usb configuration. Make sure ftdi_sio is unloaded!");
00410         }
00411     }
00412 
00413     if (usb_claim_interface(ftdi->usb_dev, ftdi->interface) != 0)
00414     {
00415         usb_close (ftdi->usb_dev);
00416         if (detach_errno == EPERM)
00417         {
00418             ftdi_error_return(-8, "inappropriate permissions on device!");
00419         }
00420         else
00421         {
00422             ftdi_error_return(-5, "unable to claim usb device. Make sure ftdi_sio is unloaded!");
00423         }
00424     }
00425 
00426     if (ftdi_usb_reset (ftdi) != 0)
00427     {
00428         usb_close (ftdi->usb_dev);
00429         ftdi_error_return(-6, "ftdi_usb_reset failed");
00430     }
00431 
00432     if (ftdi_set_baudrate (ftdi, 9600) != 0)
00433     {
00434         usb_close (ftdi->usb_dev);
00435         ftdi_error_return(-7, "set baudrate failed");
00436     }
00437 
00438     // Try to guess chip type
00439     // Bug in the BM type chips: bcdDevice is 0x200 for serial == 0
00440     if (dev->descriptor.bcdDevice == 0x400 || (dev->descriptor.bcdDevice == 0x200
00441             && dev->descriptor.iSerialNumber == 0))
00442         ftdi->type = TYPE_BM;
00443     else if (dev->descriptor.bcdDevice == 0x200)
00444         ftdi->type = TYPE_AM;
00445     else if (dev->descriptor.bcdDevice == 0x500)
00446         ftdi->type = TYPE_2232C;
00447     else if (dev->descriptor.bcdDevice == 0x600)
00448         ftdi->type = TYPE_R;
00449     else if (dev->descriptor.bcdDevice == 0x700)
00450         ftdi->type = TYPE_2232H;
00451     else if (dev->descriptor.bcdDevice == 0x800)
00452         ftdi->type = TYPE_4232H;
00453 
00454     // Set default interface on dual/quad type chips
00455     switch(ftdi->type)
00456     {
00457         case TYPE_2232C:
00458         case TYPE_2232H:
00459         case TYPE_4232H:
00460             if (!ftdi->index)
00461                 ftdi->index = INTERFACE_A;
00462             break;
00463         default:
00464             break;
00465     }
00466 
00467     ftdi_error_return(0, "all fine");
00468 }
00469 
00479 int ftdi_usb_open(struct ftdi_context *ftdi, int vendor, int product)
00480 {
00481     return ftdi_usb_open_desc(ftdi, vendor, product, NULL, NULL);
00482 }
00483 
00506 int ftdi_usb_open_desc(struct ftdi_context *ftdi, int vendor, int product,
00507                        const char* description, const char* serial)
00508 {
00509     struct usb_bus *bus;
00510     struct usb_device *dev;
00511     char string[256];
00512 
00513     usb_init();
00514 
00515     if (usb_find_busses() < 0)
00516         ftdi_error_return(-1, "usb_find_busses() failed");
00517     if (usb_find_devices() < 0)
00518         ftdi_error_return(-2, "usb_find_devices() failed");
00519 
00520     for (bus = usb_get_busses(); bus; bus = bus->next)
00521     {
00522         for (dev = bus->devices; dev; dev = dev->next)
00523         {
00524             if (dev->descriptor.idVendor == vendor
00525                     && dev->descriptor.idProduct == product)
00526             {
00527                 if (!(ftdi->usb_dev = usb_open(dev)))
00528                     ftdi_error_return(-4, "usb_open() failed");
00529 
00530                 if (description != NULL)
00531                 {
00532                     if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iProduct, string, sizeof(string)) <= 0)
00533                     {
00534                         usb_close (ftdi->usb_dev);
00535                         ftdi_error_return(-8, "unable to fetch product description");
00536                     }
00537                     if (strncmp(string, description, sizeof(string)) != 0)
00538                     {
00539                         if (usb_close (ftdi->usb_dev) != 0)
00540                             ftdi_error_return(-10, "unable to close device");
00541                         continue;
00542                     }
00543                 }
00544                 if (serial != NULL)
00545                 {
00546                     if (usb_get_string_simple(ftdi->usb_dev, dev->descriptor.iSerialNumber, string, sizeof(string)) <= 0)
00547                     {
00548                         usb_close (ftdi->usb_dev);
00549                         ftdi_error_return(-9, "unable to fetch serial number");
00550                     }
00551                     if (strncmp(string, serial, sizeof(string)) != 0)
00552                     {
00553                         if (usb_close (ftdi->usb_dev) != 0)
00554                             ftdi_error_return(-10, "unable to close device");
00555                         continue;
00556                     }
00557                 }
00558 
00559                 if (usb_close (ftdi->usb_dev) != 0)
00560                     ftdi_error_return(-10, "unable to close device");
00561 
00562                 return ftdi_usb_open_dev(ftdi, dev);
00563             }
00564         }
00565     }
00566 
00567     // device not found
00568     ftdi_error_return(-3, "device not found");
00569 }
00570 
00579 int ftdi_usb_reset(struct ftdi_context *ftdi)
00580 {
00581     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
00582                         SIO_RESET_REQUEST, SIO_RESET_SIO,
00583                         ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
00584         ftdi_error_return(-1,"FTDI reset failed");
00585 
00586     // Invalidate data in the readbuffer
00587     ftdi->readbuffer_offset = 0;
00588     ftdi->readbuffer_remaining = 0;
00589 
00590     return 0;
00591 }
00592 
00601 int ftdi_usb_purge_rx_buffer(struct ftdi_context *ftdi)
00602 {
00603     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
00604                         SIO_RESET_REQUEST, SIO_RESET_PURGE_RX,
00605                         ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
00606         ftdi_error_return(-1, "FTDI purge of RX buffer failed");
00607 
00608     // Invalidate data in the readbuffer
00609     ftdi->readbuffer_offset = 0;
00610     ftdi->readbuffer_remaining = 0;
00611 
00612     return 0;
00613 }
00614 
00623 int ftdi_usb_purge_tx_buffer(struct ftdi_context *ftdi)
00624 {
00625     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
00626                         SIO_RESET_REQUEST, SIO_RESET_PURGE_TX,
00627                         ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
00628         ftdi_error_return(-1, "FTDI purge of TX buffer failed");
00629 
00630     return 0;
00631 }
00632 
00642 int ftdi_usb_purge_buffers(struct ftdi_context *ftdi)
00643 {
00644     int result;
00645 
00646     result = ftdi_usb_purge_rx_buffer(ftdi);
00647     if (result < 0)
00648         return -1;
00649 
00650     result = ftdi_usb_purge_tx_buffer(ftdi);
00651     if (result < 0)
00652         return -2;
00653 
00654     return 0;
00655 }
00656 
00666 int ftdi_usb_close(struct ftdi_context *ftdi)
00667 {
00668     int rtn = 0;
00669 
00670 #ifdef LIBFTDI_LINUX_ASYNC_MODE
00671     /* try to release some kernel resources */
00672     ftdi_async_complete(ftdi,1);
00673 #endif
00674 
00675     if (usb_release_interface(ftdi->usb_dev, ftdi->interface) != 0)
00676         rtn = -1;
00677 
00678     if (usb_close (ftdi->usb_dev) != 0)
00679         rtn = -2;
00680 
00681     return rtn;
00682 }
00683 
00684 /*
00685     ftdi_convert_baudrate returns nearest supported baud rate to that requested.
00686     Function is only used internally
00687     \internal
00688 */
00689 static int ftdi_convert_baudrate(int baudrate, struct ftdi_context *ftdi,
00690                                  unsigned short *value, unsigned short *index)
00691 {
00692     static const char am_adjust_up[8] = {0, 0, 0, 1, 0, 3, 2, 1};
00693     static const char am_adjust_dn[8] = {0, 0, 0, 1, 0, 1, 2, 3};
00694     static const char frac_code[8] = {0, 3, 2, 4, 1, 5, 6, 7};
00695     int divisor, best_divisor, best_baud, best_baud_diff;
00696     unsigned long encoded_divisor;
00697     int i;
00698 
00699     if (baudrate <= 0)
00700     {
00701         // Return error
00702         return -1;
00703     }
00704 
00705     divisor = 24000000 / baudrate;
00706 
00707     if (ftdi->type == TYPE_AM)
00708     {
00709         // Round down to supported fraction (AM only)
00710         divisor -= am_adjust_dn[divisor & 7];
00711     }
00712 
00713     // Try this divisor and the one above it (because division rounds down)
00714     best_divisor = 0;
00715     best_baud = 0;
00716     best_baud_diff = 0;
00717     for (i = 0; i < 2; i++)
00718     {
00719         int try_divisor = divisor + i;
00720         int baud_estimate;
00721         int baud_diff;
00722 
00723         // Round up to supported divisor value
00724         if (try_divisor <= 8)
00725         {
00726             // Round up to minimum supported divisor
00727             try_divisor = 8;
00728         }
00729         else if (ftdi->type != TYPE_AM && try_divisor < 12)
00730         {
00731             // BM doesn't support divisors 9 through 11 inclusive
00732             try_divisor = 12;
00733         }
00734         else if (divisor < 16)
00735         {
00736             // AM doesn't support divisors 9 through 15 inclusive
00737             try_divisor = 16;
00738         }
00739         else
00740         {
00741             if (ftdi->type == TYPE_AM)
00742             {
00743                 // Round up to supported fraction (AM only)
00744                 try_divisor += am_adjust_up[try_divisor & 7];
00745                 if (try_divisor > 0x1FFF8)
00746                 {
00747                     // Round down to maximum supported divisor value (for AM)
00748                     try_divisor = 0x1FFF8;
00749                 }
00750             }
00751             else
00752             {
00753                 if (try_divisor > 0x1FFFF)
00754                 {
00755                     // Round down to maximum supported divisor value (for BM)
00756                     try_divisor = 0x1FFFF;
00757                 }
00758             }
00759         }
00760         // Get estimated baud rate (to nearest integer)
00761         baud_estimate = (24000000 + (try_divisor / 2)) / try_divisor;
00762         // Get absolute difference from requested baud rate
00763         if (baud_estimate < baudrate)
00764         {
00765             baud_diff = baudrate - baud_estimate;
00766         }
00767         else
00768         {
00769             baud_diff = baud_estimate - baudrate;
00770         }
00771         if (i == 0 || baud_diff < best_baud_diff)
00772         {
00773             // Closest to requested baud rate so far
00774             best_divisor = try_divisor;
00775             best_baud = baud_estimate;
00776             best_baud_diff = baud_diff;
00777             if (baud_diff == 0)
00778             {
00779                 // Spot on! No point trying
00780                 break;
00781             }
00782         }
00783     }
00784     // Encode the best divisor value
00785     encoded_divisor = (best_divisor >> 3) | (frac_code[best_divisor & 7] << 14);
00786     // Deal with special cases for encoded value
00787     if (encoded_divisor == 1)
00788     {
00789         encoded_divisor = 0;    // 3000000 baud
00790     }
00791     else if (encoded_divisor == 0x4001)
00792     {
00793         encoded_divisor = 1;    // 2000000 baud (BM only)
00794     }
00795     // Split into "value" and "index" values
00796     *value = (unsigned short)(encoded_divisor & 0xFFFF);
00797     if (ftdi->type == TYPE_2232C)
00798     {
00799         *index = (unsigned short)(encoded_divisor >> 8);
00800         *index &= 0xFF00;
00801         *index |= ftdi->index;
00802     }
00803     else
00804         *index = (unsigned short)(encoded_divisor >> 16);
00805 
00806     // Return the nearest baud rate
00807     return best_baud;
00808 }
00809 
00820 int ftdi_set_baudrate(struct ftdi_context *ftdi, int baudrate)
00821 {
00822     unsigned short value, index;
00823     int actual_baudrate;
00824 
00825     if (ftdi->bitbang_enabled)
00826     {
00827         baudrate = baudrate*4;
00828     }
00829 
00830     actual_baudrate = ftdi_convert_baudrate(baudrate, ftdi, &value, &index);
00831     if (actual_baudrate <= 0)
00832         ftdi_error_return (-1, "Silly baudrate <= 0.");
00833 
00834     // Check within tolerance (about 5%)
00835     if ((actual_baudrate * 2 < baudrate /* Catch overflows */ )
00836             || ((actual_baudrate < baudrate)
00837                 ? (actual_baudrate * 21 < baudrate * 20)
00838                 : (baudrate * 21 < actual_baudrate * 20)))
00839         ftdi_error_return (-1, "Unsupported baudrate. Note: bitbang baudrates are automatically multiplied by 4");
00840 
00841     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
00842                         SIO_SET_BAUDRATE_REQUEST, value,
00843                         index, NULL, 0, ftdi->usb_write_timeout) != 0)
00844         ftdi_error_return (-2, "Setting new baudrate failed");
00845 
00846     ftdi->baudrate = baudrate;
00847     return 0;
00848 }
00849 
00863 int ftdi_set_line_property(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
00864                            enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity)
00865 {
00866     return ftdi_set_line_property2(ftdi, bits, sbit, parity, BREAK_OFF);
00867 }
00868 
00881 int ftdi_set_line_property2(struct ftdi_context *ftdi, enum ftdi_bits_type bits,
00882                             enum ftdi_stopbits_type sbit, enum ftdi_parity_type parity,
00883                             enum ftdi_break_type break_type)
00884 {
00885     unsigned short value = bits;
00886 
00887     switch (parity)
00888     {
00889         case NONE:
00890             value |= (0x00 << 8);
00891             break;
00892         case ODD:
00893             value |= (0x01 << 8);
00894             break;
00895         case EVEN:
00896             value |= (0x02 << 8);
00897             break;
00898         case MARK:
00899             value |= (0x03 << 8);
00900             break;
00901         case SPACE:
00902             value |= (0x04 << 8);
00903             break;
00904     }
00905 
00906     switch (sbit)
00907     {
00908         case STOP_BIT_1:
00909             value |= (0x00 << 11);
00910             break;
00911         case STOP_BIT_15:
00912             value |= (0x01 << 11);
00913             break;
00914         case STOP_BIT_2:
00915             value |= (0x02 << 11);
00916             break;
00917     }
00918 
00919     switch (break_type)
00920     {
00921         case BREAK_OFF:
00922             value |= (0x00 << 14);
00923             break;
00924         case BREAK_ON:
00925             value |= (0x01 << 14);
00926             break;
00927     }
00928 
00929     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
00930                         SIO_SET_DATA_REQUEST, value,
00931                         ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
00932         ftdi_error_return (-1, "Setting new line property failed");
00933 
00934     return 0;
00935 }
00936 
00947 int ftdi_write_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
00948 {
00949     int ret;
00950     int offset = 0;
00951     int total_written = 0;
00952 
00953     while (offset < size)
00954     {
00955         int write_size = ftdi->writebuffer_chunksize;
00956 
00957         if (offset+write_size > size)
00958             write_size = size-offset;
00959 
00960         ret = usb_bulk_write(ftdi->usb_dev, ftdi->in_ep, buf+offset, write_size, ftdi->usb_write_timeout);
00961         if (ret < 0)
00962             ftdi_error_return(ret, "usb bulk write failed");
00963 
00964         total_written += ret;
00965         offset += write_size;
00966     }
00967 
00968     return total_written;
00969 }
00970 
00971 #ifdef LIBFTDI_LINUX_ASYNC_MODE
00972 /* this is strongly dependent on libusb using the same struct layout. If libusb
00973    changes in some later version this may break horribly (this is for libusb 0.1.12) */
00974 struct usb_dev_handle
00975 {
00976     int fd;
00977     // some other stuff coming here we don't need
00978 };
00979 
00984 static int _usb_get_async_urbs_pending(struct ftdi_context *ftdi)
00985 {
00986     struct usbdevfs_urb *urb;
00987     int pending=0;
00988     unsigned int i;
00989 
00990     for (i=0; i < ftdi->async_usb_buffer_size; i++)
00991     {
00992         urb=&((struct usbdevfs_urb *)(ftdi->async_usb_buffer))[i];
00993         if (urb->usercontext != FTDI_URB_USERCONTEXT_COOKIE)
00994             pending++;
00995     }
00996 
00997     return pending;
00998 }
00999 
01010 static void _usb_async_cleanup(struct ftdi_context *ftdi, int wait_for_more, int timeout_msec)
01011 {
01012     struct timeval tv;
01013     struct usbdevfs_urb *urb=NULL;
01014     int ret;
01015     fd_set writefds;
01016     int keep_going=0;
01017 
01018     FD_ZERO(&writefds);
01019     FD_SET(ftdi->usb_dev->fd, &writefds);
01020 
01021     /* init timeout only once, select writes time left after call */
01022     tv.tv_sec = timeout_msec / 1000;
01023     tv.tv_usec = (timeout_msec % 1000) * 1000;
01024 
01025     do
01026     {
01027         while (_usb_get_async_urbs_pending(ftdi)
01028                 && (ret = ioctl(ftdi->usb_dev->fd, USBDEVFS_REAPURBNDELAY, &urb)) == -1
01029                 && errno == EAGAIN)
01030         {
01031             if (keep_going && !wait_for_more)
01032             {
01033                 /* don't wait if repeating only for keep_going */
01034                 keep_going=0;
01035                 break;
01036             }
01037 
01038             /* wait for timeout msec or something written ready */
01039             select(ftdi->usb_dev->fd+1, NULL, &writefds, NULL, &tv);
01040         }
01041 
01042         if (ret == 0 && urb != NULL)
01043         {
01044             /* got a free urb, mark it */
01045             urb->usercontext = FTDI_URB_USERCONTEXT_COOKIE;
01046 
01047             /* try to get more urbs that are ready now, but don't wait anymore */
01048             urb=NULL;
01049             keep_going=1;
01050         }
01051         else
01052         {
01053             /* no more urbs waiting */
01054             keep_going=0;
01055         }
01056     }
01057     while (keep_going);
01058 }
01059 
01067 void ftdi_async_complete(struct ftdi_context *ftdi, int wait_for_more)
01068 {
01069     _usb_async_cleanup(ftdi,wait_for_more,ftdi->usb_write_timeout);
01070 }
01071 
01077 static int _usb_bulk_write_async(struct ftdi_context *ftdi, int ep, char *bytes, int size)
01078 {
01079     struct usbdevfs_urb *urb;
01080     int bytesdone = 0, requested;
01081     int ret, cleanup_count;
01082     unsigned int i;
01083 
01084     do
01085     {
01086         /* find a free urb buffer we can use */
01087         urb=NULL;
01088         for (cleanup_count=0; urb==NULL && cleanup_count <= 1; cleanup_count++)
01089         {
01090             if (i==ftdi->async_usb_buffer_size)
01091             {
01092                 /* wait until some buffers are free */
01093                 _usb_async_cleanup(ftdi,0,ftdi->usb_write_timeout);
01094             }
01095 
01096             for (i=0; i < ftdi->async_usb_buffer_size; i++)
01097             {
01098                 urb=&((struct usbdevfs_urb *)(ftdi->async_usb_buffer))[i];
01099                 if (urb->usercontext == FTDI_URB_USERCONTEXT_COOKIE)
01100                     break;  /* found a free urb position */
01101                 urb=NULL;
01102             }
01103         }
01104 
01105         /* no free urb position found */
01106         if (urb==NULL)
01107             return -1;
01108 
01109         requested = size - bytesdone;
01110         if (requested > 4096)
01111             requested = 4096;
01112 
01113         memset(urb,0,sizeof(urb));
01114 
01115         urb->type = USBDEVFS_URB_TYPE_BULK;
01116         urb->endpoint = ep;
01117         urb->flags = 0;
01118         urb->buffer = bytes + bytesdone;
01119         urb->buffer_length = requested;
01120         urb->signr = 0;
01121         urb->actual_length = 0;
01122         urb->number_of_packets = 0;
01123         urb->usercontext = 0;
01124 
01125         do
01126         {
01127             ret = ioctl(ftdi->usb_dev->fd, USBDEVFS_SUBMITURB, urb);
01128         }
01129         while (ret < 0 && errno == EINTR);
01130         if (ret < 0)
01131             return ret;       /* the caller can read errno to get more info */
01132 
01133         bytesdone += requested;
01134     }
01135     while (bytesdone < size);
01136     return bytesdone;
01137 }
01138 
01157 int ftdi_write_data_async(struct ftdi_context *ftdi, unsigned char *buf, int size)
01158 {
01159     int ret;
01160     int offset = 0;
01161     int total_written = 0;
01162 
01163     while (offset < size)
01164     {
01165         int write_size = ftdi->writebuffer_chunksize;
01166 
01167         if (offset+write_size > size)
01168             write_size = size-offset;
01169 
01170         ret = _usb_bulk_write_async(ftdi, ftdi->in_ep, buf+offset, write_size);
01171         if (ret < 0)
01172             ftdi_error_return(ret, "usb bulk write async failed");
01173 
01174         total_written += ret;
01175         offset += write_size;
01176     }
01177 
01178     return total_written;
01179 }
01180 #endif // LIBFTDI_LINUX_ASYNC_MODE
01181 
01191 int ftdi_write_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
01192 {
01193     ftdi->writebuffer_chunksize = chunksize;
01194     return 0;
01195 }
01196 
01205 int ftdi_write_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
01206 {
01207     *chunksize = ftdi->writebuffer_chunksize;
01208     return 0;
01209 }
01210 
01227 int ftdi_read_data(struct ftdi_context *ftdi, unsigned char *buf, int size)
01228 {
01229     int offset = 0, ret = 1, i, num_of_chunks, chunk_remains;
01230     int packet_size;
01231 
01232     // New hi-speed devices from FTDI use a packet size of 512 bytes
01233     if (ftdi->type == TYPE_2232H || ftdi->type == TYPE_4232H)
01234         packet_size = 512;
01235     else
01236         packet_size = 64;
01237 
01238     // everything we want is still in the readbuffer?
01239     if (size <= ftdi->readbuffer_remaining)
01240     {
01241         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, size);
01242 
01243         // Fix offsets
01244         ftdi->readbuffer_remaining -= size;
01245         ftdi->readbuffer_offset += size;
01246 
01247         /* printf("Returning bytes from buffer: %d - remaining: %d\n", size, ftdi->readbuffer_remaining); */
01248 
01249         return size;
01250     }
01251     // something still in the readbuffer, but not enough to satisfy 'size'?
01252     if (ftdi->readbuffer_remaining != 0)
01253     {
01254         memcpy (buf, ftdi->readbuffer+ftdi->readbuffer_offset, ftdi->readbuffer_remaining);
01255 
01256         // Fix offset
01257         offset += ftdi->readbuffer_remaining;
01258     }
01259     // do the actual USB read
01260     while (offset < size && ret > 0)
01261     {
01262         ftdi->readbuffer_remaining = 0;
01263         ftdi->readbuffer_offset = 0;
01264         /* returns how much received */
01265         ret = usb_bulk_read (ftdi->usb_dev, ftdi->out_ep, ftdi->readbuffer, ftdi->readbuffer_chunksize, ftdi->usb_read_timeout);
01266         if (ret < 0)
01267             ftdi_error_return(ret, "usb bulk read failed");
01268 
01269         if (ret > 2)
01270         {
01271             // skip FTDI status bytes.
01272             // Maybe stored in the future to enable modem use
01273             num_of_chunks = ret / packet_size;
01274             chunk_remains = ret % packet_size;
01275             //printf("ret = %X, num_of_chunks = %X, chunk_remains = %X, readbuffer_offset = %X\n", ret, num_of_chunks, chunk_remains, ftdi->readbuffer_offset);
01276 
01277             ftdi->readbuffer_offset += 2;
01278             ret -= 2;
01279 
01280             if (ret > packet_size - 2)
01281             {
01282                 for (i = 1; i < num_of_chunks; i++)
01283                     memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
01284                              ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
01285                              packet_size - 2);
01286                 if (chunk_remains > 2)
01287                 {
01288                     memmove (ftdi->readbuffer+ftdi->readbuffer_offset+(packet_size - 2)*i,
01289                              ftdi->readbuffer+ftdi->readbuffer_offset+packet_size*i,
01290                              chunk_remains-2);
01291                     ret -= 2*num_of_chunks;
01292                 }
01293                 else
01294                     ret -= 2*(num_of_chunks-1)+chunk_remains;
01295             }
01296         }
01297         else if (ret <= 2)
01298         {
01299             // no more data to read?
01300             return offset;
01301         }
01302         if (ret > 0)
01303         {
01304             // data still fits in buf?
01305             if (offset+ret <= size)
01306             {
01307                 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, ret);
01308                 //printf("buf[0] = %X, buf[1] = %X\n", buf[0], buf[1]);
01309                 offset += ret;
01310 
01311                 /* Did we read exactly the right amount of bytes? */
01312                 if (offset == size)
01313                     //printf("read_data exact rem %d offset %d\n",
01314                     //ftdi->readbuffer_remaining, offset);
01315                     return offset;
01316             }
01317             else
01318             {
01319                 // only copy part of the data or size <= readbuffer_chunksize
01320                 int part_size = size-offset;
01321                 memcpy (buf+offset, ftdi->readbuffer+ftdi->readbuffer_offset, part_size);
01322 
01323                 ftdi->readbuffer_offset += part_size;
01324                 ftdi->readbuffer_remaining = ret-part_size;
01325                 offset += part_size;
01326 
01327                 /* printf("Returning part: %d - size: %d - offset: %d - ret: %d - remaining: %d\n",
01328                 part_size, size, offset, ret, ftdi->readbuffer_remaining); */
01329 
01330                 return offset;
01331             }
01332         }
01333     }
01334     // never reached
01335     return -127;
01336 }
01337 
01349 int ftdi_read_data_set_chunksize(struct ftdi_context *ftdi, unsigned int chunksize)
01350 {
01351     unsigned char *new_buf;
01352 
01353     // Invalidate all remaining data
01354     ftdi->readbuffer_offset = 0;
01355     ftdi->readbuffer_remaining = 0;
01356 
01357     if ((new_buf = (unsigned char *)realloc(ftdi->readbuffer, chunksize)) == NULL)
01358         ftdi_error_return(-1, "out of memory for readbuffer");
01359 
01360     ftdi->readbuffer = new_buf;
01361     ftdi->readbuffer_chunksize = chunksize;
01362 
01363     return 0;
01364 }
01365 
01374 int ftdi_read_data_get_chunksize(struct ftdi_context *ftdi, unsigned int *chunksize)
01375 {
01376     *chunksize = ftdi->readbuffer_chunksize;
01377     return 0;
01378 }
01379 
01380 
01393 int ftdi_enable_bitbang(struct ftdi_context *ftdi, unsigned char bitmask)
01394 {
01395     unsigned short usb_val;
01396 
01397     usb_val = bitmask; // low byte: bitmask
01398     /* FT2232C: Set bitbang_mode to 2 to enable SPI */
01399     usb_val |= (ftdi->bitbang_mode << 8);
01400 
01401     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
01402                         SIO_SET_BITMODE_REQUEST, usb_val, ftdi->index,
01403                         NULL, 0, ftdi->usb_write_timeout) != 0)
01404         ftdi_error_return(-1, "unable to enter bitbang mode. Perhaps not a BM type chip?");
01405 
01406     ftdi->bitbang_enabled = 1;
01407     return 0;
01408 }
01409 
01418 int ftdi_disable_bitbang(struct ftdi_context *ftdi)
01419 {
01420     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_SET_BITMODE_REQUEST, 0, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
01421         ftdi_error_return(-1, "unable to leave bitbang mode. Perhaps not a BM type chip?");
01422 
01423     ftdi->bitbang_enabled = 0;
01424     return 0;
01425 }
01426 
01438 int ftdi_set_bitmode(struct ftdi_context *ftdi, unsigned char bitmask, unsigned char mode)
01439 {
01440     unsigned short usb_val;
01441 
01442     usb_val = bitmask; // low byte: bitmask
01443     usb_val |= (mode << 8);
01444     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_SET_BITMODE_REQUEST, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
01445         ftdi_error_return(-1, "unable to configure bitbang mode. Perhaps not a 2232C type chip?");
01446 
01447     ftdi->bitbang_mode = mode;
01448     ftdi->bitbang_enabled = (mode == BITMODE_BITBANG || mode == BITMODE_SYNCBB)?1:0;
01449     return 0;
01450 }
01451 
01461 int ftdi_read_pins(struct ftdi_context *ftdi, unsigned char *pins)
01462 {
01463     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_READ_PINS_REQUEST, 0, ftdi->index, (char *)pins, 1, ftdi->usb_read_timeout) != 1)
01464         ftdi_error_return(-1, "read pins failed");
01465 
01466     return 0;
01467 }
01468 
01483 int ftdi_set_latency_timer(struct ftdi_context *ftdi, unsigned char latency)
01484 {
01485     unsigned short usb_val;
01486 
01487     if (latency < 1)
01488         ftdi_error_return(-1, "latency out of range. Only valid for 1-255");
01489 
01490     usb_val = latency;
01491     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_SET_LATENCY_TIMER_REQUEST, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
01492         ftdi_error_return(-2, "unable to set latency timer");
01493 
01494     return 0;
01495 }
01496 
01506 int ftdi_get_latency_timer(struct ftdi_context *ftdi, unsigned char *latency)
01507 {
01508     unsigned short usb_val;
01509     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_GET_LATENCY_TIMER_REQUEST, 0, ftdi->index, (char *)&usb_val, 1, ftdi->usb_read_timeout) != 1)
01510         ftdi_error_return(-1, "reading latency timer failed");
01511 
01512     *latency = (unsigned char)usb_val;
01513     return 0;
01514 }
01515 
01555 int ftdi_poll_modem_status(struct ftdi_context *ftdi, unsigned short *status)
01556 {
01557     char usb_val[2];
01558 
01559     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_POLL_MODEM_STATUS_REQUEST, 0, ftdi->index, usb_val, 2, ftdi->usb_read_timeout) != 2)
01560         ftdi_error_return(-1, "getting modem status failed");
01561 
01562     *status = (usb_val[1] << 8) | usb_val[0];
01563 
01564     return 0;
01565 }
01566 
01577 int ftdi_setflowctrl(struct ftdi_context *ftdi, int flowctrl)
01578 {
01579     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
01580                         SIO_SET_FLOW_CTRL_REQUEST, 0, (flowctrl | ftdi->index),
01581                         NULL, 0, ftdi->usb_write_timeout) != 0)
01582         ftdi_error_return(-1, "set flow control failed");
01583 
01584     return 0;
01585 }
01586 
01596 int ftdi_setdtr(struct ftdi_context *ftdi, int state)
01597 {
01598     unsigned short usb_val;
01599 
01600     if (state)
01601         usb_val = SIO_SET_DTR_HIGH;
01602     else
01603         usb_val = SIO_SET_DTR_LOW;
01604 
01605     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
01606                         SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
01607                         NULL, 0, ftdi->usb_write_timeout) != 0)
01608         ftdi_error_return(-1, "set dtr failed");
01609 
01610     return 0;
01611 }
01612 
01622 int ftdi_setrts(struct ftdi_context *ftdi, int state)
01623 {
01624     unsigned short usb_val;
01625 
01626     if (state)
01627         usb_val = SIO_SET_RTS_HIGH;
01628     else
01629         usb_val = SIO_SET_RTS_LOW;
01630 
01631     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
01632                         SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
01633                         NULL, 0, ftdi->usb_write_timeout) != 0)
01634         ftdi_error_return(-1, "set of rts failed");
01635 
01636     return 0;
01637 }
01638 
01649 int ftdi_setdtr_rts(struct ftdi_context *ftdi, int dtr, int rts)
01650 {
01651     unsigned short usb_val;
01652 
01653     if (dtr)
01654         usb_val = SIO_SET_DTR_HIGH;
01655     else
01656         usb_val = SIO_SET_DTR_LOW;
01657 
01658     if (rts)
01659         usb_val |= SIO_SET_RTS_HIGH;
01660     else
01661         usb_val |= SIO_SET_RTS_LOW;
01662 
01663     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
01664                         SIO_SET_MODEM_CTRL_REQUEST, usb_val, ftdi->index,
01665                         NULL, 0, ftdi->usb_write_timeout) != 0)
01666         ftdi_error_return(-1, "set of rts/dtr failed");
01667 
01668     return 0;
01669 }
01670 
01681 int ftdi_set_event_char(struct ftdi_context *ftdi,
01682                         unsigned char eventch, unsigned char enable)
01683 {
01684     unsigned short usb_val;
01685 
01686     usb_val = eventch;
01687     if (enable)
01688         usb_val |= 1 << 8;
01689 
01690     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_SET_EVENT_CHAR_REQUEST, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
01691         ftdi_error_return(-1, "setting event character failed");
01692 
01693     return 0;
01694 }
01695 
01706 int ftdi_set_error_char(struct ftdi_context *ftdi,
01707                         unsigned char errorch, unsigned char enable)
01708 {
01709     unsigned short usb_val;
01710 
01711     usb_val = errorch;
01712     if (enable)
01713         usb_val |= 1 << 8;
01714 
01715     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_SET_ERROR_CHAR_REQUEST, usb_val, ftdi->index, NULL, 0, ftdi->usb_write_timeout) != 0)
01716         ftdi_error_return(-1, "setting error character failed");
01717 
01718     return 0;
01719 }
01720 
01729 void ftdi_eeprom_setsize(struct ftdi_context *ftdi, struct ftdi_eeprom *eeprom, int size)
01730 {
01731     ftdi->eeprom_size=size;
01732     eeprom->size=size;
01733 }
01734 
01740 void ftdi_eeprom_initdefaults(struct ftdi_eeprom *eeprom)
01741 {
01742     eeprom->vendor_id = 0x0403;
01743     eeprom->product_id = 0x6001;
01744 
01745     eeprom->self_powered = 1;
01746     eeprom->remote_wakeup = 1;
01747     eeprom->BM_type_chip = 1;
01748 
01749     eeprom->in_is_isochronous = 0;
01750     eeprom->out_is_isochronous = 0;
01751     eeprom->suspend_pull_downs = 0;
01752 
01753     eeprom->use_serial = 0;
01754     eeprom->change_usb_version = 0;
01755     eeprom->usb_version = 0x0200;
01756     eeprom->max_power = 0;
01757 
01758     eeprom->manufacturer = NULL;
01759     eeprom->product = NULL;
01760     eeprom->serial = NULL;
01761 
01762     eeprom->size = FTDI_DEFAULT_EEPROM_SIZE;
01763 }
01764 
01775 int ftdi_eeprom_build(struct ftdi_eeprom *eeprom, unsigned char *output)
01776 {
01777     unsigned char i, j;
01778     unsigned short checksum, value;
01779     unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
01780     int size_check;
01781 
01782     if (eeprom->manufacturer != NULL)
01783         manufacturer_size = strlen(eeprom->manufacturer);
01784     if (eeprom->product != NULL)
01785         product_size = strlen(eeprom->product);
01786     if (eeprom->serial != NULL)
01787         serial_size = strlen(eeprom->serial);
01788 
01789     size_check = eeprom->size;
01790     size_check -= 28; // 28 are always in use (fixed)
01791 
01792     // Top half of a 256byte eeprom is used just for strings and checksum
01793     // it seems that the FTDI chip will not read these strings from the lower half
01794     // Each string starts with two bytes; offset and type (0x03 for string)
01795     // the checksum needs two bytes, so without the string data that 8 bytes from the top half
01796     if (eeprom->size>=256)size_check = 120;
01797     size_check -= manufacturer_size*2;
01798     size_check -= product_size*2;
01799     size_check -= serial_size*2;
01800 
01801     // eeprom size exceeded?
01802     if (size_check < 0)
01803         return (-1);
01804 
01805     // empty eeprom
01806     memset (output, 0, eeprom->size);
01807 
01808     // Addr 00: Stay 00 00
01809     // Addr 02: Vendor ID
01810     output[0x02] = eeprom->vendor_id;
01811     output[0x03] = eeprom->vendor_id >> 8;
01812 
01813     // Addr 04: Product ID
01814     output[0x04] = eeprom->product_id;
01815     output[0x05] = eeprom->product_id >> 8;
01816 
01817     // Addr 06: Device release number (0400h for BM features)
01818     output[0x06] = 0x00;
01819 
01820     if (eeprom->BM_type_chip == 1)
01821         output[0x07] = 0x04;
01822     else
01823         output[0x07] = 0x02;
01824 
01825     // Addr 08: Config descriptor
01826     // Bit 7: always 1
01827     // Bit 6: 1 if this device is self powered, 0 if bus powered
01828     // Bit 5: 1 if this device uses remote wakeup
01829     // Bit 4: 1 if this device is battery powered
01830     j = 0x80;
01831     if (eeprom->self_powered == 1)
01832         j |= 0x40;
01833     if (eeprom->remote_wakeup == 1)
01834         j |= 0x20;
01835     output[0x08] = j;
01836 
01837     // Addr 09: Max power consumption: max power = value * 2 mA
01838     output[0x09] = eeprom->max_power;
01839 
01840     // Addr 0A: Chip configuration
01841     // Bit 7: 0 - reserved
01842     // Bit 6: 0 - reserved
01843     // Bit 5: 0 - reserved
01844     // Bit 4: 1 - Change USB version
01845     // Bit 3: 1 - Use the serial number string
01846     // Bit 2: 1 - Enable suspend pull downs for lower power
01847     // Bit 1: 1 - Out EndPoint is Isochronous
01848     // Bit 0: 1 - In EndPoint is Isochronous
01849     //
01850     j = 0;
01851     if (eeprom->in_is_isochronous == 1)
01852         j = j | 1;
01853     if (eeprom->out_is_isochronous == 1)
01854         j = j | 2;
01855     if (eeprom->suspend_pull_downs == 1)
01856         j = j | 4;
01857     if (eeprom->use_serial == 1)
01858         j = j | 8;
01859     if (eeprom->change_usb_version == 1)
01860         j = j | 16;
01861     output[0x0A] = j;
01862 
01863     // Addr 0B: reserved
01864     output[0x0B] = 0x00;
01865 
01866     // Addr 0C: USB version low byte when 0x0A bit 4 is set
01867     // Addr 0D: USB version high byte when 0x0A bit 4 is set
01868     if (eeprom->change_usb_version == 1)
01869     {
01870         output[0x0C] = eeprom->usb_version;
01871         output[0x0D] = eeprom->usb_version >> 8;
01872     }
01873 
01874 
01875     // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
01876     // Addr 0F: Length of manufacturer string
01877     output[0x0F] = manufacturer_size*2 + 2;
01878 
01879     // Addr 10: Offset of the product string + 0x80, calculated later
01880     // Addr 11: Length of product string
01881     output[0x11] = product_size*2 + 2;
01882 
01883     // Addr 12: Offset of the serial string + 0x80, calculated later
01884     // Addr 13: Length of serial string
01885     output[0x13] = serial_size*2 + 2;
01886 
01887     // Dynamic content
01888     i=0x14;
01889     if (eeprom->size>=256) i = 0x80;
01890 
01891 
01892     // Output manufacturer
01893     output[0x0E] = i | 0x80;  // calculate offset
01894     output[i++] = manufacturer_size*2 + 2;
01895     output[i++] = 0x03; // type: string
01896     for (j = 0; j < manufacturer_size; j++)
01897     {
01898         output[i] = eeprom->manufacturer[j], i++;
01899         output[i] = 0x00, i++;
01900     }
01901 
01902     // Output product name
01903     output[0x10] = i | 0x80;  // calculate offset
01904     output[i] = product_size*2 + 2, i++;
01905     output[i] = 0x03, i++;
01906     for (j = 0; j < product_size; j++)
01907     {
01908         output[i] = eeprom->product[j], i++;
01909         output[i] = 0x00, i++;
01910     }
01911 
01912     // Output serial
01913     output[0x12] = i | 0x80; // calculate offset
01914     output[i] = serial_size*2 + 2, i++;
01915     output[i] = 0x03, i++;
01916     for (j = 0; j < serial_size; j++)
01917     {
01918         output[i] = eeprom->serial[j], i++;
01919         output[i] = 0x00, i++;
01920     }
01921 
01922     // calculate checksum
01923     checksum = 0xAAAA;
01924 
01925     for (i = 0; i < eeprom->size/2-1; i++)
01926     {
01927         value = output[i*2];
01928         value += output[(i*2)+1] << 8;
01929 
01930         checksum = value^checksum;
01931         checksum = (checksum << 1) | (checksum >> 15);
01932     }
01933 
01934     output[eeprom->size-2] = checksum;
01935     output[eeprom->size-1] = checksum >> 8;
01936 
01937     return size_check;
01938 }
01939 
01953 int ftdi_eeprom_decode(struct ftdi_eeprom *eeprom, unsigned char *buf, int size)
01954 {
01955     unsigned char i, j;
01956     unsigned short checksum, eeprom_checksum, value;
01957     unsigned char manufacturer_size = 0, product_size = 0, serial_size = 0;
01958     int size_check;
01959     int eeprom_size = 128;
01960 #if 0
01961     size_check = eeprom->size;
01962     size_check -= 28; // 28 are always in use (fixed)
01963 
01964     // Top half of a 256byte eeprom is used just for strings and checksum
01965     // it seems that the FTDI chip will not read these strings from the lower half
01966     // Each string starts with two bytes; offset and type (0x03 for string)
01967     // the checksum needs two bytes, so without the string data that 8 bytes from the top half
01968     if (eeprom->size>=256)size_check = 120;
01969     size_check -= manufacturer_size*2;
01970     size_check -= product_size*2;
01971     size_check -= serial_size*2;
01972 
01973     // eeprom size exceeded?
01974     if (size_check < 0)
01975         return (-1);
01976 #endif
01977 
01978     // empty eeprom struct
01979     memset(eeprom, 0, sizeof(struct ftdi_eeprom));
01980 
01981     // Addr 00: Stay 00 00
01982 
01983     // Addr 02: Vendor ID
01984     eeprom->vendor_id = buf[0x02] + (buf[0x03] << 8);
01985 
01986     // Addr 04: Product ID
01987     eeprom->product_id = buf[0x04] + (buf[0x05] << 8);
01988 
01989     value = buf[0x06] + (buf[0x07]<<8);
01990     switch (value)
01991     {
01992         case 0x0400:
01993             eeprom->BM_type_chip = 1;
01994             break;
01995         case 0x0200:
01996             eeprom->BM_type_chip = 0;
01997             break;
01998         default: // Unknown device
01999             eeprom->BM_type_chip = 0;
02000             break;
02001     }
02002 
02003     // Addr 08: Config descriptor
02004     // Bit 7: always 1
02005     // Bit 6: 1 if this device is self powered, 0 if bus powered
02006     // Bit 5: 1 if this device uses remote wakeup
02007     // Bit 4: 1 if this device is battery powered
02008     j = buf[0x08];
02009     if (j&0x40) eeprom->self_powered = 1;
02010     if (j&0x20) eeprom->remote_wakeup = 1;
02011 
02012     // Addr 09: Max power consumption: max power = value * 2 mA
02013     eeprom->max_power = buf[0x09];
02014 
02015     // Addr 0A: Chip configuration
02016     // Bit 7: 0 - reserved
02017     // Bit 6: 0 - reserved
02018     // Bit 5: 0 - reserved
02019     // Bit 4: 1 - Change USB version
02020     // Bit 3: 1 - Use the serial number string
02021     // Bit 2: 1 - Enable suspend pull downs for lower power
02022     // Bit 1: 1 - Out EndPoint is Isochronous
02023     // Bit 0: 1 - In EndPoint is Isochronous
02024     //
02025     j = buf[0x0A];
02026     if (j&0x01) eeprom->in_is_isochronous = 1;
02027     if (j&0x02) eeprom->out_is_isochronous = 1;
02028     if (j&0x04) eeprom->suspend_pull_downs = 1;
02029     if (j&0x08) eeprom->use_serial = 1;
02030     if (j&0x10) eeprom->change_usb_version = 1;
02031 
02032     // Addr 0B: reserved
02033 
02034     // Addr 0C: USB version low byte when 0x0A bit 4 is set
02035     // Addr 0D: USB version high byte when 0x0A bit 4 is set
02036     if (eeprom->change_usb_version == 1)
02037     {
02038         eeprom->usb_version = buf[0x0C] + (buf[0x0D] << 8);
02039     }
02040 
02041     // Addr 0E: Offset of the manufacturer string + 0x80, calculated later
02042     // Addr 0F: Length of manufacturer string
02043     manufacturer_size = buf[0x0F]/2;
02044     if (manufacturer_size > 0) eeprom->manufacturer = malloc(manufacturer_size);
02045     else eeprom->manufacturer = NULL;
02046 
02047     // Addr 10: Offset of the product string + 0x80, calculated later
02048     // Addr 11: Length of product string
02049     product_size = buf[0x11]/2;
02050     if (product_size > 0) eeprom->product = malloc(product_size);
02051     else eeprom->product = NULL;
02052 
02053     // Addr 12: Offset of the serial string + 0x80, calculated later
02054     // Addr 13: Length of serial string
02055     serial_size = buf[0x13]/2;
02056     if (serial_size > 0) eeprom->serial = malloc(serial_size);
02057     else eeprom->serial = NULL;
02058 
02059     // Decode manufacturer
02060     i = buf[0x0E] & 0x7f; // offset
02061     for (j=0;j<manufacturer_size-1;j++)
02062     {
02063         eeprom->manufacturer[j] = buf[2*j+i+2];
02064     }
02065     eeprom->manufacturer[j] = '\0';
02066 
02067     // Decode product name
02068     i = buf[0x10] & 0x7f; // offset
02069     for (j=0;j<product_size-1;j++)
02070     {
02071         eeprom->product[j] = buf[2*j+i+2];
02072     }
02073     eeprom->product[j] = '\0';
02074 
02075     // Decode serial
02076     i = buf[0x12] & 0x7f; // offset
02077     for (j=0;j<serial_size-1;j++)
02078     {
02079         eeprom->serial[j] = buf[2*j+i+2];
02080     }
02081     eeprom->serial[j] = '\0';
02082 
02083     // verify checksum
02084     checksum = 0xAAAA;
02085 
02086     for (i = 0; i < eeprom_size/2-1; i++)
02087     {
02088         value = buf[i*2];
02089         value += buf[(i*2)+1] << 8;
02090 
02091         checksum = value^checksum;
02092         checksum = (checksum << 1) | (checksum >> 15);
02093     }
02094 
02095     eeprom_checksum = buf[eeprom_size-2] + (buf[eeprom_size-1] << 8);
02096 
02097     if (eeprom_checksum != checksum)
02098     {
02099         fprintf(stderr, "Checksum Error: %04x %04x\n", checksum, eeprom_checksum);
02100         return -1;
02101     }
02102 
02103     return 0;
02104 }
02105 
02115 int ftdi_read_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
02116 {
02117     int i;
02118 
02119     for (i = 0; i < ftdi->eeprom_size/2; i++)
02120     {
02121         if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_READ_EEPROM_REQUEST, 0, i, eeprom+(i*2), 2, ftdi->usb_read_timeout) != 2)
02122             ftdi_error_return(-1, "reading eeprom failed");
02123     }
02124 
02125     return 0;
02126 }
02127 
02128 /*
02129     ftdi_read_chipid_shift does the bitshift operation needed for the FTDIChip-ID
02130     Function is only used internally
02131     \internal
02132 */
02133 static unsigned char ftdi_read_chipid_shift(unsigned char value)
02134 {
02135     return ((value & 1) << 1) |
02136            ((value & 2) << 5) |
02137            ((value & 4) >> 2) |
02138            ((value & 8) << 4) |
02139            ((value & 16) >> 1) |
02140            ((value & 32) >> 1) |
02141            ((value & 64) >> 4) |
02142            ((value & 128) >> 2);
02143 }
02144 
02154 int ftdi_read_chipid(struct ftdi_context *ftdi, unsigned int *chipid)
02155 {
02156     unsigned int a = 0, b = 0;
02157 
02158     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_READ_EEPROM_REQUEST, 0, 0x43, (char *)&a, 2, ftdi->usb_read_timeout) == 2)
02159     {
02160         a = a << 8 | a >> 8;
02161         if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE, SIO_READ_EEPROM_REQUEST, 0, 0x44, (char *)&b, 2, ftdi->usb_read_timeout) == 2)
02162         {
02163             b = b << 8 | b >> 8;
02164             a = (a << 16) | (b & 0xFFFF);
02165             a = ftdi_read_chipid_shift(a) | ftdi_read_chipid_shift(a>>8)<<8
02166                 | ftdi_read_chipid_shift(a>>16)<<16 | ftdi_read_chipid_shift(a>>24)<<24;
02167             *chipid = a ^ 0xa5f0f7d1;
02168             return 0;
02169         }
02170     }
02171 
02172     ftdi_error_return(-1, "read of FTDIChip-ID failed");
02173 }
02174 
02185 int ftdi_read_eeprom_getsize(struct ftdi_context *ftdi, unsigned char *eeprom, int maxsize)
02186 {
02187     int i=0,j,minsize=32;
02188     int size=minsize;
02189 
02190     do
02191     {
02192         for (j = 0; i < maxsize/2 && j<size; j++)
02193         {
02194             if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_IN_REQTYPE,
02195                                 SIO_READ_EEPROM_REQUEST, 0, i,
02196                                 eeprom+(i*2), 2, ftdi->usb_read_timeout) != 2)
02197                 ftdi_error_return(-1, "reading eeprom failed");
02198             i++;
02199         }
02200         size*=2;
02201     }
02202     while (size<=maxsize && memcmp(eeprom,&eeprom[size/2],size/2)!=0);
02203 
02204     return size/2;
02205 }
02206 
02216 int ftdi_write_eeprom(struct ftdi_context *ftdi, unsigned char *eeprom)
02217 {
02218     unsigned short usb_val, status;
02219     int i, ret;
02220 
02221     /* These commands were traced while running MProg */
02222     if ((ret = ftdi_usb_reset(ftdi)) != 0)
02223         return ret;
02224     if ((ret = ftdi_poll_modem_status(ftdi, &status)) != 0)
02225         return ret;
02226     if ((ret = ftdi_set_latency_timer(ftdi, 0x77)) != 0)
02227         return ret;
02228 
02229     for (i = 0; i < ftdi->eeprom_size/2; i++)
02230     {
02231         usb_val = eeprom[i*2];
02232         usb_val += eeprom[(i*2)+1] << 8;
02233         if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE,
02234                             SIO_WRITE_EEPROM_REQUEST, usb_val, i,
02235                             NULL, 0, ftdi->usb_write_timeout) != 0)
02236             ftdi_error_return(-1, "unable to write eeprom");
02237     }
02238 
02239     return 0;
02240 }
02241 
02252 int ftdi_erase_eeprom(struct ftdi_context *ftdi)
02253 {
02254     if (usb_control_msg(ftdi->usb_dev, FTDI_DEVICE_OUT_REQTYPE, SIO_ERASE_EEPROM_REQUEST, 0, 0, NULL, 0, ftdi->usb_write_timeout) != 0)
02255         ftdi_error_return(-1, "unable to erase eeprom");
02256 
02257     return 0;
02258 }
02259 
02267 char *ftdi_get_error_string (struct ftdi_context *ftdi)
02268 {
02269     return ftdi->error_str;
02270 }
02271 
02272 /* @} end of doxygen libftdi group */

Generated on Tue Jun 12 16:40:47 2012 for libftdi by  doxygen 1.4.6