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