linux-old/drivers/usb/CDCEther.c
<<
>>
Prefs
   1// Portions of this file taken from
   2// Petko Manolov - Petkan (petkan@dce.bg)
   3// from his driver pegasus.c
   4
   5/*
   6 * This program is free software; you can redistribute it and/or modify
   7 * it under the terms of the GNU General Public License as published by
   8 * the Free Software Foundation; either version 2 of the License, or
   9 * (at your option) any later version.
  10 *
  11 * This program is distributed in the hope that it will be useful,
  12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14 * GNU General Public License for more details.
  15 *
  16 * You should have received a copy of the GNU General Public License
  17 * along with this program; if not, write to the Free Software
  18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  19 */
  20
  21
  22#include <linux/sched.h>
  23#include <linux/slab.h>
  24#include <linux/init.h>
  25#include <linux/delay.h>
  26#include <linux/netdevice.h>
  27#include <linux/etherdevice.h>
  28#include <linux/module.h>
  29#include <linux/ethtool.h>
  30#include <asm/uaccess.h>
  31
  32#define DEBUG
  33#include <linux/usb.h>
  34
  35#include "CDCEther.h"
  36
  37#define SHORT_DRIVER_DESC "CDC Ethernet Class"
  38#define DRIVER_VERSION "0.98.6"
  39
  40static const char driver_name[] = "CDCEther";
  41static const char *version = __FILE__ ": " DRIVER_VERSION " 7 Jan 2002 Brad Hards and another";
  42// We only try to claim CDC Ethernet model devices */
  43static struct usb_device_id CDCEther_ids[] = {
  44        { USB_INTERFACE_INFO(USB_CLASS_COMM, 6, 0) },
  45        { }
  46};
  47
  48/*
  49 * module parameter that provides an alternate upper limit on the
  50 * number of multicast filters we use, with a default to use all
  51 * the filters available to us. Note that the actual number used
  52 * is the lesser of this parameter and the number returned in the
  53 * descriptor for the particular device. See Table 41 of the CDC
  54 * spec for more info on the descriptor limit.
  55 */
  56static int multicast_filter_limit = 32767;
  57
  58//////////////////////////////////////////////////////////////////////////////
  59// Callback routines from USB device /////////////////////////////////////////
  60//////////////////////////////////////////////////////////////////////////////
  61
  62static void read_bulk_callback( struct urb *urb )
  63{
  64        ether_dev_t *ether_dev = urb->context;
  65        struct net_device *net;
  66        int count = urb->actual_length, res;
  67        struct sk_buff  *skb;
  68
  69        switch ( urb->status ) {
  70                case USB_ST_NOERROR:
  71                        break;
  72                case USB_ST_URB_KILLED:
  73                        return;
  74                default:
  75                        dbg("rx status %d", urb->status);
  76        }
  77
  78        // Sanity check
  79        if ( !ether_dev || !(ether_dev->flags & CDC_ETHER_RUNNING) ) {
  80                dbg("BULK IN callback but driver is not active!");
  81                return;
  82        }
  83
  84        net = ether_dev->net;
  85        if ( !netif_device_present(net) ) {
  86                // Somebody killed our network interface...
  87                return;
  88        }
  89
  90        if ( ether_dev->flags & CDC_ETHER_RX_BUSY ) {
  91                // Are we already trying to receive a frame???
  92                ether_dev->stats.rx_errors++;
  93                dbg("ether_dev Rx busy");
  94                return;
  95        }
  96
  97        // We are busy, leave us alone!
  98        ether_dev->flags |= CDC_ETHER_RX_BUSY;
  99
 100        switch ( urb->status ) {
 101                case USB_ST_NOERROR:
 102                        break;
 103                case USB_ST_NORESPONSE:
 104                        dbg( "no repsonse in BULK IN" );
 105                        ether_dev->flags &= ~CDC_ETHER_RX_BUSY;
 106                        break;
 107                default:
 108                        dbg( "%s: RX status %d", net->name, urb->status );
 109                        goto goon;
 110        }
 111
 112        // Check to make sure we got some data...
 113        if ( !count ) {
 114                // We got no data!!!
 115                goto goon;
 116        }
 117
 118        // Tell the kernel we want some memory
 119        if ( !(skb = dev_alloc_skb(count)) ) {
 120                // We got no receive buffer.
 121                goto goon;
 122        }
 123
 124        // Here's where it came from
 125        skb->dev = net;
 126        
 127        // Now we copy it over
 128        eth_copy_and_sum(skb, ether_dev->rx_buff, count, 0);
 129        
 130        // Not sure
 131        skb_put(skb, count);
 132        // Not sure here either
 133        skb->protocol = eth_type_trans(skb, net);
 134        
 135        // Ship it off to the kernel
 136        netif_rx(skb);
 137        
 138        // update out statistics
 139        ether_dev->stats.rx_packets++;
 140        ether_dev->stats.rx_bytes += count;
 141
 142goon:
 143        // Prep the USB to wait for another frame
 144        FILL_BULK_URB( &ether_dev->rx_urb, ether_dev->usb,
 145                        usb_rcvbulkpipe(ether_dev->usb, ether_dev->data_ep_in),
 146                        ether_dev->rx_buff, ether_dev->wMaxSegmentSize, 
 147                        read_bulk_callback, ether_dev );
 148                        
 149        // Give this to the USB subsystem so it can tell us 
 150        // when more data arrives.
 151        if ( (res = usb_submit_urb(&ether_dev->rx_urb)) ) {
 152                warn("%s failed submit rx_urb %d", __FUNCTION__, res);
 153        }
 154        
 155        // We are no longer busy, show us the frames!!!
 156        ether_dev->flags &= ~CDC_ETHER_RX_BUSY;
 157}
 158
 159static void write_bulk_callback( struct urb *urb )
 160{
 161        ether_dev_t *ether_dev = urb->context;
 162
 163        // Sanity check
 164        if ( !ether_dev || !(ether_dev->flags & CDC_ETHER_RUNNING) ) {
 165                // We are insane!!!
 166                err( "write_bulk_callback: device not running" );
 167                return;
 168        }
 169
 170        // Do we still have a valid kernel network device?
 171        if ( !netif_device_present(ether_dev->net) ) {
 172                // Someone killed our network interface.
 173                err( "write_bulk_callback: net device not present" );
 174                return;
 175        }
 176
 177        // Hmm...  What on Earth could have happened???
 178        if ( urb->status ) {
 179                dbg("%s: TX status %d", ether_dev->net->name, urb->status);
 180        }
 181
 182        // Update the network interface and tell it we are
 183        // ready for another frame
 184        ether_dev->net->trans_start = jiffies;
 185        netif_wake_queue( ether_dev->net );
 186
 187}
 188
 189#if 0
 190static void setpktfilter_done( struct urb *urb )
 191{
 192        ether_dev_t *ether_dev = urb->context;
 193        struct net_device *net;
 194
 195        if ( !ether_dev )
 196                return;
 197        dbg("got ctrl callback for setting packet filter");
 198        switch ( urb->status ) {
 199                case USB_ST_NOERROR:
 200                        break;
 201                case USB_ST_URB_KILLED:
 202                        return;
 203                default:
 204                        dbg("intr status %d", urb->status);
 205        }
 206}
 207#endif 
 208
 209static void intr_callback( struct urb *urb )
 210{
 211        ether_dev_t *ether_dev = urb->context;
 212        struct net_device *net;
 213        struct usb_ctrlrequest *event;
 214#define bNotification   bRequest
 215
 216        if ( !ether_dev )
 217                return;
 218        net = ether_dev->net;
 219        switch ( urb->status ) {
 220                case USB_ST_NOERROR:
 221                        break;
 222                case USB_ST_URB_KILLED:
 223                default:
 224                        dbg("%s intr status %d", net->name, urb->status);
 225                        return;
 226        }
 227
 228        event = urb->transfer_buffer;
 229        if (event->bRequestType != 0xA1)
 230                dbg ("%s unknown event type %x", net->name,
 231                        event->bRequestType);
 232        else switch (event->bNotification) {
 233        case 0x00:              // NETWORK CONNECTION
 234                dbg ("%s network %s", net->name,
 235                        event->wValue ? "connect" : "disconnect");
 236                if (event->wValue)
 237                        netif_carrier_on (net);
 238                else
 239                        netif_carrier_off (net);
 240                break;
 241        case 0x2A:              // CONNECTION SPEED CHANGE
 242                dbg ("%s speed change", net->name);
 243                /* ignoring eight bytes of data */
 244                break;
 245        case 0x01:              // RESPONSE AVAILABLE (none requested)
 246        default:                // else undefined for CDC Ether
 247                err ("%s illegal notification %02x", net->name,
 248                        event->bNotification);
 249        }
 250}
 251
 252//////////////////////////////////////////////////////////////////////////////
 253// Routines for turning net traffic on and off on the USB side ///////////////
 254//////////////////////////////////////////////////////////////////////////////
 255
 256static inline int enable_net_traffic( ether_dev_t *ether_dev )
 257{
 258        struct usb_device *usb = ether_dev->usb;
 259
 260        // Here would be the time to set the data interface to the configuration where
 261        // it has two endpoints that use a protocol we can understand.
 262
 263        if (usb_set_interface( usb,
 264                                ether_dev->data_bInterfaceNumber,
 265                                ether_dev->data_bAlternateSetting_with_traffic ) )  {
 266                err("usb_set_interface() failed" );
 267                err("Attempted to set interface %d", ether_dev->data_bInterfaceNumber);
 268                err("To alternate setting       %d", ether_dev->data_bAlternateSetting_with_traffic);
 269                return -1;
 270        }
 271        return 0;
 272}
 273
 274static inline void disable_net_traffic( ether_dev_t *ether_dev )
 275{
 276        // The thing to do is to set the data interface to the alternate setting that has
 277        // no endpoints.  This is what the spec suggests.
 278
 279        if (ether_dev->data_interface_altset_num_without_traffic >= 0 ) {
 280                if (usb_set_interface( ether_dev->usb,
 281                                        ether_dev->data_bInterfaceNumber,
 282                                        ether_dev->data_bAlternateSetting_without_traffic ) )   {
 283                        err("usb_set_interface() failed");
 284                }
 285        } else {
 286                // Some devices just may not support this...
 287                warn("No way to disable net traffic");
 288        }
 289}
 290
 291//////////////////////////////////////////////////////////////////////////////
 292// Callback routines for kernel Ethernet Device //////////////////////////////
 293//////////////////////////////////////////////////////////////////////////////
 294
 295static void CDCEther_tx_timeout( struct net_device *net )
 296{
 297        ether_dev_t *ether_dev = net->priv;
 298
 299        // Sanity check
 300        if ( !ether_dev ) {
 301                // Seems to be a case of insanity here
 302                return;
 303        }
 304
 305        // Tell syslog we are hosed.
 306        warn("%s: Tx timed out.", net->name);
 307        
 308        // Tear the waiting frame off the list
 309        ether_dev->tx_urb.transfer_flags |= USB_ASYNC_UNLINK;
 310        usb_unlink_urb( &ether_dev->tx_urb );
 311        
 312        // Update statistics
 313        ether_dev->stats.tx_errors++;
 314}
 315
 316static int CDCEther_start_xmit( struct sk_buff *skb, struct net_device *net )
 317{
 318        ether_dev_t     *ether_dev = net->priv;
 319        int     res;
 320
 321        // Tell the kernel, "No more frames 'til we are done
 322        // with this one.'
 323        netif_stop_queue( net );
 324
 325        // Copy it from kernel memory to OUR memory
 326        memcpy(ether_dev->tx_buff, skb->data, skb->len);
 327
 328        // Fill in the URB for shipping it out.
 329        FILL_BULK_URB( &ether_dev->tx_urb, ether_dev->usb,
 330                        usb_sndbulkpipe(ether_dev->usb, ether_dev->data_ep_out),
 331                        ether_dev->tx_buff, ether_dev->wMaxSegmentSize, 
 332                        write_bulk_callback, ether_dev );
 333
 334        // Tell the URB how much it will be transporting today
 335        ether_dev->tx_urb.transfer_buffer_length = skb->len;
 336
 337        /* Deal with the Zero Length packet problem, I hope */
 338        ether_dev->tx_urb.transfer_flags |= USB_ZERO_PACKET;
 339
 340        // Send the URB on its merry way.
 341        if ((res = usb_submit_urb(&ether_dev->tx_urb)))  {
 342                // Hmm...  It didn't go. Tell someone...
 343                warn("failed tx_urb %d", res);
 344                // update some stats...
 345                ether_dev->stats.tx_errors++;
 346                // and tell the kernel to give us another.
 347                // Maybe we'll get it right next time.
 348                netif_start_queue( net );
 349        } else {
 350                // Okay, it went out.
 351                // Update statistics
 352                ether_dev->stats.tx_packets++;
 353                ether_dev->stats.tx_bytes += skb->len;
 354                // And tell the kernel when the last transmit occurred.
 355                net->trans_start = jiffies;
 356        }
 357
 358        // We are done with the kernel's memory
 359        dev_kfree_skb(skb);
 360
 361        // We are done here.
 362        return 0;
 363}
 364
 365//////////////////////////////////////////////////////////////////////////////
 366// Standard routines for kernel Ethernet Device //////////////////////////////
 367//////////////////////////////////////////////////////////////////////////////
 368static struct net_device_stats *CDCEther_netdev_stats( struct net_device *net )
 369{
 370        // Easy enough!
 371        return &((ether_dev_t *)net->priv)->stats;
 372}
 373
 374static int CDCEther_open(struct net_device *net)
 375{
 376        ether_dev_t *ether_dev = (ether_dev_t *)net->priv;
 377        int     res;
 378
 379        // Turn on the USB and let the packets flow!!!
 380        if ( (res = enable_net_traffic( ether_dev )) ) {
 381                err("%s can't enable_net_traffic() - %d", __FUNCTION__, res );
 382                return -EIO;
 383        }
 384
 385        /* Prep a receive URB */
 386        FILL_BULK_URB( &ether_dev->rx_urb, ether_dev->usb,
 387                        usb_rcvbulkpipe(ether_dev->usb, ether_dev->data_ep_in),
 388                        ether_dev->rx_buff, ether_dev->wMaxSegmentSize,
 389                        read_bulk_callback, ether_dev );
 390
 391        /* Put it out there so the device can send us stuff */
 392        if ( (res = usb_submit_urb(&ether_dev->rx_urb)) ) {
 393                /* Hmm...  Okay... */
 394                warn( "%s failed rx_urb %d", __FUNCTION__, res );
 395        }
 396
 397        if (ether_dev->properties & HAVE_NOTIFICATION_ELEMENT) {
 398                /* Arm and submit the interrupt URB */
 399                FILL_INT_URB( &ether_dev->intr_urb,
 400                        ether_dev->usb,
 401                        usb_rcvintpipe(ether_dev->usb, ether_dev->comm_ep_in),
 402                        ether_dev->intr_buff,
 403                        sizeof ether_dev->intr_buff,
 404                        intr_callback,
 405                        ether_dev,
 406                        (ether_dev->usb->speed == USB_SPEED_HIGH)
 407                                ? ( 1 << ether_dev->intr_interval)
 408                                : ether_dev->intr_interval
 409                        );
 410                if ( (res = usb_submit_urb(&ether_dev->intr_urb)) ) {
 411                        warn("%s failed intr_urb %d", __FUNCTION__, res );
 412                }
 413        }
 414
 415        // Tell the kernel we are ready to start receiving from it
 416        netif_start_queue( net );
 417        
 418        // We are up and running.
 419        ether_dev->flags |= CDC_ETHER_RUNNING;
 420
 421        // Let's get ready to move frames!!!
 422        return 0;
 423}
 424
 425static int CDCEther_close( struct net_device *net )
 426{
 427        ether_dev_t     *ether_dev = net->priv;
 428
 429        // We are no longer running.
 430        ether_dev->flags &= ~CDC_ETHER_RUNNING;
 431        
 432        // Tell the kernel to stop sending us stuff
 433        netif_stop_queue( net );
 434        
 435        // If we are not already unplugged, turn off USB
 436        // traffic
 437        if ( !(ether_dev->flags & CDC_ETHER_UNPLUG) ) {
 438                disable_net_traffic( ether_dev );
 439        }
 440
 441        // We don't need the URBs anymore.
 442        usb_unlink_urb( &ether_dev->rx_urb );
 443        usb_unlink_urb( &ether_dev->tx_urb );
 444        usb_unlink_urb( &ether_dev->intr_urb );
 445        usb_unlink_urb( &ether_dev->ctrl_urb );
 446
 447        // That's it.  I'm done.
 448        return 0;
 449}
 450
 451static int netdev_ethtool_ioctl(struct net_device *netdev, void *useraddr)
 452{
 453        ether_dev_t *ether_dev = netdev->priv;
 454        u32 cmd;
 455        char tmp[40];
 456
 457        if (get_user(cmd, (u32 *)useraddr))
 458                return -EFAULT;
 459
 460        switch (cmd) {
 461        /* get driver info */
 462        case ETHTOOL_GDRVINFO: {
 463        struct ethtool_drvinfo info = {ETHTOOL_GDRVINFO};
 464                strncpy(info.driver, driver_name, ETHTOOL_BUSINFO_LEN);
 465                strncpy(info.version, DRIVER_VERSION, ETHTOOL_BUSINFO_LEN);
 466                sprintf(tmp, "usb%d:%d", ether_dev->usb->bus->busnum, ether_dev->usb->devnum);
 467                strncpy(info.bus_info, tmp, ETHTOOL_BUSINFO_LEN);
 468                sprintf(tmp, "CDC %x.%x", ((ether_dev->bcdCDC & 0xff00)>>8), (ether_dev->bcdCDC & 0x00ff) );
 469                strncpy(info.fw_version, tmp, ETHTOOL_BUSINFO_LEN);
 470                if (copy_to_user(useraddr, &info, sizeof(info)))
 471                        return -EFAULT;
 472                return 0;
 473        }
 474        /* get link status */
 475        case ETHTOOL_GLINK: {
 476                struct ethtool_value edata = {ETHTOOL_GLINK};
 477                edata.data = netif_carrier_ok(netdev);
 478                if (copy_to_user(useraddr, &edata, sizeof(edata)))
 479                        return -EFAULT;
 480                return 0;
 481        }
 482        }
 483        dbg("Got unsupported ioctl: %x", cmd);
 484        return -EOPNOTSUPP; /* the ethtool user space tool relies on this */
 485}
 486
 487static int CDCEther_ioctl( struct net_device *net, struct ifreq *rq, int cmd )
 488{
 489        switch(cmd) {
 490        case SIOCETHTOOL:
 491                return netdev_ethtool_ioctl(net, (void *) rq->ifr_data);
 492        default:
 493                return -ENOTTY; /* per ioctl man page */
 494        }
 495}
 496
 497/* Multicast routines */
 498
 499static void CDC_SetEthernetPacketFilter (ether_dev_t *ether_dev)
 500{
 501#if 0
 502        struct usb_ctrlrequest *dr = &ether_dev->ctrl_dr;
 503        int res;
 504
 505        dr->bRequestType = USB_TYPE_CLASS | USB_DIR_OUT | USB_RECIP_INTERFACE;
 506        dr->bRequest = SET_ETHERNET_PACKET_FILTER;
 507        dr->wValue = cpu_to_le16(ether_dev->mode_flags);
 508        dr->wIndex = cpu_to_le16((u16)ether_dev->comm_interface);
 509        dr->wLength = 0;
 510
 511        FILL_CONTROL_URB(&ether_dev->ctrl_urb,
 512                        ether_dev->usb,
 513                        usb_sndctrlpipe(ether_dev->usb, 0),
 514                        dr,
 515                        NULL,
 516                        NULL,
 517                        setpktfilter_done,
 518                        ether_dev);
 519        if ( (res = usb_submit_urb(&ether_dev->ctrl_urb)) ) {
 520                warn("%s failed submit ctrl_urb %d", __FUNCTION__, res);
 521        }
 522#endif
 523
 524}
 525
 526static void CDCEther_set_multicast( struct net_device *net )
 527{
 528        ether_dev_t *ether_dev = net->priv;
 529        int i;
 530        __u8 *buff;
 531
 532        // Tell the kernel to stop sending us frames while we get this
 533        // all set up.
 534        netif_stop_queue(net);
 535
 536        /* Note: do not reorder, GCC is clever about common statements. */
 537        if (net->flags & IFF_PROMISC) {
 538                /* Unconditionally log net taps. */
 539                dbg( "%s: Promiscuous mode enabled", net->name);
 540                ether_dev->mode_flags = MODE_FLAG_PROMISCUOUS |
 541                        MODE_FLAG_ALL_MULTICAST |
 542                        MODE_FLAG_DIRECTED |
 543                        MODE_FLAG_BROADCAST |
 544                        MODE_FLAG_MULTICAST;
 545        } else if (net->mc_count > ether_dev->wNumberMCFilters) {
 546                /* Too many to filter perfectly -- accept all multicasts. */
 547                dbg("%s: too many MC filters for hardware, using allmulti", net->name);
 548                ether_dev->mode_flags = MODE_FLAG_ALL_MULTICAST |
 549                        MODE_FLAG_DIRECTED |
 550                        MODE_FLAG_BROADCAST |
 551                        MODE_FLAG_MULTICAST;
 552        } else if (net->flags & IFF_ALLMULTI) {
 553                /* Filter in software */
 554                dbg("%s: using allmulti", net->name);
 555                ether_dev->mode_flags = MODE_FLAG_ALL_MULTICAST |
 556                        MODE_FLAG_DIRECTED |
 557                        MODE_FLAG_BROADCAST |
 558                        MODE_FLAG_MULTICAST;
 559        } else {
 560                /* do multicast filtering in hardware */
 561                struct dev_mc_list *mclist;
 562                dbg("%s: set multicast filters", net->name);
 563                ether_dev->mode_flags = MODE_FLAG_ALL_MULTICAST |
 564                        MODE_FLAG_DIRECTED |
 565                        MODE_FLAG_BROADCAST |
 566                        MODE_FLAG_MULTICAST;
 567                buff = kmalloc(6 * net->mc_count, GFP_ATOMIC);
 568                for (i = 0, mclist = net->mc_list;
 569                        mclist && i < net->mc_count;
 570                        i++, mclist = mclist->next) {
 571                                memcpy(&mclist->dmi_addr, &buff[i * 6], 6);
 572                }
 573#if 0
 574                usb_control_msg(ether_dev->usb,
 575                                usb_sndctrlpipe(ether_dev->usb, 0),
 576                                SET_ETHERNET_MULTICAST_FILTER, /* request */
 577                                USB_TYPE_CLASS | USB_DIR_OUT | USB_RECIP_INTERFACE, /* request type */
 578                                cpu_to_le16(net->mc_count), /* value */
 579                                cpu_to_le16((u16)ether_dev->comm_interface), /* index */
 580                                buff,
 581                                (6* net->mc_count), /* size */
 582                                HZ); /* timeout */
 583#endif
 584                kfree(buff);
 585        }
 586
 587        CDC_SetEthernetPacketFilter(ether_dev);
 588
 589        /* Tell the kernel to start giving frames to us again. */
 590        netif_wake_queue(net);
 591}
 592
 593//////////////////////////////////////////////////////////////////////////////
 594// Routines used to parse out the Functional Descriptors /////////////////////
 595//////////////////////////////////////////////////////////////////////////////
 596
 597/* Header Descriptor - CDC Spec 5.2.3.1, Table 26 */
 598static int parse_header_functional_descriptor( int *bFunctionLength,
 599                                               int bDescriptorType,
 600                                               int bDescriptorSubtype,
 601                                               unsigned char *data,
 602                                               ether_dev_t *ether_dev,
 603                                               int *requirements )
 604{
 605        /* Check to make sure we haven't seen one of these already. */
 606        if ( (~*requirements) & REQ_HDR_FUNC_DESCR ) {
 607                err( "Multiple Header Functional Descriptors found." );
 608                return -1;
 609        }
 610
 611        /* Check for appropriate length */
 612        if (*bFunctionLength != HEADER_FUNC_DESC_LEN) {
 613                dbg( "Invalid length in Header Functional Descriptor, working around it." );
 614                /* This is a hack to get around a particular device (NO NAMES)
 615                 * It has this function length set to the length of the
 616                 * whole class-specific descriptor */
 617                *bFunctionLength = HEADER_FUNC_DESC_LEN;
 618        }
 619        
 620        /* Nothing extremely useful here */
 621        /* We'll keep it for posterity */
 622        ether_dev->bcdCDC = data[0] + (data[1] << 8);
 623        dbg( "Found Header descriptor, CDC version %x.", ether_dev->bcdCDC);
 624
 625        /* We've seen one of these */
 626        *requirements &= ~REQ_HDR_FUNC_DESCR;
 627
 628        /* Success */
 629        return 0;
 630}
 631
 632/* Union Descriptor - CDC Spec 5.2.3.8, Table 33 */
 633static int parse_union_functional_descriptor( int *bFunctionLength, 
 634                                              int bDescriptorType, 
 635                                              int bDescriptorSubtype,
 636                                              unsigned char *data,
 637                                              ether_dev_t *ether_dev,
 638                                              int *requirements )
 639{
 640        /* Check to make sure we haven't seen one of these already. */
 641        if ( (~*requirements) & REQ_UNION_FUNC_DESCR ) {
 642                err( "Multiple Union Functional Descriptors found." );
 643                return -1;
 644        }
 645
 646        /* Check for appropriate length */
 647        if (*bFunctionLength != UNION_FUNC_DESC_LEN) {
 648                // It is NOT the size we expected.
 649                err( "Invalid length in Union Functional Descriptor." );
 650                return -1;
 651        }
 652        
 653        /* Sanity check of sorts */
 654        if (ether_dev->comm_interface != data[0]) {
 655                /* This tells us that we are chasing the wrong comm
 656                 * interface or we are crazy or something else weird. */
 657                if (ether_dev->comm_interface == data[1]) {
 658                        dbg( "Probably broken Union descriptor, fudging data interface." );
 659                        /* We'll need this in a few microseconds,
 660                         * so if the comm interface was the first slave,
 661                         * then probably the master interface is the data one
 662                         * Just hope for the best */
 663                        ether_dev->data_interface = data[0];
 664                } else {
 665                        err( "Union Functional Descriptor is broken beyond repair." );
 666                        return -1;
 667                }
 668        } else{ /* Descriptor is OK */
 669                ether_dev->data_interface = data[1];
 670        }
 671
 672        /* We've seen one of these */
 673        *requirements &= ~REQ_UNION_FUNC_DESCR;
 674
 675        /* Success */
 676        return 0;
 677}
 678
 679/* Ethernet Descriptor - CDC Spec 5.2.3.16, Table 41 */
 680static int parse_ethernet_functional_descriptor( int *bFunctionLength,
 681                                                 int bDescriptorType, 
 682                                                 int bDescriptorSubtype,
 683                                                 unsigned char *data,
 684                                                 ether_dev_t *ether_dev,
 685                                                 int *requirements )
 686{
 687        //* Check to make sure we haven't seen one of these already. */
 688        if ( (~*requirements) & REQ_ETH_FUNC_DESCR ) {
 689                err( "Multiple Ethernet Functional Descriptors found." );
 690                return -1;
 691        }
 692        
 693        /* Check for appropriate length */
 694        if (*bFunctionLength != ETHERNET_FUNC_DESC_LEN) {
 695                err( "Invalid length in Ethernet Networking Functional Descriptor." );
 696                return -1;
 697        }
 698
 699        /* Lots of goodies from this one.  They are all important. */
 700        ether_dev->iMACAddress = data[0];
 701        ether_dev->bmEthernetStatistics = data[1] + (data[2] << 8) + (data[3] << 16) + (data[4] << 24);
 702        ether_dev->wMaxSegmentSize = data[5] + (data[6] << 8);
 703        ether_dev->wNumberMCFilters = (data[7] + (data[8] << 8));
 704        if (ether_dev->wNumberMCFilters & (1 << 15)) {
 705                ether_dev->properties |= PERFECT_FILTERING;
 706                dbg("Perfect filtering support");
 707        } else {
 708                dbg("Imperfect filtering support - need sw hashing");
 709        }
 710        if (0 == (ether_dev->wNumberMCFilters & (0x7f))) {
 711                ether_dev->properties |= NO_SET_MULTICAST;
 712                dbg("Can't use SetEthernetMulticastFilters request");
 713        }
 714        if (ether_dev->wNumberMCFilters > multicast_filter_limit) {
 715                ether_dev->wNumberMCFilters = multicast_filter_limit;
 716        }
 717        ether_dev->bNumberPowerFilters = data[9];
 718        
 719        /* We've seen one of these */
 720        *requirements &= ~REQ_ETH_FUNC_DESCR;
 721
 722        /* Success */
 723        return 0;
 724}
 725
 726static int parse_protocol_unit_functional_descriptor( int *bFunctionLength, 
 727                                                      int bDescriptorType, 
 728                                                      int bDescriptorSubtype,
 729                                                      unsigned char *data,
 730                                                      ether_dev_t *ether_dev,
 731                                                      int *requirements )
 732{
 733        /* There should only be one type if we are sane */
 734        if (bDescriptorType != CS_INTERFACE) {
 735                err( "Invalid bDescriptorType found." );
 736                return -1;
 737        }
 738
 739        /* The Subtype tells the tale - CDC spec Table 25 */
 740        switch (bDescriptorSubtype) {
 741                case 0x00:      /* Header Functional Descriptor */
 742                        return parse_header_functional_descriptor( bFunctionLength,
 743                                                                   bDescriptorType,
 744                                                                   bDescriptorSubtype,
 745                                                                   data,
 746                                                                   ether_dev,
 747                                                                   requirements );
 748                        break;
 749                case 0x06:      /* Union Functional Descriptor */
 750                        return parse_union_functional_descriptor( bFunctionLength,
 751                                                                  bDescriptorType,
 752                                                                  bDescriptorSubtype,
 753                                                                  data,
 754                                                                  ether_dev,
 755                                                                  requirements );
 756                        break;
 757                case 0x0F:      /* Ethernet Networking Functional Descriptor */
 758                        return parse_ethernet_functional_descriptor( bFunctionLength,
 759                                                                     bDescriptorType,
 760                                                                     bDescriptorSubtype,
 761                                                                     data,
 762                                                                     ether_dev,
 763                                                                     requirements );
 764                        break;
 765                default:        /* We don't support this at this time... */
 766                                /* However that doesn't necessarily indicate an error. */
 767                        dbg( "Unexpected header type %x.", bDescriptorSubtype );
 768                        return 0;
 769        }
 770        /* How did we get here? */
 771        return -1;
 772}
 773
 774static int parse_ethernet_class_information( unsigned char *data, int length, ether_dev_t *ether_dev )
 775{
 776        int loc = 0;
 777        int rc;
 778        int bFunctionLength;
 779        int bDescriptorType;
 780        int bDescriptorSubtype;
 781        int requirements = REQUIREMENTS_TOTAL; /* We init to our needs, and then clear
 782                                                * bits as we find the descriptors */
 783
 784        /* As long as there is something here, we will try to parse it */
 785        /* All of the functional descriptors start with the same 3 byte pattern */
 786        while (loc < length) {
 787                /* Length */
 788                bFunctionLength = data[loc];
 789                loc++;
 790
 791                /* Type */
 792                bDescriptorType = data[loc];
 793                loc++;
 794
 795                /* Subtype */
 796                bDescriptorSubtype = data[loc];
 797                loc++;
 798                
 799                /* ship this off to be processed */
 800                rc = parse_protocol_unit_functional_descriptor( &bFunctionLength, 
 801                                                                bDescriptorType, 
 802                                                                bDescriptorSubtype, 
 803                                                                &data[loc],
 804                                                                ether_dev,
 805                                                                &requirements );
 806                /* Did it process okay? */
 807                if (rc) {
 808                        /* Something was hosed somewhere. */
 809                        /*  No need to continue */
 810                        err("Bad descriptor parsing: %x", rc );
 811                        return -1;
 812                }
 813                /* We move the loc pointer along, remembering
 814                 * that we have already taken three bytes */
 815                loc += (bFunctionLength - 3);
 816        }
 817        /* Check to see if we got everything we need. */
 818        if (requirements) {
 819                // We missed some of the requirements...
 820                err( "Not all required functional descriptors present 0x%08X.", requirements );
 821                return -1;
 822        }
 823        /* We got everything */
 824        return 0;
 825}
 826
 827//////////////////////////////////////////////////////////////////////////////
 828// Routine to check for the existence of the Functional Descriptors //////////
 829//////////////////////////////////////////////////////////////////////////////
 830
 831static int find_and_parse_ethernet_class_information( struct usb_device *device, ether_dev_t *ether_dev )
 832{
 833        struct usb_config_descriptor *conf = NULL;
 834        struct usb_interface *comm_intf_group = NULL;
 835        struct usb_interface_descriptor *comm_intf = NULL;
 836        int rc = -1;
 837        /* The assumption here is that find_ethernet_comm_interface
 838         * and find_valid_configuration
 839         * have already filled in the information about where to find
 840         * the a valid commication interface. */
 841
 842        conf = &( device->config[ether_dev->configuration_num] );
 843        comm_intf_group = &( conf->interface[ether_dev->comm_interface] );
 844        comm_intf = &( comm_intf_group->altsetting[ether_dev->comm_interface_altset_num] );
 845
 846        /* Let's check and see if it has the extra information we need */
 847        if (comm_intf->extralen > 0) {
 848                /* This is where the information is SUPPOSED to be */
 849                rc = parse_ethernet_class_information( comm_intf->extra, comm_intf->extralen, ether_dev );
 850        } else if (conf->extralen > 0) {
 851                /* This is a hack.  The spec says it should be at the interface
 852                 * location checked above.  However I have seen it here also.
 853                 * This is the same device that requires the functional descriptor hack above */
 854                dbg( "Ethernet information found at device configuration.  Trying to use it anyway." );
 855                rc = parse_ethernet_class_information( conf->extra, conf->extralen, ether_dev );
 856        } else  {
 857                /* I don't know where else to look */
 858                err( "No ethernet information found." );
 859                rc = -1;
 860        }
 861        return rc;
 862}
 863
 864//////////////////////////////////////////////////////////////////////////////
 865// Routines to verify the data interface /////////////////////////////////////
 866//////////////////////////////////////////////////////////////////////////////
 867
 868static int get_data_interface_endpoints( struct usb_device *device, ether_dev_t *ether_dev )
 869{
 870        struct usb_config_descriptor *conf = NULL;
 871        struct usb_interface *data_intf_group = NULL;
 872        struct usb_interface_descriptor *data_intf = NULL;
 873
 874        /* Walk through and get to the data interface we are checking. */
 875        conf = &( device->config[ether_dev->configuration_num] );
 876        data_intf_group = &( conf->interface[ether_dev->data_interface] );
 877        data_intf = &( data_intf_group->altsetting[ether_dev->data_interface_altset_num_with_traffic] );
 878
 879        /* Start out assuming we won't find anything we can use */
 880        ether_dev->data_ep_in = 0;
 881        ether_dev->data_ep_out = 0;
 882
 883        /* If these are not BULK endpoints, we don't want them */
 884        if ( data_intf->endpoint[0].bmAttributes != USB_ENDPOINT_XFER_BULK ) {
 885                return -1;
 886        }
 887        if ( data_intf->endpoint[1].bmAttributes != USB_ENDPOINT_XFER_BULK ) {
 888                return -1;
 889        }
 890
 891        /* Check the first endpoint to see if it is IN or OUT */
 892        if ( data_intf->endpoint[0].bEndpointAddress & USB_DIR_IN ) {
 893                ether_dev->data_ep_in = data_intf->endpoint[0].bEndpointAddress & 0x7F;
 894        } else {
 895                ether_dev->data_ep_out = data_intf->endpoint[0].bEndpointAddress;
 896                ether_dev->data_ep_out_size = data_intf->endpoint[0].wMaxPacketSize;
 897        }
 898
 899        /* Check the second endpoint to see if it is IN or OUT */
 900        if ( data_intf->endpoint[1].bEndpointAddress & USB_DIR_IN ) {
 901                ether_dev->data_ep_in = data_intf->endpoint[1].bEndpointAddress & 0x7F;
 902        } else  {
 903                ether_dev->data_ep_out = data_intf->endpoint[1].bEndpointAddress;
 904                ether_dev->data_ep_out_size = data_intf->endpoint[1].wMaxPacketSize;
 905        }
 906
 907        /* Now make sure we got both an IN and an OUT */
 908        if (ether_dev->data_ep_in && ether_dev->data_ep_out) {
 909                dbg( "detected BULK OUT packets of size %d", ether_dev->data_ep_out_size );
 910                return 0;
 911        }
 912        return -1;
 913}
 914
 915static int verify_ethernet_data_interface( struct usb_device *device, ether_dev_t *ether_dev )
 916{
 917        struct usb_config_descriptor *conf = NULL;
 918        struct usb_interface *data_intf_group = NULL;
 919        struct usb_interface_descriptor *data_intf = NULL;
 920        int rc = -1;
 921        int status;
 922        int altset_num;
 923
 924        // The assumption here is that parse_ethernet_class_information()
 925        // and find_valid_configuration() 
 926        // have already filled in the information about where to find
 927        // a data interface
 928        conf = &( device->config[ether_dev->configuration_num] );
 929        data_intf_group = &( conf->interface[ether_dev->data_interface] );
 930
 931        // start out assuming we won't find what we are looking for.
 932        ether_dev->data_interface_altset_num_with_traffic = -1;
 933        ether_dev->data_bAlternateSetting_with_traffic = -1;
 934        ether_dev->data_interface_altset_num_without_traffic = -1;
 935        ether_dev->data_bAlternateSetting_without_traffic = -1;
 936
 937        // Walk through every possible setting for this interface until
 938        // we find what makes us happy.
 939        for ( altset_num = 0; altset_num < data_intf_group->num_altsetting; altset_num++ ) {
 940                data_intf = &( data_intf_group->altsetting[altset_num] );
 941
 942                // Is this a data interface we like?
 943                if ( ( data_intf->bInterfaceClass == 0x0A )
 944                   && ( data_intf->bInterfaceSubClass == 0x00 )
 945                   && ( data_intf->bInterfaceProtocol == 0x00 ) ) {
 946                        if ( data_intf->bNumEndpoints == 2 ) {
 947                                // We are required to have one of these.
 948                                // An interface with 2 endpoints to send Ethernet traffic back and forth
 949                                // It actually may be possible that the device might only
 950                                // communicate in a vendor specific manner.
 951                                // That would not be very nice.
 952                                // We can add that one later.
 953                                ether_dev->data_bInterfaceNumber = data_intf->bInterfaceNumber;
 954                                ether_dev->data_interface_altset_num_with_traffic = altset_num;
 955                                ether_dev->data_bAlternateSetting_with_traffic = data_intf->bAlternateSetting;
 956                                status = get_data_interface_endpoints( device, ether_dev );
 957                                if (!status) {
 958                                        rc = 0;
 959                                }
 960                        }
 961                        if ( data_intf->bNumEndpoints == 0 ) {
 962                                // According to the spec we are SUPPOSED to have one of these
 963                                // In fact the device is supposed to come up in this state.
 964                                // However, I have seen a device that did not have such an interface.
 965                                // So it must be just optional for our driver...
 966                                ether_dev->data_bInterfaceNumber = data_intf->bInterfaceNumber;
 967                                ether_dev->data_interface_altset_num_without_traffic = altset_num;
 968                                ether_dev->data_bAlternateSetting_without_traffic = data_intf->bAlternateSetting;
 969                        }
 970                }
 971        }
 972        return rc;
 973}
 974
 975//////////////////////////////////////////////////////////////////////////////
 976// Routine to find a communication interface /////////////////////////////////
 977//////////////////////////////////////////////////////////////////////////////
 978
 979static int find_ethernet_comm_interface( struct usb_device *device, ether_dev_t *ether_dev )
 980{
 981        struct usb_config_descriptor *conf = NULL;
 982        struct usb_interface *comm_intf_group = NULL;
 983        struct usb_interface_descriptor *comm_intf = NULL;
 984        int intf_num;
 985        int altset_num;
 986        int rc;
 987
 988        conf = &( device->config[ether_dev->configuration_num] );
 989
 990        // We need to check and see if any of these interfaces are something we want.
 991        // Walk through each interface one at a time
 992        for ( intf_num = 0; intf_num < conf->bNumInterfaces; intf_num++ ) {
 993                comm_intf_group = &( conf->interface[intf_num] );
 994                // Now for each of those interfaces, check every possible
 995                // alternate setting.
 996                for ( altset_num = 0; altset_num < comm_intf_group->num_altsetting; altset_num++ ) {
 997                        comm_intf = &( comm_intf_group->altsetting[altset_num] );
 998
 999                        /* Good, we found one, we will try this one */
1000                        /* Fill in the structure */
1001                        ether_dev->comm_interface = intf_num;
1002                        ether_dev->comm_bInterfaceNumber = comm_intf->bInterfaceNumber;
1003                        ether_dev->comm_interface_altset_num = altset_num;
1004                        ether_dev->comm_bAlternateSetting = comm_intf->bAlternateSetting;
1005
1006                        // Look for the Ethernet Functional Descriptors
1007                        rc = find_and_parse_ethernet_class_information( device, ether_dev );
1008                        if (rc) {
1009                                // Nope this was no good after all.
1010                                continue;
1011                        }
1012
1013                        /* Check that we really can talk to the data interface
1014                         * This includes # of endpoints, protocols, etc. */
1015                        rc = verify_ethernet_data_interface( device, ether_dev );
1016                        if (rc) {
1017                                /* We got something we didn't like */
1018                                continue;
1019                        }
1020                        /* It is a bit ambiguous whether the Ethernet model really requires
1021                         * the notification element (usually an interrupt endpoint) or not
1022                         * And some products (eg Sharp Zaurus) don't support it, so we
1023                         * only use the notification element if present */
1024                        /* We check for a sane endpoint before using it */
1025                        if ( (comm_intf->bNumEndpoints == 1) &&
1026                                (comm_intf->endpoint[0].bEndpointAddress & USB_DIR_IN) &&
1027                                (comm_intf->endpoint[0].bmAttributes == USB_ENDPOINT_XFER_INT)) {
1028                                        ether_dev->properties |= HAVE_NOTIFICATION_ELEMENT;
1029                                        ether_dev->comm_ep_in = (comm_intf->endpoint[0].bEndpointAddress & 0x7F);
1030                                        dbg("interrupt address: %x",ether_dev->comm_ep_in);
1031                                        ether_dev->intr_interval = (comm_intf->endpoint[0].bInterval);
1032                                        dbg("interrupt interval: %d",ether_dev->intr_interval);
1033                        }
1034                        // This communication interface seems to give us everything
1035                        // we require.  We have all the ethernet info we need.
1036
1037                        return 0;
1038                } // end for altset_num
1039        } // end for intf_num
1040        return -1;
1041}
1042
1043//////////////////////////////////////////////////////////////////////////////
1044// Routine to go through all configurations and find one that ////////////////
1045// is an Ethernet Networking Device //////////////////////////////////////////
1046//////////////////////////////////////////////////////////////////////////////
1047
1048static int find_valid_configuration( struct usb_device *device, ether_dev_t *ether_dev )
1049{
1050        struct usb_config_descriptor *conf = NULL;
1051        int conf_num;
1052        int rc;
1053
1054        // We will try each and every possible configuration
1055        for ( conf_num = 0; conf_num < device->descriptor.bNumConfigurations; conf_num++ ) {
1056                conf = &( device->config[conf_num] );
1057
1058                // Our first requirement : 2 interfaces
1059                if ( conf->bNumInterfaces != 2 ) {
1060                        // I currently don't know how to handle devices with any number of interfaces
1061                        // other than 2.
1062                        continue;
1063                }
1064
1065                // This one passed our first check, fill in some 
1066                // useful data
1067                ether_dev->configuration_num = conf_num;
1068                ether_dev->bConfigurationValue = conf->bConfigurationValue;
1069
1070                // Now run it through the ringers and see what comes
1071                // out the other side.
1072                rc = find_ethernet_comm_interface( device, ether_dev );
1073
1074                // Check if we found an ethernet Communcation Device
1075                if ( !rc ) {
1076                        // We found one.
1077                        return 0;
1078                }
1079        }
1080        // None of the configurations suited us.
1081        return -1;
1082}
1083
1084//////////////////////////////////////////////////////////////////////////////
1085// Routine that checks a given configuration to see if any driver ////////////
1086// has claimed any of the devices interfaces /////////////////////////////////
1087//////////////////////////////////////////////////////////////////////////////
1088
1089static int check_for_claimed_interfaces( struct usb_config_descriptor *config )
1090{
1091        struct usb_interface *comm_intf_group;
1092        int intf_num;
1093
1094        // Go through all the interfaces and make sure none are 
1095        // claimed by anybody else.
1096        for ( intf_num = 0; intf_num < config->bNumInterfaces; intf_num++ ) {
1097                comm_intf_group = &( config->interface[intf_num] );
1098                if ( usb_interface_claimed( comm_intf_group ) ) {
1099                        // Somebody has beat us to this guy.
1100                        // We can't change the configuration out from underneath of whoever
1101                        // is using this device, so we will go ahead and give up.
1102                        return -1;
1103                }
1104        }
1105        // We made it all the way through.
1106        // I guess no one has claimed any of these interfaces.
1107        return 0;
1108}
1109
1110//////////////////////////////////////////////////////////////////////////////
1111// Routines to ask for and set the kernel network interface's MAC address ////
1112// Used by driver's probe routine ////////////////////////////////////////////
1113//////////////////////////////////////////////////////////////////////////////
1114
1115static inline unsigned char hex2dec( unsigned char digit )
1116{
1117        /* Is there a standard way to do this??? */
1118        /* I have written this code TOO MANY times. */
1119        if ( (digit >= '0') && (digit <= '9') ) {
1120                return (digit - '0');
1121        }
1122        if ( (digit >= 'a') && (digit <= 'f') ) {
1123                return (digit - 'a' + 10);
1124        }
1125        if ( (digit >= 'A') && (digit <= 'F') ) {
1126                return (digit - 'A' + 10);
1127        }
1128        return 16;
1129}
1130
1131/* CDC Ethernet devices provide the MAC address as a string */
1132/* We get an index to the string in the Ethernet functional header */
1133/* This routine retrieves the string, sanity checks it, and sets the */
1134/* MAC address in the network device */
1135/* The encoding is a bit wacky - see CDC Spec Table 41 for details */
1136static void set_ethernet_addr( ether_dev_t *ether_dev )
1137{
1138        unsigned char   mac_addr[6];
1139        int             i;
1140        int             len;
1141        unsigned char   buffer[13];
1142
1143        /* Let's assume we don't get anything */
1144        mac_addr[0] = 0x00;
1145        mac_addr[1] = 0x00;
1146        mac_addr[2] = 0x00;
1147        mac_addr[3] = 0x00;
1148        mac_addr[4] = 0x00;
1149        mac_addr[5] = 0x00;
1150
1151        /* Let's ask the device */
1152        if (0 > (len = usb_string(ether_dev->usb, ether_dev->iMACAddress, buffer, 13))) {
1153                err("Attempting to get MAC address failed: %d", -1*len);
1154                return;
1155        }
1156
1157        /* Sanity check */
1158        if (len != 12)  {
1159                /* You gotta love failing sanity checks */
1160                err("Attempting to get MAC address returned %d bytes", len);
1161                return;
1162        }
1163
1164        /* Fill in the mac_addr */
1165        for (i = 0; i < 6; i++) {
1166                if ((16 == buffer[2 * i]) || (16 == buffer[2 * i + 1])) {
1167                        err("Bad value in MAC address");
1168                }
1169                else {
1170                        mac_addr[i] = ( hex2dec( buffer[2 * i] ) << 4 ) + hex2dec( buffer[2 * i + 1] );
1171                }
1172        }
1173
1174        /* Now copy it over to our network device structure */
1175        memcpy( ether_dev->net->dev_addr, mac_addr, sizeof(mac_addr) );
1176}
1177
1178//////////////////////////////////////////////////////////////////////////////
1179// Routine to print to syslog information about the driver ///////////////////
1180// Used by driver's probe routine ////////////////////////////////////////////
1181//////////////////////////////////////////////////////////////////////////////
1182
1183void log_device_info(ether_dev_t *ether_dev)
1184{
1185        int len;
1186        int string_num;
1187        unsigned char manu[256];
1188        unsigned char prod[256];
1189        unsigned char sern[256];
1190        unsigned char *mac_addr;
1191
1192        /* Default empty strings in case we don't find a real one */
1193        manu[0] = 0x00;
1194        prod[0] = 0x00;
1195        sern[0] = 0x00;
1196
1197        /*  Try to get the device Manufacturer */
1198        string_num = ether_dev->usb->descriptor.iManufacturer;
1199        if (string_num) {
1200                // Put it into its buffer
1201                len = usb_string(ether_dev->usb, string_num, manu, 255);
1202                // Just to be safe
1203                manu[len] = 0x00;
1204        }
1205
1206        /* Try to get the device Product Name */
1207        string_num = ether_dev->usb->descriptor.iProduct;
1208        if (string_num) {
1209                // Put it into its buffer
1210                len = usb_string(ether_dev->usb, string_num, prod, 255);
1211                // Just to be safe
1212                prod[len] = 0x00;
1213        }
1214
1215        /* Try to get the device Serial Number */
1216        string_num = ether_dev->usb->descriptor.iSerialNumber;
1217        if (string_num) {
1218                // Put it into its buffer
1219                len = usb_string(ether_dev->usb, string_num, sern, 255);
1220                // Just to be safe
1221                sern[len] = 0x00;
1222        }
1223
1224        /* This makes it easier for us to print */
1225        mac_addr = ether_dev->net->dev_addr;
1226
1227        /* Now send everything we found to the syslog */
1228        info( "%s: %s %s %s", ether_dev->net->name, manu, prod, sern);
1229        dbg( "%s: %02X:%02X:%02X:%02X:%02X:%02X",
1230                ether_dev->net->name,
1231                mac_addr[0],
1232                mac_addr[1],
1233                mac_addr[2],
1234                mac_addr[3],
1235                mac_addr[4],
1236                mac_addr[5] );
1237
1238}
1239
1240/* Forward declaration */
1241static struct usb_driver CDCEther_driver ;
1242
1243//////////////////////////////////////////////////////////////////////////////
1244// Module's probe routine ////////////////////////////////////////////////////
1245// claims interfaces if they are for an Ethernet CDC /////////////////////////
1246//////////////////////////////////////////////////////////////////////////////
1247
1248static void * CDCEther_probe( struct usb_device *usb, unsigned int ifnum,
1249                             const struct usb_device_id *id)
1250{
1251        struct net_device       *net;
1252        ether_dev_t             *ether_dev;
1253        int                     rc;
1254
1255        // First we should check the active configuration to see if 
1256        // any other driver has claimed any of the interfaces.
1257        if ( check_for_claimed_interfaces( usb->actconfig ) ) {
1258                // Someone has already put there grubby paws on this device.
1259                // We don't want it now...
1260                return NULL;
1261        }
1262
1263        // We might be finding a device we can use.
1264        // We all go ahead and allocate our storage space.
1265        // We need to because we have to start filling in the data that
1266        // we are going to need later.
1267        if(!(ether_dev = kmalloc(sizeof(ether_dev_t), GFP_KERNEL))) {
1268                err("out of memory allocating device structure");
1269                return NULL;
1270        }
1271
1272        // Zero everything out.
1273        memset(ether_dev, 0, sizeof(ether_dev_t));
1274
1275        // Let's see if we can find a configuration we can use.
1276        rc = find_valid_configuration( usb, ether_dev );
1277        if (rc) {
1278                // Nope we couldn't find one we liked.
1279                // This device was not meant for us to control.
1280                kfree( ether_dev );
1281                return  NULL;
1282        }
1283
1284        // Now that we FOUND a configuration. let's try to make the 
1285        // device go into it.
1286        if ( usb_set_configuration( usb, ether_dev->bConfigurationValue ) ) {
1287                err("usb_set_configuration() failed");
1288                kfree( ether_dev );
1289                return NULL;
1290        }
1291
1292        // Now set the communication interface up as required.
1293        if (usb_set_interface(usb, ether_dev->comm_bInterfaceNumber, ether_dev->comm_bAlternateSetting)) {
1294                err("usb_set_interface() failed");
1295                kfree( ether_dev );
1296                return NULL;
1297        }
1298
1299        // Only turn traffic on right now if we must...
1300        if (ether_dev->data_interface_altset_num_without_traffic >= 0)  {
1301                // We found an alternate setting for the data
1302                // interface that allows us to turn off traffic.
1303                // We should use it.
1304                if (usb_set_interface( usb, 
1305                                       ether_dev->data_bInterfaceNumber, 
1306                                       ether_dev->data_bAlternateSetting_without_traffic)) {
1307                        err("usb_set_interface() failed");
1308                        kfree( ether_dev );
1309                        return NULL;
1310                }
1311        } else  {
1312                // We didn't find an alternate setting for the data
1313                // interface that would let us turn off traffic.
1314                // Oh well, let's go ahead and do what we must...
1315                if (usb_set_interface( usb, 
1316                                       ether_dev->data_bInterfaceNumber, 
1317                                       ether_dev->data_bAlternateSetting_with_traffic)) {
1318                        err("usb_set_interface() failed");
1319                        kfree( ether_dev );
1320                        return NULL;
1321                }
1322        }
1323
1324        // Now we need to get a kernel Ethernet interface.
1325        net = init_etherdev( NULL, 0 );
1326        if ( !net ) {
1327                // Hmm...  The kernel is not sharing today...
1328                // Fine, we didn't want it anyway...
1329                err( "Unable to initialize ethernet device" );
1330                kfree( ether_dev );
1331                return  NULL;
1332        }
1333
1334        // Now that we have an ethernet device, let's set it up
1335        // (And I don't mean "set [it] up the bomb".)
1336        net->priv = ether_dev;
1337        SET_MODULE_OWNER(net);
1338        net->open = CDCEther_open;
1339        net->stop = CDCEther_close;
1340        net->watchdog_timeo = CDC_ETHER_TX_TIMEOUT;
1341        net->tx_timeout = CDCEther_tx_timeout;   // TX timeout function
1342        net->do_ioctl = CDCEther_ioctl;
1343        net->hard_start_xmit = CDCEther_start_xmit;
1344        net->set_multicast_list = CDCEther_set_multicast;
1345        net->get_stats = CDCEther_netdev_stats;
1346        net->mtu = ether_dev->wMaxSegmentSize - 14;
1347
1348        // We'll keep track of this information for later...
1349        ether_dev->usb = usb;
1350        ether_dev->net = net;
1351        
1352        // and don't forget the MAC address.
1353        set_ethernet_addr( ether_dev );
1354
1355        // Send a message to syslog about what we are handling
1356        log_device_info( ether_dev );
1357
1358        /* We need to manually claim the data interface, while the comm interface gets claimed in the return */
1359        usb_driver_claim_interface( &CDCEther_driver, 
1360                                    &(usb->config[ether_dev->configuration_num].interface[ether_dev->data_interface]), 
1361                                    ether_dev );
1362
1363        // Does this REALLY do anything???
1364        usb_inc_dev_use( usb );
1365
1366        // Okay, we are finally done...
1367        return ether_dev;
1368}
1369
1370
1371//////////////////////////////////////////////////////////////////////////////
1372// Module's disconnect routine ///////////////////////////////////////////////
1373// Called when the driver is unloaded or the device is unplugged /////////////
1374// (Whichever happens first assuming the driver suceeded at its probe) ///////
1375//////////////////////////////////////////////////////////////////////////////
1376
1377static void CDCEther_disconnect( struct usb_device *usb, void *ptr )
1378{
1379        ether_dev_t *ether_dev = ptr;
1380
1381        // Sanity check!!!
1382        if ( !ether_dev || !ether_dev->usb ) {
1383                // We failed.  We are insane!!!
1384                warn("unregistering non-existant device");
1385                return;
1386        }
1387
1388        // Make sure we fail the sanity check if we try this again.
1389        ether_dev->usb = NULL;
1390        
1391        // It is possible that this function is called before
1392        // the "close" function.
1393        // This tells the close function we are already disconnected
1394        ether_dev->flags |= CDC_ETHER_UNPLUG;
1395        
1396        // We don't need the network device any more
1397        unregister_netdev( ether_dev->net );
1398        
1399        // For sanity checks
1400        ether_dev->net = NULL;
1401
1402        // I ask again, does this do anything???
1403        usb_dec_dev_use( usb );
1404
1405        // We are done with this interface
1406        usb_driver_release_interface( &CDCEther_driver, 
1407                                      &(usb->config[ether_dev->configuration_num].interface[ether_dev->comm_interface]) );
1408
1409        // We are done with this interface too
1410        usb_driver_release_interface( &CDCEther_driver, 
1411                                      &(usb->config[ether_dev->configuration_num].interface[ether_dev->data_interface]) );
1412
1413        // No more tied up kernel memory
1414        kfree( ether_dev );
1415        
1416        // This does no good, but it looks nice!
1417        ether_dev = NULL;
1418}
1419
1420//////////////////////////////////////////////////////////////////////////////
1421// Driver info ///////////////////////////////////////////////////////////////
1422//////////////////////////////////////////////////////////////////////////////
1423
1424static struct usb_driver CDCEther_driver = {
1425        name:           driver_name,
1426        probe:          CDCEther_probe,
1427        disconnect:     CDCEther_disconnect,
1428        id_table:       CDCEther_ids,
1429};
1430
1431//////////////////////////////////////////////////////////////////////////////
1432// init and exit routines called when driver is installed and uninstalled ////
1433//////////////////////////////////////////////////////////////////////////////
1434
1435int __init CDCEther_init(void)
1436{
1437        dbg( "%s", version );
1438        return usb_register( &CDCEther_driver );
1439}
1440
1441void __exit CDCEther_exit(void)
1442{
1443        usb_deregister( &CDCEther_driver );
1444}
1445
1446//////////////////////////////////////////////////////////////////////////////
1447// Module info ///////////////////////////////////////////////////////////////
1448//////////////////////////////////////////////////////////////////////////////
1449
1450module_init( CDCEther_init );
1451module_exit( CDCEther_exit );
1452
1453MODULE_AUTHOR("Brad Hards and another");
1454MODULE_DESCRIPTION("USB CDC Ethernet driver");
1455MODULE_LICENSE("GPL");
1456
1457MODULE_DEVICE_TABLE (usb, CDCEther_ids);
1458MODULE_PARM (multicast_filter_limit, "i");
1459MODULE_PARM_DESC (multicast_filter_limit, "CDCEther maximum number of filtered multicast addresses");
1460
1461//////////////////////////////////////////////////////////////////////////////
1462// End of file ///////////////////////////////////////////////////////////////
1463//////////////////////////////////////////////////////////////////////////////
1464
lxr.linux.no kindly hosted by Redpill Linpro AS, provider of Linux consulting and operations services since 1995.