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