linux/drivers/usb/gadget/legacy/inode.c
<<
>>
Prefs
   1/*
   2 * inode.c -- user mode filesystem api for usb gadget controllers
   3 *
   4 * Copyright (C) 2003-2004 David Brownell
   5 * Copyright (C) 2003 Agilent Technologies
   6 *
   7 * This program is free software; you can redistribute it and/or modify
   8 * it under the terms of the GNU General Public License as published by
   9 * the Free Software Foundation; either version 2 of the License, or
  10 * (at your option) any later version.
  11 */
  12
  13
  14/* #define VERBOSE_DEBUG */
  15
  16#include <linux/init.h>
  17#include <linux/module.h>
  18#include <linux/fs.h>
  19#include <linux/pagemap.h>
  20#include <linux/uts.h>
  21#include <linux/wait.h>
  22#include <linux/compiler.h>
  23#include <asm/uaccess.h>
  24#include <linux/sched.h>
  25#include <linux/slab.h>
  26#include <linux/poll.h>
  27#include <linux/mmu_context.h>
  28#include <linux/aio.h>
  29
  30#include <linux/device.h>
  31#include <linux/moduleparam.h>
  32
  33#include <linux/usb/gadgetfs.h>
  34#include <linux/usb/gadget.h>
  35
  36
  37/*
  38 * The gadgetfs API maps each endpoint to a file descriptor so that you
  39 * can use standard synchronous read/write calls for I/O.  There's some
  40 * O_NONBLOCK and O_ASYNC/FASYNC style i/o support.  Example usermode
  41 * drivers show how this works in practice.  You can also use AIO to
  42 * eliminate I/O gaps between requests, to help when streaming data.
  43 *
  44 * Key parts that must be USB-specific are protocols defining how the
  45 * read/write operations relate to the hardware state machines.  There
  46 * are two types of files.  One type is for the device, implementing ep0.
  47 * The other type is for each IN or OUT endpoint.  In both cases, the
  48 * user mode driver must configure the hardware before using it.
  49 *
  50 * - First, dev_config() is called when /dev/gadget/$CHIP is configured
  51 *   (by writing configuration and device descriptors).  Afterwards it
  52 *   may serve as a source of device events, used to handle all control
  53 *   requests other than basic enumeration.
  54 *
  55 * - Then, after a SET_CONFIGURATION control request, ep_config() is
  56 *   called when each /dev/gadget/ep* file is configured (by writing
  57 *   endpoint descriptors).  Afterwards these files are used to write()
  58 *   IN data or to read() OUT data.  To halt the endpoint, a "wrong
  59 *   direction" request is issued (like reading an IN endpoint).
  60 *
  61 * Unlike "usbfs" the only ioctl()s are for things that are rare, and maybe
  62 * not possible on all hardware.  For example, precise fault handling with
  63 * respect to data left in endpoint fifos after aborted operations; or
  64 * selective clearing of endpoint halts, to implement SET_INTERFACE.
  65 */
  66
  67#define DRIVER_DESC     "USB Gadget filesystem"
  68#define DRIVER_VERSION  "24 Aug 2004"
  69
  70static const char driver_desc [] = DRIVER_DESC;
  71static const char shortname [] = "gadgetfs";
  72
  73MODULE_DESCRIPTION (DRIVER_DESC);
  74MODULE_AUTHOR ("David Brownell");
  75MODULE_LICENSE ("GPL");
  76
  77
  78/*----------------------------------------------------------------------*/
  79
  80#define GADGETFS_MAGIC          0xaee71ee7
  81
  82/* /dev/gadget/$CHIP represents ep0 and the whole device */
  83enum ep0_state {
  84        /* DISBLED is the initial state.
  85         */
  86        STATE_DEV_DISABLED = 0,
  87
  88        /* Only one open() of /dev/gadget/$CHIP; only one file tracks
  89         * ep0/device i/o modes and binding to the controller.  Driver
  90         * must always write descriptors to initialize the device, then
  91         * the device becomes UNCONNECTED until enumeration.
  92         */
  93        STATE_DEV_OPENED,
  94
  95        /* From then on, ep0 fd is in either of two basic modes:
  96         * - (UN)CONNECTED: read usb_gadgetfs_event(s) from it
  97         * - SETUP: read/write will transfer control data and succeed;
  98         *   or if "wrong direction", performs protocol stall
  99         */
 100        STATE_DEV_UNCONNECTED,
 101        STATE_DEV_CONNECTED,
 102        STATE_DEV_SETUP,
 103
 104        /* UNBOUND means the driver closed ep0, so the device won't be
 105         * accessible again (DEV_DISABLED) until all fds are closed.
 106         */
 107        STATE_DEV_UNBOUND,
 108};
 109
 110/* enough for the whole queue: most events invalidate others */
 111#define N_EVENT                 5
 112
 113struct dev_data {
 114        spinlock_t                      lock;
 115        atomic_t                        count;
 116        enum ep0_state                  state;          /* P: lock */
 117        struct usb_gadgetfs_event       event [N_EVENT];
 118        unsigned                        ev_next;
 119        struct fasync_struct            *fasync;
 120        u8                              current_config;
 121
 122        /* drivers reading ep0 MUST handle control requests (SETUP)
 123         * reported that way; else the host will time out.
 124         */
 125        unsigned                        usermode_setup : 1,
 126                                        setup_in : 1,
 127                                        setup_can_stall : 1,
 128                                        setup_out_ready : 1,
 129                                        setup_out_error : 1,
 130                                        setup_abort : 1;
 131        unsigned                        setup_wLength;
 132
 133        /* the rest is basically write-once */
 134        struct usb_config_descriptor    *config, *hs_config;
 135        struct usb_device_descriptor    *dev;
 136        struct usb_request              *req;
 137        struct usb_gadget               *gadget;
 138        struct list_head                epfiles;
 139        void                            *buf;
 140        wait_queue_head_t               wait;
 141        struct super_block              *sb;
 142        struct dentry                   *dentry;
 143
 144        /* except this scratch i/o buffer for ep0 */
 145        u8                              rbuf [256];
 146};
 147
 148static inline void get_dev (struct dev_data *data)
 149{
 150        atomic_inc (&data->count);
 151}
 152
 153static void put_dev (struct dev_data *data)
 154{
 155        if (likely (!atomic_dec_and_test (&data->count)))
 156                return;
 157        /* needs no more cleanup */
 158        BUG_ON (waitqueue_active (&data->wait));
 159        kfree (data);
 160}
 161
 162static struct dev_data *dev_new (void)
 163{
 164        struct dev_data         *dev;
 165
 166        dev = kzalloc(sizeof(*dev), GFP_KERNEL);
 167        if (!dev)
 168                return NULL;
 169        dev->state = STATE_DEV_DISABLED;
 170        atomic_set (&dev->count, 1);
 171        spin_lock_init (&dev->lock);
 172        INIT_LIST_HEAD (&dev->epfiles);
 173        init_waitqueue_head (&dev->wait);
 174        return dev;
 175}
 176
 177/*----------------------------------------------------------------------*/
 178
 179/* other /dev/gadget/$ENDPOINT files represent endpoints */
 180enum ep_state {
 181        STATE_EP_DISABLED = 0,
 182        STATE_EP_READY,
 183        STATE_EP_ENABLED,
 184        STATE_EP_UNBOUND,
 185};
 186
 187struct ep_data {
 188        struct mutex                    lock;
 189        enum ep_state                   state;
 190        atomic_t                        count;
 191        struct dev_data                 *dev;
 192        /* must hold dev->lock before accessing ep or req */
 193        struct usb_ep                   *ep;
 194        struct usb_request              *req;
 195        ssize_t                         status;
 196        char                            name [16];
 197        struct usb_endpoint_descriptor  desc, hs_desc;
 198        struct list_head                epfiles;
 199        wait_queue_head_t               wait;
 200        struct dentry                   *dentry;
 201};
 202
 203static inline void get_ep (struct ep_data *data)
 204{
 205        atomic_inc (&data->count);
 206}
 207
 208static void put_ep (struct ep_data *data)
 209{
 210        if (likely (!atomic_dec_and_test (&data->count)))
 211                return;
 212        put_dev (data->dev);
 213        /* needs no more cleanup */
 214        BUG_ON (!list_empty (&data->epfiles));
 215        BUG_ON (waitqueue_active (&data->wait));
 216        kfree (data);
 217}
 218
 219/*----------------------------------------------------------------------*/
 220
 221/* most "how to use the hardware" policy choices are in userspace:
 222 * mapping endpoint roles (which the driver needs) to the capabilities
 223 * which the usb controller has.  most of those capabilities are exposed
 224 * implicitly, starting with the driver name and then endpoint names.
 225 */
 226
 227static const char *CHIP;
 228
 229/*----------------------------------------------------------------------*/
 230
 231/* NOTE:  don't use dev_printk calls before binding to the gadget
 232 * at the end of ep0 configuration, or after unbind.
 233 */
 234
 235/* too wordy: dev_printk(level , &(d)->gadget->dev , fmt , ## args) */
 236#define xprintk(d,level,fmt,args...) \
 237        printk(level "%s: " fmt , shortname , ## args)
 238
 239#ifdef DEBUG
 240#define DBG(dev,fmt,args...) \
 241        xprintk(dev , KERN_DEBUG , fmt , ## args)
 242#else
 243#define DBG(dev,fmt,args...) \
 244        do { } while (0)
 245#endif /* DEBUG */
 246
 247#ifdef VERBOSE_DEBUG
 248#define VDEBUG  DBG
 249#else
 250#define VDEBUG(dev,fmt,args...) \
 251        do { } while (0)
 252#endif /* DEBUG */
 253
 254#define ERROR(dev,fmt,args...) \
 255        xprintk(dev , KERN_ERR , fmt , ## args)
 256#define INFO(dev,fmt,args...) \
 257        xprintk(dev , KERN_INFO , fmt , ## args)
 258
 259
 260/*----------------------------------------------------------------------*/
 261
 262/* SYNCHRONOUS ENDPOINT OPERATIONS (bulk/intr/iso)
 263 *
 264 * After opening, configure non-control endpoints.  Then use normal
 265 * stream read() and write() requests; and maybe ioctl() to get more
 266 * precise FIFO status when recovering from cancellation.
 267 */
 268
 269static void epio_complete (struct usb_ep *ep, struct usb_request *req)
 270{
 271        struct ep_data  *epdata = ep->driver_data;
 272
 273        if (!req->context)
 274                return;
 275        if (req->status)
 276                epdata->status = req->status;
 277        else
 278                epdata->status = req->actual;
 279        complete ((struct completion *)req->context);
 280}
 281
 282/* tasklock endpoint, returning when it's connected.
 283 * still need dev->lock to use epdata->ep.
 284 */
 285static int
 286get_ready_ep (unsigned f_flags, struct ep_data *epdata)
 287{
 288        int     val;
 289
 290        if (f_flags & O_NONBLOCK) {
 291                if (!mutex_trylock(&epdata->lock))
 292                        goto nonblock;
 293                if (epdata->state != STATE_EP_ENABLED) {
 294                        mutex_unlock(&epdata->lock);
 295nonblock:
 296                        val = -EAGAIN;
 297                } else
 298                        val = 0;
 299                return val;
 300        }
 301
 302        val = mutex_lock_interruptible(&epdata->lock);
 303        if (val < 0)
 304                return val;
 305
 306        switch (epdata->state) {
 307        case STATE_EP_ENABLED:
 308                break;
 309        // case STATE_EP_DISABLED:              /* "can't happen" */
 310        // case STATE_EP_READY:                 /* "can't happen" */
 311        default:                                /* error! */
 312                pr_debug ("%s: ep %p not available, state %d\n",
 313                                shortname, epdata, epdata->state);
 314                // FALLTHROUGH
 315        case STATE_EP_UNBOUND:                  /* clean disconnect */
 316                val = -ENODEV;
 317                mutex_unlock(&epdata->lock);
 318        }
 319        return val;
 320}
 321
 322static ssize_t
 323ep_io (struct ep_data *epdata, void *buf, unsigned len)
 324{
 325        DECLARE_COMPLETION_ONSTACK (done);
 326        int value;
 327
 328        spin_lock_irq (&epdata->dev->lock);
 329        if (likely (epdata->ep != NULL)) {
 330                struct usb_request      *req = epdata->req;
 331
 332                req->context = &done;
 333                req->complete = epio_complete;
 334                req->buf = buf;
 335                req->length = len;
 336                value = usb_ep_queue (epdata->ep, req, GFP_ATOMIC);
 337        } else
 338                value = -ENODEV;
 339        spin_unlock_irq (&epdata->dev->lock);
 340
 341        if (likely (value == 0)) {
 342                value = wait_event_interruptible (done.wait, done.done);
 343                if (value != 0) {
 344                        spin_lock_irq (&epdata->dev->lock);
 345                        if (likely (epdata->ep != NULL)) {
 346                                DBG (epdata->dev, "%s i/o interrupted\n",
 347                                                epdata->name);
 348                                usb_ep_dequeue (epdata->ep, epdata->req);
 349                                spin_unlock_irq (&epdata->dev->lock);
 350
 351                                wait_event (done.wait, done.done);
 352                                if (epdata->status == -ECONNRESET)
 353                                        epdata->status = -EINTR;
 354                        } else {
 355                                spin_unlock_irq (&epdata->dev->lock);
 356
 357                                DBG (epdata->dev, "endpoint gone\n");
 358                                epdata->status = -ENODEV;
 359                        }
 360                }
 361                return epdata->status;
 362        }
 363        return value;
 364}
 365
 366
 367/* handle a synchronous OUT bulk/intr/iso transfer */
 368static ssize_t
 369ep_read (struct file *fd, char __user *buf, size_t len, loff_t *ptr)
 370{
 371        struct ep_data          *data = fd->private_data;
 372        void                    *kbuf;
 373        ssize_t                 value;
 374
 375        if ((value = get_ready_ep (fd->f_flags, data)) < 0)
 376                return value;
 377
 378        /* halt any endpoint by doing a "wrong direction" i/o call */
 379        if (usb_endpoint_dir_in(&data->desc)) {
 380                if (usb_endpoint_xfer_isoc(&data->desc)) {
 381                        mutex_unlock(&data->lock);
 382                        return -EINVAL;
 383                }
 384                DBG (data->dev, "%s halt\n", data->name);
 385                spin_lock_irq (&data->dev->lock);
 386                if (likely (data->ep != NULL))
 387                        usb_ep_set_halt (data->ep);
 388                spin_unlock_irq (&data->dev->lock);
 389                mutex_unlock(&data->lock);
 390                return -EBADMSG;
 391        }
 392
 393        /* FIXME readahead for O_NONBLOCK and poll(); careful with ZLPs */
 394
 395        value = -ENOMEM;
 396        kbuf = kmalloc (len, GFP_KERNEL);
 397        if (unlikely (!kbuf))
 398                goto free1;
 399
 400        value = ep_io (data, kbuf, len);
 401        VDEBUG (data->dev, "%s read %zu OUT, status %d\n",
 402                data->name, len, (int) value);
 403        if (value >= 0 && copy_to_user (buf, kbuf, value))
 404                value = -EFAULT;
 405
 406free1:
 407        mutex_unlock(&data->lock);
 408        kfree (kbuf);
 409        return value;
 410}
 411
 412/* handle a synchronous IN bulk/intr/iso transfer */
 413static ssize_t
 414ep_write (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
 415{
 416        struct ep_data          *data = fd->private_data;
 417        void                    *kbuf;
 418        ssize_t                 value;
 419
 420        if ((value = get_ready_ep (fd->f_flags, data)) < 0)
 421                return value;
 422
 423        /* halt any endpoint by doing a "wrong direction" i/o call */
 424        if (!usb_endpoint_dir_in(&data->desc)) {
 425                if (usb_endpoint_xfer_isoc(&data->desc)) {
 426                        mutex_unlock(&data->lock);
 427                        return -EINVAL;
 428                }
 429                DBG (data->dev, "%s halt\n", data->name);
 430                spin_lock_irq (&data->dev->lock);
 431                if (likely (data->ep != NULL))
 432                        usb_ep_set_halt (data->ep);
 433                spin_unlock_irq (&data->dev->lock);
 434                mutex_unlock(&data->lock);
 435                return -EBADMSG;
 436        }
 437
 438        /* FIXME writebehind for O_NONBLOCK and poll(), qlen = 1 */
 439
 440        value = -ENOMEM;
 441        kbuf = memdup_user(buf, len);
 442        if (IS_ERR(kbuf)) {
 443                value = PTR_ERR(kbuf);
 444                kbuf = NULL;
 445                goto free1;
 446        }
 447
 448        value = ep_io (data, kbuf, len);
 449        VDEBUG (data->dev, "%s write %zu IN, status %d\n",
 450                data->name, len, (int) value);
 451free1:
 452        mutex_unlock(&data->lock);
 453        kfree (kbuf);
 454        return value;
 455}
 456
 457static int
 458ep_release (struct inode *inode, struct file *fd)
 459{
 460        struct ep_data          *data = fd->private_data;
 461        int value;
 462
 463        value = mutex_lock_interruptible(&data->lock);
 464        if (value < 0)
 465                return value;
 466
 467        /* clean up if this can be reopened */
 468        if (data->state != STATE_EP_UNBOUND) {
 469                data->state = STATE_EP_DISABLED;
 470                data->desc.bDescriptorType = 0;
 471                data->hs_desc.bDescriptorType = 0;
 472                usb_ep_disable(data->ep);
 473        }
 474        mutex_unlock(&data->lock);
 475        put_ep (data);
 476        return 0;
 477}
 478
 479static long ep_ioctl(struct file *fd, unsigned code, unsigned long value)
 480{
 481        struct ep_data          *data = fd->private_data;
 482        int                     status;
 483
 484        if ((status = get_ready_ep (fd->f_flags, data)) < 0)
 485                return status;
 486
 487        spin_lock_irq (&data->dev->lock);
 488        if (likely (data->ep != NULL)) {
 489                switch (code) {
 490                case GADGETFS_FIFO_STATUS:
 491                        status = usb_ep_fifo_status (data->ep);
 492                        break;
 493                case GADGETFS_FIFO_FLUSH:
 494                        usb_ep_fifo_flush (data->ep);
 495                        break;
 496                case GADGETFS_CLEAR_HALT:
 497                        status = usb_ep_clear_halt (data->ep);
 498                        break;
 499                default:
 500                        status = -ENOTTY;
 501                }
 502        } else
 503                status = -ENODEV;
 504        spin_unlock_irq (&data->dev->lock);
 505        mutex_unlock(&data->lock);
 506        return status;
 507}
 508
 509/*----------------------------------------------------------------------*/
 510
 511/* ASYNCHRONOUS ENDPOINT I/O OPERATIONS (bulk/intr/iso) */
 512
 513struct kiocb_priv {
 514        struct usb_request      *req;
 515        struct ep_data          *epdata;
 516        struct kiocb            *iocb;
 517        struct mm_struct        *mm;
 518        struct work_struct      work;
 519        void                    *buf;
 520        const struct iovec      *iv;
 521        unsigned long           nr_segs;
 522        unsigned                actual;
 523};
 524
 525static int ep_aio_cancel(struct kiocb *iocb)
 526{
 527        struct kiocb_priv       *priv = iocb->private;
 528        struct ep_data          *epdata;
 529        int                     value;
 530
 531        local_irq_disable();
 532        epdata = priv->epdata;
 533        // spin_lock(&epdata->dev->lock);
 534        if (likely(epdata && epdata->ep && priv->req))
 535                value = usb_ep_dequeue (epdata->ep, priv->req);
 536        else
 537                value = -EINVAL;
 538        // spin_unlock(&epdata->dev->lock);
 539        local_irq_enable();
 540
 541        return value;
 542}
 543
 544static ssize_t ep_copy_to_user(struct kiocb_priv *priv)
 545{
 546        ssize_t                 len, total;
 547        void                    *to_copy;
 548        int                     i;
 549
 550        /* copy stuff into user buffers */
 551        total = priv->actual;
 552        len = 0;
 553        to_copy = priv->buf;
 554        for (i=0; i < priv->nr_segs; i++) {
 555                ssize_t this = min((ssize_t)(priv->iv[i].iov_len), total);
 556
 557                if (copy_to_user(priv->iv[i].iov_base, to_copy, this)) {
 558                        if (len == 0)
 559                                len = -EFAULT;
 560                        break;
 561                }
 562
 563                total -= this;
 564                len += this;
 565                to_copy += this;
 566                if (total == 0)
 567                        break;
 568        }
 569
 570        return len;
 571}
 572
 573static void ep_user_copy_worker(struct work_struct *work)
 574{
 575        struct kiocb_priv *priv = container_of(work, struct kiocb_priv, work);
 576        struct mm_struct *mm = priv->mm;
 577        struct kiocb *iocb = priv->iocb;
 578        size_t ret;
 579
 580        use_mm(mm);
 581        ret = ep_copy_to_user(priv);
 582        unuse_mm(mm);
 583
 584        /* completing the iocb can drop the ctx and mm, don't touch mm after */
 585        aio_complete(iocb, ret, ret);
 586
 587        kfree(priv->buf);
 588        kfree(priv);
 589}
 590
 591static void ep_aio_complete(struct usb_ep *ep, struct usb_request *req)
 592{
 593        struct kiocb            *iocb = req->context;
 594        struct kiocb_priv       *priv = iocb->private;
 595        struct ep_data          *epdata = priv->epdata;
 596
 597        /* lock against disconnect (and ideally, cancel) */
 598        spin_lock(&epdata->dev->lock);
 599        priv->req = NULL;
 600        priv->epdata = NULL;
 601
 602        /* if this was a write or a read returning no data then we
 603         * don't need to copy anything to userspace, so we can
 604         * complete the aio request immediately.
 605         */
 606        if (priv->iv == NULL || unlikely(req->actual == 0)) {
 607                kfree(req->buf);
 608                kfree(priv);
 609                iocb->private = NULL;
 610                /* aio_complete() reports bytes-transferred _and_ faults */
 611                aio_complete(iocb, req->actual ? req->actual : req->status,
 612                                req->status);
 613        } else {
 614                /* ep_copy_to_user() won't report both; we hide some faults */
 615                if (unlikely(0 != req->status))
 616                        DBG(epdata->dev, "%s fault %d len %d\n",
 617                                ep->name, req->status, req->actual);
 618
 619                priv->buf = req->buf;
 620                priv->actual = req->actual;
 621                schedule_work(&priv->work);
 622        }
 623        spin_unlock(&epdata->dev->lock);
 624
 625        usb_ep_free_request(ep, req);
 626        put_ep(epdata);
 627}
 628
 629static ssize_t
 630ep_aio_rwtail(
 631        struct kiocb    *iocb,
 632        char            *buf,
 633        size_t          len,
 634        struct ep_data  *epdata,
 635        const struct iovec *iv,
 636        unsigned long   nr_segs
 637)
 638{
 639        struct kiocb_priv       *priv;
 640        struct usb_request      *req;
 641        ssize_t                 value;
 642
 643        priv = kmalloc(sizeof *priv, GFP_KERNEL);
 644        if (!priv) {
 645                value = -ENOMEM;
 646fail:
 647                kfree(buf);
 648                return value;
 649        }
 650        iocb->private = priv;
 651        priv->iocb = iocb;
 652        priv->iv = iv;
 653        priv->nr_segs = nr_segs;
 654        INIT_WORK(&priv->work, ep_user_copy_worker);
 655
 656        value = get_ready_ep(iocb->ki_filp->f_flags, epdata);
 657        if (unlikely(value < 0)) {
 658                kfree(priv);
 659                goto fail;
 660        }
 661
 662        kiocb_set_cancel_fn(iocb, ep_aio_cancel);
 663        get_ep(epdata);
 664        priv->epdata = epdata;
 665        priv->actual = 0;
 666        priv->mm = current->mm; /* mm teardown waits for iocbs in exit_aio() */
 667
 668        /* each kiocb is coupled to one usb_request, but we can't
 669         * allocate or submit those if the host disconnected.
 670         */
 671        spin_lock_irq(&epdata->dev->lock);
 672        if (likely(epdata->ep)) {
 673                req = usb_ep_alloc_request(epdata->ep, GFP_ATOMIC);
 674                if (likely(req)) {
 675                        priv->req = req;
 676                        req->buf = buf;
 677                        req->length = len;
 678                        req->complete = ep_aio_complete;
 679                        req->context = iocb;
 680                        value = usb_ep_queue(epdata->ep, req, GFP_ATOMIC);
 681                        if (unlikely(0 != value))
 682                                usb_ep_free_request(epdata->ep, req);
 683                } else
 684                        value = -EAGAIN;
 685        } else
 686                value = -ENODEV;
 687        spin_unlock_irq(&epdata->dev->lock);
 688
 689        mutex_unlock(&epdata->lock);
 690
 691        if (unlikely(value)) {
 692                kfree(priv);
 693                put_ep(epdata);
 694        } else
 695                value = -EIOCBQUEUED;
 696        return value;
 697}
 698
 699static ssize_t
 700ep_aio_read(struct kiocb *iocb, const struct iovec *iov,
 701                unsigned long nr_segs, loff_t o)
 702{
 703        struct ep_data          *epdata = iocb->ki_filp->private_data;
 704        char                    *buf;
 705
 706        if (unlikely(usb_endpoint_dir_in(&epdata->desc)))
 707                return -EINVAL;
 708
 709        buf = kmalloc(iocb->ki_nbytes, GFP_KERNEL);
 710        if (unlikely(!buf))
 711                return -ENOMEM;
 712
 713        return ep_aio_rwtail(iocb, buf, iocb->ki_nbytes, epdata, iov, nr_segs);
 714}
 715
 716static ssize_t
 717ep_aio_write(struct kiocb *iocb, const struct iovec *iov,
 718                unsigned long nr_segs, loff_t o)
 719{
 720        struct ep_data          *epdata = iocb->ki_filp->private_data;
 721        char                    *buf;
 722        size_t                  len = 0;
 723        int                     i = 0;
 724
 725        if (unlikely(!usb_endpoint_dir_in(&epdata->desc)))
 726                return -EINVAL;
 727
 728        buf = kmalloc(iocb->ki_nbytes, GFP_KERNEL);
 729        if (unlikely(!buf))
 730                return -ENOMEM;
 731
 732        for (i=0; i < nr_segs; i++) {
 733                if (unlikely(copy_from_user(&buf[len], iov[i].iov_base,
 734                                iov[i].iov_len) != 0)) {
 735                        kfree(buf);
 736                        return -EFAULT;
 737                }
 738                len += iov[i].iov_len;
 739        }
 740        return ep_aio_rwtail(iocb, buf, len, epdata, NULL, 0);
 741}
 742
 743/*----------------------------------------------------------------------*/
 744
 745/* used after endpoint configuration */
 746static const struct file_operations ep_io_operations = {
 747        .owner =        THIS_MODULE,
 748        .llseek =       no_llseek,
 749
 750        .read =         ep_read,
 751        .write =        ep_write,
 752        .unlocked_ioctl = ep_ioctl,
 753        .release =      ep_release,
 754
 755        .aio_read =     ep_aio_read,
 756        .aio_write =    ep_aio_write,
 757};
 758
 759/* ENDPOINT INITIALIZATION
 760 *
 761 *     fd = open ("/dev/gadget/$ENDPOINT", O_RDWR)
 762 *     status = write (fd, descriptors, sizeof descriptors)
 763 *
 764 * That write establishes the endpoint configuration, configuring
 765 * the controller to process bulk, interrupt, or isochronous transfers
 766 * at the right maxpacket size, and so on.
 767 *
 768 * The descriptors are message type 1, identified by a host order u32
 769 * at the beginning of what's written.  Descriptor order is: full/low
 770 * speed descriptor, then optional high speed descriptor.
 771 */
 772static ssize_t
 773ep_config (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
 774{
 775        struct ep_data          *data = fd->private_data;
 776        struct usb_ep           *ep;
 777        u32                     tag;
 778        int                     value, length = len;
 779
 780        value = mutex_lock_interruptible(&data->lock);
 781        if (value < 0)
 782                return value;
 783
 784        if (data->state != STATE_EP_READY) {
 785                value = -EL2HLT;
 786                goto fail;
 787        }
 788
 789        value = len;
 790        if (len < USB_DT_ENDPOINT_SIZE + 4)
 791                goto fail0;
 792
 793        /* we might need to change message format someday */
 794        if (copy_from_user (&tag, buf, 4)) {
 795                goto fail1;
 796        }
 797        if (tag != 1) {
 798                DBG(data->dev, "config %s, bad tag %d\n", data->name, tag);
 799                goto fail0;
 800        }
 801        buf += 4;
 802        len -= 4;
 803
 804        /* NOTE:  audio endpoint extensions not accepted here;
 805         * just don't include the extra bytes.
 806         */
 807
 808        /* full/low speed descriptor, then high speed */
 809        if (copy_from_user (&data->desc, buf, USB_DT_ENDPOINT_SIZE)) {
 810                goto fail1;
 811        }
 812        if (data->desc.bLength != USB_DT_ENDPOINT_SIZE
 813                        || data->desc.bDescriptorType != USB_DT_ENDPOINT)
 814                goto fail0;
 815        if (len != USB_DT_ENDPOINT_SIZE) {
 816                if (len != 2 * USB_DT_ENDPOINT_SIZE)
 817                        goto fail0;
 818                if (copy_from_user (&data->hs_desc, buf + USB_DT_ENDPOINT_SIZE,
 819                                        USB_DT_ENDPOINT_SIZE)) {
 820                        goto fail1;
 821                }
 822                if (data->hs_desc.bLength != USB_DT_ENDPOINT_SIZE
 823                                || data->hs_desc.bDescriptorType
 824                                        != USB_DT_ENDPOINT) {
 825                        DBG(data->dev, "config %s, bad hs length or type\n",
 826                                        data->name);
 827                        goto fail0;
 828                }
 829        }
 830
 831        spin_lock_irq (&data->dev->lock);
 832        if (data->dev->state == STATE_DEV_UNBOUND) {
 833                value = -ENOENT;
 834                goto gone;
 835        } else if ((ep = data->ep) == NULL) {
 836                value = -ENODEV;
 837                goto gone;
 838        }
 839        switch (data->dev->gadget->speed) {
 840        case USB_SPEED_LOW:
 841        case USB_SPEED_FULL:
 842                ep->desc = &data->desc;
 843                value = usb_ep_enable(ep);
 844                if (value == 0)
 845                        data->state = STATE_EP_ENABLED;
 846                break;
 847        case USB_SPEED_HIGH:
 848                /* fails if caller didn't provide that descriptor... */
 849                ep->desc = &data->hs_desc;
 850                value = usb_ep_enable(ep);
 851                if (value == 0)
 852                        data->state = STATE_EP_ENABLED;
 853                break;
 854        default:
 855                DBG(data->dev, "unconnected, %s init abandoned\n",
 856                                data->name);
 857                value = -EINVAL;
 858        }
 859        if (value == 0) {
 860                fd->f_op = &ep_io_operations;
 861                value = length;
 862        }
 863gone:
 864        spin_unlock_irq (&data->dev->lock);
 865        if (value < 0) {
 866fail:
 867                data->desc.bDescriptorType = 0;
 868                data->hs_desc.bDescriptorType = 0;
 869        }
 870        mutex_unlock(&data->lock);
 871        return value;
 872fail0:
 873        value = -EINVAL;
 874        goto fail;
 875fail1:
 876        value = -EFAULT;
 877        goto fail;
 878}
 879
 880static int
 881ep_open (struct inode *inode, struct file *fd)
 882{
 883        struct ep_data          *data = inode->i_private;
 884        int                     value = -EBUSY;
 885
 886        if (mutex_lock_interruptible(&data->lock) != 0)
 887                return -EINTR;
 888        spin_lock_irq (&data->dev->lock);
 889        if (data->dev->state == STATE_DEV_UNBOUND)
 890                value = -ENOENT;
 891        else if (data->state == STATE_EP_DISABLED) {
 892                value = 0;
 893                data->state = STATE_EP_READY;
 894                get_ep (data);
 895                fd->private_data = data;
 896                VDEBUG (data->dev, "%s ready\n", data->name);
 897        } else
 898                DBG (data->dev, "%s state %d\n",
 899                        data->name, data->state);
 900        spin_unlock_irq (&data->dev->lock);
 901        mutex_unlock(&data->lock);
 902        return value;
 903}
 904
 905/* used before endpoint configuration */
 906static const struct file_operations ep_config_operations = {
 907        .llseek =       no_llseek,
 908
 909        .open =         ep_open,
 910        .write =        ep_config,
 911        .release =      ep_release,
 912};
 913
 914/*----------------------------------------------------------------------*/
 915
 916/* EP0 IMPLEMENTATION can be partly in userspace.
 917 *
 918 * Drivers that use this facility receive various events, including
 919 * control requests the kernel doesn't handle.  Drivers that don't
 920 * use this facility may be too simple-minded for real applications.
 921 */
 922
 923static inline void ep0_readable (struct dev_data *dev)
 924{
 925        wake_up (&dev->wait);
 926        kill_fasync (&dev->fasync, SIGIO, POLL_IN);
 927}
 928
 929static void clean_req (struct usb_ep *ep, struct usb_request *req)
 930{
 931        struct dev_data         *dev = ep->driver_data;
 932
 933        if (req->buf != dev->rbuf) {
 934                kfree(req->buf);
 935                req->buf = dev->rbuf;
 936        }
 937        req->complete = epio_complete;
 938        dev->setup_out_ready = 0;
 939}
 940
 941static void ep0_complete (struct usb_ep *ep, struct usb_request *req)
 942{
 943        struct dev_data         *dev = ep->driver_data;
 944        unsigned long           flags;
 945        int                     free = 1;
 946
 947        /* for control OUT, data must still get to userspace */
 948        spin_lock_irqsave(&dev->lock, flags);
 949        if (!dev->setup_in) {
 950                dev->setup_out_error = (req->status != 0);
 951                if (!dev->setup_out_error)
 952                        free = 0;
 953                dev->setup_out_ready = 1;
 954                ep0_readable (dev);
 955        }
 956
 957        /* clean up as appropriate */
 958        if (free && req->buf != &dev->rbuf)
 959                clean_req (ep, req);
 960        req->complete = epio_complete;
 961        spin_unlock_irqrestore(&dev->lock, flags);
 962}
 963
 964static int setup_req (struct usb_ep *ep, struct usb_request *req, u16 len)
 965{
 966        struct dev_data *dev = ep->driver_data;
 967
 968        if (dev->setup_out_ready) {
 969                DBG (dev, "ep0 request busy!\n");
 970                return -EBUSY;
 971        }
 972        if (len > sizeof (dev->rbuf))
 973                req->buf = kmalloc(len, GFP_ATOMIC);
 974        if (req->buf == NULL) {
 975                req->buf = dev->rbuf;
 976                return -ENOMEM;
 977        }
 978        req->complete = ep0_complete;
 979        req->length = len;
 980        req->zero = 0;
 981        return 0;
 982}
 983
 984static ssize_t
 985ep0_read (struct file *fd, char __user *buf, size_t len, loff_t *ptr)
 986{
 987        struct dev_data                 *dev = fd->private_data;
 988        ssize_t                         retval;
 989        enum ep0_state                  state;
 990
 991        spin_lock_irq (&dev->lock);
 992
 993        /* report fd mode change before acting on it */
 994        if (dev->setup_abort) {
 995                dev->setup_abort = 0;
 996                retval = -EIDRM;
 997                goto done;
 998        }
 999
1000        /* control DATA stage */
1001        if ((state = dev->state) == STATE_DEV_SETUP) {
1002
1003                if (dev->setup_in) {            /* stall IN */
1004                        VDEBUG(dev, "ep0in stall\n");
1005                        (void) usb_ep_set_halt (dev->gadget->ep0);
1006                        retval = -EL2HLT;
1007                        dev->state = STATE_DEV_CONNECTED;
1008
1009                } else if (len == 0) {          /* ack SET_CONFIGURATION etc */
1010                        struct usb_ep           *ep = dev->gadget->ep0;
1011                        struct usb_request      *req = dev->req;
1012
1013                        if ((retval = setup_req (ep, req, 0)) == 0)
1014                                retval = usb_ep_queue (ep, req, GFP_ATOMIC);
1015                        dev->state = STATE_DEV_CONNECTED;
1016
1017                        /* assume that was SET_CONFIGURATION */
1018                        if (dev->current_config) {
1019                                unsigned power;
1020
1021                                if (gadget_is_dualspeed(dev->gadget)
1022                                                && (dev->gadget->speed
1023                                                        == USB_SPEED_HIGH))
1024                                        power = dev->hs_config->bMaxPower;
1025                                else
1026                                        power = dev->config->bMaxPower;
1027                                usb_gadget_vbus_draw(dev->gadget, 2 * power);
1028                        }
1029
1030                } else {                        /* collect OUT data */
1031                        if ((fd->f_flags & O_NONBLOCK) != 0
1032                                        && !dev->setup_out_ready) {
1033                                retval = -EAGAIN;
1034                                goto done;
1035                        }
1036                        spin_unlock_irq (&dev->lock);
1037                        retval = wait_event_interruptible (dev->wait,
1038                                        dev->setup_out_ready != 0);
1039
1040                        /* FIXME state could change from under us */
1041                        spin_lock_irq (&dev->lock);
1042                        if (retval)
1043                                goto done;
1044
1045                        if (dev->state != STATE_DEV_SETUP) {
1046                                retval = -ECANCELED;
1047                                goto done;
1048                        }
1049                        dev->state = STATE_DEV_CONNECTED;
1050
1051                        if (dev->setup_out_error)
1052                                retval = -EIO;
1053                        else {
1054                                len = min (len, (size_t)dev->req->actual);
1055// FIXME don't call this with the spinlock held ...
1056                                if (copy_to_user (buf, dev->req->buf, len))
1057                                        retval = -EFAULT;
1058                                else
1059                                        retval = len;
1060                                clean_req (dev->gadget->ep0, dev->req);
1061                                /* NOTE userspace can't yet choose to stall */
1062                        }
1063                }
1064                goto done;
1065        }
1066
1067        /* else normal: return event data */
1068        if (len < sizeof dev->event [0]) {
1069                retval = -EINVAL;
1070                goto done;
1071        }
1072        len -= len % sizeof (struct usb_gadgetfs_event);
1073        dev->usermode_setup = 1;
1074
1075scan:
1076        /* return queued events right away */
1077        if (dev->ev_next != 0) {
1078                unsigned                i, n;
1079
1080                n = len / sizeof (struct usb_gadgetfs_event);
1081                if (dev->ev_next < n)
1082                        n = dev->ev_next;
1083
1084                /* ep0 i/o has special semantics during STATE_DEV_SETUP */
1085                for (i = 0; i < n; i++) {
1086                        if (dev->event [i].type == GADGETFS_SETUP) {
1087                                dev->state = STATE_DEV_SETUP;
1088                                n = i + 1;
1089                                break;
1090                        }
1091                }
1092                spin_unlock_irq (&dev->lock);
1093                len = n * sizeof (struct usb_gadgetfs_event);
1094                if (copy_to_user (buf, &dev->event, len))
1095                        retval = -EFAULT;
1096                else
1097                        retval = len;
1098                if (len > 0) {
1099                        /* NOTE this doesn't guard against broken drivers;
1100                         * concurrent ep0 readers may lose events.
1101                         */
1102                        spin_lock_irq (&dev->lock);
1103                        if (dev->ev_next > n) {
1104                                memmove(&dev->event[0], &dev->event[n],
1105                                        sizeof (struct usb_gadgetfs_event)
1106                                                * (dev->ev_next - n));
1107                        }
1108                        dev->ev_next -= n;
1109                        spin_unlock_irq (&dev->lock);
1110                }
1111                return retval;
1112        }
1113        if (fd->f_flags & O_NONBLOCK) {
1114                retval = -EAGAIN;
1115                goto done;
1116        }
1117
1118        switch (state) {
1119        default:
1120                DBG (dev, "fail %s, state %d\n", __func__, state);
1121                retval = -ESRCH;
1122                break;
1123        case STATE_DEV_UNCONNECTED:
1124        case STATE_DEV_CONNECTED:
1125                spin_unlock_irq (&dev->lock);
1126                DBG (dev, "%s wait\n", __func__);
1127
1128                /* wait for events */
1129                retval = wait_event_interruptible (dev->wait,
1130                                dev->ev_next != 0);
1131                if (retval < 0)
1132                        return retval;
1133                spin_lock_irq (&dev->lock);
1134                goto scan;
1135        }
1136
1137done:
1138        spin_unlock_irq (&dev->lock);
1139        return retval;
1140}
1141
1142static struct usb_gadgetfs_event *
1143next_event (struct dev_data *dev, enum usb_gadgetfs_event_type type)
1144{
1145        struct usb_gadgetfs_event       *event;
1146        unsigned                        i;
1147
1148        switch (type) {
1149        /* these events purge the queue */
1150        case GADGETFS_DISCONNECT:
1151                if (dev->state == STATE_DEV_SETUP)
1152                        dev->setup_abort = 1;
1153                // FALL THROUGH
1154        case GADGETFS_CONNECT:
1155                dev->ev_next = 0;
1156                break;
1157        case GADGETFS_SETUP:            /* previous request timed out */
1158        case GADGETFS_SUSPEND:          /* same effect */
1159                /* these events can't be repeated */
1160                for (i = 0; i != dev->ev_next; i++) {
1161                        if (dev->event [i].type != type)
1162                                continue;
1163                        DBG(dev, "discard old event[%d] %d\n", i, type);
1164                        dev->ev_next--;
1165                        if (i == dev->ev_next)
1166                                break;
1167                        /* indices start at zero, for simplicity */
1168                        memmove (&dev->event [i], &dev->event [i + 1],
1169                                sizeof (struct usb_gadgetfs_event)
1170                                        * (dev->ev_next - i));
1171                }
1172                break;
1173        default:
1174                BUG ();
1175        }
1176        VDEBUG(dev, "event[%d] = %d\n", dev->ev_next, type);
1177        event = &dev->event [dev->ev_next++];
1178        BUG_ON (dev->ev_next > N_EVENT);
1179        memset (event, 0, sizeof *event);
1180        event->type = type;
1181        return event;
1182}
1183
1184static ssize_t
1185ep0_write (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
1186{
1187        struct dev_data         *dev = fd->private_data;
1188        ssize_t                 retval = -ESRCH;
1189
1190        spin_lock_irq (&dev->lock);
1191
1192        /* report fd mode change before acting on it */
1193        if (dev->setup_abort) {
1194                dev->setup_abort = 0;
1195                retval = -EIDRM;
1196
1197        /* data and/or status stage for control request */
1198        } else if (dev->state == STATE_DEV_SETUP) {
1199
1200                /* IN DATA+STATUS caller makes len <= wLength */
1201                if (dev->setup_in) {
1202                        retval = setup_req (dev->gadget->ep0, dev->req, len);
1203                        if (retval == 0) {
1204                                dev->state = STATE_DEV_CONNECTED;
1205                                spin_unlock_irq (&dev->lock);
1206                                if (copy_from_user (dev->req->buf, buf, len))
1207                                        retval = -EFAULT;
1208                                else {
1209                                        if (len < dev->setup_wLength)
1210                                                dev->req->zero = 1;
1211                                        retval = usb_ep_queue (
1212                                                dev->gadget->ep0, dev->req,
1213                                                GFP_KERNEL);
1214                                }
1215                                if (retval < 0) {
1216                                        spin_lock_irq (&dev->lock);
1217                                        clean_req (dev->gadget->ep0, dev->req);
1218                                        spin_unlock_irq (&dev->lock);
1219                                } else
1220                                        retval = len;
1221
1222                                return retval;
1223                        }
1224
1225                /* can stall some OUT transfers */
1226                } else if (dev->setup_can_stall) {
1227                        VDEBUG(dev, "ep0out stall\n");
1228                        (void) usb_ep_set_halt (dev->gadget->ep0);
1229                        retval = -EL2HLT;
1230                        dev->state = STATE_DEV_CONNECTED;
1231                } else {
1232                        DBG(dev, "bogus ep0out stall!\n");
1233                }
1234        } else
1235                DBG (dev, "fail %s, state %d\n", __func__, dev->state);
1236
1237        spin_unlock_irq (&dev->lock);
1238        return retval;
1239}
1240
1241static int
1242ep0_fasync (int f, struct file *fd, int on)
1243{
1244        struct dev_data         *dev = fd->private_data;
1245        // caller must F_SETOWN before signal delivery happens
1246        VDEBUG (dev, "%s %s\n", __func__, on ? "on" : "off");
1247        return fasync_helper (f, fd, on, &dev->fasync);
1248}
1249
1250static struct usb_gadget_driver gadgetfs_driver;
1251
1252static int
1253dev_release (struct inode *inode, struct file *fd)
1254{
1255        struct dev_data         *dev = fd->private_data;
1256
1257        /* closing ep0 === shutdown all */
1258
1259        usb_gadget_unregister_driver (&gadgetfs_driver);
1260
1261        /* at this point "good" hardware has disconnected the
1262         * device from USB; the host won't see it any more.
1263         * alternatively, all host requests will time out.
1264         */
1265
1266        kfree (dev->buf);
1267        dev->buf = NULL;
1268
1269        /* other endpoints were all decoupled from this device */
1270        spin_lock_irq(&dev->lock);
1271        dev->state = STATE_DEV_DISABLED;
1272        spin_unlock_irq(&dev->lock);
1273
1274        put_dev (dev);
1275        return 0;
1276}
1277
1278static unsigned int
1279ep0_poll (struct file *fd, poll_table *wait)
1280{
1281       struct dev_data         *dev = fd->private_data;
1282       int                     mask = 0;
1283
1284       poll_wait(fd, &dev->wait, wait);
1285
1286       spin_lock_irq (&dev->lock);
1287
1288       /* report fd mode change before acting on it */
1289       if (dev->setup_abort) {
1290               dev->setup_abort = 0;
1291               mask = POLLHUP;
1292               goto out;
1293       }
1294
1295       if (dev->state == STATE_DEV_SETUP) {
1296               if (dev->setup_in || dev->setup_can_stall)
1297                       mask = POLLOUT;
1298       } else {
1299               if (dev->ev_next != 0)
1300                       mask = POLLIN;
1301       }
1302out:
1303       spin_unlock_irq(&dev->lock);
1304       return mask;
1305}
1306
1307static long dev_ioctl (struct file *fd, unsigned code, unsigned long value)
1308{
1309        struct dev_data         *dev = fd->private_data;
1310        struct usb_gadget       *gadget = dev->gadget;
1311        long ret = -ENOTTY;
1312
1313        if (gadget->ops->ioctl)
1314                ret = gadget->ops->ioctl (gadget, code, value);
1315
1316        return ret;
1317}
1318
1319/* used after device configuration */
1320static const struct file_operations ep0_io_operations = {
1321        .owner =        THIS_MODULE,
1322        .llseek =       no_llseek,
1323
1324        .read =         ep0_read,
1325        .write =        ep0_write,
1326        .fasync =       ep0_fasync,
1327        .poll =         ep0_poll,
1328        .unlocked_ioctl =       dev_ioctl,
1329        .release =      dev_release,
1330};
1331
1332/*----------------------------------------------------------------------*/
1333
1334/* The in-kernel gadget driver handles most ep0 issues, in particular
1335 * enumerating the single configuration (as provided from user space).
1336 *
1337 * Unrecognized ep0 requests may be handled in user space.
1338 */
1339
1340static void make_qualifier (struct dev_data *dev)
1341{
1342        struct usb_qualifier_descriptor         qual;
1343        struct usb_device_descriptor            *desc;
1344
1345        qual.bLength = sizeof qual;
1346        qual.bDescriptorType = USB_DT_DEVICE_QUALIFIER;
1347        qual.bcdUSB = cpu_to_le16 (0x0200);
1348
1349        desc = dev->dev;
1350        qual.bDeviceClass = desc->bDeviceClass;
1351        qual.bDeviceSubClass = desc->bDeviceSubClass;
1352        qual.bDeviceProtocol = desc->bDeviceProtocol;
1353
1354        /* assumes ep0 uses the same value for both speeds ... */
1355        qual.bMaxPacketSize0 = dev->gadget->ep0->maxpacket;
1356
1357        qual.bNumConfigurations = 1;
1358        qual.bRESERVED = 0;
1359
1360        memcpy (dev->rbuf, &qual, sizeof qual);
1361}
1362
1363static int
1364config_buf (struct dev_data *dev, u8 type, unsigned index)
1365{
1366        int             len;
1367        int             hs = 0;
1368
1369        /* only one configuration */
1370        if (index > 0)
1371                return -EINVAL;
1372
1373        if (gadget_is_dualspeed(dev->gadget)) {
1374                hs = (dev->gadget->speed == USB_SPEED_HIGH);
1375                if (type == USB_DT_OTHER_SPEED_CONFIG)
1376                        hs = !hs;
1377        }
1378        if (hs) {
1379                dev->req->buf = dev->hs_config;
1380                len = le16_to_cpu(dev->hs_config->wTotalLength);
1381        } else {
1382                dev->req->buf = dev->config;
1383                len = le16_to_cpu(dev->config->wTotalLength);
1384        }
1385        ((u8 *)dev->req->buf) [1] = type;
1386        return len;
1387}
1388
1389static int
1390gadgetfs_setup (struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
1391{
1392        struct dev_data                 *dev = get_gadget_data (gadget);
1393        struct usb_request              *req = dev->req;
1394        int                             value = -EOPNOTSUPP;
1395        struct usb_gadgetfs_event       *event;
1396        u16                             w_value = le16_to_cpu(ctrl->wValue);
1397        u16                             w_length = le16_to_cpu(ctrl->wLength);
1398
1399        spin_lock (&dev->lock);
1400        dev->setup_abort = 0;
1401        if (dev->state == STATE_DEV_UNCONNECTED) {
1402                if (gadget_is_dualspeed(gadget)
1403                                && gadget->speed == USB_SPEED_HIGH
1404                                && dev->hs_config == NULL) {
1405                        spin_unlock(&dev->lock);
1406                        ERROR (dev, "no high speed config??\n");
1407                        return -EINVAL;
1408                }
1409
1410                dev->state = STATE_DEV_CONNECTED;
1411
1412                INFO (dev, "connected\n");
1413                event = next_event (dev, GADGETFS_CONNECT);
1414                event->u.speed = gadget->speed;
1415                ep0_readable (dev);
1416
1417        /* host may have given up waiting for response.  we can miss control
1418         * requests handled lower down (device/endpoint status and features);
1419         * then ep0_{read,write} will report the wrong status. controller
1420         * driver will have aborted pending i/o.
1421         */
1422        } else if (dev->state == STATE_DEV_SETUP)
1423                dev->setup_abort = 1;
1424
1425        req->buf = dev->rbuf;
1426        req->context = NULL;
1427        value = -EOPNOTSUPP;
1428        switch (ctrl->bRequest) {
1429
1430        case USB_REQ_GET_DESCRIPTOR:
1431                if (ctrl->bRequestType != USB_DIR_IN)
1432                        goto unrecognized;
1433                switch (w_value >> 8) {
1434
1435                case USB_DT_DEVICE:
1436                        value = min (w_length, (u16) sizeof *dev->dev);
1437                        dev->dev->bMaxPacketSize0 = dev->gadget->ep0->maxpacket;
1438                        req->buf = dev->dev;
1439                        break;
1440                case USB_DT_DEVICE_QUALIFIER:
1441                        if (!dev->hs_config)
1442                                break;
1443                        value = min (w_length, (u16)
1444                                sizeof (struct usb_qualifier_descriptor));
1445                        make_qualifier (dev);
1446                        break;
1447                case USB_DT_OTHER_SPEED_CONFIG:
1448                        // FALLTHROUGH
1449                case USB_DT_CONFIG:
1450                        value = config_buf (dev,
1451                                        w_value >> 8,
1452                                        w_value & 0xff);
1453                        if (value >= 0)
1454                                value = min (w_length, (u16) value);
1455                        break;
1456                case USB_DT_STRING:
1457                        goto unrecognized;
1458
1459                default:                // all others are errors
1460                        break;
1461                }
1462                break;
1463
1464        /* currently one config, two speeds */
1465        case USB_REQ_SET_CONFIGURATION:
1466                if (ctrl->bRequestType != 0)
1467                        goto unrecognized;
1468                if (0 == (u8) w_value) {
1469                        value = 0;
1470                        dev->current_config = 0;
1471                        usb_gadget_vbus_draw(gadget, 8 /* mA */ );
1472                        // user mode expected to disable endpoints
1473                } else {
1474                        u8      config, power;
1475
1476                        if (gadget_is_dualspeed(gadget)
1477                                        && gadget->speed == USB_SPEED_HIGH) {
1478                                config = dev->hs_config->bConfigurationValue;
1479                                power = dev->hs_config->bMaxPower;
1480                        } else {
1481                                config = dev->config->bConfigurationValue;
1482                                power = dev->config->bMaxPower;
1483                        }
1484
1485                        if (config == (u8) w_value) {
1486                                value = 0;
1487                                dev->current_config = config;
1488                                usb_gadget_vbus_draw(gadget, 2 * power);
1489                        }
1490                }
1491
1492                /* report SET_CONFIGURATION like any other control request,
1493                 * except that usermode may not stall this.  the next
1494                 * request mustn't be allowed start until this finishes:
1495                 * endpoints and threads set up, etc.
1496                 *
1497                 * NOTE:  older PXA hardware (before PXA 255: without UDCCFR)
1498                 * has bad/racey automagic that prevents synchronizing here.
1499                 * even kernel mode drivers often miss them.
1500                 */
1501                if (value == 0) {
1502                        INFO (dev, "configuration #%d\n", dev->current_config);
1503                        usb_gadget_set_state(gadget, USB_STATE_CONFIGURED);
1504                        if (dev->usermode_setup) {
1505                                dev->setup_can_stall = 0;
1506                                goto delegate;
1507                        }
1508                }
1509                break;
1510
1511#ifndef CONFIG_USB_PXA25X
1512        /* PXA automagically handles this request too */
1513        case USB_REQ_GET_CONFIGURATION:
1514                if (ctrl->bRequestType != 0x80)
1515                        goto unrecognized;
1516                *(u8 *)req->buf = dev->current_config;
1517                value = min (w_length, (u16) 1);
1518                break;
1519#endif
1520
1521        default:
1522unrecognized:
1523                VDEBUG (dev, "%s req%02x.%02x v%04x i%04x l%d\n",
1524                        dev->usermode_setup ? "delegate" : "fail",
1525                        ctrl->bRequestType, ctrl->bRequest,
1526                        w_value, le16_to_cpu(ctrl->wIndex), w_length);
1527
1528                /* if there's an ep0 reader, don't stall */
1529                if (dev->usermode_setup) {
1530                        dev->setup_can_stall = 1;
1531delegate:
1532                        dev->setup_in = (ctrl->bRequestType & USB_DIR_IN)
1533                                                ? 1 : 0;
1534                        dev->setup_wLength = w_length;
1535                        dev->setup_out_ready = 0;
1536                        dev->setup_out_error = 0;
1537                        value = 0;
1538
1539                        /* read DATA stage for OUT right away */
1540                        if (unlikely (!dev->setup_in && w_length)) {
1541                                value = setup_req (gadget->ep0, dev->req,
1542                                                        w_length);
1543                                if (value < 0)
1544                                        break;
1545                                value = usb_ep_queue (gadget->ep0, dev->req,
1546                                                        GFP_ATOMIC);
1547                                if (value < 0) {
1548                                        clean_req (gadget->ep0, dev->req);
1549                                        break;
1550                                }
1551
1552                                /* we can't currently stall these */
1553                                dev->setup_can_stall = 0;
1554                        }
1555
1556                        /* state changes when reader collects event */
1557                        event = next_event (dev, GADGETFS_SETUP);
1558                        event->u.setup = *ctrl;
1559                        ep0_readable (dev);
1560                        spin_unlock (&dev->lock);
1561                        return 0;
1562                }
1563        }
1564
1565        /* proceed with data transfer and status phases? */
1566        if (value >= 0 && dev->state != STATE_DEV_SETUP) {
1567                req->length = value;
1568                req->zero = value < w_length;
1569                value = usb_ep_queue (gadget->ep0, req, GFP_ATOMIC);
1570                if (value < 0) {
1571                        DBG (dev, "ep_queue --> %d\n", value);
1572                        req->status = 0;
1573                }
1574        }
1575
1576        /* device stalls when value < 0 */
1577        spin_unlock (&dev->lock);
1578        return value;
1579}
1580
1581static void destroy_ep_files (struct dev_data *dev)
1582{
1583        DBG (dev, "%s %d\n", __func__, dev->state);
1584
1585        /* dev->state must prevent interference */
1586        spin_lock_irq (&dev->lock);
1587        while (!list_empty(&dev->epfiles)) {
1588                struct ep_data  *ep;
1589                struct inode    *parent;
1590                struct dentry   *dentry;
1591
1592                /* break link to FS */
1593                ep = list_first_entry (&dev->epfiles, struct ep_data, epfiles);
1594                list_del_init (&ep->epfiles);
1595                dentry = ep->dentry;
1596                ep->dentry = NULL;
1597                parent = dentry->d_parent->d_inode;
1598
1599                /* break link to controller */
1600                if (ep->state == STATE_EP_ENABLED)
1601                        (void) usb_ep_disable (ep->ep);
1602                ep->state = STATE_EP_UNBOUND;
1603                usb_ep_free_request (ep->ep, ep->req);
1604                ep->ep = NULL;
1605                wake_up (&ep->wait);
1606                put_ep (ep);
1607
1608                spin_unlock_irq (&dev->lock);
1609
1610                /* break link to dcache */
1611                mutex_lock (&parent->i_mutex);
1612                d_delete (dentry);
1613                dput (dentry);
1614                mutex_unlock (&parent->i_mutex);
1615
1616                spin_lock_irq (&dev->lock);
1617        }
1618        spin_unlock_irq (&dev->lock);
1619}
1620
1621
1622static struct dentry *
1623gadgetfs_create_file (struct super_block *sb, char const *name,
1624                void *data, const struct file_operations *fops);
1625
1626static int activate_ep_files (struct dev_data *dev)
1627{
1628        struct usb_ep   *ep;
1629        struct ep_data  *data;
1630
1631        gadget_for_each_ep (ep, dev->gadget) {
1632
1633                data = kzalloc(sizeof(*data), GFP_KERNEL);
1634                if (!data)
1635                        goto enomem0;
1636                data->state = STATE_EP_DISABLED;
1637                mutex_init(&data->lock);
1638                init_waitqueue_head (&data->wait);
1639
1640                strncpy (data->name, ep->name, sizeof (data->name) - 1);
1641                atomic_set (&data->count, 1);
1642                data->dev = dev;
1643                get_dev (dev);
1644
1645                data->ep = ep;
1646                ep->driver_data = data;
1647
1648                data->req = usb_ep_alloc_request (ep, GFP_KERNEL);
1649                if (!data->req)
1650                        goto enomem1;
1651
1652                data->dentry = gadgetfs_create_file (dev->sb, data->name,
1653                                data, &ep_config_operations);
1654                if (!data->dentry)
1655                        goto enomem2;
1656                list_add_tail (&data->epfiles, &dev->epfiles);
1657        }
1658        return 0;
1659
1660enomem2:
1661        usb_ep_free_request (ep, data->req);
1662enomem1:
1663        put_dev (dev);
1664        kfree (data);
1665enomem0:
1666        DBG (dev, "%s enomem\n", __func__);
1667        destroy_ep_files (dev);
1668        return -ENOMEM;
1669}
1670
1671static void
1672gadgetfs_unbind (struct usb_gadget *gadget)
1673{
1674        struct dev_data         *dev = get_gadget_data (gadget);
1675
1676        DBG (dev, "%s\n", __func__);
1677
1678        spin_lock_irq (&dev->lock);
1679        dev->state = STATE_DEV_UNBOUND;
1680        spin_unlock_irq (&dev->lock);
1681
1682        destroy_ep_files (dev);
1683        gadget->ep0->driver_data = NULL;
1684        set_gadget_data (gadget, NULL);
1685
1686        /* we've already been disconnected ... no i/o is active */
1687        if (dev->req)
1688                usb_ep_free_request (gadget->ep0, dev->req);
1689        DBG (dev, "%s done\n", __func__);
1690        put_dev (dev);
1691}
1692
1693static struct dev_data          *the_device;
1694
1695static int gadgetfs_bind(struct usb_gadget *gadget,
1696                struct usb_gadget_driver *driver)
1697{
1698        struct dev_data         *dev = the_device;
1699
1700        if (!dev)
1701                return -ESRCH;
1702        if (0 != strcmp (CHIP, gadget->name)) {
1703                pr_err("%s expected %s controller not %s\n",
1704                        shortname, CHIP, gadget->name);
1705                return -ENODEV;
1706        }
1707
1708        set_gadget_data (gadget, dev);
1709        dev->gadget = gadget;
1710        gadget->ep0->driver_data = dev;
1711
1712        /* preallocate control response and buffer */
1713        dev->req = usb_ep_alloc_request (gadget->ep0, GFP_KERNEL);
1714        if (!dev->req)
1715                goto enomem;
1716        dev->req->context = NULL;
1717        dev->req->complete = epio_complete;
1718
1719        if (activate_ep_files (dev) < 0)
1720                goto enomem;
1721
1722        INFO (dev, "bound to %s driver\n", gadget->name);
1723        spin_lock_irq(&dev->lock);
1724        dev->state = STATE_DEV_UNCONNECTED;
1725        spin_unlock_irq(&dev->lock);
1726        get_dev (dev);
1727        return 0;
1728
1729enomem:
1730        gadgetfs_unbind (gadget);
1731        return -ENOMEM;
1732}
1733
1734static void
1735gadgetfs_disconnect (struct usb_gadget *gadget)
1736{
1737        struct dev_data         *dev = get_gadget_data (gadget);
1738        unsigned long           flags;
1739
1740        spin_lock_irqsave (&dev->lock, flags);
1741        if (dev->state == STATE_DEV_UNCONNECTED)
1742                goto exit;
1743        dev->state = STATE_DEV_UNCONNECTED;
1744
1745        INFO (dev, "disconnected\n");
1746        next_event (dev, GADGETFS_DISCONNECT);
1747        ep0_readable (dev);
1748exit:
1749        spin_unlock_irqrestore (&dev->lock, flags);
1750}
1751
1752static void
1753gadgetfs_suspend (struct usb_gadget *gadget)
1754{
1755        struct dev_data         *dev = get_gadget_data (gadget);
1756
1757        INFO (dev, "suspended from state %d\n", dev->state);
1758        spin_lock (&dev->lock);
1759        switch (dev->state) {
1760        case STATE_DEV_SETUP:           // VERY odd... host died??
1761        case STATE_DEV_CONNECTED:
1762        case STATE_DEV_UNCONNECTED:
1763                next_event (dev, GADGETFS_SUSPEND);
1764                ep0_readable (dev);
1765                /* FALLTHROUGH */
1766        default:
1767                break;
1768        }
1769        spin_unlock (&dev->lock);
1770}
1771
1772static struct usb_gadget_driver gadgetfs_driver = {
1773        .function       = (char *) driver_desc,
1774        .bind           = gadgetfs_bind,
1775        .unbind         = gadgetfs_unbind,
1776        .setup          = gadgetfs_setup,
1777        .reset          = gadgetfs_disconnect,
1778        .disconnect     = gadgetfs_disconnect,
1779        .suspend        = gadgetfs_suspend,
1780
1781        .driver = {
1782                .name           = (char *) shortname,
1783        },
1784};
1785
1786/*----------------------------------------------------------------------*/
1787
1788static void gadgetfs_nop(struct usb_gadget *arg) { }
1789
1790static int gadgetfs_probe(struct usb_gadget *gadget,
1791                struct usb_gadget_driver *driver)
1792{
1793        CHIP = gadget->name;
1794        return -EISNAM;
1795}
1796
1797static struct usb_gadget_driver probe_driver = {
1798        .max_speed      = USB_SPEED_HIGH,
1799        .bind           = gadgetfs_probe,
1800        .unbind         = gadgetfs_nop,
1801        .setup          = (void *)gadgetfs_nop,
1802        .disconnect     = gadgetfs_nop,
1803        .driver = {
1804                .name           = "nop",
1805        },
1806};
1807
1808
1809/* DEVICE INITIALIZATION
1810 *
1811 *     fd = open ("/dev/gadget/$CHIP", O_RDWR)
1812 *     status = write (fd, descriptors, sizeof descriptors)
1813 *
1814 * That write establishes the device configuration, so the kernel can
1815 * bind to the controller ... guaranteeing it can handle enumeration
1816 * at all necessary speeds.  Descriptor order is:
1817 *
1818 * . message tag (u32, host order) ... for now, must be zero; it
1819 *      would change to support features like multi-config devices
1820 * . full/low speed config ... all wTotalLength bytes (with interface,
1821 *      class, altsetting, endpoint, and other descriptors)
1822 * . high speed config ... all descriptors, for high speed operation;
1823 *      this one's optional except for high-speed hardware
1824 * . device descriptor
1825 *
1826 * Endpoints are not yet enabled. Drivers must wait until device
1827 * configuration and interface altsetting changes create
1828 * the need to configure (or unconfigure) them.
1829 *
1830 * After initialization, the device stays active for as long as that
1831 * $CHIP file is open.  Events must then be read from that descriptor,
1832 * such as configuration notifications.
1833 */
1834
1835static int is_valid_config (struct usb_config_descriptor *config)
1836{
1837        return config->bDescriptorType == USB_DT_CONFIG
1838                && config->bLength == USB_DT_CONFIG_SIZE
1839                && config->bConfigurationValue != 0
1840                && (config->bmAttributes & USB_CONFIG_ATT_ONE) != 0
1841                && (config->bmAttributes & USB_CONFIG_ATT_WAKEUP) == 0;
1842        /* FIXME if gadget->is_otg, _must_ include an otg descriptor */
1843        /* FIXME check lengths: walk to end */
1844}
1845
1846static ssize_t
1847dev_config (struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
1848{
1849        struct dev_data         *dev = fd->private_data;
1850        ssize_t                 value = len, length = len;
1851        unsigned                total;
1852        u32                     tag;
1853        char                    *kbuf;
1854
1855        if (len < (USB_DT_CONFIG_SIZE + USB_DT_DEVICE_SIZE + 4))
1856                return -EINVAL;
1857
1858        /* we might need to change message format someday */
1859        if (copy_from_user (&tag, buf, 4))
1860                return -EFAULT;
1861        if (tag != 0)
1862                return -EINVAL;
1863        buf += 4;
1864        length -= 4;
1865
1866        kbuf = memdup_user(buf, length);
1867        if (IS_ERR(kbuf))
1868                return PTR_ERR(kbuf);
1869
1870        spin_lock_irq (&dev->lock);
1871        value = -EINVAL;
1872        if (dev->buf)
1873                goto fail;
1874        dev->buf = kbuf;
1875
1876        /* full or low speed config */
1877        dev->config = (void *) kbuf;
1878        total = le16_to_cpu(dev->config->wTotalLength);
1879        if (!is_valid_config (dev->config) || total >= length)
1880                goto fail;
1881        kbuf += total;
1882        length -= total;
1883
1884        /* optional high speed config */
1885        if (kbuf [1] == USB_DT_CONFIG) {
1886                dev->hs_config = (void *) kbuf;
1887                total = le16_to_cpu(dev->hs_config->wTotalLength);
1888                if (!is_valid_config (dev->hs_config) || total >= length)
1889                        goto fail;
1890                kbuf += total;
1891                length -= total;
1892        }
1893
1894        /* could support multiple configs, using another encoding! */
1895
1896        /* device descriptor (tweaked for paranoia) */
1897        if (length != USB_DT_DEVICE_SIZE)
1898                goto fail;
1899        dev->dev = (void *)kbuf;
1900        if (dev->dev->bLength != USB_DT_DEVICE_SIZE
1901                        || dev->dev->bDescriptorType != USB_DT_DEVICE
1902                        || dev->dev->bNumConfigurations != 1)
1903                goto fail;
1904        dev->dev->bNumConfigurations = 1;
1905        dev->dev->bcdUSB = cpu_to_le16 (0x0200);
1906
1907        /* triggers gadgetfs_bind(); then we can enumerate. */
1908        spin_unlock_irq (&dev->lock);
1909        if (dev->hs_config)
1910                gadgetfs_driver.max_speed = USB_SPEED_HIGH;
1911        else
1912                gadgetfs_driver.max_speed = USB_SPEED_FULL;
1913
1914        value = usb_gadget_probe_driver(&gadgetfs_driver);
1915        if (value != 0) {
1916                kfree (dev->buf);
1917                dev->buf = NULL;
1918        } else {
1919                /* at this point "good" hardware has for the first time
1920                 * let the USB the host see us.  alternatively, if users
1921                 * unplug/replug that will clear all the error state.
1922                 *
1923                 * note:  everything running before here was guaranteed
1924                 * to choke driver model style diagnostics.  from here
1925                 * on, they can work ... except in cleanup paths that
1926                 * kick in after the ep0 descriptor is closed.
1927                 */
1928                fd->f_op = &ep0_io_operations;
1929                value = len;
1930        }
1931        return value;
1932
1933fail:
1934        spin_unlock_irq (&dev->lock);
1935        pr_debug ("%s: %s fail %Zd, %p\n", shortname, __func__, value, dev);
1936        kfree (dev->buf);
1937        dev->buf = NULL;
1938        return value;
1939}
1940
1941static int
1942dev_open (struct inode *inode, struct file *fd)
1943{
1944        struct dev_data         *dev = inode->i_private;
1945        int                     value = -EBUSY;
1946
1947        spin_lock_irq(&dev->lock);
1948        if (dev->state == STATE_DEV_DISABLED) {
1949                dev->ev_next = 0;
1950                dev->state = STATE_DEV_OPENED;
1951                fd->private_data = dev;
1952                get_dev (dev);
1953                value = 0;
1954        }
1955        spin_unlock_irq(&dev->lock);
1956        return value;
1957}
1958
1959static const struct file_operations dev_init_operations = {
1960        .llseek =       no_llseek,
1961
1962        .open =         dev_open,
1963        .write =        dev_config,
1964        .fasync =       ep0_fasync,
1965        .unlocked_ioctl = dev_ioctl,
1966        .release =      dev_release,
1967};
1968
1969/*----------------------------------------------------------------------*/
1970
1971/* FILESYSTEM AND SUPERBLOCK OPERATIONS
1972 *
1973 * Mounting the filesystem creates a controller file, used first for
1974 * device configuration then later for event monitoring.
1975 */
1976
1977
1978/* FIXME PAM etc could set this security policy without mount options
1979 * if epfiles inherited ownership and permissons from ep0 ...
1980 */
1981
1982static unsigned default_uid;
1983static unsigned default_gid;
1984static unsigned default_perm = S_IRUSR | S_IWUSR;
1985
1986module_param (default_uid, uint, 0644);
1987module_param (default_gid, uint, 0644);
1988module_param (default_perm, uint, 0644);
1989
1990
1991static struct inode *
1992gadgetfs_make_inode (struct super_block *sb,
1993                void *data, const struct file_operations *fops,
1994                int mode)
1995{
1996        struct inode *inode = new_inode (sb);
1997
1998        if (inode) {
1999                inode->i_ino = get_next_ino();
2000                inode->i_mode = mode;
2001                inode->i_uid = make_kuid(&init_user_ns, default_uid);
2002                inode->i_gid = make_kgid(&init_user_ns, default_gid);
2003                inode->i_atime = inode->i_mtime = inode->i_ctime
2004                                = CURRENT_TIME;
2005                inode->i_private = data;
2006                inode->i_fop = fops;
2007        }
2008        return inode;
2009}
2010
2011/* creates in fs root directory, so non-renamable and non-linkable.
2012 * so inode and dentry are paired, until device reconfig.
2013 */
2014static struct dentry *
2015gadgetfs_create_file (struct super_block *sb, char const *name,
2016                void *data, const struct file_operations *fops)
2017{
2018        struct dentry   *dentry;
2019        struct inode    *inode;
2020
2021        dentry = d_alloc_name(sb->s_root, name);
2022        if (!dentry)
2023                return NULL;
2024
2025        inode = gadgetfs_make_inode (sb, data, fops,
2026                        S_IFREG | (default_perm & S_IRWXUGO));
2027        if (!inode) {
2028                dput(dentry);
2029                return NULL;
2030        }
2031        d_add (dentry, inode);
2032        return dentry;
2033}
2034
2035static const struct super_operations gadget_fs_operations = {
2036        .statfs =       simple_statfs,
2037        .drop_inode =   generic_delete_inode,
2038};
2039
2040static int
2041gadgetfs_fill_super (struct super_block *sb, void *opts, int silent)
2042{
2043        struct inode    *inode;
2044        struct dev_data *dev;
2045
2046        if (the_device)
2047                return -ESRCH;
2048
2049        /* fake probe to determine $CHIP */
2050        CHIP = NULL;
2051        usb_gadget_probe_driver(&probe_driver);
2052        if (!CHIP)
2053                return -ENODEV;
2054
2055        /* superblock */
2056        sb->s_blocksize = PAGE_CACHE_SIZE;
2057        sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
2058        sb->s_magic = GADGETFS_MAGIC;
2059        sb->s_op = &gadget_fs_operations;
2060        sb->s_time_gran = 1;
2061
2062        /* root inode */
2063        inode = gadgetfs_make_inode (sb,
2064                        NULL, &simple_dir_operations,
2065                        S_IFDIR | S_IRUGO | S_IXUGO);
2066        if (!inode)
2067                goto Enomem;
2068        inode->i_op = &simple_dir_inode_operations;
2069        if (!(sb->s_root = d_make_root (inode)))
2070                goto Enomem;
2071
2072        /* the ep0 file is named after the controller we expect;
2073         * user mode code can use it for sanity checks, like we do.
2074         */
2075        dev = dev_new ();
2076        if (!dev)
2077                goto Enomem;
2078
2079        dev->sb = sb;
2080        dev->dentry = gadgetfs_create_file(sb, CHIP, dev, &dev_init_operations);
2081        if (!dev->dentry) {
2082                put_dev(dev);
2083                goto Enomem;
2084        }
2085
2086        /* other endpoint files are available after hardware setup,
2087         * from binding to a controller.
2088         */
2089        the_device = dev;
2090        return 0;
2091
2092Enomem:
2093        return -ENOMEM;
2094}
2095
2096/* "mount -t gadgetfs path /dev/gadget" ends up here */
2097static struct dentry *
2098gadgetfs_mount (struct file_system_type *t, int flags,
2099                const char *path, void *opts)
2100{
2101        return mount_single (t, flags, opts, gadgetfs_fill_super);
2102}
2103
2104static void
2105gadgetfs_kill_sb (struct super_block *sb)
2106{
2107        kill_litter_super (sb);
2108        if (the_device) {
2109                put_dev (the_device);
2110                the_device = NULL;
2111        }
2112}
2113
2114/*----------------------------------------------------------------------*/
2115
2116static struct file_system_type gadgetfs_type = {
2117        .owner          = THIS_MODULE,
2118        .name           = shortname,
2119        .mount          = gadgetfs_mount,
2120        .kill_sb        = gadgetfs_kill_sb,
2121};
2122MODULE_ALIAS_FS("gadgetfs");
2123
2124/*----------------------------------------------------------------------*/
2125
2126static int __init init (void)
2127{
2128        int status;
2129
2130        status = register_filesystem (&gadgetfs_type);
2131        if (status == 0)
2132                pr_info ("%s: %s, version " DRIVER_VERSION "\n",
2133                        shortname, driver_desc);
2134        return status;
2135}
2136module_init (init);
2137
2138static void __exit cleanup (void)
2139{
2140        pr_debug ("unregister %s\n", shortname);
2141        unregister_filesystem (&gadgetfs_type);
2142}
2143module_exit (cleanup);
2144
2145