GNU Linux-libre 4.14.266-gnu1
[releases.git] / drivers / usb / gadget / function / f_hid.c
1 /*
2  * f_hid.c -- USB HID function driver
3  *
4  * Copyright (C) 2010 Fabien Chouteau <fabien.chouteau@barco.com>
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
12 #include <linux/kernel.h>
13 #include <linux/module.h>
14 #include <linux/hid.h>
15 #include <linux/idr.h>
16 #include <linux/cdev.h>
17 #include <linux/mutex.h>
18 #include <linux/poll.h>
19 #include <linux/uaccess.h>
20 #include <linux/wait.h>
21 #include <linux/sched.h>
22 #include <linux/usb/g_hid.h>
23
24 #include "u_f.h"
25 #include "u_hid.h"
26
27 #define HIDG_MINORS     4
28
29 static int major, minors;
30 static struct class *hidg_class;
31 static DEFINE_IDA(hidg_ida);
32 static DEFINE_MUTEX(hidg_ida_lock); /* protects access to hidg_ida */
33
34 /*-------------------------------------------------------------------------*/
35 /*                            HID gadget struct                            */
36
37 struct f_hidg_req_list {
38         struct usb_request      *req;
39         unsigned int            pos;
40         struct list_head        list;
41 };
42
43 struct f_hidg {
44         /* configuration */
45         unsigned char                   bInterfaceSubClass;
46         unsigned char                   bInterfaceProtocol;
47         unsigned char                   protocol;
48         unsigned char                   idle;
49         unsigned short                  report_desc_length;
50         char                            *report_desc;
51         unsigned short                  report_length;
52
53         /* recv report */
54         struct list_head                completed_out_req;
55         spinlock_t                      read_spinlock;
56         wait_queue_head_t               read_queue;
57         unsigned int                    qlen;
58
59         /* send report */
60         spinlock_t                      write_spinlock;
61         bool                            write_pending;
62         wait_queue_head_t               write_queue;
63         struct usb_request              *req;
64
65         int                             minor;
66         struct cdev                     cdev;
67         struct usb_function             func;
68
69         struct usb_ep                   *in_ep;
70         struct usb_ep                   *out_ep;
71 };
72
73 static inline struct f_hidg *func_to_hidg(struct usb_function *f)
74 {
75         return container_of(f, struct f_hidg, func);
76 }
77
78 /*-------------------------------------------------------------------------*/
79 /*                           Static descriptors                            */
80
81 static struct usb_interface_descriptor hidg_interface_desc = {
82         .bLength                = sizeof hidg_interface_desc,
83         .bDescriptorType        = USB_DT_INTERFACE,
84         /* .bInterfaceNumber    = DYNAMIC */
85         .bAlternateSetting      = 0,
86         .bNumEndpoints          = 2,
87         .bInterfaceClass        = USB_CLASS_HID,
88         /* .bInterfaceSubClass  = DYNAMIC */
89         /* .bInterfaceProtocol  = DYNAMIC */
90         /* .iInterface          = DYNAMIC */
91 };
92
93 static struct hid_descriptor hidg_desc = {
94         .bLength                        = sizeof hidg_desc,
95         .bDescriptorType                = HID_DT_HID,
96         .bcdHID                         = cpu_to_le16(0x0101),
97         .bCountryCode                   = 0x00,
98         .bNumDescriptors                = 0x1,
99         /*.desc[0].bDescriptorType      = DYNAMIC */
100         /*.desc[0].wDescriptorLenght    = DYNAMIC */
101 };
102
103 /* Super-Speed Support */
104
105 static struct usb_endpoint_descriptor hidg_ss_in_ep_desc = {
106         .bLength                = USB_DT_ENDPOINT_SIZE,
107         .bDescriptorType        = USB_DT_ENDPOINT,
108         .bEndpointAddress       = USB_DIR_IN,
109         .bmAttributes           = USB_ENDPOINT_XFER_INT,
110         /*.wMaxPacketSize       = DYNAMIC */
111         .bInterval              = 4, /* FIXME: Add this field in the
112                                       * HID gadget configuration?
113                                       * (struct hidg_func_descriptor)
114                                       */
115 };
116
117 static struct usb_ss_ep_comp_descriptor hidg_ss_in_comp_desc = {
118         .bLength                = sizeof(hidg_ss_in_comp_desc),
119         .bDescriptorType        = USB_DT_SS_ENDPOINT_COMP,
120
121         /* .bMaxBurst           = 0, */
122         /* .bmAttributes        = 0, */
123         /* .wBytesPerInterval   = DYNAMIC */
124 };
125
126 static struct usb_endpoint_descriptor hidg_ss_out_ep_desc = {
127         .bLength                = USB_DT_ENDPOINT_SIZE,
128         .bDescriptorType        = USB_DT_ENDPOINT,
129         .bEndpointAddress       = USB_DIR_OUT,
130         .bmAttributes           = USB_ENDPOINT_XFER_INT,
131         /*.wMaxPacketSize       = DYNAMIC */
132         .bInterval              = 4, /* FIXME: Add this field in the
133                                       * HID gadget configuration?
134                                       * (struct hidg_func_descriptor)
135                                       */
136 };
137
138 static struct usb_ss_ep_comp_descriptor hidg_ss_out_comp_desc = {
139         .bLength                = sizeof(hidg_ss_out_comp_desc),
140         .bDescriptorType        = USB_DT_SS_ENDPOINT_COMP,
141
142         /* .bMaxBurst           = 0, */
143         /* .bmAttributes        = 0, */
144         /* .wBytesPerInterval   = DYNAMIC */
145 };
146
147 static struct usb_descriptor_header *hidg_ss_descriptors[] = {
148         (struct usb_descriptor_header *)&hidg_interface_desc,
149         (struct usb_descriptor_header *)&hidg_desc,
150         (struct usb_descriptor_header *)&hidg_ss_in_ep_desc,
151         (struct usb_descriptor_header *)&hidg_ss_in_comp_desc,
152         (struct usb_descriptor_header *)&hidg_ss_out_ep_desc,
153         (struct usb_descriptor_header *)&hidg_ss_out_comp_desc,
154         NULL,
155 };
156
157 /* High-Speed Support */
158
159 static struct usb_endpoint_descriptor hidg_hs_in_ep_desc = {
160         .bLength                = USB_DT_ENDPOINT_SIZE,
161         .bDescriptorType        = USB_DT_ENDPOINT,
162         .bEndpointAddress       = USB_DIR_IN,
163         .bmAttributes           = USB_ENDPOINT_XFER_INT,
164         /*.wMaxPacketSize       = DYNAMIC */
165         .bInterval              = 4, /* FIXME: Add this field in the
166                                       * HID gadget configuration?
167                                       * (struct hidg_func_descriptor)
168                                       */
169 };
170
171 static struct usb_endpoint_descriptor hidg_hs_out_ep_desc = {
172         .bLength                = USB_DT_ENDPOINT_SIZE,
173         .bDescriptorType        = USB_DT_ENDPOINT,
174         .bEndpointAddress       = USB_DIR_OUT,
175         .bmAttributes           = USB_ENDPOINT_XFER_INT,
176         /*.wMaxPacketSize       = DYNAMIC */
177         .bInterval              = 4, /* FIXME: Add this field in the
178                                       * HID gadget configuration?
179                                       * (struct hidg_func_descriptor)
180                                       */
181 };
182
183 static struct usb_descriptor_header *hidg_hs_descriptors[] = {
184         (struct usb_descriptor_header *)&hidg_interface_desc,
185         (struct usb_descriptor_header *)&hidg_desc,
186         (struct usb_descriptor_header *)&hidg_hs_in_ep_desc,
187         (struct usb_descriptor_header *)&hidg_hs_out_ep_desc,
188         NULL,
189 };
190
191 /* Full-Speed Support */
192
193 static struct usb_endpoint_descriptor hidg_fs_in_ep_desc = {
194         .bLength                = USB_DT_ENDPOINT_SIZE,
195         .bDescriptorType        = USB_DT_ENDPOINT,
196         .bEndpointAddress       = USB_DIR_IN,
197         .bmAttributes           = USB_ENDPOINT_XFER_INT,
198         /*.wMaxPacketSize       = DYNAMIC */
199         .bInterval              = 10, /* FIXME: Add this field in the
200                                        * HID gadget configuration?
201                                        * (struct hidg_func_descriptor)
202                                        */
203 };
204
205 static struct usb_endpoint_descriptor hidg_fs_out_ep_desc = {
206         .bLength                = USB_DT_ENDPOINT_SIZE,
207         .bDescriptorType        = USB_DT_ENDPOINT,
208         .bEndpointAddress       = USB_DIR_OUT,
209         .bmAttributes           = USB_ENDPOINT_XFER_INT,
210         /*.wMaxPacketSize       = DYNAMIC */
211         .bInterval              = 10, /* FIXME: Add this field in the
212                                        * HID gadget configuration?
213                                        * (struct hidg_func_descriptor)
214                                        */
215 };
216
217 static struct usb_descriptor_header *hidg_fs_descriptors[] = {
218         (struct usb_descriptor_header *)&hidg_interface_desc,
219         (struct usb_descriptor_header *)&hidg_desc,
220         (struct usb_descriptor_header *)&hidg_fs_in_ep_desc,
221         (struct usb_descriptor_header *)&hidg_fs_out_ep_desc,
222         NULL,
223 };
224
225 /*-------------------------------------------------------------------------*/
226 /*                                 Strings                                 */
227
228 #define CT_FUNC_HID_IDX 0
229
230 static struct usb_string ct_func_string_defs[] = {
231         [CT_FUNC_HID_IDX].s     = "HID Interface",
232         {},                     /* end of list */
233 };
234
235 static struct usb_gadget_strings ct_func_string_table = {
236         .language       = 0x0409,       /* en-US */
237         .strings        = ct_func_string_defs,
238 };
239
240 static struct usb_gadget_strings *ct_func_strings[] = {
241         &ct_func_string_table,
242         NULL,
243 };
244
245 /*-------------------------------------------------------------------------*/
246 /*                              Char Device                                */
247
248 static ssize_t f_hidg_read(struct file *file, char __user *buffer,
249                         size_t count, loff_t *ptr)
250 {
251         struct f_hidg *hidg = file->private_data;
252         struct f_hidg_req_list *list;
253         struct usb_request *req;
254         unsigned long flags;
255         int ret;
256
257         if (!count)
258                 return 0;
259
260         if (!access_ok(VERIFY_WRITE, buffer, count))
261                 return -EFAULT;
262
263         spin_lock_irqsave(&hidg->read_spinlock, flags);
264
265 #define READ_COND (!list_empty(&hidg->completed_out_req))
266
267         /* wait for at least one buffer to complete */
268         while (!READ_COND) {
269                 spin_unlock_irqrestore(&hidg->read_spinlock, flags);
270                 if (file->f_flags & O_NONBLOCK)
271                         return -EAGAIN;
272
273                 if (wait_event_interruptible(hidg->read_queue, READ_COND))
274                         return -ERESTARTSYS;
275
276                 spin_lock_irqsave(&hidg->read_spinlock, flags);
277         }
278
279         /* pick the first one */
280         list = list_first_entry(&hidg->completed_out_req,
281                                 struct f_hidg_req_list, list);
282
283         /*
284          * Remove this from list to protect it from beign free()
285          * while host disables our function
286          */
287         list_del(&list->list);
288
289         req = list->req;
290         count = min_t(unsigned int, count, req->actual - list->pos);
291         spin_unlock_irqrestore(&hidg->read_spinlock, flags);
292
293         /* copy to user outside spinlock */
294         count -= copy_to_user(buffer, req->buf + list->pos, count);
295         list->pos += count;
296
297         /*
298          * if this request is completely handled and transfered to
299          * userspace, remove its entry from the list and requeue it
300          * again. Otherwise, we will revisit it again upon the next
301          * call, taking into account its current read position.
302          */
303         if (list->pos == req->actual) {
304                 kfree(list);
305
306                 req->length = hidg->report_length;
307                 ret = usb_ep_queue(hidg->out_ep, req, GFP_KERNEL);
308                 if (ret < 0) {
309                         free_ep_req(hidg->out_ep, req);
310                         return ret;
311                 }
312         } else {
313                 spin_lock_irqsave(&hidg->read_spinlock, flags);
314                 list_add(&list->list, &hidg->completed_out_req);
315                 spin_unlock_irqrestore(&hidg->read_spinlock, flags);
316
317                 wake_up(&hidg->read_queue);
318         }
319
320         return count;
321 }
322
323 static void f_hidg_req_complete(struct usb_ep *ep, struct usb_request *req)
324 {
325         struct f_hidg *hidg = (struct f_hidg *)ep->driver_data;
326         unsigned long flags;
327
328         if (req->status != 0) {
329                 ERROR(hidg->func.config->cdev,
330                         "End Point Request ERROR: %d\n", req->status);
331         }
332
333         spin_lock_irqsave(&hidg->write_spinlock, flags);
334         hidg->write_pending = 0;
335         spin_unlock_irqrestore(&hidg->write_spinlock, flags);
336         wake_up(&hidg->write_queue);
337 }
338
339 static ssize_t f_hidg_write(struct file *file, const char __user *buffer,
340                             size_t count, loff_t *offp)
341 {
342         struct f_hidg *hidg  = file->private_data;
343         struct usb_request *req;
344         unsigned long flags;
345         ssize_t status = -ENOMEM;
346
347         if (!access_ok(VERIFY_READ, buffer, count))
348                 return -EFAULT;
349
350         spin_lock_irqsave(&hidg->write_spinlock, flags);
351
352         if (!hidg->req) {
353                 spin_unlock_irqrestore(&hidg->write_spinlock, flags);
354                 return -ESHUTDOWN;
355         }
356
357 #define WRITE_COND (!hidg->write_pending)
358 try_again:
359         /* write queue */
360         while (!WRITE_COND) {
361                 spin_unlock_irqrestore(&hidg->write_spinlock, flags);
362                 if (file->f_flags & O_NONBLOCK)
363                         return -EAGAIN;
364
365                 if (wait_event_interruptible_exclusive(
366                                 hidg->write_queue, WRITE_COND))
367                         return -ERESTARTSYS;
368
369                 spin_lock_irqsave(&hidg->write_spinlock, flags);
370         }
371
372         hidg->write_pending = 1;
373         req = hidg->req;
374         count  = min_t(unsigned, count, hidg->report_length);
375
376         spin_unlock_irqrestore(&hidg->write_spinlock, flags);
377
378         if (!req) {
379                 ERROR(hidg->func.config->cdev, "hidg->req is NULL\n");
380                 status = -ESHUTDOWN;
381                 goto release_write_pending;
382         }
383
384         status = copy_from_user(req->buf, buffer, count);
385         if (status != 0) {
386                 ERROR(hidg->func.config->cdev,
387                         "copy_from_user error\n");
388                 status = -EINVAL;
389                 goto release_write_pending;
390         }
391
392         spin_lock_irqsave(&hidg->write_spinlock, flags);
393
394         /* when our function has been disabled by host */
395         if (!hidg->req) {
396                 free_ep_req(hidg->in_ep, req);
397                 /*
398                  * TODO
399                  * Should we fail with error here?
400                  */
401                 goto try_again;
402         }
403
404         req->status   = 0;
405         req->zero     = 0;
406         req->length   = count;
407         req->complete = f_hidg_req_complete;
408         req->context  = hidg;
409
410         spin_unlock_irqrestore(&hidg->write_spinlock, flags);
411
412         if (!hidg->in_ep->enabled) {
413                 ERROR(hidg->func.config->cdev, "in_ep is disabled\n");
414                 status = -ESHUTDOWN;
415                 goto release_write_pending;
416         }
417
418         status = usb_ep_queue(hidg->in_ep, req, GFP_ATOMIC);
419         if (status < 0)
420                 goto release_write_pending;
421         else
422                 status = count;
423
424         return status;
425 release_write_pending:
426         spin_lock_irqsave(&hidg->write_spinlock, flags);
427         hidg->write_pending = 0;
428         spin_unlock_irqrestore(&hidg->write_spinlock, flags);
429
430         wake_up(&hidg->write_queue);
431
432         return status;
433 }
434
435 static unsigned int f_hidg_poll(struct file *file, poll_table *wait)
436 {
437         struct f_hidg   *hidg  = file->private_data;
438         unsigned int    ret = 0;
439
440         poll_wait(file, &hidg->read_queue, wait);
441         poll_wait(file, &hidg->write_queue, wait);
442
443         if (WRITE_COND)
444                 ret |= POLLOUT | POLLWRNORM;
445
446         if (READ_COND)
447                 ret |= POLLIN | POLLRDNORM;
448
449         return ret;
450 }
451
452 #undef WRITE_COND
453 #undef READ_COND
454
455 static int f_hidg_release(struct inode *inode, struct file *fd)
456 {
457         fd->private_data = NULL;
458         return 0;
459 }
460
461 static int f_hidg_open(struct inode *inode, struct file *fd)
462 {
463         struct f_hidg *hidg =
464                 container_of(inode->i_cdev, struct f_hidg, cdev);
465
466         fd->private_data = hidg;
467
468         return 0;
469 }
470
471 /*-------------------------------------------------------------------------*/
472 /*                                usb_function                             */
473
474 static inline struct usb_request *hidg_alloc_ep_req(struct usb_ep *ep,
475                                                     unsigned length)
476 {
477         return alloc_ep_req(ep, length);
478 }
479
480 static void hidg_set_report_complete(struct usb_ep *ep, struct usb_request *req)
481 {
482         struct f_hidg *hidg = (struct f_hidg *) req->context;
483         struct usb_composite_dev *cdev = hidg->func.config->cdev;
484         struct f_hidg_req_list *req_list;
485         unsigned long flags;
486
487         switch (req->status) {
488         case 0:
489                 req_list = kzalloc(sizeof(*req_list), GFP_ATOMIC);
490                 if (!req_list) {
491                         ERROR(cdev, "Unable to allocate mem for req_list\n");
492                         goto free_req;
493                 }
494
495                 req_list->req = req;
496
497                 spin_lock_irqsave(&hidg->read_spinlock, flags);
498                 list_add_tail(&req_list->list, &hidg->completed_out_req);
499                 spin_unlock_irqrestore(&hidg->read_spinlock, flags);
500
501                 wake_up(&hidg->read_queue);
502                 break;
503         default:
504                 ERROR(cdev, "Set report failed %d\n", req->status);
505                 /* FALLTHROUGH */
506         case -ECONNABORTED:             /* hardware forced ep reset */
507         case -ECONNRESET:               /* request dequeued */
508         case -ESHUTDOWN:                /* disconnect from host */
509 free_req:
510                 free_ep_req(ep, req);
511                 return;
512         }
513 }
514
515 static int hidg_setup(struct usb_function *f,
516                 const struct usb_ctrlrequest *ctrl)
517 {
518         struct f_hidg                   *hidg = func_to_hidg(f);
519         struct usb_composite_dev        *cdev = f->config->cdev;
520         struct usb_request              *req  = cdev->req;
521         int status = 0;
522         __u16 value, length;
523
524         value   = __le16_to_cpu(ctrl->wValue);
525         length  = __le16_to_cpu(ctrl->wLength);
526
527         VDBG(cdev,
528              "%s crtl_request : bRequestType:0x%x bRequest:0x%x Value:0x%x\n",
529              __func__, ctrl->bRequestType, ctrl->bRequest, value);
530
531         switch ((ctrl->bRequestType << 8) | ctrl->bRequest) {
532         case ((USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8
533                   | HID_REQ_GET_REPORT):
534                 VDBG(cdev, "get_report\n");
535
536                 /* send an empty report */
537                 length = min_t(unsigned, length, hidg->report_length);
538                 memset(req->buf, 0x0, length);
539
540                 goto respond;
541                 break;
542
543         case ((USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8
544                   | HID_REQ_GET_PROTOCOL):
545                 VDBG(cdev, "get_protocol\n");
546                 length = min_t(unsigned int, length, 1);
547                 ((u8 *) req->buf)[0] = hidg->protocol;
548                 goto respond;
549                 break;
550
551         case ((USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8
552                   | HID_REQ_GET_IDLE):
553                 VDBG(cdev, "get_idle\n");
554                 length = min_t(unsigned int, length, 1);
555                 ((u8 *) req->buf)[0] = hidg->idle;
556                 goto respond;
557                 break;
558
559         case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8
560                   | HID_REQ_SET_REPORT):
561                 VDBG(cdev, "set_report | wLength=%d\n", ctrl->wLength);
562                 goto stall;
563                 break;
564
565         case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8
566                   | HID_REQ_SET_PROTOCOL):
567                 VDBG(cdev, "set_protocol\n");
568                 if (value > HID_REPORT_PROTOCOL)
569                         goto stall;
570                 length = 0;
571                 /*
572                  * We assume that programs implementing the Boot protocol
573                  * are also compatible with the Report Protocol
574                  */
575                 if (hidg->bInterfaceSubClass == USB_INTERFACE_SUBCLASS_BOOT) {
576                         hidg->protocol = value;
577                         goto respond;
578                 }
579                 goto stall;
580                 break;
581
582         case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8
583                   | HID_REQ_SET_IDLE):
584                 VDBG(cdev, "set_idle\n");
585                 length = 0;
586                 hidg->idle = value >> 8;
587                 goto respond;
588                 break;
589
590         case ((USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_INTERFACE) << 8
591                   | USB_REQ_GET_DESCRIPTOR):
592                 switch (value >> 8) {
593                 case HID_DT_HID:
594                 {
595                         struct hid_descriptor hidg_desc_copy = hidg_desc;
596
597                         VDBG(cdev, "USB_REQ_GET_DESCRIPTOR: HID\n");
598                         hidg_desc_copy.desc[0].bDescriptorType = HID_DT_REPORT;
599                         hidg_desc_copy.desc[0].wDescriptorLength =
600                                 cpu_to_le16(hidg->report_desc_length);
601
602                         length = min_t(unsigned short, length,
603                                                    hidg_desc_copy.bLength);
604                         memcpy(req->buf, &hidg_desc_copy, length);
605                         goto respond;
606                         break;
607                 }
608                 case HID_DT_REPORT:
609                         VDBG(cdev, "USB_REQ_GET_DESCRIPTOR: REPORT\n");
610                         length = min_t(unsigned short, length,
611                                                    hidg->report_desc_length);
612                         memcpy(req->buf, hidg->report_desc, length);
613                         goto respond;
614                         break;
615
616                 default:
617                         VDBG(cdev, "Unknown descriptor request 0x%x\n",
618                                  value >> 8);
619                         goto stall;
620                         break;
621                 }
622                 break;
623
624         default:
625                 VDBG(cdev, "Unknown request 0x%x\n",
626                          ctrl->bRequest);
627                 goto stall;
628                 break;
629         }
630
631 stall:
632         return -EOPNOTSUPP;
633
634 respond:
635         req->zero = 0;
636         req->length = length;
637         status = usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC);
638         if (status < 0)
639                 ERROR(cdev, "usb_ep_queue error on ep0 %d\n", value);
640         return status;
641 }
642
643 static void hidg_disable(struct usb_function *f)
644 {
645         struct f_hidg *hidg = func_to_hidg(f);
646         struct f_hidg_req_list *list, *next;
647         unsigned long flags;
648
649         usb_ep_disable(hidg->in_ep);
650         usb_ep_disable(hidg->out_ep);
651
652         spin_lock_irqsave(&hidg->read_spinlock, flags);
653         list_for_each_entry_safe(list, next, &hidg->completed_out_req, list) {
654                 free_ep_req(hidg->out_ep, list->req);
655                 list_del(&list->list);
656                 kfree(list);
657         }
658         spin_unlock_irqrestore(&hidg->read_spinlock, flags);
659
660         spin_lock_irqsave(&hidg->write_spinlock, flags);
661         if (!hidg->write_pending) {
662                 free_ep_req(hidg->in_ep, hidg->req);
663                 hidg->write_pending = 1;
664         }
665
666         hidg->req = NULL;
667         spin_unlock_irqrestore(&hidg->write_spinlock, flags);
668 }
669
670 static int hidg_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
671 {
672         struct usb_composite_dev                *cdev = f->config->cdev;
673         struct f_hidg                           *hidg = func_to_hidg(f);
674         struct usb_request                      *req_in = NULL;
675         unsigned long                           flags;
676         int i, status = 0;
677
678         VDBG(cdev, "hidg_set_alt intf:%d alt:%d\n", intf, alt);
679
680         if (hidg->in_ep != NULL) {
681                 /* restart endpoint */
682                 usb_ep_disable(hidg->in_ep);
683
684                 status = config_ep_by_speed(f->config->cdev->gadget, f,
685                                             hidg->in_ep);
686                 if (status) {
687                         ERROR(cdev, "config_ep_by_speed FAILED!\n");
688                         goto fail;
689                 }
690                 status = usb_ep_enable(hidg->in_ep);
691                 if (status < 0) {
692                         ERROR(cdev, "Enable IN endpoint FAILED!\n");
693                         goto fail;
694                 }
695                 hidg->in_ep->driver_data = hidg;
696
697                 req_in = hidg_alloc_ep_req(hidg->in_ep, hidg->report_length);
698                 if (!req_in) {
699                         status = -ENOMEM;
700                         goto disable_ep_in;
701                 }
702         }
703
704
705         if (hidg->out_ep != NULL) {
706                 /* restart endpoint */
707                 usb_ep_disable(hidg->out_ep);
708
709                 status = config_ep_by_speed(f->config->cdev->gadget, f,
710                                             hidg->out_ep);
711                 if (status) {
712                         ERROR(cdev, "config_ep_by_speed FAILED!\n");
713                         goto free_req_in;
714                 }
715                 status = usb_ep_enable(hidg->out_ep);
716                 if (status < 0) {
717                         ERROR(cdev, "Enable OUT endpoint FAILED!\n");
718                         goto free_req_in;
719                 }
720                 hidg->out_ep->driver_data = hidg;
721
722                 /*
723                  * allocate a bunch of read buffers and queue them all at once.
724                  */
725                 for (i = 0; i < hidg->qlen && status == 0; i++) {
726                         struct usb_request *req =
727                                         hidg_alloc_ep_req(hidg->out_ep,
728                                                           hidg->report_length);
729                         if (req) {
730                                 req->complete = hidg_set_report_complete;
731                                 req->context  = hidg;
732                                 status = usb_ep_queue(hidg->out_ep, req,
733                                                       GFP_ATOMIC);
734                                 if (status) {
735                                         ERROR(cdev, "%s queue req --> %d\n",
736                                                 hidg->out_ep->name, status);
737                                         free_ep_req(hidg->out_ep, req);
738                                 }
739                         } else {
740                                 status = -ENOMEM;
741                                 goto disable_out_ep;
742                         }
743                 }
744         }
745
746         if (hidg->in_ep != NULL) {
747                 spin_lock_irqsave(&hidg->write_spinlock, flags);
748                 hidg->req = req_in;
749                 hidg->write_pending = 0;
750                 spin_unlock_irqrestore(&hidg->write_spinlock, flags);
751
752                 wake_up(&hidg->write_queue);
753         }
754         return 0;
755 disable_out_ep:
756         usb_ep_disable(hidg->out_ep);
757 free_req_in:
758         if (req_in)
759                 free_ep_req(hidg->in_ep, req_in);
760
761 disable_ep_in:
762         if (hidg->in_ep)
763                 usb_ep_disable(hidg->in_ep);
764
765 fail:
766         return status;
767 }
768
769 static const struct file_operations f_hidg_fops = {
770         .owner          = THIS_MODULE,
771         .open           = f_hidg_open,
772         .release        = f_hidg_release,
773         .write          = f_hidg_write,
774         .read           = f_hidg_read,
775         .poll           = f_hidg_poll,
776         .llseek         = noop_llseek,
777 };
778
779 static int hidg_bind(struct usb_configuration *c, struct usb_function *f)
780 {
781         struct usb_ep           *ep;
782         struct f_hidg           *hidg = func_to_hidg(f);
783         struct usb_string       *us;
784         struct device           *device;
785         int                     status;
786         dev_t                   dev;
787
788         /* maybe allocate device-global string IDs, and patch descriptors */
789         us = usb_gstrings_attach(c->cdev, ct_func_strings,
790                                  ARRAY_SIZE(ct_func_string_defs));
791         if (IS_ERR(us))
792                 return PTR_ERR(us);
793         hidg_interface_desc.iInterface = us[CT_FUNC_HID_IDX].id;
794
795         /* allocate instance-specific interface IDs, and patch descriptors */
796         status = usb_interface_id(c, f);
797         if (status < 0)
798                 goto fail;
799         hidg_interface_desc.bInterfaceNumber = status;
800
801         /* allocate instance-specific endpoints */
802         status = -ENODEV;
803         ep = usb_ep_autoconfig(c->cdev->gadget, &hidg_fs_in_ep_desc);
804         if (!ep)
805                 goto fail;
806         hidg->in_ep = ep;
807
808         ep = usb_ep_autoconfig(c->cdev->gadget, &hidg_fs_out_ep_desc);
809         if (!ep)
810                 goto fail;
811         hidg->out_ep = ep;
812
813         /* set descriptor dynamic values */
814         hidg_interface_desc.bInterfaceSubClass = hidg->bInterfaceSubClass;
815         hidg_interface_desc.bInterfaceProtocol = hidg->bInterfaceProtocol;
816         hidg->protocol = HID_REPORT_PROTOCOL;
817         hidg->idle = 1;
818         hidg_ss_in_ep_desc.wMaxPacketSize = cpu_to_le16(hidg->report_length);
819         hidg_ss_in_comp_desc.wBytesPerInterval =
820                                 cpu_to_le16(hidg->report_length);
821         hidg_hs_in_ep_desc.wMaxPacketSize = cpu_to_le16(hidg->report_length);
822         hidg_fs_in_ep_desc.wMaxPacketSize = cpu_to_le16(hidg->report_length);
823         hidg_ss_out_ep_desc.wMaxPacketSize = cpu_to_le16(hidg->report_length);
824         hidg_ss_out_comp_desc.wBytesPerInterval =
825                                 cpu_to_le16(hidg->report_length);
826         hidg_hs_out_ep_desc.wMaxPacketSize = cpu_to_le16(hidg->report_length);
827         hidg_fs_out_ep_desc.wMaxPacketSize = cpu_to_le16(hidg->report_length);
828         /*
829          * We can use hidg_desc struct here but we should not relay
830          * that its content won't change after returning from this function.
831          */
832         hidg_desc.desc[0].bDescriptorType = HID_DT_REPORT;
833         hidg_desc.desc[0].wDescriptorLength =
834                 cpu_to_le16(hidg->report_desc_length);
835
836         hidg_hs_in_ep_desc.bEndpointAddress =
837                 hidg_fs_in_ep_desc.bEndpointAddress;
838         hidg_hs_out_ep_desc.bEndpointAddress =
839                 hidg_fs_out_ep_desc.bEndpointAddress;
840
841         hidg_ss_in_ep_desc.bEndpointAddress =
842                 hidg_fs_in_ep_desc.bEndpointAddress;
843         hidg_ss_out_ep_desc.bEndpointAddress =
844                 hidg_fs_out_ep_desc.bEndpointAddress;
845
846         status = usb_assign_descriptors(f, hidg_fs_descriptors,
847                         hidg_hs_descriptors, hidg_ss_descriptors,
848                         hidg_ss_descriptors);
849         if (status)
850                 goto fail;
851
852         spin_lock_init(&hidg->write_spinlock);
853         hidg->write_pending = 1;
854         hidg->req = NULL;
855         spin_lock_init(&hidg->read_spinlock);
856         init_waitqueue_head(&hidg->write_queue);
857         init_waitqueue_head(&hidg->read_queue);
858         INIT_LIST_HEAD(&hidg->completed_out_req);
859
860         /* create char device */
861         cdev_init(&hidg->cdev, &f_hidg_fops);
862         dev = MKDEV(major, hidg->minor);
863         status = cdev_add(&hidg->cdev, dev, 1);
864         if (status)
865                 goto fail_free_descs;
866
867         device = device_create(hidg_class, NULL, dev, NULL,
868                                "%s%d", "hidg", hidg->minor);
869         if (IS_ERR(device)) {
870                 status = PTR_ERR(device);
871                 goto del;
872         }
873
874         return 0;
875 del:
876         cdev_del(&hidg->cdev);
877 fail_free_descs:
878         usb_free_all_descriptors(f);
879 fail:
880         ERROR(f->config->cdev, "hidg_bind FAILED\n");
881         if (hidg->req != NULL)
882                 free_ep_req(hidg->in_ep, hidg->req);
883
884         return status;
885 }
886
887 static inline int hidg_get_minor(void)
888 {
889         int ret;
890
891         ret = ida_simple_get(&hidg_ida, 0, 0, GFP_KERNEL);
892         if (ret >= HIDG_MINORS) {
893                 ida_simple_remove(&hidg_ida, ret);
894                 ret = -ENODEV;
895         }
896
897         return ret;
898 }
899
900 static inline struct f_hid_opts *to_f_hid_opts(struct config_item *item)
901 {
902         return container_of(to_config_group(item), struct f_hid_opts,
903                             func_inst.group);
904 }
905
906 static void hid_attr_release(struct config_item *item)
907 {
908         struct f_hid_opts *opts = to_f_hid_opts(item);
909
910         usb_put_function_instance(&opts->func_inst);
911 }
912
913 static struct configfs_item_operations hidg_item_ops = {
914         .release        = hid_attr_release,
915 };
916
917 #define F_HID_OPT(name, prec, limit)                                    \
918 static ssize_t f_hid_opts_##name##_show(struct config_item *item, char *page)\
919 {                                                                       \
920         struct f_hid_opts *opts = to_f_hid_opts(item);                  \
921         int result;                                                     \
922                                                                         \
923         mutex_lock(&opts->lock);                                        \
924         result = sprintf(page, "%d\n", opts->name);                     \
925         mutex_unlock(&opts->lock);                                      \
926                                                                         \
927         return result;                                                  \
928 }                                                                       \
929                                                                         \
930 static ssize_t f_hid_opts_##name##_store(struct config_item *item,      \
931                                          const char *page, size_t len)  \
932 {                                                                       \
933         struct f_hid_opts *opts = to_f_hid_opts(item);                  \
934         int ret;                                                        \
935         u##prec num;                                                    \
936                                                                         \
937         mutex_lock(&opts->lock);                                        \
938         if (opts->refcnt) {                                             \
939                 ret = -EBUSY;                                           \
940                 goto end;                                               \
941         }                                                               \
942                                                                         \
943         ret = kstrtou##prec(page, 0, &num);                             \
944         if (ret)                                                        \
945                 goto end;                                               \
946                                                                         \
947         if (num > limit) {                                              \
948                 ret = -EINVAL;                                          \
949                 goto end;                                               \
950         }                                                               \
951         opts->name = num;                                               \
952         ret = len;                                                      \
953                                                                         \
954 end:                                                                    \
955         mutex_unlock(&opts->lock);                                      \
956         return ret;                                                     \
957 }                                                                       \
958                                                                         \
959 CONFIGFS_ATTR(f_hid_opts_, name)
960
961 F_HID_OPT(subclass, 8, 255);
962 F_HID_OPT(protocol, 8, 255);
963 F_HID_OPT(report_length, 16, 65535);
964
965 static ssize_t f_hid_opts_report_desc_show(struct config_item *item, char *page)
966 {
967         struct f_hid_opts *opts = to_f_hid_opts(item);
968         int result;
969
970         mutex_lock(&opts->lock);
971         result = opts->report_desc_length;
972         memcpy(page, opts->report_desc, opts->report_desc_length);
973         mutex_unlock(&opts->lock);
974
975         return result;
976 }
977
978 static ssize_t f_hid_opts_report_desc_store(struct config_item *item,
979                                             const char *page, size_t len)
980 {
981         struct f_hid_opts *opts = to_f_hid_opts(item);
982         int ret = -EBUSY;
983         char *d;
984
985         mutex_lock(&opts->lock);
986
987         if (opts->refcnt)
988                 goto end;
989         if (len > PAGE_SIZE) {
990                 ret = -ENOSPC;
991                 goto end;
992         }
993         d = kmemdup(page, len, GFP_KERNEL);
994         if (!d) {
995                 ret = -ENOMEM;
996                 goto end;
997         }
998         kfree(opts->report_desc);
999         opts->report_desc = d;
1000         opts->report_desc_length = len;
1001         opts->report_desc_alloc = true;
1002         ret = len;
1003 end:
1004         mutex_unlock(&opts->lock);
1005         return ret;
1006 }
1007
1008 CONFIGFS_ATTR(f_hid_opts_, report_desc);
1009
1010 static ssize_t f_hid_opts_dev_show(struct config_item *item, char *page)
1011 {
1012         struct f_hid_opts *opts = to_f_hid_opts(item);
1013
1014         return sprintf(page, "%d:%d\n", major, opts->minor);
1015 }
1016
1017 CONFIGFS_ATTR_RO(f_hid_opts_, dev);
1018
1019 static struct configfs_attribute *hid_attrs[] = {
1020         &f_hid_opts_attr_subclass,
1021         &f_hid_opts_attr_protocol,
1022         &f_hid_opts_attr_report_length,
1023         &f_hid_opts_attr_report_desc,
1024         &f_hid_opts_attr_dev,
1025         NULL,
1026 };
1027
1028 static struct config_item_type hid_func_type = {
1029         .ct_item_ops    = &hidg_item_ops,
1030         .ct_attrs       = hid_attrs,
1031         .ct_owner       = THIS_MODULE,
1032 };
1033
1034 static inline void hidg_put_minor(int minor)
1035 {
1036         ida_simple_remove(&hidg_ida, minor);
1037 }
1038
1039 static void hidg_free_inst(struct usb_function_instance *f)
1040 {
1041         struct f_hid_opts *opts;
1042
1043         opts = container_of(f, struct f_hid_opts, func_inst);
1044
1045         mutex_lock(&hidg_ida_lock);
1046
1047         hidg_put_minor(opts->minor);
1048         if (ida_is_empty(&hidg_ida))
1049                 ghid_cleanup();
1050
1051         mutex_unlock(&hidg_ida_lock);
1052
1053         if (opts->report_desc_alloc)
1054                 kfree(opts->report_desc);
1055
1056         kfree(opts);
1057 }
1058
1059 static struct usb_function_instance *hidg_alloc_inst(void)
1060 {
1061         struct f_hid_opts *opts;
1062         struct usb_function_instance *ret;
1063         int status = 0;
1064
1065         opts = kzalloc(sizeof(*opts), GFP_KERNEL);
1066         if (!opts)
1067                 return ERR_PTR(-ENOMEM);
1068         mutex_init(&opts->lock);
1069         opts->func_inst.free_func_inst = hidg_free_inst;
1070         ret = &opts->func_inst;
1071
1072         mutex_lock(&hidg_ida_lock);
1073
1074         if (ida_is_empty(&hidg_ida)) {
1075                 status = ghid_setup(NULL, HIDG_MINORS);
1076                 if (status)  {
1077                         ret = ERR_PTR(status);
1078                         kfree(opts);
1079                         goto unlock;
1080                 }
1081         }
1082
1083         opts->minor = hidg_get_minor();
1084         if (opts->minor < 0) {
1085                 ret = ERR_PTR(opts->minor);
1086                 kfree(opts);
1087                 if (ida_is_empty(&hidg_ida))
1088                         ghid_cleanup();
1089                 goto unlock;
1090         }
1091         config_group_init_type_name(&opts->func_inst.group, "", &hid_func_type);
1092
1093 unlock:
1094         mutex_unlock(&hidg_ida_lock);
1095         return ret;
1096 }
1097
1098 static void hidg_free(struct usb_function *f)
1099 {
1100         struct f_hidg *hidg;
1101         struct f_hid_opts *opts;
1102
1103         hidg = func_to_hidg(f);
1104         opts = container_of(f->fi, struct f_hid_opts, func_inst);
1105         kfree(hidg->report_desc);
1106         kfree(hidg);
1107         mutex_lock(&opts->lock);
1108         --opts->refcnt;
1109         mutex_unlock(&opts->lock);
1110 }
1111
1112 static void hidg_unbind(struct usb_configuration *c, struct usb_function *f)
1113 {
1114         struct f_hidg *hidg = func_to_hidg(f);
1115
1116         device_destroy(hidg_class, MKDEV(major, hidg->minor));
1117         cdev_del(&hidg->cdev);
1118
1119         usb_free_all_descriptors(f);
1120 }
1121
1122 static struct usb_function *hidg_alloc(struct usb_function_instance *fi)
1123 {
1124         struct f_hidg *hidg;
1125         struct f_hid_opts *opts;
1126
1127         /* allocate and initialize one new instance */
1128         hidg = kzalloc(sizeof(*hidg), GFP_KERNEL);
1129         if (!hidg)
1130                 return ERR_PTR(-ENOMEM);
1131
1132         opts = container_of(fi, struct f_hid_opts, func_inst);
1133
1134         mutex_lock(&opts->lock);
1135         ++opts->refcnt;
1136
1137         hidg->minor = opts->minor;
1138         hidg->bInterfaceSubClass = opts->subclass;
1139         hidg->bInterfaceProtocol = opts->protocol;
1140         hidg->report_length = opts->report_length;
1141         hidg->report_desc_length = opts->report_desc_length;
1142         if (opts->report_desc) {
1143                 hidg->report_desc = kmemdup(opts->report_desc,
1144                                             opts->report_desc_length,
1145                                             GFP_KERNEL);
1146                 if (!hidg->report_desc) {
1147                         kfree(hidg);
1148                         mutex_unlock(&opts->lock);
1149                         return ERR_PTR(-ENOMEM);
1150                 }
1151         }
1152
1153         mutex_unlock(&opts->lock);
1154
1155         hidg->func.name    = "hid";
1156         hidg->func.bind    = hidg_bind;
1157         hidg->func.unbind  = hidg_unbind;
1158         hidg->func.set_alt = hidg_set_alt;
1159         hidg->func.disable = hidg_disable;
1160         hidg->func.setup   = hidg_setup;
1161         hidg->func.free_func = hidg_free;
1162
1163         /* this could me made configurable at some point */
1164         hidg->qlen         = 4;
1165
1166         return &hidg->func;
1167 }
1168
1169 DECLARE_USB_FUNCTION_INIT(hid, hidg_alloc_inst, hidg_alloc);
1170 MODULE_LICENSE("GPL");
1171 MODULE_AUTHOR("Fabien Chouteau");
1172
1173 int ghid_setup(struct usb_gadget *g, int count)
1174 {
1175         int status;
1176         dev_t dev;
1177
1178         hidg_class = class_create(THIS_MODULE, "hidg");
1179         if (IS_ERR(hidg_class)) {
1180                 status = PTR_ERR(hidg_class);
1181                 hidg_class = NULL;
1182                 return status;
1183         }
1184
1185         status = alloc_chrdev_region(&dev, 0, count, "hidg");
1186         if (status) {
1187                 class_destroy(hidg_class);
1188                 hidg_class = NULL;
1189                 return status;
1190         }
1191
1192         major = MAJOR(dev);
1193         minors = count;
1194
1195         return 0;
1196 }
1197
1198 void ghid_cleanup(void)
1199 {
1200         if (major) {
1201                 unregister_chrdev_region(MKDEV(major, 0), minors);
1202                 major = minors = 0;
1203         }
1204
1205         class_destroy(hidg_class);
1206         hidg_class = NULL;
1207 }