aboutsummaryrefslogtreecommitdiffstats
path: root/drivers/usb/gadget/function
diff options
context:
space:
mode:
Diffstat (limited to 'drivers/usb/gadget/function')
-rw-r--r--drivers/usb/gadget/function/Makefile34
-rw-r--r--drivers/usb/gadget/function/f_acm.c848
-rw-r--r--drivers/usb/gadget/function/f_ecm.c973
-rw-r--r--drivers/usb/gadget/function/f_eem.c660
-rw-r--r--drivers/usb/gadget/function/f_fs.c3349
-rw-r--r--drivers/usb/gadget/function/f_hid.c763
-rw-r--r--drivers/usb/gadget/function/f_loopback.c571
-rw-r--r--drivers/usb/gadget/function/f_mass_storage.c3668
-rw-r--r--drivers/usb/gadget/function/f_mass_storage.h166
-rw-r--r--drivers/usb/gadget/function/f_midi.c986
-rw-r--r--drivers/usb/gadget/function/f_ncm.c1622
-rw-r--r--drivers/usb/gadget/function/f_obex.c533
-rw-r--r--drivers/usb/gadget/function/f_phonet.c758
-rw-r--r--drivers/usb/gadget/function/f_rndis.c1035
-rw-r--r--drivers/usb/gadget/function/f_serial.c385
-rw-r--r--drivers/usb/gadget/function/f_sourcesink.c1247
-rw-r--r--drivers/usb/gadget/function/f_subset.c519
-rw-r--r--drivers/usb/gadget/function/f_uac1.c768
-rw-r--r--drivers/usb/gadget/function/f_uac2.c1374
-rw-r--r--drivers/usb/gadget/function/f_uvc.c836
-rw-r--r--drivers/usb/gadget/function/f_uvc.h27
-rw-r--r--drivers/usb/gadget/function/g_zero.h67
-rw-r--r--drivers/usb/gadget/function/ndis.h47
-rw-r--r--drivers/usb/gadget/function/rndis.c1190
-rw-r--r--drivers/usb/gadget/function/rndis.h220
-rw-r--r--drivers/usb/gadget/function/storage_common.c504
-rw-r--r--drivers/usb/gadget/function/storage_common.h225
-rw-r--r--drivers/usb/gadget/function/u_ecm.h36
-rw-r--r--drivers/usb/gadget/function/u_eem.h36
-rw-r--r--drivers/usb/gadget/function/u_ether.c1182
-rw-r--r--drivers/usb/gadget/function/u_ether.h272
-rw-r--r--drivers/usb/gadget/function/u_ether_configfs.h164
-rw-r--r--drivers/usb/gadget/function/u_fs.h270
-rw-r--r--drivers/usb/gadget/function/u_gether.h36
-rw-r--r--drivers/usb/gadget/function/u_ncm.h36
-rw-r--r--drivers/usb/gadget/function/u_phonet.h29
-rw-r--r--drivers/usb/gadget/function/u_rndis.h46
-rw-r--r--drivers/usb/gadget/function/u_serial.c1347
-rw-r--r--drivers/usb/gadget/function/u_serial.h71
-rw-r--r--drivers/usb/gadget/function/u_uac1.c330
-rw-r--r--drivers/usb/gadget/function/u_uac1.h56
-rw-r--r--drivers/usb/gadget/function/uvc.h202
-rw-r--r--drivers/usb/gadget/function/uvc_queue.c407
-rw-r--r--drivers/usb/gadget/function/uvc_queue.h63
-rw-r--r--drivers/usb/gadget/function/uvc_v4l2.c365
-rw-r--r--drivers/usb/gadget/function/uvc_video.c394
46 files changed, 28717 insertions, 0 deletions
diff --git a/drivers/usb/gadget/function/Makefile b/drivers/usb/gadget/function/Makefile
new file mode 100644
index 000000000000..6d91f21b52a6
--- /dev/null
+++ b/drivers/usb/gadget/function/Makefile
@@ -0,0 +1,34 @@
1#
2# USB peripheral controller drivers
3#
4
5ccflags-y := -I$(PWD)/drivers/usb/gadget/
6ccflags-y += -I$(PWD)/drivers/usb/gadget/udc/
7
8# USB Functions
9usb_f_acm-y := f_acm.o
10obj-$(CONFIG_USB_F_ACM) += usb_f_acm.o
11usb_f_ss_lb-y := f_loopback.o f_sourcesink.o
12obj-$(CONFIG_USB_F_SS_LB) += usb_f_ss_lb.o
13obj-$(CONFIG_USB_U_SERIAL) += u_serial.o
14usb_f_serial-y := f_serial.o
15obj-$(CONFIG_USB_F_SERIAL) += usb_f_serial.o
16usb_f_obex-y := f_obex.o
17obj-$(CONFIG_USB_F_OBEX) += usb_f_obex.o
18obj-$(CONFIG_USB_U_ETHER) += u_ether.o
19usb_f_ncm-y := f_ncm.o
20obj-$(CONFIG_USB_F_NCM) += usb_f_ncm.o
21usb_f_ecm-y := f_ecm.o
22obj-$(CONFIG_USB_F_ECM) += usb_f_ecm.o
23usb_f_phonet-y := f_phonet.o
24obj-$(CONFIG_USB_F_PHONET) += usb_f_phonet.o
25usb_f_eem-y := f_eem.o
26obj-$(CONFIG_USB_F_EEM) += usb_f_eem.o
27usb_f_ecm_subset-y := f_subset.o
28obj-$(CONFIG_USB_F_SUBSET) += usb_f_ecm_subset.o
29usb_f_rndis-y := f_rndis.o rndis.o
30obj-$(CONFIG_USB_F_RNDIS) += usb_f_rndis.o
31usb_f_mass_storage-y := f_mass_storage.o storage_common.o
32obj-$(CONFIG_USB_F_MASS_STORAGE)+= usb_f_mass_storage.o
33usb_f_fs-y := f_fs.o
34obj-$(CONFIG_USB_F_FS) += usb_f_fs.o
diff --git a/drivers/usb/gadget/function/f_acm.c b/drivers/usb/gadget/function/f_acm.c
new file mode 100644
index 000000000000..ab1065afbbd0
--- /dev/null
+++ b/drivers/usb/gadget/function/f_acm.c
@@ -0,0 +1,848 @@
1/*
2 * f_acm.c -- USB CDC serial (ACM) function driver
3 *
4 * Copyright (C) 2003 Al Borchers (alborchers@steinerpoint.com)
5 * Copyright (C) 2008 by David Brownell
6 * Copyright (C) 2008 by Nokia Corporation
7 * Copyright (C) 2009 by Samsung Electronics
8 * Author: Michal Nazarewicz (mina86@mina86.com)
9 *
10 * This software is distributed under the terms of the GNU General
11 * Public License ("GPL") as published by the Free Software Foundation,
12 * either version 2 of that License or (at your option) any later version.
13 */
14
15/* #define VERBOSE_DEBUG */
16
17#include <linux/slab.h>
18#include <linux/kernel.h>
19#include <linux/module.h>
20#include <linux/device.h>
21#include <linux/err.h>
22
23#include "u_serial.h"
24#include "gadget_chips.h"
25
26
27/*
28 * This CDC ACM function support just wraps control functions and
29 * notifications around the generic serial-over-usb code.
30 *
31 * Because CDC ACM is standardized by the USB-IF, many host operating
32 * systems have drivers for it. Accordingly, ACM is the preferred
33 * interop solution for serial-port type connections. The control
34 * models are often not necessary, and in any case don't do much in
35 * this bare-bones implementation.
36 *
37 * Note that even MS-Windows has some support for ACM. However, that
38 * support is somewhat broken because when you use ACM in a composite
39 * device, having multiple interfaces confuses the poor OS. It doesn't
40 * seem to understand CDC Union descriptors. The new "association"
41 * descriptors (roughly equivalent to CDC Unions) may sometimes help.
42 */
43
44struct f_acm {
45 struct gserial port;
46 u8 ctrl_id, data_id;
47 u8 port_num;
48
49 u8 pending;
50
51 /* lock is mostly for pending and notify_req ... they get accessed
52 * by callbacks both from tty (open/close/break) under its spinlock,
53 * and notify_req.complete() which can't use that lock.
54 */
55 spinlock_t lock;
56
57 struct usb_ep *notify;
58 struct usb_request *notify_req;
59
60 struct usb_cdc_line_coding port_line_coding; /* 8-N-1 etc */
61
62 /* SetControlLineState request -- CDC 1.1 section 6.2.14 (INPUT) */
63 u16 port_handshake_bits;
64#define ACM_CTRL_RTS (1 << 1) /* unused with full duplex */
65#define ACM_CTRL_DTR (1 << 0) /* host is ready for data r/w */
66
67 /* SerialState notification -- CDC 1.1 section 6.3.5 (OUTPUT) */
68 u16 serial_state;
69#define ACM_CTRL_OVERRUN (1 << 6)
70#define ACM_CTRL_PARITY (1 << 5)
71#define ACM_CTRL_FRAMING (1 << 4)
72#define ACM_CTRL_RI (1 << 3)
73#define ACM_CTRL_BRK (1 << 2)
74#define ACM_CTRL_DSR (1 << 1)
75#define ACM_CTRL_DCD (1 << 0)
76};
77
78static inline struct f_acm *func_to_acm(struct usb_function *f)
79{
80 return container_of(f, struct f_acm, port.func);
81}
82
83static inline struct f_acm *port_to_acm(struct gserial *p)
84{
85 return container_of(p, struct f_acm, port);
86}
87
88/*-------------------------------------------------------------------------*/
89
90/* notification endpoint uses smallish and infrequent fixed-size messages */
91
92#define GS_NOTIFY_INTERVAL_MS 32
93#define GS_NOTIFY_MAXPACKET 10 /* notification + 2 bytes */
94
95/* interface and class descriptors: */
96
97static struct usb_interface_assoc_descriptor
98acm_iad_descriptor = {
99 .bLength = sizeof acm_iad_descriptor,
100 .bDescriptorType = USB_DT_INTERFACE_ASSOCIATION,
101
102 /* .bFirstInterface = DYNAMIC, */
103 .bInterfaceCount = 2, // control + data
104 .bFunctionClass = USB_CLASS_COMM,
105 .bFunctionSubClass = USB_CDC_SUBCLASS_ACM,
106 .bFunctionProtocol = USB_CDC_ACM_PROTO_AT_V25TER,
107 /* .iFunction = DYNAMIC */
108};
109
110
111static struct usb_interface_descriptor acm_control_interface_desc = {
112 .bLength = USB_DT_INTERFACE_SIZE,
113 .bDescriptorType = USB_DT_INTERFACE,
114 /* .bInterfaceNumber = DYNAMIC */
115 .bNumEndpoints = 1,
116 .bInterfaceClass = USB_CLASS_COMM,
117 .bInterfaceSubClass = USB_CDC_SUBCLASS_ACM,
118 .bInterfaceProtocol = USB_CDC_ACM_PROTO_AT_V25TER,
119 /* .iInterface = DYNAMIC */
120};
121
122static struct usb_interface_descriptor acm_data_interface_desc = {
123 .bLength = USB_DT_INTERFACE_SIZE,
124 .bDescriptorType = USB_DT_INTERFACE,
125 /* .bInterfaceNumber = DYNAMIC */
126 .bNumEndpoints = 2,
127 .bInterfaceClass = USB_CLASS_CDC_DATA,
128 .bInterfaceSubClass = 0,
129 .bInterfaceProtocol = 0,
130 /* .iInterface = DYNAMIC */
131};
132
133static struct usb_cdc_header_desc acm_header_desc = {
134 .bLength = sizeof(acm_header_desc),
135 .bDescriptorType = USB_DT_CS_INTERFACE,
136 .bDescriptorSubType = USB_CDC_HEADER_TYPE,
137 .bcdCDC = cpu_to_le16(0x0110),
138};
139
140static struct usb_cdc_call_mgmt_descriptor
141acm_call_mgmt_descriptor = {
142 .bLength = sizeof(acm_call_mgmt_descriptor),
143 .bDescriptorType = USB_DT_CS_INTERFACE,
144 .bDescriptorSubType = USB_CDC_CALL_MANAGEMENT_TYPE,
145 .bmCapabilities = 0,
146 /* .bDataInterface = DYNAMIC */
147};
148
149static struct usb_cdc_acm_descriptor acm_descriptor = {
150 .bLength = sizeof(acm_descriptor),
151 .bDescriptorType = USB_DT_CS_INTERFACE,
152 .bDescriptorSubType = USB_CDC_ACM_TYPE,
153 .bmCapabilities = USB_CDC_CAP_LINE,
154};
155
156static struct usb_cdc_union_desc acm_union_desc = {
157 .bLength = sizeof(acm_union_desc),
158 .bDescriptorType = USB_DT_CS_INTERFACE,
159 .bDescriptorSubType = USB_CDC_UNION_TYPE,
160 /* .bMasterInterface0 = DYNAMIC */
161 /* .bSlaveInterface0 = DYNAMIC */
162};
163
164/* full speed support: */
165
166static struct usb_endpoint_descriptor acm_fs_notify_desc = {
167 .bLength = USB_DT_ENDPOINT_SIZE,
168 .bDescriptorType = USB_DT_ENDPOINT,
169 .bEndpointAddress = USB_DIR_IN,
170 .bmAttributes = USB_ENDPOINT_XFER_INT,
171 .wMaxPacketSize = cpu_to_le16(GS_NOTIFY_MAXPACKET),
172 .bInterval = GS_NOTIFY_INTERVAL_MS,
173};
174
175static struct usb_endpoint_descriptor acm_fs_in_desc = {
176 .bLength = USB_DT_ENDPOINT_SIZE,
177 .bDescriptorType = USB_DT_ENDPOINT,
178 .bEndpointAddress = USB_DIR_IN,
179 .bmAttributes = USB_ENDPOINT_XFER_BULK,
180};
181
182static struct usb_endpoint_descriptor acm_fs_out_desc = {
183 .bLength = USB_DT_ENDPOINT_SIZE,
184 .bDescriptorType = USB_DT_ENDPOINT,
185 .bEndpointAddress = USB_DIR_OUT,
186 .bmAttributes = USB_ENDPOINT_XFER_BULK,
187};
188
189static struct usb_descriptor_header *acm_fs_function[] = {
190 (struct usb_descriptor_header *) &acm_iad_descriptor,
191 (struct usb_descriptor_header *) &acm_control_interface_desc,
192 (struct usb_descriptor_header *) &acm_header_desc,
193 (struct usb_descriptor_header *) &acm_call_mgmt_descriptor,
194 (struct usb_descriptor_header *) &acm_descriptor,
195 (struct usb_descriptor_header *) &acm_union_desc,
196 (struct usb_descriptor_header *) &acm_fs_notify_desc,
197 (struct usb_descriptor_header *) &acm_data_interface_desc,
198 (struct usb_descriptor_header *) &acm_fs_in_desc,
199 (struct usb_descriptor_header *) &acm_fs_out_desc,
200 NULL,
201};
202
203/* high speed support: */
204static struct usb_endpoint_descriptor acm_hs_notify_desc = {
205 .bLength = USB_DT_ENDPOINT_SIZE,
206 .bDescriptorType = USB_DT_ENDPOINT,
207 .bEndpointAddress = USB_DIR_IN,
208 .bmAttributes = USB_ENDPOINT_XFER_INT,
209 .wMaxPacketSize = cpu_to_le16(GS_NOTIFY_MAXPACKET),
210 .bInterval = USB_MS_TO_HS_INTERVAL(GS_NOTIFY_INTERVAL_MS),
211};
212
213static struct usb_endpoint_descriptor acm_hs_in_desc = {
214 .bLength = USB_DT_ENDPOINT_SIZE,
215 .bDescriptorType = USB_DT_ENDPOINT,
216 .bmAttributes = USB_ENDPOINT_XFER_BULK,
217 .wMaxPacketSize = cpu_to_le16(512),
218};
219
220static struct usb_endpoint_descriptor acm_hs_out_desc = {
221 .bLength = USB_DT_ENDPOINT_SIZE,
222 .bDescriptorType = USB_DT_ENDPOINT,
223 .bmAttributes = USB_ENDPOINT_XFER_BULK,
224 .wMaxPacketSize = cpu_to_le16(512),
225};
226
227static struct usb_descriptor_header *acm_hs_function[] = {
228 (struct usb_descriptor_header *) &acm_iad_descriptor,
229 (struct usb_descriptor_header *) &acm_control_interface_desc,
230 (struct usb_descriptor_header *) &acm_header_desc,
231 (struct usb_descriptor_header *) &acm_call_mgmt_descriptor,
232 (struct usb_descriptor_header *) &acm_descriptor,
233 (struct usb_descriptor_header *) &acm_union_desc,
234 (struct usb_descriptor_header *) &acm_hs_notify_desc,
235 (struct usb_descriptor_header *) &acm_data_interface_desc,
236 (struct usb_descriptor_header *) &acm_hs_in_desc,
237 (struct usb_descriptor_header *) &acm_hs_out_desc,
238 NULL,
239};
240
241static struct usb_endpoint_descriptor acm_ss_in_desc = {
242 .bLength = USB_DT_ENDPOINT_SIZE,
243 .bDescriptorType = USB_DT_ENDPOINT,
244 .bmAttributes = USB_ENDPOINT_XFER_BULK,
245 .wMaxPacketSize = cpu_to_le16(1024),
246};
247
248static struct usb_endpoint_descriptor acm_ss_out_desc = {
249 .bLength = USB_DT_ENDPOINT_SIZE,
250 .bDescriptorType = USB_DT_ENDPOINT,
251 .bmAttributes = USB_ENDPOINT_XFER_BULK,
252 .wMaxPacketSize = cpu_to_le16(1024),
253};
254
255static struct usb_ss_ep_comp_descriptor acm_ss_bulk_comp_desc = {
256 .bLength = sizeof acm_ss_bulk_comp_desc,
257 .bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
258};
259
260static struct usb_descriptor_header *acm_ss_function[] = {
261 (struct usb_descriptor_header *) &acm_iad_descriptor,
262 (struct usb_descriptor_header *) &acm_control_interface_desc,
263 (struct usb_descriptor_header *) &acm_header_desc,
264 (struct usb_descriptor_header *) &acm_call_mgmt_descriptor,
265 (struct usb_descriptor_header *) &acm_descriptor,
266 (struct usb_descriptor_header *) &acm_union_desc,
267 (struct usb_descriptor_header *) &acm_hs_notify_desc,
268 (struct usb_descriptor_header *) &acm_ss_bulk_comp_desc,
269 (struct usb_descriptor_header *) &acm_data_interface_desc,
270 (struct usb_descriptor_header *) &acm_ss_in_desc,
271 (struct usb_descriptor_header *) &acm_ss_bulk_comp_desc,
272 (struct usb_descriptor_header *) &acm_ss_out_desc,
273 (struct usb_descriptor_header *) &acm_ss_bulk_comp_desc,
274 NULL,
275};
276
277/* string descriptors: */
278
279#define ACM_CTRL_IDX 0
280#define ACM_DATA_IDX 1
281#define ACM_IAD_IDX 2
282
283/* static strings, in UTF-8 */
284static struct usb_string acm_string_defs[] = {
285 [ACM_CTRL_IDX].s = "CDC Abstract Control Model (ACM)",
286 [ACM_DATA_IDX].s = "CDC ACM Data",
287 [ACM_IAD_IDX ].s = "CDC Serial",
288 { } /* end of list */
289};
290
291static struct usb_gadget_strings acm_string_table = {
292 .language = 0x0409, /* en-us */
293 .strings = acm_string_defs,
294};
295
296static struct usb_gadget_strings *acm_strings[] = {
297 &acm_string_table,
298 NULL,
299};
300
301/*-------------------------------------------------------------------------*/
302
303/* ACM control ... data handling is delegated to tty library code.
304 * The main task of this function is to activate and deactivate
305 * that code based on device state; track parameters like line
306 * speed, handshake state, and so on; and issue notifications.
307 */
308
309static void acm_complete_set_line_coding(struct usb_ep *ep,
310 struct usb_request *req)
311{
312 struct f_acm *acm = ep->driver_data;
313 struct usb_composite_dev *cdev = acm->port.func.config->cdev;
314
315 if (req->status != 0) {
316 DBG(cdev, "acm ttyGS%d completion, err %d\n",
317 acm->port_num, req->status);
318 return;
319 }
320
321 /* normal completion */
322 if (req->actual != sizeof(acm->port_line_coding)) {
323 DBG(cdev, "acm ttyGS%d short resp, len %d\n",
324 acm->port_num, req->actual);
325 usb_ep_set_halt(ep);
326 } else {
327 struct usb_cdc_line_coding *value = req->buf;
328
329 /* REVISIT: we currently just remember this data.
330 * If we change that, (a) validate it first, then
331 * (b) update whatever hardware needs updating,
332 * (c) worry about locking. This is information on
333 * the order of 9600-8-N-1 ... most of which means
334 * nothing unless we control a real RS232 line.
335 */
336 acm->port_line_coding = *value;
337 }
338}
339
340static int acm_setup(struct usb_function *f, const struct usb_ctrlrequest *ctrl)
341{
342 struct f_acm *acm = func_to_acm(f);
343 struct usb_composite_dev *cdev = f->config->cdev;
344 struct usb_request *req = cdev->req;
345 int value = -EOPNOTSUPP;
346 u16 w_index = le16_to_cpu(ctrl->wIndex);
347 u16 w_value = le16_to_cpu(ctrl->wValue);
348 u16 w_length = le16_to_cpu(ctrl->wLength);
349
350 /* composite driver infrastructure handles everything except
351 * CDC class messages; interface activation uses set_alt().
352 *
353 * Note CDC spec table 4 lists the ACM request profile. It requires
354 * encapsulated command support ... we don't handle any, and respond
355 * to them by stalling. Options include get/set/clear comm features
356 * (not that useful) and SEND_BREAK.
357 */
358 switch ((ctrl->bRequestType << 8) | ctrl->bRequest) {
359
360 /* SET_LINE_CODING ... just read and save what the host sends */
361 case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
362 | USB_CDC_REQ_SET_LINE_CODING:
363 if (w_length != sizeof(struct usb_cdc_line_coding)
364 || w_index != acm->ctrl_id)
365 goto invalid;
366
367 value = w_length;
368 cdev->gadget->ep0->driver_data = acm;
369 req->complete = acm_complete_set_line_coding;
370 break;
371
372 /* GET_LINE_CODING ... return what host sent, or initial value */
373 case ((USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
374 | USB_CDC_REQ_GET_LINE_CODING:
375 if (w_index != acm->ctrl_id)
376 goto invalid;
377
378 value = min_t(unsigned, w_length,
379 sizeof(struct usb_cdc_line_coding));
380 memcpy(req->buf, &acm->port_line_coding, value);
381 break;
382
383 /* SET_CONTROL_LINE_STATE ... save what the host sent */
384 case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
385 | USB_CDC_REQ_SET_CONTROL_LINE_STATE:
386 if (w_index != acm->ctrl_id)
387 goto invalid;
388
389 value = 0;
390
391 /* FIXME we should not allow data to flow until the
392 * host sets the ACM_CTRL_DTR bit; and when it clears
393 * that bit, we should return to that no-flow state.
394 */
395 acm->port_handshake_bits = w_value;
396 break;
397
398 default:
399invalid:
400 VDBG(cdev, "invalid control req%02x.%02x v%04x i%04x l%d\n",
401 ctrl->bRequestType, ctrl->bRequest,
402 w_value, w_index, w_length);
403 }
404
405 /* respond with data transfer or status phase? */
406 if (value >= 0) {
407 DBG(cdev, "acm ttyGS%d req%02x.%02x v%04x i%04x l%d\n",
408 acm->port_num, ctrl->bRequestType, ctrl->bRequest,
409 w_value, w_index, w_length);
410 req->zero = 0;
411 req->length = value;
412 value = usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC);
413 if (value < 0)
414 ERROR(cdev, "acm response on ttyGS%d, err %d\n",
415 acm->port_num, value);
416 }
417
418 /* device either stalls (value < 0) or reports success */
419 return value;
420}
421
422static int acm_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
423{
424 struct f_acm *acm = func_to_acm(f);
425 struct usb_composite_dev *cdev = f->config->cdev;
426
427 /* we know alt == 0, so this is an activation or a reset */
428
429 if (intf == acm->ctrl_id) {
430 if (acm->notify->driver_data) {
431 VDBG(cdev, "reset acm control interface %d\n", intf);
432 usb_ep_disable(acm->notify);
433 } else {
434 VDBG(cdev, "init acm ctrl interface %d\n", intf);
435 if (config_ep_by_speed(cdev->gadget, f, acm->notify))
436 return -EINVAL;
437 }
438 usb_ep_enable(acm->notify);
439 acm->notify->driver_data = acm;
440
441 } else if (intf == acm->data_id) {
442 if (acm->port.in->driver_data) {
443 DBG(cdev, "reset acm ttyGS%d\n", acm->port_num);
444 gserial_disconnect(&acm->port);
445 }
446 if (!acm->port.in->desc || !acm->port.out->desc) {
447 DBG(cdev, "activate acm ttyGS%d\n", acm->port_num);
448 if (config_ep_by_speed(cdev->gadget, f,
449 acm->port.in) ||
450 config_ep_by_speed(cdev->gadget, f,
451 acm->port.out)) {
452 acm->port.in->desc = NULL;
453 acm->port.out->desc = NULL;
454 return -EINVAL;
455 }
456 }
457 gserial_connect(&acm->port, acm->port_num);
458
459 } else
460 return -EINVAL;
461
462 return 0;
463}
464
465static void acm_disable(struct usb_function *f)
466{
467 struct f_acm *acm = func_to_acm(f);
468 struct usb_composite_dev *cdev = f->config->cdev;
469
470 DBG(cdev, "acm ttyGS%d deactivated\n", acm->port_num);
471 gserial_disconnect(&acm->port);
472 usb_ep_disable(acm->notify);
473 acm->notify->driver_data = NULL;
474}
475
476/*-------------------------------------------------------------------------*/
477
478/**
479 * acm_cdc_notify - issue CDC notification to host
480 * @acm: wraps host to be notified
481 * @type: notification type
482 * @value: Refer to cdc specs, wValue field.
483 * @data: data to be sent
484 * @length: size of data
485 * Context: irqs blocked, acm->lock held, acm_notify_req non-null
486 *
487 * Returns zero on success or a negative errno.
488 *
489 * See section 6.3.5 of the CDC 1.1 specification for information
490 * about the only notification we issue: SerialState change.
491 */
492static int acm_cdc_notify(struct f_acm *acm, u8 type, u16 value,
493 void *data, unsigned length)
494{
495 struct usb_ep *ep = acm->notify;
496 struct usb_request *req;
497 struct usb_cdc_notification *notify;
498 const unsigned len = sizeof(*notify) + length;
499 void *buf;
500 int status;
501
502 req = acm->notify_req;
503 acm->notify_req = NULL;
504 acm->pending = false;
505
506 req->length = len;
507 notify = req->buf;
508 buf = notify + 1;
509
510 notify->bmRequestType = USB_DIR_IN | USB_TYPE_CLASS
511 | USB_RECIP_INTERFACE;
512 notify->bNotificationType = type;
513 notify->wValue = cpu_to_le16(value);
514 notify->wIndex = cpu_to_le16(acm->ctrl_id);
515 notify->wLength = cpu_to_le16(length);
516 memcpy(buf, data, length);
517
518 /* ep_queue() can complete immediately if it fills the fifo... */
519 spin_unlock(&acm->lock);
520 status = usb_ep_queue(ep, req, GFP_ATOMIC);
521 spin_lock(&acm->lock);
522
523 if (status < 0) {
524 ERROR(acm->port.func.config->cdev,
525 "acm ttyGS%d can't notify serial state, %d\n",
526 acm->port_num, status);
527 acm->notify_req = req;
528 }
529
530 return status;
531}
532
533static int acm_notify_serial_state(struct f_acm *acm)
534{
535 struct usb_composite_dev *cdev = acm->port.func.config->cdev;
536 int status;
537
538 spin_lock(&acm->lock);
539 if (acm->notify_req) {
540 DBG(cdev, "acm ttyGS%d serial state %04x\n",
541 acm->port_num, acm->serial_state);
542 status = acm_cdc_notify(acm, USB_CDC_NOTIFY_SERIAL_STATE,
543 0, &acm->serial_state, sizeof(acm->serial_state));
544 } else {
545 acm->pending = true;
546 status = 0;
547 }
548 spin_unlock(&acm->lock);
549 return status;
550}
551
552static void acm_cdc_notify_complete(struct usb_ep *ep, struct usb_request *req)
553{
554 struct f_acm *acm = req->context;
555 u8 doit = false;
556
557 /* on this call path we do NOT hold the port spinlock,
558 * which is why ACM needs its own spinlock
559 */
560 spin_lock(&acm->lock);
561 if (req->status != -ESHUTDOWN)
562 doit = acm->pending;
563 acm->notify_req = req;
564 spin_unlock(&acm->lock);
565
566 if (doit)
567 acm_notify_serial_state(acm);
568}
569
570/* connect == the TTY link is open */
571
572static void acm_connect(struct gserial *port)
573{
574 struct f_acm *acm = port_to_acm(port);
575
576 acm->serial_state |= ACM_CTRL_DSR | ACM_CTRL_DCD;
577 acm_notify_serial_state(acm);
578}
579
580static void acm_disconnect(struct gserial *port)
581{
582 struct f_acm *acm = port_to_acm(port);
583
584 acm->serial_state &= ~(ACM_CTRL_DSR | ACM_CTRL_DCD);
585 acm_notify_serial_state(acm);
586}
587
588static int acm_send_break(struct gserial *port, int duration)
589{
590 struct f_acm *acm = port_to_acm(port);
591 u16 state;
592
593 state = acm->serial_state;
594 state &= ~ACM_CTRL_BRK;
595 if (duration)
596 state |= ACM_CTRL_BRK;
597
598 acm->serial_state = state;
599 return acm_notify_serial_state(acm);
600}
601
602/*-------------------------------------------------------------------------*/
603
604/* ACM function driver setup/binding */
605static int
606acm_bind(struct usb_configuration *c, struct usb_function *f)
607{
608 struct usb_composite_dev *cdev = c->cdev;
609 struct f_acm *acm = func_to_acm(f);
610 struct usb_string *us;
611 int status;
612 struct usb_ep *ep;
613
614 /* REVISIT might want instance-specific strings to help
615 * distinguish instances ...
616 */
617
618 /* maybe allocate device-global string IDs, and patch descriptors */
619 us = usb_gstrings_attach(cdev, acm_strings,
620 ARRAY_SIZE(acm_string_defs));
621 if (IS_ERR(us))
622 return PTR_ERR(us);
623 acm_control_interface_desc.iInterface = us[ACM_CTRL_IDX].id;
624 acm_data_interface_desc.iInterface = us[ACM_DATA_IDX].id;
625 acm_iad_descriptor.iFunction = us[ACM_IAD_IDX].id;
626
627 /* allocate instance-specific interface IDs, and patch descriptors */
628 status = usb_interface_id(c, f);
629 if (status < 0)
630 goto fail;
631 acm->ctrl_id = status;
632 acm_iad_descriptor.bFirstInterface = status;
633
634 acm_control_interface_desc.bInterfaceNumber = status;
635 acm_union_desc .bMasterInterface0 = status;
636
637 status = usb_interface_id(c, f);
638 if (status < 0)
639 goto fail;
640 acm->data_id = status;
641
642 acm_data_interface_desc.bInterfaceNumber = status;
643 acm_union_desc.bSlaveInterface0 = status;
644 acm_call_mgmt_descriptor.bDataInterface = status;
645
646 status = -ENODEV;
647
648 /* allocate instance-specific endpoints */
649 ep = usb_ep_autoconfig(cdev->gadget, &acm_fs_in_desc);
650 if (!ep)
651 goto fail;
652 acm->port.in = ep;
653 ep->driver_data = cdev; /* claim */
654
655 ep = usb_ep_autoconfig(cdev->gadget, &acm_fs_out_desc);
656 if (!ep)
657 goto fail;
658 acm->port.out = ep;
659 ep->driver_data = cdev; /* claim */
660
661 ep = usb_ep_autoconfig(cdev->gadget, &acm_fs_notify_desc);
662 if (!ep)
663 goto fail;
664 acm->notify = ep;
665 ep->driver_data = cdev; /* claim */
666
667 /* allocate notification */
668 acm->notify_req = gs_alloc_req(ep,
669 sizeof(struct usb_cdc_notification) + 2,
670 GFP_KERNEL);
671 if (!acm->notify_req)
672 goto fail;
673
674 acm->notify_req->complete = acm_cdc_notify_complete;
675 acm->notify_req->context = acm;
676
677 /* support all relevant hardware speeds... we expect that when
678 * hardware is dual speed, all bulk-capable endpoints work at
679 * both speeds
680 */
681 acm_hs_in_desc.bEndpointAddress = acm_fs_in_desc.bEndpointAddress;
682 acm_hs_out_desc.bEndpointAddress = acm_fs_out_desc.bEndpointAddress;
683 acm_hs_notify_desc.bEndpointAddress =
684 acm_fs_notify_desc.bEndpointAddress;
685
686 acm_ss_in_desc.bEndpointAddress = acm_fs_in_desc.bEndpointAddress;
687 acm_ss_out_desc.bEndpointAddress = acm_fs_out_desc.bEndpointAddress;
688
689 status = usb_assign_descriptors(f, acm_fs_function, acm_hs_function,
690 acm_ss_function);
691 if (status)
692 goto fail;
693
694 DBG(cdev, "acm ttyGS%d: %s speed IN/%s OUT/%s NOTIFY/%s\n",
695 acm->port_num,
696 gadget_is_superspeed(c->cdev->gadget) ? "super" :
697 gadget_is_dualspeed(c->cdev->gadget) ? "dual" : "full",
698 acm->port.in->name, acm->port.out->name,
699 acm->notify->name);
700 return 0;
701
702fail:
703 if (acm->notify_req)
704 gs_free_req(acm->notify, acm->notify_req);
705
706 /* we might as well release our claims on endpoints */
707 if (acm->notify)
708 acm->notify->driver_data = NULL;
709 if (acm->port.out)
710 acm->port.out->driver_data = NULL;
711 if (acm->port.in)
712 acm->port.in->driver_data = NULL;
713
714 ERROR(cdev, "%s/%p: can't bind, err %d\n", f->name, f, status);
715
716 return status;
717}
718
719static void acm_unbind(struct usb_configuration *c, struct usb_function *f)
720{
721 struct f_acm *acm = func_to_acm(f);
722
723 acm_string_defs[0].id = 0;
724 usb_free_all_descriptors(f);
725 if (acm->notify_req)
726 gs_free_req(acm->notify, acm->notify_req);
727}
728
729static void acm_free_func(struct usb_function *f)
730{
731 struct f_acm *acm = func_to_acm(f);
732
733 kfree(acm);
734}
735
736static struct usb_function *acm_alloc_func(struct usb_function_instance *fi)
737{
738 struct f_serial_opts *opts;
739 struct f_acm *acm;
740
741 acm = kzalloc(sizeof(*acm), GFP_KERNEL);
742 if (!acm)
743 return ERR_PTR(-ENOMEM);
744
745 spin_lock_init(&acm->lock);
746
747 acm->port.connect = acm_connect;
748 acm->port.disconnect = acm_disconnect;
749 acm->port.send_break = acm_send_break;
750
751 acm->port.func.name = "acm";
752 acm->port.func.strings = acm_strings;
753 /* descriptors are per-instance copies */
754 acm->port.func.bind = acm_bind;
755 acm->port.func.set_alt = acm_set_alt;
756 acm->port.func.setup = acm_setup;
757 acm->port.func.disable = acm_disable;
758
759 opts = container_of(fi, struct f_serial_opts, func_inst);
760 acm->port_num = opts->port_num;
761 acm->port.func.unbind = acm_unbind;
762 acm->port.func.free_func = acm_free_func;
763
764 return &acm->port.func;
765}
766
767static inline struct f_serial_opts *to_f_serial_opts(struct config_item *item)
768{
769 return container_of(to_config_group(item), struct f_serial_opts,
770 func_inst.group);
771}
772
773CONFIGFS_ATTR_STRUCT(f_serial_opts);
774static ssize_t f_acm_attr_show(struct config_item *item,
775 struct configfs_attribute *attr,
776 char *page)
777{
778 struct f_serial_opts *opts = to_f_serial_opts(item);
779 struct f_serial_opts_attribute *f_serial_opts_attr =
780 container_of(attr, struct f_serial_opts_attribute, attr);
781 ssize_t ret = 0;
782
783 if (f_serial_opts_attr->show)
784 ret = f_serial_opts_attr->show(opts, page);
785 return ret;
786}
787
788static void acm_attr_release(struct config_item *item)
789{
790 struct f_serial_opts *opts = to_f_serial_opts(item);
791
792 usb_put_function_instance(&opts->func_inst);
793}
794
795static struct configfs_item_operations acm_item_ops = {
796 .release = acm_attr_release,
797 .show_attribute = f_acm_attr_show,
798};
799
800static ssize_t f_acm_port_num_show(struct f_serial_opts *opts, char *page)
801{
802 return sprintf(page, "%u\n", opts->port_num);
803}
804
805static struct f_serial_opts_attribute f_acm_port_num =
806 __CONFIGFS_ATTR_RO(port_num, f_acm_port_num_show);
807
808
809static struct configfs_attribute *acm_attrs[] = {
810 &f_acm_port_num.attr,
811 NULL,
812};
813
814static struct config_item_type acm_func_type = {
815 .ct_item_ops = &acm_item_ops,
816 .ct_attrs = acm_attrs,
817 .ct_owner = THIS_MODULE,
818};
819
820static void acm_free_instance(struct usb_function_instance *fi)
821{
822 struct f_serial_opts *opts;
823
824 opts = container_of(fi, struct f_serial_opts, func_inst);
825 gserial_free_line(opts->port_num);
826 kfree(opts);
827}
828
829static struct usb_function_instance *acm_alloc_instance(void)
830{
831 struct f_serial_opts *opts;
832 int ret;
833
834 opts = kzalloc(sizeof(*opts), GFP_KERNEL);
835 if (!opts)
836 return ERR_PTR(-ENOMEM);
837 opts->func_inst.free_func_inst = acm_free_instance;
838 ret = gserial_alloc_line(&opts->port_num);
839 if (ret) {
840 kfree(opts);
841 return ERR_PTR(ret);
842 }
843 config_group_init_type_name(&opts->func_inst.group, "",
844 &acm_func_type);
845 return &opts->func_inst;
846}
847DECLARE_USB_FUNCTION_INIT(acm, acm_alloc_instance, acm_alloc_func);
848MODULE_LICENSE("GPL");
diff --git a/drivers/usb/gadget/function/f_ecm.c b/drivers/usb/gadget/function/f_ecm.c
new file mode 100644
index 000000000000..798760fa7e70
--- /dev/null
+++ b/drivers/usb/gadget/function/f_ecm.c
@@ -0,0 +1,973 @@
1/*
2 * f_ecm.c -- USB CDC Ethernet (ECM) link function driver
3 *
4 * Copyright (C) 2003-2005,2008 David Brownell
5 * Copyright (C) 2008 Nokia Corporation
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 */
12
13/* #define VERBOSE_DEBUG */
14
15#include <linux/slab.h>
16#include <linux/kernel.h>
17#include <linux/module.h>
18#include <linux/device.h>
19#include <linux/etherdevice.h>
20
21#include "u_ether.h"
22#include "u_ether_configfs.h"
23#include "u_ecm.h"
24
25
26/*
27 * This function is a "CDC Ethernet Networking Control Model" (CDC ECM)
28 * Ethernet link. The data transfer model is simple (packets sent and
29 * received over bulk endpoints using normal short packet termination),
30 * and the control model exposes various data and optional notifications.
31 *
32 * ECM is well standardized and (except for Microsoft) supported by most
33 * operating systems with USB host support. It's the preferred interop
34 * solution for Ethernet over USB, at least for firmware based solutions.
35 * (Hardware solutions tend to be more minimalist.) A newer and simpler
36 * "Ethernet Emulation Model" (CDC EEM) hasn't yet caught on.
37 *
38 * Note that ECM requires the use of "alternate settings" for its data
39 * interface. This means that the set_alt() method has real work to do,
40 * and also means that a get_alt() method is required.
41 */
42
43
44enum ecm_notify_state {
45 ECM_NOTIFY_NONE, /* don't notify */
46 ECM_NOTIFY_CONNECT, /* issue CONNECT next */
47 ECM_NOTIFY_SPEED, /* issue SPEED_CHANGE next */
48};
49
50struct f_ecm {
51 struct gether port;
52 u8 ctrl_id, data_id;
53
54 char ethaddr[14];
55
56 struct usb_ep *notify;
57 struct usb_request *notify_req;
58 u8 notify_state;
59 bool is_open;
60
61 /* FIXME is_open needs some irq-ish locking
62 * ... possibly the same as port.ioport
63 */
64};
65
66static inline struct f_ecm *func_to_ecm(struct usb_function *f)
67{
68 return container_of(f, struct f_ecm, port.func);
69}
70
71/* peak (theoretical) bulk transfer rate in bits-per-second */
72static inline unsigned ecm_bitrate(struct usb_gadget *g)
73{
74 if (gadget_is_superspeed(g) && g->speed == USB_SPEED_SUPER)
75 return 13 * 1024 * 8 * 1000 * 8;
76 else if (gadget_is_dualspeed(g) && g->speed == USB_SPEED_HIGH)
77 return 13 * 512 * 8 * 1000 * 8;
78 else
79 return 19 * 64 * 1 * 1000 * 8;
80}
81
82/*-------------------------------------------------------------------------*/
83
84/*
85 * Include the status endpoint if we can, even though it's optional.
86 *
87 * Use wMaxPacketSize big enough to fit CDC_NOTIFY_SPEED_CHANGE in one
88 * packet, to simplify cancellation; and a big transfer interval, to
89 * waste less bandwidth.
90 *
91 * Some drivers (like Linux 2.4 cdc-ether!) "need" it to exist even
92 * if they ignore the connect/disconnect notifications that real aether
93 * can provide. More advanced cdc configurations might want to support
94 * encapsulated commands (vendor-specific, using control-OUT).
95 */
96
97#define ECM_STATUS_INTERVAL_MS 32
98#define ECM_STATUS_BYTECOUNT 16 /* 8 byte header + data */
99
100
101/* interface descriptor: */
102
103static struct usb_interface_assoc_descriptor
104ecm_iad_descriptor = {
105 .bLength = sizeof ecm_iad_descriptor,
106 .bDescriptorType = USB_DT_INTERFACE_ASSOCIATION,
107
108 /* .bFirstInterface = DYNAMIC, */
109 .bInterfaceCount = 2, /* control + data */
110 .bFunctionClass = USB_CLASS_COMM,
111 .bFunctionSubClass = USB_CDC_SUBCLASS_ETHERNET,
112 .bFunctionProtocol = USB_CDC_PROTO_NONE,
113 /* .iFunction = DYNAMIC */
114};
115
116
117static struct usb_interface_descriptor ecm_control_intf = {
118 .bLength = sizeof ecm_control_intf,
119 .bDescriptorType = USB_DT_INTERFACE,
120
121 /* .bInterfaceNumber = DYNAMIC */
122 /* status endpoint is optional; this could be patched later */
123 .bNumEndpoints = 1,
124 .bInterfaceClass = USB_CLASS_COMM,
125 .bInterfaceSubClass = USB_CDC_SUBCLASS_ETHERNET,
126 .bInterfaceProtocol = USB_CDC_PROTO_NONE,
127 /* .iInterface = DYNAMIC */
128};
129
130static struct usb_cdc_header_desc ecm_header_desc = {
131 .bLength = sizeof ecm_header_desc,
132 .bDescriptorType = USB_DT_CS_INTERFACE,
133 .bDescriptorSubType = USB_CDC_HEADER_TYPE,
134
135 .bcdCDC = cpu_to_le16(0x0110),
136};
137
138static struct usb_cdc_union_desc ecm_union_desc = {
139 .bLength = sizeof(ecm_union_desc),
140 .bDescriptorType = USB_DT_CS_INTERFACE,
141 .bDescriptorSubType = USB_CDC_UNION_TYPE,
142 /* .bMasterInterface0 = DYNAMIC */
143 /* .bSlaveInterface0 = DYNAMIC */
144};
145
146static struct usb_cdc_ether_desc ecm_desc = {
147 .bLength = sizeof ecm_desc,
148 .bDescriptorType = USB_DT_CS_INTERFACE,
149 .bDescriptorSubType = USB_CDC_ETHERNET_TYPE,
150
151 /* this descriptor actually adds value, surprise! */
152 /* .iMACAddress = DYNAMIC */
153 .bmEthernetStatistics = cpu_to_le32(0), /* no statistics */
154 .wMaxSegmentSize = cpu_to_le16(ETH_FRAME_LEN),
155 .wNumberMCFilters = cpu_to_le16(0),
156 .bNumberPowerFilters = 0,
157};
158
159/* the default data interface has no endpoints ... */
160
161static struct usb_interface_descriptor ecm_data_nop_intf = {
162 .bLength = sizeof ecm_data_nop_intf,
163 .bDescriptorType = USB_DT_INTERFACE,
164
165 .bInterfaceNumber = 1,
166 .bAlternateSetting = 0,
167 .bNumEndpoints = 0,
168 .bInterfaceClass = USB_CLASS_CDC_DATA,
169 .bInterfaceSubClass = 0,
170 .bInterfaceProtocol = 0,
171 /* .iInterface = DYNAMIC */
172};
173
174/* ... but the "real" data interface has two bulk endpoints */
175
176static struct usb_interface_descriptor ecm_data_intf = {
177 .bLength = sizeof ecm_data_intf,
178 .bDescriptorType = USB_DT_INTERFACE,
179
180 .bInterfaceNumber = 1,
181 .bAlternateSetting = 1,
182 .bNumEndpoints = 2,
183 .bInterfaceClass = USB_CLASS_CDC_DATA,
184 .bInterfaceSubClass = 0,
185 .bInterfaceProtocol = 0,
186 /* .iInterface = DYNAMIC */
187};
188
189/* full speed support: */
190
191static struct usb_endpoint_descriptor fs_ecm_notify_desc = {
192 .bLength = USB_DT_ENDPOINT_SIZE,
193 .bDescriptorType = USB_DT_ENDPOINT,
194
195 .bEndpointAddress = USB_DIR_IN,
196 .bmAttributes = USB_ENDPOINT_XFER_INT,
197 .wMaxPacketSize = cpu_to_le16(ECM_STATUS_BYTECOUNT),
198 .bInterval = ECM_STATUS_INTERVAL_MS,
199};
200
201static struct usb_endpoint_descriptor fs_ecm_in_desc = {
202 .bLength = USB_DT_ENDPOINT_SIZE,
203 .bDescriptorType = USB_DT_ENDPOINT,
204
205 .bEndpointAddress = USB_DIR_IN,
206 .bmAttributes = USB_ENDPOINT_XFER_BULK,
207};
208
209static struct usb_endpoint_descriptor fs_ecm_out_desc = {
210 .bLength = USB_DT_ENDPOINT_SIZE,
211 .bDescriptorType = USB_DT_ENDPOINT,
212
213 .bEndpointAddress = USB_DIR_OUT,
214 .bmAttributes = USB_ENDPOINT_XFER_BULK,
215};
216
217static struct usb_descriptor_header *ecm_fs_function[] = {
218 /* CDC ECM control descriptors */
219 (struct usb_descriptor_header *) &ecm_iad_descriptor,
220 (struct usb_descriptor_header *) &ecm_control_intf,
221 (struct usb_descriptor_header *) &ecm_header_desc,
222 (struct usb_descriptor_header *) &ecm_union_desc,
223 (struct usb_descriptor_header *) &ecm_desc,
224
225 /* NOTE: status endpoint might need to be removed */
226 (struct usb_descriptor_header *) &fs_ecm_notify_desc,
227
228 /* data interface, altsettings 0 and 1 */
229 (struct usb_descriptor_header *) &ecm_data_nop_intf,
230 (struct usb_descriptor_header *) &ecm_data_intf,
231 (struct usb_descriptor_header *) &fs_ecm_in_desc,
232 (struct usb_descriptor_header *) &fs_ecm_out_desc,
233 NULL,
234};
235
236/* high speed support: */
237
238static struct usb_endpoint_descriptor hs_ecm_notify_desc = {
239 .bLength = USB_DT_ENDPOINT_SIZE,
240 .bDescriptorType = USB_DT_ENDPOINT,
241
242 .bEndpointAddress = USB_DIR_IN,
243 .bmAttributes = USB_ENDPOINT_XFER_INT,
244 .wMaxPacketSize = cpu_to_le16(ECM_STATUS_BYTECOUNT),
245 .bInterval = USB_MS_TO_HS_INTERVAL(ECM_STATUS_INTERVAL_MS),
246};
247
248static struct usb_endpoint_descriptor hs_ecm_in_desc = {
249 .bLength = USB_DT_ENDPOINT_SIZE,
250 .bDescriptorType = USB_DT_ENDPOINT,
251
252 .bEndpointAddress = USB_DIR_IN,
253 .bmAttributes = USB_ENDPOINT_XFER_BULK,
254 .wMaxPacketSize = cpu_to_le16(512),
255};
256
257static struct usb_endpoint_descriptor hs_ecm_out_desc = {
258 .bLength = USB_DT_ENDPOINT_SIZE,
259 .bDescriptorType = USB_DT_ENDPOINT,
260
261 .bEndpointAddress = USB_DIR_OUT,
262 .bmAttributes = USB_ENDPOINT_XFER_BULK,
263 .wMaxPacketSize = cpu_to_le16(512),
264};
265
266static struct usb_descriptor_header *ecm_hs_function[] = {
267 /* CDC ECM control descriptors */
268 (struct usb_descriptor_header *) &ecm_iad_descriptor,
269 (struct usb_descriptor_header *) &ecm_control_intf,
270 (struct usb_descriptor_header *) &ecm_header_desc,
271 (struct usb_descriptor_header *) &ecm_union_desc,
272 (struct usb_descriptor_header *) &ecm_desc,
273
274 /* NOTE: status endpoint might need to be removed */
275 (struct usb_descriptor_header *) &hs_ecm_notify_desc,
276
277 /* data interface, altsettings 0 and 1 */
278 (struct usb_descriptor_header *) &ecm_data_nop_intf,
279 (struct usb_descriptor_header *) &ecm_data_intf,
280 (struct usb_descriptor_header *) &hs_ecm_in_desc,
281 (struct usb_descriptor_header *) &hs_ecm_out_desc,
282 NULL,
283};
284
285/* super speed support: */
286
287static struct usb_endpoint_descriptor ss_ecm_notify_desc = {
288 .bLength = USB_DT_ENDPOINT_SIZE,
289 .bDescriptorType = USB_DT_ENDPOINT,
290
291 .bEndpointAddress = USB_DIR_IN,
292 .bmAttributes = USB_ENDPOINT_XFER_INT,
293 .wMaxPacketSize = cpu_to_le16(ECM_STATUS_BYTECOUNT),
294 .bInterval = USB_MS_TO_HS_INTERVAL(ECM_STATUS_INTERVAL_MS),
295};
296
297static struct usb_ss_ep_comp_descriptor ss_ecm_intr_comp_desc = {
298 .bLength = sizeof ss_ecm_intr_comp_desc,
299 .bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
300
301 /* the following 3 values can be tweaked if necessary */
302 /* .bMaxBurst = 0, */
303 /* .bmAttributes = 0, */
304 .wBytesPerInterval = cpu_to_le16(ECM_STATUS_BYTECOUNT),
305};
306
307static struct usb_endpoint_descriptor ss_ecm_in_desc = {
308 .bLength = USB_DT_ENDPOINT_SIZE,
309 .bDescriptorType = USB_DT_ENDPOINT,
310
311 .bEndpointAddress = USB_DIR_IN,
312 .bmAttributes = USB_ENDPOINT_XFER_BULK,
313 .wMaxPacketSize = cpu_to_le16(1024),
314};
315
316static struct usb_endpoint_descriptor ss_ecm_out_desc = {
317 .bLength = USB_DT_ENDPOINT_SIZE,
318 .bDescriptorType = USB_DT_ENDPOINT,
319
320 .bEndpointAddress = USB_DIR_OUT,
321 .bmAttributes = USB_ENDPOINT_XFER_BULK,
322 .wMaxPacketSize = cpu_to_le16(1024),
323};
324
325static struct usb_ss_ep_comp_descriptor ss_ecm_bulk_comp_desc = {
326 .bLength = sizeof ss_ecm_bulk_comp_desc,
327 .bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
328
329 /* the following 2 values can be tweaked if necessary */
330 /* .bMaxBurst = 0, */
331 /* .bmAttributes = 0, */
332};
333
334static struct usb_descriptor_header *ecm_ss_function[] = {
335 /* CDC ECM control descriptors */
336 (struct usb_descriptor_header *) &ecm_iad_descriptor,
337 (struct usb_descriptor_header *) &ecm_control_intf,
338 (struct usb_descriptor_header *) &ecm_header_desc,
339 (struct usb_descriptor_header *) &ecm_union_desc,
340 (struct usb_descriptor_header *) &ecm_desc,
341
342 /* NOTE: status endpoint might need to be removed */
343 (struct usb_descriptor_header *) &ss_ecm_notify_desc,
344 (struct usb_descriptor_header *) &ss_ecm_intr_comp_desc,
345
346 /* data interface, altsettings 0 and 1 */
347 (struct usb_descriptor_header *) &ecm_data_nop_intf,
348 (struct usb_descriptor_header *) &ecm_data_intf,
349 (struct usb_descriptor_header *) &ss_ecm_in_desc,
350 (struct usb_descriptor_header *) &ss_ecm_bulk_comp_desc,
351 (struct usb_descriptor_header *) &ss_ecm_out_desc,
352 (struct usb_descriptor_header *) &ss_ecm_bulk_comp_desc,
353 NULL,
354};
355
356/* string descriptors: */
357
358static struct usb_string ecm_string_defs[] = {
359 [0].s = "CDC Ethernet Control Model (ECM)",
360 [1].s = "",
361 [2].s = "CDC Ethernet Data",
362 [3].s = "CDC ECM",
363 { } /* end of list */
364};
365
366static struct usb_gadget_strings ecm_string_table = {
367 .language = 0x0409, /* en-us */
368 .strings = ecm_string_defs,
369};
370
371static struct usb_gadget_strings *ecm_strings[] = {
372 &ecm_string_table,
373 NULL,
374};
375
376/*-------------------------------------------------------------------------*/
377
378static void ecm_do_notify(struct f_ecm *ecm)
379{
380 struct usb_request *req = ecm->notify_req;
381 struct usb_cdc_notification *event;
382 struct usb_composite_dev *cdev = ecm->port.func.config->cdev;
383 __le32 *data;
384 int status;
385
386 /* notification already in flight? */
387 if (!req)
388 return;
389
390 event = req->buf;
391 switch (ecm->notify_state) {
392 case ECM_NOTIFY_NONE:
393 return;
394
395 case ECM_NOTIFY_CONNECT:
396 event->bNotificationType = USB_CDC_NOTIFY_NETWORK_CONNECTION;
397 if (ecm->is_open)
398 event->wValue = cpu_to_le16(1);
399 else
400 event->wValue = cpu_to_le16(0);
401 event->wLength = 0;
402 req->length = sizeof *event;
403
404 DBG(cdev, "notify connect %s\n",
405 ecm->is_open ? "true" : "false");
406 ecm->notify_state = ECM_NOTIFY_SPEED;
407 break;
408
409 case ECM_NOTIFY_SPEED:
410 event->bNotificationType = USB_CDC_NOTIFY_SPEED_CHANGE;
411 event->wValue = cpu_to_le16(0);
412 event->wLength = cpu_to_le16(8);
413 req->length = ECM_STATUS_BYTECOUNT;
414
415 /* SPEED_CHANGE data is up/down speeds in bits/sec */
416 data = req->buf + sizeof *event;
417 data[0] = cpu_to_le32(ecm_bitrate(cdev->gadget));
418 data[1] = data[0];
419
420 DBG(cdev, "notify speed %d\n", ecm_bitrate(cdev->gadget));
421 ecm->notify_state = ECM_NOTIFY_NONE;
422 break;
423 }
424 event->bmRequestType = 0xA1;
425 event->wIndex = cpu_to_le16(ecm->ctrl_id);
426
427 ecm->notify_req = NULL;
428 status = usb_ep_queue(ecm->notify, req, GFP_ATOMIC);
429 if (status < 0) {
430 ecm->notify_req = req;
431 DBG(cdev, "notify --> %d\n", status);
432 }
433}
434
435static void ecm_notify(struct f_ecm *ecm)
436{
437 /* NOTE on most versions of Linux, host side cdc-ethernet
438 * won't listen for notifications until its netdevice opens.
439 * The first notification then sits in the FIFO for a long
440 * time, and the second one is queued.
441 */
442 ecm->notify_state = ECM_NOTIFY_CONNECT;
443 ecm_do_notify(ecm);
444}
445
446static void ecm_notify_complete(struct usb_ep *ep, struct usb_request *req)
447{
448 struct f_ecm *ecm = req->context;
449 struct usb_composite_dev *cdev = ecm->port.func.config->cdev;
450 struct usb_cdc_notification *event = req->buf;
451
452 switch (req->status) {
453 case 0:
454 /* no fault */
455 break;
456 case -ECONNRESET:
457 case -ESHUTDOWN:
458 ecm->notify_state = ECM_NOTIFY_NONE;
459 break;
460 default:
461 DBG(cdev, "event %02x --> %d\n",
462 event->bNotificationType, req->status);
463 break;
464 }
465 ecm->notify_req = req;
466 ecm_do_notify(ecm);
467}
468
469static int ecm_setup(struct usb_function *f, const struct usb_ctrlrequest *ctrl)
470{
471 struct f_ecm *ecm = func_to_ecm(f);
472 struct usb_composite_dev *cdev = f->config->cdev;
473 struct usb_request *req = cdev->req;
474 int value = -EOPNOTSUPP;
475 u16 w_index = le16_to_cpu(ctrl->wIndex);
476 u16 w_value = le16_to_cpu(ctrl->wValue);
477 u16 w_length = le16_to_cpu(ctrl->wLength);
478
479 /* composite driver infrastructure handles everything except
480 * CDC class messages; interface activation uses set_alt().
481 */
482 switch ((ctrl->bRequestType << 8) | ctrl->bRequest) {
483 case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
484 | USB_CDC_SET_ETHERNET_PACKET_FILTER:
485 /* see 6.2.30: no data, wIndex = interface,
486 * wValue = packet filter bitmap
487 */
488 if (w_length != 0 || w_index != ecm->ctrl_id)
489 goto invalid;
490 DBG(cdev, "packet filter %02x\n", w_value);
491 /* REVISIT locking of cdc_filter. This assumes the UDC
492 * driver won't have a concurrent packet TX irq running on
493 * another CPU; or that if it does, this write is atomic...
494 */
495 ecm->port.cdc_filter = w_value;
496 value = 0;
497 break;
498
499 /* and optionally:
500 * case USB_CDC_SEND_ENCAPSULATED_COMMAND:
501 * case USB_CDC_GET_ENCAPSULATED_RESPONSE:
502 * case USB_CDC_SET_ETHERNET_MULTICAST_FILTERS:
503 * case USB_CDC_SET_ETHERNET_PM_PATTERN_FILTER:
504 * case USB_CDC_GET_ETHERNET_PM_PATTERN_FILTER:
505 * case USB_CDC_GET_ETHERNET_STATISTIC:
506 */
507
508 default:
509invalid:
510 DBG(cdev, "invalid control req%02x.%02x v%04x i%04x l%d\n",
511 ctrl->bRequestType, ctrl->bRequest,
512 w_value, w_index, w_length);
513 }
514
515 /* respond with data transfer or status phase? */
516 if (value >= 0) {
517 DBG(cdev, "ecm req%02x.%02x v%04x i%04x l%d\n",
518 ctrl->bRequestType, ctrl->bRequest,
519 w_value, w_index, w_length);
520 req->zero = 0;
521 req->length = value;
522 value = usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC);
523 if (value < 0)
524 ERROR(cdev, "ecm req %02x.%02x response err %d\n",
525 ctrl->bRequestType, ctrl->bRequest,
526 value);
527 }
528
529 /* device either stalls (value < 0) or reports success */
530 return value;
531}
532
533
534static int ecm_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
535{
536 struct f_ecm *ecm = func_to_ecm(f);
537 struct usb_composite_dev *cdev = f->config->cdev;
538
539 /* Control interface has only altsetting 0 */
540 if (intf == ecm->ctrl_id) {
541 if (alt != 0)
542 goto fail;
543
544 if (ecm->notify->driver_data) {
545 VDBG(cdev, "reset ecm control %d\n", intf);
546 usb_ep_disable(ecm->notify);
547 }
548 if (!(ecm->notify->desc)) {
549 VDBG(cdev, "init ecm ctrl %d\n", intf);
550 if (config_ep_by_speed(cdev->gadget, f, ecm->notify))
551 goto fail;
552 }
553 usb_ep_enable(ecm->notify);
554 ecm->notify->driver_data = ecm;
555
556 /* Data interface has two altsettings, 0 and 1 */
557 } else if (intf == ecm->data_id) {
558 if (alt > 1)
559 goto fail;
560
561 if (ecm->port.in_ep->driver_data) {
562 DBG(cdev, "reset ecm\n");
563 gether_disconnect(&ecm->port);
564 }
565
566 if (!ecm->port.in_ep->desc ||
567 !ecm->port.out_ep->desc) {
568 DBG(cdev, "init ecm\n");
569 if (config_ep_by_speed(cdev->gadget, f,
570 ecm->port.in_ep) ||
571 config_ep_by_speed(cdev->gadget, f,
572 ecm->port.out_ep)) {
573 ecm->port.in_ep->desc = NULL;
574 ecm->port.out_ep->desc = NULL;
575 goto fail;
576 }
577 }
578
579 /* CDC Ethernet only sends data in non-default altsettings.
580 * Changing altsettings resets filters, statistics, etc.
581 */
582 if (alt == 1) {
583 struct net_device *net;
584
585 /* Enable zlps by default for ECM conformance;
586 * override for musb_hdrc (avoids txdma ovhead).
587 */
588 ecm->port.is_zlp_ok = !(gadget_is_musbhdrc(cdev->gadget)
589 );
590 ecm->port.cdc_filter = DEFAULT_FILTER;
591 DBG(cdev, "activate ecm\n");
592 net = gether_connect(&ecm->port);
593 if (IS_ERR(net))
594 return PTR_ERR(net);
595 }
596
597 /* NOTE this can be a minor disagreement with the ECM spec,
598 * which says speed notifications will "always" follow
599 * connection notifications. But we allow one connect to
600 * follow another (if the first is in flight), and instead
601 * just guarantee that a speed notification is always sent.
602 */
603 ecm_notify(ecm);
604 } else
605 goto fail;
606
607 return 0;
608fail:
609 return -EINVAL;
610}
611
612/* Because the data interface supports multiple altsettings,
613 * this ECM function *MUST* implement a get_alt() method.
614 */
615static int ecm_get_alt(struct usb_function *f, unsigned intf)
616{
617 struct f_ecm *ecm = func_to_ecm(f);
618
619 if (intf == ecm->ctrl_id)
620 return 0;
621 return ecm->port.in_ep->driver_data ? 1 : 0;
622}
623
624static void ecm_disable(struct usb_function *f)
625{
626 struct f_ecm *ecm = func_to_ecm(f);
627 struct usb_composite_dev *cdev = f->config->cdev;
628
629 DBG(cdev, "ecm deactivated\n");
630
631 if (ecm->port.in_ep->driver_data)
632 gether_disconnect(&ecm->port);
633
634 if (ecm->notify->driver_data) {
635 usb_ep_disable(ecm->notify);
636 ecm->notify->driver_data = NULL;
637 ecm->notify->desc = NULL;
638 }
639}
640
641/*-------------------------------------------------------------------------*/
642
643/*
644 * Callbacks let us notify the host about connect/disconnect when the
645 * net device is opened or closed.
646 *
647 * For testing, note that link states on this side include both opened
648 * and closed variants of:
649 *
650 * - disconnected/unconfigured
651 * - configured but inactive (data alt 0)
652 * - configured and active (data alt 1)
653 *
654 * Each needs to be tested with unplug, rmmod, SET_CONFIGURATION, and
655 * SET_INTERFACE (altsetting). Remember also that "configured" doesn't
656 * imply the host is actually polling the notification endpoint, and
657 * likewise that "active" doesn't imply it's actually using the data
658 * endpoints for traffic.
659 */
660
661static void ecm_open(struct gether *geth)
662{
663 struct f_ecm *ecm = func_to_ecm(&geth->func);
664
665 DBG(ecm->port.func.config->cdev, "%s\n", __func__);
666
667 ecm->is_open = true;
668 ecm_notify(ecm);
669}
670
671static void ecm_close(struct gether *geth)
672{
673 struct f_ecm *ecm = func_to_ecm(&geth->func);
674
675 DBG(ecm->port.func.config->cdev, "%s\n", __func__);
676
677 ecm->is_open = false;
678 ecm_notify(ecm);
679}
680
681/*-------------------------------------------------------------------------*/
682
683/* ethernet function driver setup/binding */
684
685static int
686ecm_bind(struct usb_configuration *c, struct usb_function *f)
687{
688 struct usb_composite_dev *cdev = c->cdev;
689 struct f_ecm *ecm = func_to_ecm(f);
690 struct usb_string *us;
691 int status;
692 struct usb_ep *ep;
693
694 struct f_ecm_opts *ecm_opts;
695
696 if (!can_support_ecm(cdev->gadget))
697 return -EINVAL;
698
699 ecm_opts = container_of(f->fi, struct f_ecm_opts, func_inst);
700
701 /*
702 * in drivers/usb/gadget/configfs.c:configfs_composite_bind()
703 * configurations are bound in sequence with list_for_each_entry,
704 * in each configuration its functions are bound in sequence
705 * with list_for_each_entry, so we assume no race condition
706 * with regard to ecm_opts->bound access
707 */
708 if (!ecm_opts->bound) {
709 mutex_lock(&ecm_opts->lock);
710 gether_set_gadget(ecm_opts->net, cdev->gadget);
711 status = gether_register_netdev(ecm_opts->net);
712 mutex_unlock(&ecm_opts->lock);
713 if (status)
714 return status;
715 ecm_opts->bound = true;
716 }
717
718 us = usb_gstrings_attach(cdev, ecm_strings,
719 ARRAY_SIZE(ecm_string_defs));
720 if (IS_ERR(us))
721 return PTR_ERR(us);
722 ecm_control_intf.iInterface = us[0].id;
723 ecm_data_intf.iInterface = us[2].id;
724 ecm_desc.iMACAddress = us[1].id;
725 ecm_iad_descriptor.iFunction = us[3].id;
726
727 /* allocate instance-specific interface IDs */
728 status = usb_interface_id(c, f);
729 if (status < 0)
730 goto fail;
731 ecm->ctrl_id = status;
732 ecm_iad_descriptor.bFirstInterface = status;
733
734 ecm_control_intf.bInterfaceNumber = status;
735 ecm_union_desc.bMasterInterface0 = status;
736
737 status = usb_interface_id(c, f);
738 if (status < 0)
739 goto fail;
740 ecm->data_id = status;
741
742 ecm_data_nop_intf.bInterfaceNumber = status;
743 ecm_data_intf.bInterfaceNumber = status;
744 ecm_union_desc.bSlaveInterface0 = status;
745
746 status = -ENODEV;
747
748 /* allocate instance-specific endpoints */
749 ep = usb_ep_autoconfig(cdev->gadget, &fs_ecm_in_desc);
750 if (!ep)
751 goto fail;
752 ecm->port.in_ep = ep;
753 ep->driver_data = cdev; /* claim */
754
755 ep = usb_ep_autoconfig(cdev->gadget, &fs_ecm_out_desc);
756 if (!ep)
757 goto fail;
758 ecm->port.out_ep = ep;
759 ep->driver_data = cdev; /* claim */
760
761 /* NOTE: a status/notification endpoint is *OPTIONAL* but we
762 * don't treat it that way. It's simpler, and some newer CDC
763 * profiles (wireless handsets) no longer treat it as optional.
764 */
765 ep = usb_ep_autoconfig(cdev->gadget, &fs_ecm_notify_desc);
766 if (!ep)
767 goto fail;
768 ecm->notify = ep;
769 ep->driver_data = cdev; /* claim */
770
771 status = -ENOMEM;
772
773 /* allocate notification request and buffer */
774 ecm->notify_req = usb_ep_alloc_request(ep, GFP_KERNEL);
775 if (!ecm->notify_req)
776 goto fail;
777 ecm->notify_req->buf = kmalloc(ECM_STATUS_BYTECOUNT, GFP_KERNEL);
778 if (!ecm->notify_req->buf)
779 goto fail;
780 ecm->notify_req->context = ecm;
781 ecm->notify_req->complete = ecm_notify_complete;
782
783 /* support all relevant hardware speeds... we expect that when
784 * hardware is dual speed, all bulk-capable endpoints work at
785 * both speeds
786 */
787 hs_ecm_in_desc.bEndpointAddress = fs_ecm_in_desc.bEndpointAddress;
788 hs_ecm_out_desc.bEndpointAddress = fs_ecm_out_desc.bEndpointAddress;
789 hs_ecm_notify_desc.bEndpointAddress =
790 fs_ecm_notify_desc.bEndpointAddress;
791
792 ss_ecm_in_desc.bEndpointAddress = fs_ecm_in_desc.bEndpointAddress;
793 ss_ecm_out_desc.bEndpointAddress = fs_ecm_out_desc.bEndpointAddress;
794 ss_ecm_notify_desc.bEndpointAddress =
795 fs_ecm_notify_desc.bEndpointAddress;
796
797 status = usb_assign_descriptors(f, ecm_fs_function, ecm_hs_function,
798 ecm_ss_function);
799 if (status)
800 goto fail;
801
802 /* NOTE: all that is done without knowing or caring about
803 * the network link ... which is unavailable to this code
804 * until we're activated via set_alt().
805 */
806
807 ecm->port.open = ecm_open;
808 ecm->port.close = ecm_close;
809
810 DBG(cdev, "CDC Ethernet: %s speed IN/%s OUT/%s NOTIFY/%s\n",
811 gadget_is_superspeed(c->cdev->gadget) ? "super" :
812 gadget_is_dualspeed(c->cdev->gadget) ? "dual" : "full",
813 ecm->port.in_ep->name, ecm->port.out_ep->name,
814 ecm->notify->name);
815 return 0;
816
817fail:
818 if (ecm->notify_req) {
819 kfree(ecm->notify_req->buf);
820 usb_ep_free_request(ecm->notify, ecm->notify_req);
821 }
822
823 /* we might as well release our claims on endpoints */
824 if (ecm->notify)
825 ecm->notify->driver_data = NULL;
826 if (ecm->port.out_ep)
827 ecm->port.out_ep->driver_data = NULL;
828 if (ecm->port.in_ep)
829 ecm->port.in_ep->driver_data = NULL;
830
831 ERROR(cdev, "%s: can't bind, err %d\n", f->name, status);
832
833 return status;
834}
835
836static inline struct f_ecm_opts *to_f_ecm_opts(struct config_item *item)
837{
838 return container_of(to_config_group(item), struct f_ecm_opts,
839 func_inst.group);
840}
841
842/* f_ecm_item_ops */
843USB_ETHERNET_CONFIGFS_ITEM(ecm);
844
845/* f_ecm_opts_dev_addr */
846USB_ETHERNET_CONFIGFS_ITEM_ATTR_DEV_ADDR(ecm);
847
848/* f_ecm_opts_host_addr */
849USB_ETHERNET_CONFIGFS_ITEM_ATTR_HOST_ADDR(ecm);
850
851/* f_ecm_opts_qmult */
852USB_ETHERNET_CONFIGFS_ITEM_ATTR_QMULT(ecm);
853
854/* f_ecm_opts_ifname */
855USB_ETHERNET_CONFIGFS_ITEM_ATTR_IFNAME(ecm);
856
857static struct configfs_attribute *ecm_attrs[] = {
858 &f_ecm_opts_dev_addr.attr,
859 &f_ecm_opts_host_addr.attr,
860 &f_ecm_opts_qmult.attr,
861 &f_ecm_opts_ifname.attr,
862 NULL,
863};
864
865static struct config_item_type ecm_func_type = {
866 .ct_item_ops = &ecm_item_ops,
867 .ct_attrs = ecm_attrs,
868 .ct_owner = THIS_MODULE,
869};
870
871static void ecm_free_inst(struct usb_function_instance *f)
872{
873 struct f_ecm_opts *opts;
874
875 opts = container_of(f, struct f_ecm_opts, func_inst);
876 if (opts->bound)
877 gether_cleanup(netdev_priv(opts->net));
878 else
879 free_netdev(opts->net);
880 kfree(opts);
881}
882
883static struct usb_function_instance *ecm_alloc_inst(void)
884{
885 struct f_ecm_opts *opts;
886
887 opts = kzalloc(sizeof(*opts), GFP_KERNEL);
888 if (!opts)
889 return ERR_PTR(-ENOMEM);
890 mutex_init(&opts->lock);
891 opts->func_inst.free_func_inst = ecm_free_inst;
892 opts->net = gether_setup_default();
893 if (IS_ERR(opts->net)) {
894 struct net_device *net = opts->net;
895 kfree(opts);
896 return ERR_CAST(net);
897 }
898
899 config_group_init_type_name(&opts->func_inst.group, "", &ecm_func_type);
900
901 return &opts->func_inst;
902}
903
904static void ecm_free(struct usb_function *f)
905{
906 struct f_ecm *ecm;
907 struct f_ecm_opts *opts;
908
909 ecm = func_to_ecm(f);
910 opts = container_of(f->fi, struct f_ecm_opts, func_inst);
911 kfree(ecm);
912 mutex_lock(&opts->lock);
913 opts->refcnt--;
914 mutex_unlock(&opts->lock);
915}
916
917static void ecm_unbind(struct usb_configuration *c, struct usb_function *f)
918{
919 struct f_ecm *ecm = func_to_ecm(f);
920
921 DBG(c->cdev, "ecm unbind\n");
922
923 usb_free_all_descriptors(f);
924
925 kfree(ecm->notify_req->buf);
926 usb_ep_free_request(ecm->notify, ecm->notify_req);
927}
928
929static struct usb_function *ecm_alloc(struct usb_function_instance *fi)
930{
931 struct f_ecm *ecm;
932 struct f_ecm_opts *opts;
933 int status;
934
935 /* allocate and initialize one new instance */
936 ecm = kzalloc(sizeof(*ecm), GFP_KERNEL);
937 if (!ecm)
938 return ERR_PTR(-ENOMEM);
939
940 opts = container_of(fi, struct f_ecm_opts, func_inst);
941 mutex_lock(&opts->lock);
942 opts->refcnt++;
943
944 /* export host's Ethernet address in CDC format */
945 status = gether_get_host_addr_cdc(opts->net, ecm->ethaddr,
946 sizeof(ecm->ethaddr));
947 if (status < 12) {
948 kfree(ecm);
949 mutex_unlock(&opts->lock);
950 return ERR_PTR(-EINVAL);
951 }
952 ecm_string_defs[1].s = ecm->ethaddr;
953
954 ecm->port.ioport = netdev_priv(opts->net);
955 mutex_unlock(&opts->lock);
956 ecm->port.cdc_filter = DEFAULT_FILTER;
957
958 ecm->port.func.name = "cdc_ethernet";
959 /* descriptors are per-instance copies */
960 ecm->port.func.bind = ecm_bind;
961 ecm->port.func.unbind = ecm_unbind;
962 ecm->port.func.set_alt = ecm_set_alt;
963 ecm->port.func.get_alt = ecm_get_alt;
964 ecm->port.func.setup = ecm_setup;
965 ecm->port.func.disable = ecm_disable;
966 ecm->port.func.free_func = ecm_free;
967
968 return &ecm->port.func;
969}
970
971DECLARE_USB_FUNCTION_INIT(ecm, ecm_alloc_inst, ecm_alloc);
972MODULE_LICENSE("GPL");
973MODULE_AUTHOR("David Brownell");
diff --git a/drivers/usb/gadget/function/f_eem.c b/drivers/usb/gadget/function/f_eem.c
new file mode 100644
index 000000000000..4d8b236ea608
--- /dev/null
+++ b/drivers/usb/gadget/function/f_eem.c
@@ -0,0 +1,660 @@
1/*
2 * f_eem.c -- USB CDC Ethernet (EEM) link function driver
3 *
4 * Copyright (C) 2003-2005,2008 David Brownell
5 * Copyright (C) 2008 Nokia Corporation
6 * Copyright (C) 2009 EF Johnson Technologies
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 */
13
14#include <linux/kernel.h>
15#include <linux/module.h>
16#include <linux/device.h>
17#include <linux/etherdevice.h>
18#include <linux/crc32.h>
19#include <linux/slab.h>
20
21#include "u_ether.h"
22#include "u_ether_configfs.h"
23#include "u_eem.h"
24
25#define EEM_HLEN 2
26
27/*
28 * This function is a "CDC Ethernet Emulation Model" (CDC EEM)
29 * Ethernet link.
30 */
31
32struct f_eem {
33 struct gether port;
34 u8 ctrl_id;
35};
36
37static inline struct f_eem *func_to_eem(struct usb_function *f)
38{
39 return container_of(f, struct f_eem, port.func);
40}
41
42/*-------------------------------------------------------------------------*/
43
44/* interface descriptor: */
45
46static struct usb_interface_descriptor eem_intf = {
47 .bLength = sizeof eem_intf,
48 .bDescriptorType = USB_DT_INTERFACE,
49
50 /* .bInterfaceNumber = DYNAMIC */
51 .bNumEndpoints = 2,
52 .bInterfaceClass = USB_CLASS_COMM,
53 .bInterfaceSubClass = USB_CDC_SUBCLASS_EEM,
54 .bInterfaceProtocol = USB_CDC_PROTO_EEM,
55 /* .iInterface = DYNAMIC */
56};
57
58/* full speed support: */
59
60static struct usb_endpoint_descriptor eem_fs_in_desc = {
61 .bLength = USB_DT_ENDPOINT_SIZE,
62 .bDescriptorType = USB_DT_ENDPOINT,
63
64 .bEndpointAddress = USB_DIR_IN,
65 .bmAttributes = USB_ENDPOINT_XFER_BULK,
66};
67
68static struct usb_endpoint_descriptor eem_fs_out_desc = {
69 .bLength = USB_DT_ENDPOINT_SIZE,
70 .bDescriptorType = USB_DT_ENDPOINT,
71
72 .bEndpointAddress = USB_DIR_OUT,
73 .bmAttributes = USB_ENDPOINT_XFER_BULK,
74};
75
76static struct usb_descriptor_header *eem_fs_function[] = {
77 /* CDC EEM control descriptors */
78 (struct usb_descriptor_header *) &eem_intf,
79 (struct usb_descriptor_header *) &eem_fs_in_desc,
80 (struct usb_descriptor_header *) &eem_fs_out_desc,
81 NULL,
82};
83
84/* high speed support: */
85
86static struct usb_endpoint_descriptor eem_hs_in_desc = {
87 .bLength = USB_DT_ENDPOINT_SIZE,
88 .bDescriptorType = USB_DT_ENDPOINT,
89
90 .bEndpointAddress = USB_DIR_IN,
91 .bmAttributes = USB_ENDPOINT_XFER_BULK,
92 .wMaxPacketSize = cpu_to_le16(512),
93};
94
95static struct usb_endpoint_descriptor eem_hs_out_desc = {
96 .bLength = USB_DT_ENDPOINT_SIZE,
97 .bDescriptorType = USB_DT_ENDPOINT,
98
99 .bEndpointAddress = USB_DIR_OUT,
100 .bmAttributes = USB_ENDPOINT_XFER_BULK,
101 .wMaxPacketSize = cpu_to_le16(512),
102};
103
104static struct usb_descriptor_header *eem_hs_function[] = {
105 /* CDC EEM control descriptors */
106 (struct usb_descriptor_header *) &eem_intf,
107 (struct usb_descriptor_header *) &eem_hs_in_desc,
108 (struct usb_descriptor_header *) &eem_hs_out_desc,
109 NULL,
110};
111
112/* super speed support: */
113
114static struct usb_endpoint_descriptor eem_ss_in_desc = {
115 .bLength = USB_DT_ENDPOINT_SIZE,
116 .bDescriptorType = USB_DT_ENDPOINT,
117
118 .bEndpointAddress = USB_DIR_IN,
119 .bmAttributes = USB_ENDPOINT_XFER_BULK,
120 .wMaxPacketSize = cpu_to_le16(1024),
121};
122
123static struct usb_endpoint_descriptor eem_ss_out_desc = {
124 .bLength = USB_DT_ENDPOINT_SIZE,
125 .bDescriptorType = USB_DT_ENDPOINT,
126
127 .bEndpointAddress = USB_DIR_OUT,
128 .bmAttributes = USB_ENDPOINT_XFER_BULK,
129 .wMaxPacketSize = cpu_to_le16(1024),
130};
131
132static struct usb_ss_ep_comp_descriptor eem_ss_bulk_comp_desc = {
133 .bLength = sizeof eem_ss_bulk_comp_desc,
134 .bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
135
136 /* the following 2 values can be tweaked if necessary */
137 /* .bMaxBurst = 0, */
138 /* .bmAttributes = 0, */
139};
140
141static struct usb_descriptor_header *eem_ss_function[] = {
142 /* CDC EEM control descriptors */
143 (struct usb_descriptor_header *) &eem_intf,
144 (struct usb_descriptor_header *) &eem_ss_in_desc,
145 (struct usb_descriptor_header *) &eem_ss_bulk_comp_desc,
146 (struct usb_descriptor_header *) &eem_ss_out_desc,
147 (struct usb_descriptor_header *) &eem_ss_bulk_comp_desc,
148 NULL,
149};
150
151/* string descriptors: */
152
153static struct usb_string eem_string_defs[] = {
154 [0].s = "CDC Ethernet Emulation Model (EEM)",
155 { } /* end of list */
156};
157
158static struct usb_gadget_strings eem_string_table = {
159 .language = 0x0409, /* en-us */
160 .strings = eem_string_defs,
161};
162
163static struct usb_gadget_strings *eem_strings[] = {
164 &eem_string_table,
165 NULL,
166};
167
168/*-------------------------------------------------------------------------*/
169
170static int eem_setup(struct usb_function *f, const struct usb_ctrlrequest *ctrl)
171{
172 struct usb_composite_dev *cdev = f->config->cdev;
173 int value = -EOPNOTSUPP;
174 u16 w_index = le16_to_cpu(ctrl->wIndex);
175 u16 w_value = le16_to_cpu(ctrl->wValue);
176 u16 w_length = le16_to_cpu(ctrl->wLength);
177
178 DBG(cdev, "invalid control req%02x.%02x v%04x i%04x l%d\n",
179 ctrl->bRequestType, ctrl->bRequest,
180 w_value, w_index, w_length);
181
182 /* device either stalls (value < 0) or reports success */
183 return value;
184}
185
186
187static int eem_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
188{
189 struct f_eem *eem = func_to_eem(f);
190 struct usb_composite_dev *cdev = f->config->cdev;
191 struct net_device *net;
192
193 /* we know alt == 0, so this is an activation or a reset */
194 if (alt != 0)
195 goto fail;
196
197 if (intf == eem->ctrl_id) {
198
199 if (eem->port.in_ep->driver_data) {
200 DBG(cdev, "reset eem\n");
201 gether_disconnect(&eem->port);
202 }
203
204 if (!eem->port.in_ep->desc || !eem->port.out_ep->desc) {
205 DBG(cdev, "init eem\n");
206 if (config_ep_by_speed(cdev->gadget, f,
207 eem->port.in_ep) ||
208 config_ep_by_speed(cdev->gadget, f,
209 eem->port.out_ep)) {
210 eem->port.in_ep->desc = NULL;
211 eem->port.out_ep->desc = NULL;
212 goto fail;
213 }
214 }
215
216 /* zlps should not occur because zero-length EEM packets
217 * will be inserted in those cases where they would occur
218 */
219 eem->port.is_zlp_ok = 1;
220 eem->port.cdc_filter = DEFAULT_FILTER;
221 DBG(cdev, "activate eem\n");
222 net = gether_connect(&eem->port);
223 if (IS_ERR(net))
224 return PTR_ERR(net);
225 } else
226 goto fail;
227
228 return 0;
229fail:
230 return -EINVAL;
231}
232
233static void eem_disable(struct usb_function *f)
234{
235 struct f_eem *eem = func_to_eem(f);
236 struct usb_composite_dev *cdev = f->config->cdev;
237
238 DBG(cdev, "eem deactivated\n");
239
240 if (eem->port.in_ep->driver_data)
241 gether_disconnect(&eem->port);
242}
243
244/*-------------------------------------------------------------------------*/
245
246/* EEM function driver setup/binding */
247
248static int eem_bind(struct usb_configuration *c, struct usb_function *f)
249{
250 struct usb_composite_dev *cdev = c->cdev;
251 struct f_eem *eem = func_to_eem(f);
252 struct usb_string *us;
253 int status;
254 struct usb_ep *ep;
255
256 struct f_eem_opts *eem_opts;
257
258 eem_opts = container_of(f->fi, struct f_eem_opts, func_inst);
259 /*
260 * in drivers/usb/gadget/configfs.c:configfs_composite_bind()
261 * configurations are bound in sequence with list_for_each_entry,
262 * in each configuration its functions are bound in sequence
263 * with list_for_each_entry, so we assume no race condition
264 * with regard to eem_opts->bound access
265 */
266 if (!eem_opts->bound) {
267 mutex_lock(&eem_opts->lock);
268 gether_set_gadget(eem_opts->net, cdev->gadget);
269 status = gether_register_netdev(eem_opts->net);
270 mutex_unlock(&eem_opts->lock);
271 if (status)
272 return status;
273 eem_opts->bound = true;
274 }
275
276 us = usb_gstrings_attach(cdev, eem_strings,
277 ARRAY_SIZE(eem_string_defs));
278 if (IS_ERR(us))
279 return PTR_ERR(us);
280 eem_intf.iInterface = us[0].id;
281
282 /* allocate instance-specific interface IDs */
283 status = usb_interface_id(c, f);
284 if (status < 0)
285 goto fail;
286 eem->ctrl_id = status;
287 eem_intf.bInterfaceNumber = status;
288
289 status = -ENODEV;
290
291 /* allocate instance-specific endpoints */
292 ep = usb_ep_autoconfig(cdev->gadget, &eem_fs_in_desc);
293 if (!ep)
294 goto fail;
295 eem->port.in_ep = ep;
296 ep->driver_data = cdev; /* claim */
297
298 ep = usb_ep_autoconfig(cdev->gadget, &eem_fs_out_desc);
299 if (!ep)
300 goto fail;
301 eem->port.out_ep = ep;
302 ep->driver_data = cdev; /* claim */
303
304 status = -ENOMEM;
305
306 /* support all relevant hardware speeds... we expect that when
307 * hardware is dual speed, all bulk-capable endpoints work at
308 * both speeds
309 */
310 eem_hs_in_desc.bEndpointAddress = eem_fs_in_desc.bEndpointAddress;
311 eem_hs_out_desc.bEndpointAddress = eem_fs_out_desc.bEndpointAddress;
312
313 eem_ss_in_desc.bEndpointAddress = eem_fs_in_desc.bEndpointAddress;
314 eem_ss_out_desc.bEndpointAddress = eem_fs_out_desc.bEndpointAddress;
315
316 status = usb_assign_descriptors(f, eem_fs_function, eem_hs_function,
317 eem_ss_function);
318 if (status)
319 goto fail;
320
321 DBG(cdev, "CDC Ethernet (EEM): %s speed IN/%s OUT/%s\n",
322 gadget_is_superspeed(c->cdev->gadget) ? "super" :
323 gadget_is_dualspeed(c->cdev->gadget) ? "dual" : "full",
324 eem->port.in_ep->name, eem->port.out_ep->name);
325 return 0;
326
327fail:
328 usb_free_all_descriptors(f);
329 if (eem->port.out_ep)
330 eem->port.out_ep->driver_data = NULL;
331 if (eem->port.in_ep)
332 eem->port.in_ep->driver_data = NULL;
333
334 ERROR(cdev, "%s: can't bind, err %d\n", f->name, status);
335
336 return status;
337}
338
339static void eem_cmd_complete(struct usb_ep *ep, struct usb_request *req)
340{
341 struct sk_buff *skb = (struct sk_buff *)req->context;
342
343 dev_kfree_skb_any(skb);
344}
345
346/*
347 * Add the EEM header and ethernet checksum.
348 * We currently do not attempt to put multiple ethernet frames
349 * into a single USB transfer
350 */
351static struct sk_buff *eem_wrap(struct gether *port, struct sk_buff *skb)
352{
353 struct sk_buff *skb2 = NULL;
354 struct usb_ep *in = port->in_ep;
355 int padlen = 0;
356 u16 len = skb->len;
357
358 int headroom = skb_headroom(skb);
359 int tailroom = skb_tailroom(skb);
360
361 /* When (len + EEM_HLEN + ETH_FCS_LEN) % in->maxpacket) is 0,
362 * stick two bytes of zero-length EEM packet on the end.
363 */
364 if (((len + EEM_HLEN + ETH_FCS_LEN) % in->maxpacket) == 0)
365 padlen += 2;
366
367 if ((tailroom >= (ETH_FCS_LEN + padlen)) &&
368 (headroom >= EEM_HLEN) && !skb_cloned(skb))
369 goto done;
370
371 skb2 = skb_copy_expand(skb, EEM_HLEN, ETH_FCS_LEN + padlen, GFP_ATOMIC);
372 dev_kfree_skb_any(skb);
373 skb = skb2;
374 if (!skb)
375 return skb;
376
377done:
378 /* use the "no CRC" option */
379 put_unaligned_be32(0xdeadbeef, skb_put(skb, 4));
380
381 /* EEM packet header format:
382 * b0..13: length of ethernet frame
383 * b14: bmCRC (0 == sentinel CRC)
384 * b15: bmType (0 == data)
385 */
386 len = skb->len;
387 put_unaligned_le16(len & 0x3FFF, skb_push(skb, 2));
388
389 /* add a zero-length EEM packet, if needed */
390 if (padlen)
391 put_unaligned_le16(0, skb_put(skb, 2));
392
393 return skb;
394}
395
396/*
397 * Remove the EEM header. Note that there can be many EEM packets in a single
398 * USB transfer, so we need to break them out and handle them independently.
399 */
400static int eem_unwrap(struct gether *port,
401 struct sk_buff *skb,
402 struct sk_buff_head *list)
403{
404 struct usb_composite_dev *cdev = port->func.config->cdev;
405 int status = 0;
406
407 do {
408 struct sk_buff *skb2;
409 u16 header;
410 u16 len = 0;
411
412 if (skb->len < EEM_HLEN) {
413 status = -EINVAL;
414 DBG(cdev, "invalid EEM header\n");
415 goto error;
416 }
417
418 /* remove the EEM header */
419 header = get_unaligned_le16(skb->data);
420 skb_pull(skb, EEM_HLEN);
421
422 /* EEM packet header format:
423 * b0..14: EEM type dependent (data or command)
424 * b15: bmType (0 == data, 1 == command)
425 */
426 if (header & BIT(15)) {
427 struct usb_request *req = cdev->req;
428 u16 bmEEMCmd;
429
430 /* EEM command packet format:
431 * b0..10: bmEEMCmdParam
432 * b11..13: bmEEMCmd
433 * b14: reserved (must be zero)
434 * b15: bmType (1 == command)
435 */
436 if (header & BIT(14))
437 continue;
438
439 bmEEMCmd = (header >> 11) & 0x7;
440 switch (bmEEMCmd) {
441 case 0: /* echo */
442 len = header & 0x7FF;
443 if (skb->len < len) {
444 status = -EOVERFLOW;
445 goto error;
446 }
447
448 skb2 = skb_clone(skb, GFP_ATOMIC);
449 if (unlikely(!skb2)) {
450 DBG(cdev, "EEM echo response error\n");
451 goto next;
452 }
453 skb_trim(skb2, len);
454 put_unaligned_le16(BIT(15) | BIT(11) | len,
455 skb_push(skb2, 2));
456 skb_copy_bits(skb2, 0, req->buf, skb2->len);
457 req->length = skb2->len;
458 req->complete = eem_cmd_complete;
459 req->zero = 1;
460 req->context = skb2;
461 if (usb_ep_queue(port->in_ep, req, GFP_ATOMIC))
462 DBG(cdev, "echo response queue fail\n");
463 break;
464
465 case 1: /* echo response */
466 case 2: /* suspend hint */
467 case 3: /* response hint */
468 case 4: /* response complete hint */
469 case 5: /* tickle */
470 default: /* reserved */
471 continue;
472 }
473 } else {
474 u32 crc, crc2;
475 struct sk_buff *skb3;
476
477 /* check for zero-length EEM packet */
478 if (header == 0)
479 continue;
480
481 /* EEM data packet format:
482 * b0..13: length of ethernet frame
483 * b14: bmCRC (0 == sentinel, 1 == calculated)
484 * b15: bmType (0 == data)
485 */
486 len = header & 0x3FFF;
487 if ((skb->len < len)
488 || (len < (ETH_HLEN + ETH_FCS_LEN))) {
489 status = -EINVAL;
490 goto error;
491 }
492
493 /* validate CRC */
494 if (header & BIT(14)) {
495 crc = get_unaligned_le32(skb->data + len
496 - ETH_FCS_LEN);
497 crc2 = ~crc32_le(~0,
498 skb->data, len - ETH_FCS_LEN);
499 } else {
500 crc = get_unaligned_be32(skb->data + len
501 - ETH_FCS_LEN);
502 crc2 = 0xdeadbeef;
503 }
504 if (crc != crc2) {
505 DBG(cdev, "invalid EEM CRC\n");
506 goto next;
507 }
508
509 skb2 = skb_clone(skb, GFP_ATOMIC);
510 if (unlikely(!skb2)) {
511 DBG(cdev, "unable to unframe EEM packet\n");
512 continue;
513 }
514 skb_trim(skb2, len - ETH_FCS_LEN);
515
516 skb3 = skb_copy_expand(skb2,
517 NET_IP_ALIGN,
518 0,
519 GFP_ATOMIC);
520 if (unlikely(!skb3)) {
521 DBG(cdev, "unable to realign EEM packet\n");
522 dev_kfree_skb_any(skb2);
523 continue;
524 }
525 dev_kfree_skb_any(skb2);
526 skb_queue_tail(list, skb3);
527 }
528next:
529 skb_pull(skb, len);
530 } while (skb->len);
531
532error:
533 dev_kfree_skb_any(skb);
534 return status;
535}
536
537static inline struct f_eem_opts *to_f_eem_opts(struct config_item *item)
538{
539 return container_of(to_config_group(item), struct f_eem_opts,
540 func_inst.group);
541}
542
543/* f_eem_item_ops */
544USB_ETHERNET_CONFIGFS_ITEM(eem);
545
546/* f_eem_opts_dev_addr */
547USB_ETHERNET_CONFIGFS_ITEM_ATTR_DEV_ADDR(eem);
548
549/* f_eem_opts_host_addr */
550USB_ETHERNET_CONFIGFS_ITEM_ATTR_HOST_ADDR(eem);
551
552/* f_eem_opts_qmult */
553USB_ETHERNET_CONFIGFS_ITEM_ATTR_QMULT(eem);
554
555/* f_eem_opts_ifname */
556USB_ETHERNET_CONFIGFS_ITEM_ATTR_IFNAME(eem);
557
558static struct configfs_attribute *eem_attrs[] = {
559 &f_eem_opts_dev_addr.attr,
560 &f_eem_opts_host_addr.attr,
561 &f_eem_opts_qmult.attr,
562 &f_eem_opts_ifname.attr,
563 NULL,
564};
565
566static struct config_item_type eem_func_type = {
567 .ct_item_ops = &eem_item_ops,
568 .ct_attrs = eem_attrs,
569 .ct_owner = THIS_MODULE,
570};
571
572static void eem_free_inst(struct usb_function_instance *f)
573{
574 struct f_eem_opts *opts;
575
576 opts = container_of(f, struct f_eem_opts, func_inst);
577 if (opts->bound)
578 gether_cleanup(netdev_priv(opts->net));
579 else
580 free_netdev(opts->net);
581 kfree(opts);
582}
583
584static struct usb_function_instance *eem_alloc_inst(void)
585{
586 struct f_eem_opts *opts;
587
588 opts = kzalloc(sizeof(*opts), GFP_KERNEL);
589 if (!opts)
590 return ERR_PTR(-ENOMEM);
591 mutex_init(&opts->lock);
592 opts->func_inst.free_func_inst = eem_free_inst;
593 opts->net = gether_setup_default();
594 if (IS_ERR(opts->net)) {
595 struct net_device *net = opts->net;
596 kfree(opts);
597 return ERR_CAST(net);
598 }
599
600 config_group_init_type_name(&opts->func_inst.group, "", &eem_func_type);
601
602 return &opts->func_inst;
603}
604
605static void eem_free(struct usb_function *f)
606{
607 struct f_eem *eem;
608 struct f_eem_opts *opts;
609
610 eem = func_to_eem(f);
611 opts = container_of(f->fi, struct f_eem_opts, func_inst);
612 kfree(eem);
613 mutex_lock(&opts->lock);
614 opts->refcnt--;
615 mutex_unlock(&opts->lock);
616}
617
618static void eem_unbind(struct usb_configuration *c, struct usb_function *f)
619{
620 DBG(c->cdev, "eem unbind\n");
621
622 usb_free_all_descriptors(f);
623}
624
625static struct usb_function *eem_alloc(struct usb_function_instance *fi)
626{
627 struct f_eem *eem;
628 struct f_eem_opts *opts;
629
630 /* allocate and initialize one new instance */
631 eem = kzalloc(sizeof(*eem), GFP_KERNEL);
632 if (!eem)
633 return ERR_PTR(-ENOMEM);
634
635 opts = container_of(fi, struct f_eem_opts, func_inst);
636 mutex_lock(&opts->lock);
637 opts->refcnt++;
638
639 eem->port.ioport = netdev_priv(opts->net);
640 mutex_unlock(&opts->lock);
641 eem->port.cdc_filter = DEFAULT_FILTER;
642
643 eem->port.func.name = "cdc_eem";
644 /* descriptors are per-instance copies */
645 eem->port.func.bind = eem_bind;
646 eem->port.func.unbind = eem_unbind;
647 eem->port.func.set_alt = eem_set_alt;
648 eem->port.func.setup = eem_setup;
649 eem->port.func.disable = eem_disable;
650 eem->port.func.free_func = eem_free;
651 eem->port.wrap = eem_wrap;
652 eem->port.unwrap = eem_unwrap;
653 eem->port.header_len = EEM_HLEN;
654
655 return &eem->port.func;
656}
657
658DECLARE_USB_FUNCTION_INIT(eem, eem_alloc_inst, eem_alloc);
659MODULE_LICENSE("GPL");
660MODULE_AUTHOR("David Brownell");
diff --git a/drivers/usb/gadget/function/f_fs.c b/drivers/usb/gadget/function/f_fs.c
new file mode 100644
index 000000000000..dc30adf15a01
--- /dev/null
+++ b/drivers/usb/gadget/function/f_fs.c
@@ -0,0 +1,3349 @@
1/*
2 * f_fs.c -- user mode file system API for USB composite function controllers
3 *
4 * Copyright (C) 2010 Samsung Electronics
5 * Author: Michal Nazarewicz <mina86@mina86.com>
6 *
7 * Based on inode.c (GadgetFS) which was:
8 * Copyright (C) 2003-2004 David Brownell
9 * Copyright (C) 2003 Agilent Technologies
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
15 */
16
17
18/* #define DEBUG */
19/* #define VERBOSE_DEBUG */
20
21#include <linux/blkdev.h>
22#include <linux/pagemap.h>
23#include <linux/export.h>
24#include <linux/hid.h>
25#include <linux/module.h>
26#include <asm/unaligned.h>
27
28#include <linux/usb/composite.h>
29#include <linux/usb/functionfs.h>
30
31#include <linux/aio.h>
32#include <linux/mmu_context.h>
33#include <linux/poll.h>
34
35#include "u_fs.h"
36#include "u_f.h"
37#include "u_os_desc.h"
38#include "configfs.h"
39
40#define FUNCTIONFS_MAGIC 0xa647361 /* Chosen by a honest dice roll ;) */
41
42/* Reference counter handling */
43static void ffs_data_get(struct ffs_data *ffs);
44static void ffs_data_put(struct ffs_data *ffs);
45/* Creates new ffs_data object. */
46static struct ffs_data *__must_check ffs_data_new(void) __attribute__((malloc));
47
48/* Opened counter handling. */
49static void ffs_data_opened(struct ffs_data *ffs);
50static void ffs_data_closed(struct ffs_data *ffs);
51
52/* Called with ffs->mutex held; take over ownership of data. */
53static int __must_check
54__ffs_data_got_descs(struct ffs_data *ffs, char *data, size_t len);
55static int __must_check
56__ffs_data_got_strings(struct ffs_data *ffs, char *data, size_t len);
57
58
59/* The function structure ***************************************************/
60
61struct ffs_ep;
62
63struct ffs_function {
64 struct usb_configuration *conf;
65 struct usb_gadget *gadget;
66 struct ffs_data *ffs;
67
68 struct ffs_ep *eps;
69 u8 eps_revmap[16];
70 short *interfaces_nums;
71
72 struct usb_function function;
73};
74
75
76static struct ffs_function *ffs_func_from_usb(struct usb_function *f)
77{
78 return container_of(f, struct ffs_function, function);
79}
80
81
82static inline enum ffs_setup_state
83ffs_setup_state_clear_cancelled(struct ffs_data *ffs)
84{
85 return (enum ffs_setup_state)
86 cmpxchg(&ffs->setup_state, FFS_SETUP_CANCELLED, FFS_NO_SETUP);
87}
88
89
90static void ffs_func_eps_disable(struct ffs_function *func);
91static int __must_check ffs_func_eps_enable(struct ffs_function *func);
92
93static int ffs_func_bind(struct usb_configuration *,
94 struct usb_function *);
95static int ffs_func_set_alt(struct usb_function *, unsigned, unsigned);
96static void ffs_func_disable(struct usb_function *);
97static int ffs_func_setup(struct usb_function *,
98 const struct usb_ctrlrequest *);
99static void ffs_func_suspend(struct usb_function *);
100static void ffs_func_resume(struct usb_function *);
101
102
103static int ffs_func_revmap_ep(struct ffs_function *func, u8 num);
104static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf);
105
106
107/* The endpoints structures *************************************************/
108
109struct ffs_ep {
110 struct usb_ep *ep; /* P: ffs->eps_lock */
111 struct usb_request *req; /* P: epfile->mutex */
112
113 /* [0]: full speed, [1]: high speed, [2]: super speed */
114 struct usb_endpoint_descriptor *descs[3];
115
116 u8 num;
117
118 int status; /* P: epfile->mutex */
119};
120
121struct ffs_epfile {
122 /* Protects ep->ep and ep->req. */
123 struct mutex mutex;
124 wait_queue_head_t wait;
125
126 struct ffs_data *ffs;
127 struct ffs_ep *ep; /* P: ffs->eps_lock */
128
129 struct dentry *dentry;
130
131 char name[5];
132
133 unsigned char in; /* P: ffs->eps_lock */
134 unsigned char isoc; /* P: ffs->eps_lock */
135
136 unsigned char _pad;
137};
138
139/* ffs_io_data structure ***************************************************/
140
141struct ffs_io_data {
142 bool aio;
143 bool read;
144
145 struct kiocb *kiocb;
146 const struct iovec *iovec;
147 unsigned long nr_segs;
148 char __user *buf;
149 size_t len;
150
151 struct mm_struct *mm;
152 struct work_struct work;
153
154 struct usb_ep *ep;
155 struct usb_request *req;
156};
157
158static int __must_check ffs_epfiles_create(struct ffs_data *ffs);
159static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count);
160
161static struct inode *__must_check
162ffs_sb_create_file(struct super_block *sb, const char *name, void *data,
163 const struct file_operations *fops,
164 struct dentry **dentry_p);
165
166/* Devices management *******************************************************/
167
168DEFINE_MUTEX(ffs_lock);
169EXPORT_SYMBOL_GPL(ffs_lock);
170
171static struct ffs_dev *_ffs_find_dev(const char *name);
172static struct ffs_dev *_ffs_alloc_dev(void);
173static int _ffs_name_dev(struct ffs_dev *dev, const char *name);
174static void _ffs_free_dev(struct ffs_dev *dev);
175static void *ffs_acquire_dev(const char *dev_name);
176static void ffs_release_dev(struct ffs_data *ffs_data);
177static int ffs_ready(struct ffs_data *ffs);
178static void ffs_closed(struct ffs_data *ffs);
179
180/* Misc helper functions ****************************************************/
181
182static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
183 __attribute__((warn_unused_result, nonnull));
184static char *ffs_prepare_buffer(const char __user *buf, size_t len)
185 __attribute__((warn_unused_result, nonnull));
186
187
188/* Control file aka ep0 *****************************************************/
189
190static void ffs_ep0_complete(struct usb_ep *ep, struct usb_request *req)
191{
192 struct ffs_data *ffs = req->context;
193
194 complete_all(&ffs->ep0req_completion);
195}
196
197static int __ffs_ep0_queue_wait(struct ffs_data *ffs, char *data, size_t len)
198{
199 struct usb_request *req = ffs->ep0req;
200 int ret;
201
202 req->zero = len < le16_to_cpu(ffs->ev.setup.wLength);
203
204 spin_unlock_irq(&ffs->ev.waitq.lock);
205
206 req->buf = data;
207 req->length = len;
208
209 /*
210 * UDC layer requires to provide a buffer even for ZLP, but should
211 * not use it at all. Let's provide some poisoned pointer to catch
212 * possible bug in the driver.
213 */
214 if (req->buf == NULL)
215 req->buf = (void *)0xDEADBABE;
216
217 reinit_completion(&ffs->ep0req_completion);
218
219 ret = usb_ep_queue(ffs->gadget->ep0, req, GFP_ATOMIC);
220 if (unlikely(ret < 0))
221 return ret;
222
223 ret = wait_for_completion_interruptible(&ffs->ep0req_completion);
224 if (unlikely(ret)) {
225 usb_ep_dequeue(ffs->gadget->ep0, req);
226 return -EINTR;
227 }
228
229 ffs->setup_state = FFS_NO_SETUP;
230 return req->status ? req->status : req->actual;
231}
232
233static int __ffs_ep0_stall(struct ffs_data *ffs)
234{
235 if (ffs->ev.can_stall) {
236 pr_vdebug("ep0 stall\n");
237 usb_ep_set_halt(ffs->gadget->ep0);
238 ffs->setup_state = FFS_NO_SETUP;
239 return -EL2HLT;
240 } else {
241 pr_debug("bogus ep0 stall!\n");
242 return -ESRCH;
243 }
244}
245
246static ssize_t ffs_ep0_write(struct file *file, const char __user *buf,
247 size_t len, loff_t *ptr)
248{
249 struct ffs_data *ffs = file->private_data;
250 ssize_t ret;
251 char *data;
252
253 ENTER();
254
255 /* Fast check if setup was canceled */
256 if (ffs_setup_state_clear_cancelled(ffs) == FFS_SETUP_CANCELLED)
257 return -EIDRM;
258
259 /* Acquire mutex */
260 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
261 if (unlikely(ret < 0))
262 return ret;
263
264 /* Check state */
265 switch (ffs->state) {
266 case FFS_READ_DESCRIPTORS:
267 case FFS_READ_STRINGS:
268 /* Copy data */
269 if (unlikely(len < 16)) {
270 ret = -EINVAL;
271 break;
272 }
273
274 data = ffs_prepare_buffer(buf, len);
275 if (IS_ERR(data)) {
276 ret = PTR_ERR(data);
277 break;
278 }
279
280 /* Handle data */
281 if (ffs->state == FFS_READ_DESCRIPTORS) {
282 pr_info("read descriptors\n");
283 ret = __ffs_data_got_descs(ffs, data, len);
284 if (unlikely(ret < 0))
285 break;
286
287 ffs->state = FFS_READ_STRINGS;
288 ret = len;
289 } else {
290 pr_info("read strings\n");
291 ret = __ffs_data_got_strings(ffs, data, len);
292 if (unlikely(ret < 0))
293 break;
294
295 ret = ffs_epfiles_create(ffs);
296 if (unlikely(ret)) {
297 ffs->state = FFS_CLOSING;
298 break;
299 }
300
301 ffs->state = FFS_ACTIVE;
302 mutex_unlock(&ffs->mutex);
303
304 ret = ffs_ready(ffs);
305 if (unlikely(ret < 0)) {
306 ffs->state = FFS_CLOSING;
307 return ret;
308 }
309
310 set_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags);
311 return len;
312 }
313 break;
314
315 case FFS_ACTIVE:
316 data = NULL;
317 /*
318 * We're called from user space, we can use _irq
319 * rather then _irqsave
320 */
321 spin_lock_irq(&ffs->ev.waitq.lock);
322 switch (ffs_setup_state_clear_cancelled(ffs)) {
323 case FFS_SETUP_CANCELLED:
324 ret = -EIDRM;
325 goto done_spin;
326
327 case FFS_NO_SETUP:
328 ret = -ESRCH;
329 goto done_spin;
330
331 case FFS_SETUP_PENDING:
332 break;
333 }
334
335 /* FFS_SETUP_PENDING */
336 if (!(ffs->ev.setup.bRequestType & USB_DIR_IN)) {
337 spin_unlock_irq(&ffs->ev.waitq.lock);
338 ret = __ffs_ep0_stall(ffs);
339 break;
340 }
341
342 /* FFS_SETUP_PENDING and not stall */
343 len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
344
345 spin_unlock_irq(&ffs->ev.waitq.lock);
346
347 data = ffs_prepare_buffer(buf, len);
348 if (IS_ERR(data)) {
349 ret = PTR_ERR(data);
350 break;
351 }
352
353 spin_lock_irq(&ffs->ev.waitq.lock);
354
355 /*
356 * We are guaranteed to be still in FFS_ACTIVE state
357 * but the state of setup could have changed from
358 * FFS_SETUP_PENDING to FFS_SETUP_CANCELLED so we need
359 * to check for that. If that happened we copied data
360 * from user space in vain but it's unlikely.
361 *
362 * For sure we are not in FFS_NO_SETUP since this is
363 * the only place FFS_SETUP_PENDING -> FFS_NO_SETUP
364 * transition can be performed and it's protected by
365 * mutex.
366 */
367 if (ffs_setup_state_clear_cancelled(ffs) ==
368 FFS_SETUP_CANCELLED) {
369 ret = -EIDRM;
370done_spin:
371 spin_unlock_irq(&ffs->ev.waitq.lock);
372 } else {
373 /* unlocks spinlock */
374 ret = __ffs_ep0_queue_wait(ffs, data, len);
375 }
376 kfree(data);
377 break;
378
379 default:
380 ret = -EBADFD;
381 break;
382 }
383
384 mutex_unlock(&ffs->mutex);
385 return ret;
386}
387
388static ssize_t __ffs_ep0_read_events(struct ffs_data *ffs, char __user *buf,
389 size_t n)
390{
391 /*
392 * We are holding ffs->ev.waitq.lock and ffs->mutex and we need
393 * to release them.
394 */
395 struct usb_functionfs_event events[n];
396 unsigned i = 0;
397
398 memset(events, 0, sizeof events);
399
400 do {
401 events[i].type = ffs->ev.types[i];
402 if (events[i].type == FUNCTIONFS_SETUP) {
403 events[i].u.setup = ffs->ev.setup;
404 ffs->setup_state = FFS_SETUP_PENDING;
405 }
406 } while (++i < n);
407
408 if (n < ffs->ev.count) {
409 ffs->ev.count -= n;
410 memmove(ffs->ev.types, ffs->ev.types + n,
411 ffs->ev.count * sizeof *ffs->ev.types);
412 } else {
413 ffs->ev.count = 0;
414 }
415
416 spin_unlock_irq(&ffs->ev.waitq.lock);
417 mutex_unlock(&ffs->mutex);
418
419 return unlikely(__copy_to_user(buf, events, sizeof events))
420 ? -EFAULT : sizeof events;
421}
422
423static ssize_t ffs_ep0_read(struct file *file, char __user *buf,
424 size_t len, loff_t *ptr)
425{
426 struct ffs_data *ffs = file->private_data;
427 char *data = NULL;
428 size_t n;
429 int ret;
430
431 ENTER();
432
433 /* Fast check if setup was canceled */
434 if (ffs_setup_state_clear_cancelled(ffs) == FFS_SETUP_CANCELLED)
435 return -EIDRM;
436
437 /* Acquire mutex */
438 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
439 if (unlikely(ret < 0))
440 return ret;
441
442 /* Check state */
443 if (ffs->state != FFS_ACTIVE) {
444 ret = -EBADFD;
445 goto done_mutex;
446 }
447
448 /*
449 * We're called from user space, we can use _irq rather then
450 * _irqsave
451 */
452 spin_lock_irq(&ffs->ev.waitq.lock);
453
454 switch (ffs_setup_state_clear_cancelled(ffs)) {
455 case FFS_SETUP_CANCELLED:
456 ret = -EIDRM;
457 break;
458
459 case FFS_NO_SETUP:
460 n = len / sizeof(struct usb_functionfs_event);
461 if (unlikely(!n)) {
462 ret = -EINVAL;
463 break;
464 }
465
466 if ((file->f_flags & O_NONBLOCK) && !ffs->ev.count) {
467 ret = -EAGAIN;
468 break;
469 }
470
471 if (wait_event_interruptible_exclusive_locked_irq(ffs->ev.waitq,
472 ffs->ev.count)) {
473 ret = -EINTR;
474 break;
475 }
476
477 return __ffs_ep0_read_events(ffs, buf,
478 min(n, (size_t)ffs->ev.count));
479
480 case FFS_SETUP_PENDING:
481 if (ffs->ev.setup.bRequestType & USB_DIR_IN) {
482 spin_unlock_irq(&ffs->ev.waitq.lock);
483 ret = __ffs_ep0_stall(ffs);
484 goto done_mutex;
485 }
486
487 len = min(len, (size_t)le16_to_cpu(ffs->ev.setup.wLength));
488
489 spin_unlock_irq(&ffs->ev.waitq.lock);
490
491 if (likely(len)) {
492 data = kmalloc(len, GFP_KERNEL);
493 if (unlikely(!data)) {
494 ret = -ENOMEM;
495 goto done_mutex;
496 }
497 }
498
499 spin_lock_irq(&ffs->ev.waitq.lock);
500
501 /* See ffs_ep0_write() */
502 if (ffs_setup_state_clear_cancelled(ffs) ==
503 FFS_SETUP_CANCELLED) {
504 ret = -EIDRM;
505 break;
506 }
507
508 /* unlocks spinlock */
509 ret = __ffs_ep0_queue_wait(ffs, data, len);
510 if (likely(ret > 0) && unlikely(__copy_to_user(buf, data, len)))
511 ret = -EFAULT;
512 goto done_mutex;
513
514 default:
515 ret = -EBADFD;
516 break;
517 }
518
519 spin_unlock_irq(&ffs->ev.waitq.lock);
520done_mutex:
521 mutex_unlock(&ffs->mutex);
522 kfree(data);
523 return ret;
524}
525
526static int ffs_ep0_open(struct inode *inode, struct file *file)
527{
528 struct ffs_data *ffs = inode->i_private;
529
530 ENTER();
531
532 if (unlikely(ffs->state == FFS_CLOSING))
533 return -EBUSY;
534
535 file->private_data = ffs;
536 ffs_data_opened(ffs);
537
538 return 0;
539}
540
541static int ffs_ep0_release(struct inode *inode, struct file *file)
542{
543 struct ffs_data *ffs = file->private_data;
544
545 ENTER();
546
547 ffs_data_closed(ffs);
548
549 return 0;
550}
551
552static long ffs_ep0_ioctl(struct file *file, unsigned code, unsigned long value)
553{
554 struct ffs_data *ffs = file->private_data;
555 struct usb_gadget *gadget = ffs->gadget;
556 long ret;
557
558 ENTER();
559
560 if (code == FUNCTIONFS_INTERFACE_REVMAP) {
561 struct ffs_function *func = ffs->func;
562 ret = func ? ffs_func_revmap_intf(func, value) : -ENODEV;
563 } else if (gadget && gadget->ops->ioctl) {
564 ret = gadget->ops->ioctl(gadget, code, value);
565 } else {
566 ret = -ENOTTY;
567 }
568
569 return ret;
570}
571
572static unsigned int ffs_ep0_poll(struct file *file, poll_table *wait)
573{
574 struct ffs_data *ffs = file->private_data;
575 unsigned int mask = POLLWRNORM;
576 int ret;
577
578 poll_wait(file, &ffs->ev.waitq, wait);
579
580 ret = ffs_mutex_lock(&ffs->mutex, file->f_flags & O_NONBLOCK);
581 if (unlikely(ret < 0))
582 return mask;
583
584 switch (ffs->state) {
585 case FFS_READ_DESCRIPTORS:
586 case FFS_READ_STRINGS:
587 mask |= POLLOUT;
588 break;
589
590 case FFS_ACTIVE:
591 switch (ffs->setup_state) {
592 case FFS_NO_SETUP:
593 if (ffs->ev.count)
594 mask |= POLLIN;
595 break;
596
597 case FFS_SETUP_PENDING:
598 case FFS_SETUP_CANCELLED:
599 mask |= (POLLIN | POLLOUT);
600 break;
601 }
602 case FFS_CLOSING:
603 break;
604 }
605
606 mutex_unlock(&ffs->mutex);
607
608 return mask;
609}
610
611static const struct file_operations ffs_ep0_operations = {
612 .llseek = no_llseek,
613
614 .open = ffs_ep0_open,
615 .write = ffs_ep0_write,
616 .read = ffs_ep0_read,
617 .release = ffs_ep0_release,
618 .unlocked_ioctl = ffs_ep0_ioctl,
619 .poll = ffs_ep0_poll,
620};
621
622
623/* "Normal" endpoints operations ********************************************/
624
625static void ffs_epfile_io_complete(struct usb_ep *_ep, struct usb_request *req)
626{
627 ENTER();
628 if (likely(req->context)) {
629 struct ffs_ep *ep = _ep->driver_data;
630 ep->status = req->status ? req->status : req->actual;
631 complete(req->context);
632 }
633}
634
635static void ffs_user_copy_worker(struct work_struct *work)
636{
637 struct ffs_io_data *io_data = container_of(work, struct ffs_io_data,
638 work);
639 int ret = io_data->req->status ? io_data->req->status :
640 io_data->req->actual;
641
642 if (io_data->read && ret > 0) {
643 int i;
644 size_t pos = 0;
645 use_mm(io_data->mm);
646 for (i = 0; i < io_data->nr_segs; i++) {
647 if (unlikely(copy_to_user(io_data->iovec[i].iov_base,
648 &io_data->buf[pos],
649 io_data->iovec[i].iov_len))) {
650 ret = -EFAULT;
651 break;
652 }
653 pos += io_data->iovec[i].iov_len;
654 }
655 unuse_mm(io_data->mm);
656 }
657
658 aio_complete(io_data->kiocb, ret, ret);
659
660 usb_ep_free_request(io_data->ep, io_data->req);
661
662 io_data->kiocb->private = NULL;
663 if (io_data->read)
664 kfree(io_data->iovec);
665 kfree(io_data->buf);
666 kfree(io_data);
667}
668
669static void ffs_epfile_async_io_complete(struct usb_ep *_ep,
670 struct usb_request *req)
671{
672 struct ffs_io_data *io_data = req->context;
673
674 ENTER();
675
676 INIT_WORK(&io_data->work, ffs_user_copy_worker);
677 schedule_work(&io_data->work);
678}
679
680static ssize_t ffs_epfile_io(struct file *file, struct ffs_io_data *io_data)
681{
682 struct ffs_epfile *epfile = file->private_data;
683 struct ffs_ep *ep;
684 char *data = NULL;
685 ssize_t ret, data_len;
686 int halt;
687
688 /* Are we still active? */
689 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE)) {
690 ret = -ENODEV;
691 goto error;
692 }
693
694 /* Wait for endpoint to be enabled */
695 ep = epfile->ep;
696 if (!ep) {
697 if (file->f_flags & O_NONBLOCK) {
698 ret = -EAGAIN;
699 goto error;
700 }
701
702 ret = wait_event_interruptible(epfile->wait, (ep = epfile->ep));
703 if (ret) {
704 ret = -EINTR;
705 goto error;
706 }
707 }
708
709 /* Do we halt? */
710 halt = (!io_data->read == !epfile->in);
711 if (halt && epfile->isoc) {
712 ret = -EINVAL;
713 goto error;
714 }
715
716 /* Allocate & copy */
717 if (!halt) {
718 /*
719 * if we _do_ wait above, the epfile->ffs->gadget might be NULL
720 * before the waiting completes, so do not assign to 'gadget' earlier
721 */
722 struct usb_gadget *gadget = epfile->ffs->gadget;
723
724 spin_lock_irq(&epfile->ffs->eps_lock);
725 /* In the meantime, endpoint got disabled or changed. */
726 if (epfile->ep != ep) {
727 spin_unlock_irq(&epfile->ffs->eps_lock);
728 return -ESHUTDOWN;
729 }
730 /*
731 * Controller may require buffer size to be aligned to
732 * maxpacketsize of an out endpoint.
733 */
734 data_len = io_data->read ?
735 usb_ep_align_maybe(gadget, ep->ep, io_data->len) :
736 io_data->len;
737 spin_unlock_irq(&epfile->ffs->eps_lock);
738
739 data = kmalloc(data_len, GFP_KERNEL);
740 if (unlikely(!data))
741 return -ENOMEM;
742 if (io_data->aio && !io_data->read) {
743 int i;
744 size_t pos = 0;
745 for (i = 0; i < io_data->nr_segs; i++) {
746 if (unlikely(copy_from_user(&data[pos],
747 io_data->iovec[i].iov_base,
748 io_data->iovec[i].iov_len))) {
749 ret = -EFAULT;
750 goto error;
751 }
752 pos += io_data->iovec[i].iov_len;
753 }
754 } else {
755 if (!io_data->read &&
756 unlikely(__copy_from_user(data, io_data->buf,
757 io_data->len))) {
758 ret = -EFAULT;
759 goto error;
760 }
761 }
762 }
763
764 /* We will be using request */
765 ret = ffs_mutex_lock(&epfile->mutex, file->f_flags & O_NONBLOCK);
766 if (unlikely(ret))
767 goto error;
768
769 spin_lock_irq(&epfile->ffs->eps_lock);
770
771 if (epfile->ep != ep) {
772 /* In the meantime, endpoint got disabled or changed. */
773 ret = -ESHUTDOWN;
774 spin_unlock_irq(&epfile->ffs->eps_lock);
775 } else if (halt) {
776 /* Halt */
777 if (likely(epfile->ep == ep) && !WARN_ON(!ep->ep))
778 usb_ep_set_halt(ep->ep);
779 spin_unlock_irq(&epfile->ffs->eps_lock);
780 ret = -EBADMSG;
781 } else {
782 /* Fire the request */
783 struct usb_request *req;
784
785 if (io_data->aio) {
786 req = usb_ep_alloc_request(ep->ep, GFP_KERNEL);
787 if (unlikely(!req))
788 goto error_lock;
789
790 req->buf = data;
791 req->length = io_data->len;
792
793 io_data->buf = data;
794 io_data->ep = ep->ep;
795 io_data->req = req;
796
797 req->context = io_data;
798 req->complete = ffs_epfile_async_io_complete;
799
800 ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
801 if (unlikely(ret)) {
802 usb_ep_free_request(ep->ep, req);
803 goto error_lock;
804 }
805 ret = -EIOCBQUEUED;
806
807 spin_unlock_irq(&epfile->ffs->eps_lock);
808 } else {
809 DECLARE_COMPLETION_ONSTACK(done);
810
811 req = ep->req;
812 req->buf = data;
813 req->length = io_data->len;
814
815 req->context = &done;
816 req->complete = ffs_epfile_io_complete;
817
818 ret = usb_ep_queue(ep->ep, req, GFP_ATOMIC);
819
820 spin_unlock_irq(&epfile->ffs->eps_lock);
821
822 if (unlikely(ret < 0)) {
823 /* nop */
824 } else if (unlikely(
825 wait_for_completion_interruptible(&done))) {
826 ret = -EINTR;
827 usb_ep_dequeue(ep->ep, req);
828 } else {
829 /*
830 * XXX We may end up silently droping data
831 * here. Since data_len (i.e. req->length) may
832 * be bigger than len (after being rounded up
833 * to maxpacketsize), we may end up with more
834 * data then user space has space for.
835 */
836 ret = ep->status;
837 if (io_data->read && ret > 0) {
838 ret = min_t(size_t, ret, io_data->len);
839
840 if (unlikely(copy_to_user(io_data->buf,
841 data, ret)))
842 ret = -EFAULT;
843 }
844 }
845 kfree(data);
846 }
847 }
848
849 mutex_unlock(&epfile->mutex);
850 return ret;
851
852error_lock:
853 spin_unlock_irq(&epfile->ffs->eps_lock);
854 mutex_unlock(&epfile->mutex);
855error:
856 kfree(data);
857 return ret;
858}
859
860static ssize_t
861ffs_epfile_write(struct file *file, const char __user *buf, size_t len,
862 loff_t *ptr)
863{
864 struct ffs_io_data io_data;
865
866 ENTER();
867
868 io_data.aio = false;
869 io_data.read = false;
870 io_data.buf = (char * __user)buf;
871 io_data.len = len;
872
873 return ffs_epfile_io(file, &io_data);
874}
875
876static ssize_t
877ffs_epfile_read(struct file *file, char __user *buf, size_t len, loff_t *ptr)
878{
879 struct ffs_io_data io_data;
880
881 ENTER();
882
883 io_data.aio = false;
884 io_data.read = true;
885 io_data.buf = buf;
886 io_data.len = len;
887
888 return ffs_epfile_io(file, &io_data);
889}
890
891static int
892ffs_epfile_open(struct inode *inode, struct file *file)
893{
894 struct ffs_epfile *epfile = inode->i_private;
895
896 ENTER();
897
898 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
899 return -ENODEV;
900
901 file->private_data = epfile;
902 ffs_data_opened(epfile->ffs);
903
904 return 0;
905}
906
907static int ffs_aio_cancel(struct kiocb *kiocb)
908{
909 struct ffs_io_data *io_data = kiocb->private;
910 struct ffs_epfile *epfile = kiocb->ki_filp->private_data;
911 int value;
912
913 ENTER();
914
915 spin_lock_irq(&epfile->ffs->eps_lock);
916
917 if (likely(io_data && io_data->ep && io_data->req))
918 value = usb_ep_dequeue(io_data->ep, io_data->req);
919 else
920 value = -EINVAL;
921
922 spin_unlock_irq(&epfile->ffs->eps_lock);
923
924 return value;
925}
926
927static ssize_t ffs_epfile_aio_write(struct kiocb *kiocb,
928 const struct iovec *iovec,
929 unsigned long nr_segs, loff_t loff)
930{
931 struct ffs_io_data *io_data;
932
933 ENTER();
934
935 io_data = kmalloc(sizeof(*io_data), GFP_KERNEL);
936 if (unlikely(!io_data))
937 return -ENOMEM;
938
939 io_data->aio = true;
940 io_data->read = false;
941 io_data->kiocb = kiocb;
942 io_data->iovec = iovec;
943 io_data->nr_segs = nr_segs;
944 io_data->len = kiocb->ki_nbytes;
945 io_data->mm = current->mm;
946
947 kiocb->private = io_data;
948
949 kiocb_set_cancel_fn(kiocb, ffs_aio_cancel);
950
951 return ffs_epfile_io(kiocb->ki_filp, io_data);
952}
953
954static ssize_t ffs_epfile_aio_read(struct kiocb *kiocb,
955 const struct iovec *iovec,
956 unsigned long nr_segs, loff_t loff)
957{
958 struct ffs_io_data *io_data;
959 struct iovec *iovec_copy;
960
961 ENTER();
962
963 iovec_copy = kmalloc_array(nr_segs, sizeof(*iovec_copy), GFP_KERNEL);
964 if (unlikely(!iovec_copy))
965 return -ENOMEM;
966
967 memcpy(iovec_copy, iovec, sizeof(struct iovec)*nr_segs);
968
969 io_data = kmalloc(sizeof(*io_data), GFP_KERNEL);
970 if (unlikely(!io_data)) {
971 kfree(iovec_copy);
972 return -ENOMEM;
973 }
974
975 io_data->aio = true;
976 io_data->read = true;
977 io_data->kiocb = kiocb;
978 io_data->iovec = iovec_copy;
979 io_data->nr_segs = nr_segs;
980 io_data->len = kiocb->ki_nbytes;
981 io_data->mm = current->mm;
982
983 kiocb->private = io_data;
984
985 kiocb_set_cancel_fn(kiocb, ffs_aio_cancel);
986
987 return ffs_epfile_io(kiocb->ki_filp, io_data);
988}
989
990static int
991ffs_epfile_release(struct inode *inode, struct file *file)
992{
993 struct ffs_epfile *epfile = inode->i_private;
994
995 ENTER();
996
997 ffs_data_closed(epfile->ffs);
998
999 return 0;
1000}
1001
1002static long ffs_epfile_ioctl(struct file *file, unsigned code,
1003 unsigned long value)
1004{
1005 struct ffs_epfile *epfile = file->private_data;
1006 int ret;
1007
1008 ENTER();
1009
1010 if (WARN_ON(epfile->ffs->state != FFS_ACTIVE))
1011 return -ENODEV;
1012
1013 spin_lock_irq(&epfile->ffs->eps_lock);
1014 if (likely(epfile->ep)) {
1015 switch (code) {
1016 case FUNCTIONFS_FIFO_STATUS:
1017 ret = usb_ep_fifo_status(epfile->ep->ep);
1018 break;
1019 case FUNCTIONFS_FIFO_FLUSH:
1020 usb_ep_fifo_flush(epfile->ep->ep);
1021 ret = 0;
1022 break;
1023 case FUNCTIONFS_CLEAR_HALT:
1024 ret = usb_ep_clear_halt(epfile->ep->ep);
1025 break;
1026 case FUNCTIONFS_ENDPOINT_REVMAP:
1027 ret = epfile->ep->num;
1028 break;
1029 default:
1030 ret = -ENOTTY;
1031 }
1032 } else {
1033 ret = -ENODEV;
1034 }
1035 spin_unlock_irq(&epfile->ffs->eps_lock);
1036
1037 return ret;
1038}
1039
1040static const struct file_operations ffs_epfile_operations = {
1041 .llseek = no_llseek,
1042
1043 .open = ffs_epfile_open,
1044 .write = ffs_epfile_write,
1045 .read = ffs_epfile_read,
1046 .aio_write = ffs_epfile_aio_write,
1047 .aio_read = ffs_epfile_aio_read,
1048 .release = ffs_epfile_release,
1049 .unlocked_ioctl = ffs_epfile_ioctl,
1050};
1051
1052
1053/* File system and super block operations ***********************************/
1054
1055/*
1056 * Mounting the file system creates a controller file, used first for
1057 * function configuration then later for event monitoring.
1058 */
1059
1060static struct inode *__must_check
1061ffs_sb_make_inode(struct super_block *sb, void *data,
1062 const struct file_operations *fops,
1063 const struct inode_operations *iops,
1064 struct ffs_file_perms *perms)
1065{
1066 struct inode *inode;
1067
1068 ENTER();
1069
1070 inode = new_inode(sb);
1071
1072 if (likely(inode)) {
1073 struct timespec current_time = CURRENT_TIME;
1074
1075 inode->i_ino = get_next_ino();
1076 inode->i_mode = perms->mode;
1077 inode->i_uid = perms->uid;
1078 inode->i_gid = perms->gid;
1079 inode->i_atime = current_time;
1080 inode->i_mtime = current_time;
1081 inode->i_ctime = current_time;
1082 inode->i_private = data;
1083 if (fops)
1084 inode->i_fop = fops;
1085 if (iops)
1086 inode->i_op = iops;
1087 }
1088
1089 return inode;
1090}
1091
1092/* Create "regular" file */
1093static struct inode *ffs_sb_create_file(struct super_block *sb,
1094 const char *name, void *data,
1095 const struct file_operations *fops,
1096 struct dentry **dentry_p)
1097{
1098 struct ffs_data *ffs = sb->s_fs_info;
1099 struct dentry *dentry;
1100 struct inode *inode;
1101
1102 ENTER();
1103
1104 dentry = d_alloc_name(sb->s_root, name);
1105 if (unlikely(!dentry))
1106 return NULL;
1107
1108 inode = ffs_sb_make_inode(sb, data, fops, NULL, &ffs->file_perms);
1109 if (unlikely(!inode)) {
1110 dput(dentry);
1111 return NULL;
1112 }
1113
1114 d_add(dentry, inode);
1115 if (dentry_p)
1116 *dentry_p = dentry;
1117
1118 return inode;
1119}
1120
1121/* Super block */
1122static const struct super_operations ffs_sb_operations = {
1123 .statfs = simple_statfs,
1124 .drop_inode = generic_delete_inode,
1125};
1126
1127struct ffs_sb_fill_data {
1128 struct ffs_file_perms perms;
1129 umode_t root_mode;
1130 const char *dev_name;
1131 struct ffs_data *ffs_data;
1132};
1133
1134static int ffs_sb_fill(struct super_block *sb, void *_data, int silent)
1135{
1136 struct ffs_sb_fill_data *data = _data;
1137 struct inode *inode;
1138 struct ffs_data *ffs = data->ffs_data;
1139
1140 ENTER();
1141
1142 ffs->sb = sb;
1143 data->ffs_data = NULL;
1144 sb->s_fs_info = ffs;
1145 sb->s_blocksize = PAGE_CACHE_SIZE;
1146 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1147 sb->s_magic = FUNCTIONFS_MAGIC;
1148 sb->s_op = &ffs_sb_operations;
1149 sb->s_time_gran = 1;
1150
1151 /* Root inode */
1152 data->perms.mode = data->root_mode;
1153 inode = ffs_sb_make_inode(sb, NULL,
1154 &simple_dir_operations,
1155 &simple_dir_inode_operations,
1156 &data->perms);
1157 sb->s_root = d_make_root(inode);
1158 if (unlikely(!sb->s_root))
1159 return -ENOMEM;
1160
1161 /* EP0 file */
1162 if (unlikely(!ffs_sb_create_file(sb, "ep0", ffs,
1163 &ffs_ep0_operations, NULL)))
1164 return -ENOMEM;
1165
1166 return 0;
1167}
1168
1169static int ffs_fs_parse_opts(struct ffs_sb_fill_data *data, char *opts)
1170{
1171 ENTER();
1172
1173 if (!opts || !*opts)
1174 return 0;
1175
1176 for (;;) {
1177 unsigned long value;
1178 char *eq, *comma;
1179
1180 /* Option limit */
1181 comma = strchr(opts, ',');
1182 if (comma)
1183 *comma = 0;
1184
1185 /* Value limit */
1186 eq = strchr(opts, '=');
1187 if (unlikely(!eq)) {
1188 pr_err("'=' missing in %s\n", opts);
1189 return -EINVAL;
1190 }
1191 *eq = 0;
1192
1193 /* Parse value */
1194 if (kstrtoul(eq + 1, 0, &value)) {
1195 pr_err("%s: invalid value: %s\n", opts, eq + 1);
1196 return -EINVAL;
1197 }
1198
1199 /* Interpret option */
1200 switch (eq - opts) {
1201 case 5:
1202 if (!memcmp(opts, "rmode", 5))
1203 data->root_mode = (value & 0555) | S_IFDIR;
1204 else if (!memcmp(opts, "fmode", 5))
1205 data->perms.mode = (value & 0666) | S_IFREG;
1206 else
1207 goto invalid;
1208 break;
1209
1210 case 4:
1211 if (!memcmp(opts, "mode", 4)) {
1212 data->root_mode = (value & 0555) | S_IFDIR;
1213 data->perms.mode = (value & 0666) | S_IFREG;
1214 } else {
1215 goto invalid;
1216 }
1217 break;
1218
1219 case 3:
1220 if (!memcmp(opts, "uid", 3)) {
1221 data->perms.uid = make_kuid(current_user_ns(), value);
1222 if (!uid_valid(data->perms.uid)) {
1223 pr_err("%s: unmapped value: %lu\n", opts, value);
1224 return -EINVAL;
1225 }
1226 } else if (!memcmp(opts, "gid", 3)) {
1227 data->perms.gid = make_kgid(current_user_ns(), value);
1228 if (!gid_valid(data->perms.gid)) {
1229 pr_err("%s: unmapped value: %lu\n", opts, value);
1230 return -EINVAL;
1231 }
1232 } else {
1233 goto invalid;
1234 }
1235 break;
1236
1237 default:
1238invalid:
1239 pr_err("%s: invalid option\n", opts);
1240 return -EINVAL;
1241 }
1242
1243 /* Next iteration */
1244 if (!comma)
1245 break;
1246 opts = comma + 1;
1247 }
1248
1249 return 0;
1250}
1251
1252/* "mount -t functionfs dev_name /dev/function" ends up here */
1253
1254static struct dentry *
1255ffs_fs_mount(struct file_system_type *t, int flags,
1256 const char *dev_name, void *opts)
1257{
1258 struct ffs_sb_fill_data data = {
1259 .perms = {
1260 .mode = S_IFREG | 0600,
1261 .uid = GLOBAL_ROOT_UID,
1262 .gid = GLOBAL_ROOT_GID,
1263 },
1264 .root_mode = S_IFDIR | 0500,
1265 };
1266 struct dentry *rv;
1267 int ret;
1268 void *ffs_dev;
1269 struct ffs_data *ffs;
1270
1271 ENTER();
1272
1273 ret = ffs_fs_parse_opts(&data, opts);
1274 if (unlikely(ret < 0))
1275 return ERR_PTR(ret);
1276
1277 ffs = ffs_data_new();
1278 if (unlikely(!ffs))
1279 return ERR_PTR(-ENOMEM);
1280 ffs->file_perms = data.perms;
1281
1282 ffs->dev_name = kstrdup(dev_name, GFP_KERNEL);
1283 if (unlikely(!ffs->dev_name)) {
1284 ffs_data_put(ffs);
1285 return ERR_PTR(-ENOMEM);
1286 }
1287
1288 ffs_dev = ffs_acquire_dev(dev_name);
1289 if (IS_ERR(ffs_dev)) {
1290 ffs_data_put(ffs);
1291 return ERR_CAST(ffs_dev);
1292 }
1293 ffs->private_data = ffs_dev;
1294 data.ffs_data = ffs;
1295
1296 rv = mount_nodev(t, flags, &data, ffs_sb_fill);
1297 if (IS_ERR(rv) && data.ffs_data) {
1298 ffs_release_dev(data.ffs_data);
1299 ffs_data_put(data.ffs_data);
1300 }
1301 return rv;
1302}
1303
1304static void
1305ffs_fs_kill_sb(struct super_block *sb)
1306{
1307 ENTER();
1308
1309 kill_litter_super(sb);
1310 if (sb->s_fs_info) {
1311 ffs_release_dev(sb->s_fs_info);
1312 ffs_data_put(sb->s_fs_info);
1313 }
1314}
1315
1316static struct file_system_type ffs_fs_type = {
1317 .owner = THIS_MODULE,
1318 .name = "functionfs",
1319 .mount = ffs_fs_mount,
1320 .kill_sb = ffs_fs_kill_sb,
1321};
1322MODULE_ALIAS_FS("functionfs");
1323
1324
1325/* Driver's main init/cleanup functions *************************************/
1326
1327static int functionfs_init(void)
1328{
1329 int ret;
1330
1331 ENTER();
1332
1333 ret = register_filesystem(&ffs_fs_type);
1334 if (likely(!ret))
1335 pr_info("file system registered\n");
1336 else
1337 pr_err("failed registering file system (%d)\n", ret);
1338
1339 return ret;
1340}
1341
1342static void functionfs_cleanup(void)
1343{
1344 ENTER();
1345
1346 pr_info("unloading\n");
1347 unregister_filesystem(&ffs_fs_type);
1348}
1349
1350
1351/* ffs_data and ffs_function construction and destruction code **************/
1352
1353static void ffs_data_clear(struct ffs_data *ffs);
1354static void ffs_data_reset(struct ffs_data *ffs);
1355
1356static void ffs_data_get(struct ffs_data *ffs)
1357{
1358 ENTER();
1359
1360 atomic_inc(&ffs->ref);
1361}
1362
1363static void ffs_data_opened(struct ffs_data *ffs)
1364{
1365 ENTER();
1366
1367 atomic_inc(&ffs->ref);
1368 atomic_inc(&ffs->opened);
1369}
1370
1371static void ffs_data_put(struct ffs_data *ffs)
1372{
1373 ENTER();
1374
1375 if (unlikely(atomic_dec_and_test(&ffs->ref))) {
1376 pr_info("%s(): freeing\n", __func__);
1377 ffs_data_clear(ffs);
1378 BUG_ON(waitqueue_active(&ffs->ev.waitq) ||
1379 waitqueue_active(&ffs->ep0req_completion.wait));
1380 kfree(ffs->dev_name);
1381 kfree(ffs);
1382 }
1383}
1384
1385static void ffs_data_closed(struct ffs_data *ffs)
1386{
1387 ENTER();
1388
1389 if (atomic_dec_and_test(&ffs->opened)) {
1390 ffs->state = FFS_CLOSING;
1391 ffs_data_reset(ffs);
1392 }
1393
1394 ffs_data_put(ffs);
1395}
1396
1397static struct ffs_data *ffs_data_new(void)
1398{
1399 struct ffs_data *ffs = kzalloc(sizeof *ffs, GFP_KERNEL);
1400 if (unlikely(!ffs))
1401 return NULL;
1402
1403 ENTER();
1404
1405 atomic_set(&ffs->ref, 1);
1406 atomic_set(&ffs->opened, 0);
1407 ffs->state = FFS_READ_DESCRIPTORS;
1408 mutex_init(&ffs->mutex);
1409 spin_lock_init(&ffs->eps_lock);
1410 init_waitqueue_head(&ffs->ev.waitq);
1411 init_completion(&ffs->ep0req_completion);
1412
1413 /* XXX REVISIT need to update it in some places, or do we? */
1414 ffs->ev.can_stall = 1;
1415
1416 return ffs;
1417}
1418
1419static void ffs_data_clear(struct ffs_data *ffs)
1420{
1421 ENTER();
1422
1423 if (test_and_clear_bit(FFS_FL_CALL_CLOSED_CALLBACK, &ffs->flags))
1424 ffs_closed(ffs);
1425
1426 BUG_ON(ffs->gadget);
1427
1428 if (ffs->epfiles)
1429 ffs_epfiles_destroy(ffs->epfiles, ffs->eps_count);
1430
1431 kfree(ffs->raw_descs_data);
1432 kfree(ffs->raw_strings);
1433 kfree(ffs->stringtabs);
1434}
1435
1436static void ffs_data_reset(struct ffs_data *ffs)
1437{
1438 ENTER();
1439
1440 ffs_data_clear(ffs);
1441
1442 ffs->epfiles = NULL;
1443 ffs->raw_descs_data = NULL;
1444 ffs->raw_descs = NULL;
1445 ffs->raw_strings = NULL;
1446 ffs->stringtabs = NULL;
1447
1448 ffs->raw_descs_length = 0;
1449 ffs->fs_descs_count = 0;
1450 ffs->hs_descs_count = 0;
1451 ffs->ss_descs_count = 0;
1452
1453 ffs->strings_count = 0;
1454 ffs->interfaces_count = 0;
1455 ffs->eps_count = 0;
1456
1457 ffs->ev.count = 0;
1458
1459 ffs->state = FFS_READ_DESCRIPTORS;
1460 ffs->setup_state = FFS_NO_SETUP;
1461 ffs->flags = 0;
1462}
1463
1464
1465static int functionfs_bind(struct ffs_data *ffs, struct usb_composite_dev *cdev)
1466{
1467 struct usb_gadget_strings **lang;
1468 int first_id;
1469
1470 ENTER();
1471
1472 if (WARN_ON(ffs->state != FFS_ACTIVE
1473 || test_and_set_bit(FFS_FL_BOUND, &ffs->flags)))
1474 return -EBADFD;
1475
1476 first_id = usb_string_ids_n(cdev, ffs->strings_count);
1477 if (unlikely(first_id < 0))
1478 return first_id;
1479
1480 ffs->ep0req = usb_ep_alloc_request(cdev->gadget->ep0, GFP_KERNEL);
1481 if (unlikely(!ffs->ep0req))
1482 return -ENOMEM;
1483 ffs->ep0req->complete = ffs_ep0_complete;
1484 ffs->ep0req->context = ffs;
1485
1486 lang = ffs->stringtabs;
1487 if (lang) {
1488 for (; *lang; ++lang) {
1489 struct usb_string *str = (*lang)->strings;
1490 int id = first_id;
1491 for (; str->s; ++id, ++str)
1492 str->id = id;
1493 }
1494 }
1495
1496 ffs->gadget = cdev->gadget;
1497 ffs_data_get(ffs);
1498 return 0;
1499}
1500
1501static void functionfs_unbind(struct ffs_data *ffs)
1502{
1503 ENTER();
1504
1505 if (!WARN_ON(!ffs->gadget)) {
1506 usb_ep_free_request(ffs->gadget->ep0, ffs->ep0req);
1507 ffs->ep0req = NULL;
1508 ffs->gadget = NULL;
1509 clear_bit(FFS_FL_BOUND, &ffs->flags);
1510 ffs_data_put(ffs);
1511 }
1512}
1513
1514static int ffs_epfiles_create(struct ffs_data *ffs)
1515{
1516 struct ffs_epfile *epfile, *epfiles;
1517 unsigned i, count;
1518
1519 ENTER();
1520
1521 count = ffs->eps_count;
1522 epfiles = kcalloc(count, sizeof(*epfiles), GFP_KERNEL);
1523 if (!epfiles)
1524 return -ENOMEM;
1525
1526 epfile = epfiles;
1527 for (i = 1; i <= count; ++i, ++epfile) {
1528 epfile->ffs = ffs;
1529 mutex_init(&epfile->mutex);
1530 init_waitqueue_head(&epfile->wait);
1531 sprintf(epfiles->name, "ep%u", i);
1532 if (!unlikely(ffs_sb_create_file(ffs->sb, epfiles->name, epfile,
1533 &ffs_epfile_operations,
1534 &epfile->dentry))) {
1535 ffs_epfiles_destroy(epfiles, i - 1);
1536 return -ENOMEM;
1537 }
1538 }
1539
1540 ffs->epfiles = epfiles;
1541 return 0;
1542}
1543
1544static void ffs_epfiles_destroy(struct ffs_epfile *epfiles, unsigned count)
1545{
1546 struct ffs_epfile *epfile = epfiles;
1547
1548 ENTER();
1549
1550 for (; count; --count, ++epfile) {
1551 BUG_ON(mutex_is_locked(&epfile->mutex) ||
1552 waitqueue_active(&epfile->wait));
1553 if (epfile->dentry) {
1554 d_delete(epfile->dentry);
1555 dput(epfile->dentry);
1556 epfile->dentry = NULL;
1557 }
1558 }
1559
1560 kfree(epfiles);
1561}
1562
1563
1564static void ffs_func_eps_disable(struct ffs_function *func)
1565{
1566 struct ffs_ep *ep = func->eps;
1567 struct ffs_epfile *epfile = func->ffs->epfiles;
1568 unsigned count = func->ffs->eps_count;
1569 unsigned long flags;
1570
1571 spin_lock_irqsave(&func->ffs->eps_lock, flags);
1572 do {
1573 /* pending requests get nuked */
1574 if (likely(ep->ep))
1575 usb_ep_disable(ep->ep);
1576 epfile->ep = NULL;
1577
1578 ++ep;
1579 ++epfile;
1580 } while (--count);
1581 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1582}
1583
1584static int ffs_func_eps_enable(struct ffs_function *func)
1585{
1586 struct ffs_data *ffs = func->ffs;
1587 struct ffs_ep *ep = func->eps;
1588 struct ffs_epfile *epfile = ffs->epfiles;
1589 unsigned count = ffs->eps_count;
1590 unsigned long flags;
1591 int ret = 0;
1592
1593 spin_lock_irqsave(&func->ffs->eps_lock, flags);
1594 do {
1595 struct usb_endpoint_descriptor *ds;
1596 int desc_idx;
1597
1598 if (ffs->gadget->speed == USB_SPEED_SUPER)
1599 desc_idx = 2;
1600 else if (ffs->gadget->speed == USB_SPEED_HIGH)
1601 desc_idx = 1;
1602 else
1603 desc_idx = 0;
1604
1605 /* fall-back to lower speed if desc missing for current speed */
1606 do {
1607 ds = ep->descs[desc_idx];
1608 } while (!ds && --desc_idx >= 0);
1609
1610 if (!ds) {
1611 ret = -EINVAL;
1612 break;
1613 }
1614
1615 ep->ep->driver_data = ep;
1616 ep->ep->desc = ds;
1617 ret = usb_ep_enable(ep->ep);
1618 if (likely(!ret)) {
1619 epfile->ep = ep;
1620 epfile->in = usb_endpoint_dir_in(ds);
1621 epfile->isoc = usb_endpoint_xfer_isoc(ds);
1622 } else {
1623 break;
1624 }
1625
1626 wake_up(&epfile->wait);
1627
1628 ++ep;
1629 ++epfile;
1630 } while (--count);
1631 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
1632
1633 return ret;
1634}
1635
1636
1637/* Parsing and building descriptors and strings *****************************/
1638
1639/*
1640 * This validates if data pointed by data is a valid USB descriptor as
1641 * well as record how many interfaces, endpoints and strings are
1642 * required by given configuration. Returns address after the
1643 * descriptor or NULL if data is invalid.
1644 */
1645
1646enum ffs_entity_type {
1647 FFS_DESCRIPTOR, FFS_INTERFACE, FFS_STRING, FFS_ENDPOINT
1648};
1649
1650enum ffs_os_desc_type {
1651 FFS_OS_DESC, FFS_OS_DESC_EXT_COMPAT, FFS_OS_DESC_EXT_PROP
1652};
1653
1654typedef int (*ffs_entity_callback)(enum ffs_entity_type entity,
1655 u8 *valuep,
1656 struct usb_descriptor_header *desc,
1657 void *priv);
1658
1659typedef int (*ffs_os_desc_callback)(enum ffs_os_desc_type entity,
1660 struct usb_os_desc_header *h, void *data,
1661 unsigned len, void *priv);
1662
1663static int __must_check ffs_do_single_desc(char *data, unsigned len,
1664 ffs_entity_callback entity,
1665 void *priv)
1666{
1667 struct usb_descriptor_header *_ds = (void *)data;
1668 u8 length;
1669 int ret;
1670
1671 ENTER();
1672
1673 /* At least two bytes are required: length and type */
1674 if (len < 2) {
1675 pr_vdebug("descriptor too short\n");
1676 return -EINVAL;
1677 }
1678
1679 /* If we have at least as many bytes as the descriptor takes? */
1680 length = _ds->bLength;
1681 if (len < length) {
1682 pr_vdebug("descriptor longer then available data\n");
1683 return -EINVAL;
1684 }
1685
1686#define __entity_check_INTERFACE(val) 1
1687#define __entity_check_STRING(val) (val)
1688#define __entity_check_ENDPOINT(val) ((val) & USB_ENDPOINT_NUMBER_MASK)
1689#define __entity(type, val) do { \
1690 pr_vdebug("entity " #type "(%02x)\n", (val)); \
1691 if (unlikely(!__entity_check_ ##type(val))) { \
1692 pr_vdebug("invalid entity's value\n"); \
1693 return -EINVAL; \
1694 } \
1695 ret = entity(FFS_ ##type, &val, _ds, priv); \
1696 if (unlikely(ret < 0)) { \
1697 pr_debug("entity " #type "(%02x); ret = %d\n", \
1698 (val), ret); \
1699 return ret; \
1700 } \
1701 } while (0)
1702
1703 /* Parse descriptor depending on type. */
1704 switch (_ds->bDescriptorType) {
1705 case USB_DT_DEVICE:
1706 case USB_DT_CONFIG:
1707 case USB_DT_STRING:
1708 case USB_DT_DEVICE_QUALIFIER:
1709 /* function can't have any of those */
1710 pr_vdebug("descriptor reserved for gadget: %d\n",
1711 _ds->bDescriptorType);
1712 return -EINVAL;
1713
1714 case USB_DT_INTERFACE: {
1715 struct usb_interface_descriptor *ds = (void *)_ds;
1716 pr_vdebug("interface descriptor\n");
1717 if (length != sizeof *ds)
1718 goto inv_length;
1719
1720 __entity(INTERFACE, ds->bInterfaceNumber);
1721 if (ds->iInterface)
1722 __entity(STRING, ds->iInterface);
1723 }
1724 break;
1725
1726 case USB_DT_ENDPOINT: {
1727 struct usb_endpoint_descriptor *ds = (void *)_ds;
1728 pr_vdebug("endpoint descriptor\n");
1729 if (length != USB_DT_ENDPOINT_SIZE &&
1730 length != USB_DT_ENDPOINT_AUDIO_SIZE)
1731 goto inv_length;
1732 __entity(ENDPOINT, ds->bEndpointAddress);
1733 }
1734 break;
1735
1736 case HID_DT_HID:
1737 pr_vdebug("hid descriptor\n");
1738 if (length != sizeof(struct hid_descriptor))
1739 goto inv_length;
1740 break;
1741
1742 case USB_DT_OTG:
1743 if (length != sizeof(struct usb_otg_descriptor))
1744 goto inv_length;
1745 break;
1746
1747 case USB_DT_INTERFACE_ASSOCIATION: {
1748 struct usb_interface_assoc_descriptor *ds = (void *)_ds;
1749 pr_vdebug("interface association descriptor\n");
1750 if (length != sizeof *ds)
1751 goto inv_length;
1752 if (ds->iFunction)
1753 __entity(STRING, ds->iFunction);
1754 }
1755 break;
1756
1757 case USB_DT_SS_ENDPOINT_COMP:
1758 pr_vdebug("EP SS companion descriptor\n");
1759 if (length != sizeof(struct usb_ss_ep_comp_descriptor))
1760 goto inv_length;
1761 break;
1762
1763 case USB_DT_OTHER_SPEED_CONFIG:
1764 case USB_DT_INTERFACE_POWER:
1765 case USB_DT_DEBUG:
1766 case USB_DT_SECURITY:
1767 case USB_DT_CS_RADIO_CONTROL:
1768 /* TODO */
1769 pr_vdebug("unimplemented descriptor: %d\n", _ds->bDescriptorType);
1770 return -EINVAL;
1771
1772 default:
1773 /* We should never be here */
1774 pr_vdebug("unknown descriptor: %d\n", _ds->bDescriptorType);
1775 return -EINVAL;
1776
1777inv_length:
1778 pr_vdebug("invalid length: %d (descriptor %d)\n",
1779 _ds->bLength, _ds->bDescriptorType);
1780 return -EINVAL;
1781 }
1782
1783#undef __entity
1784#undef __entity_check_DESCRIPTOR
1785#undef __entity_check_INTERFACE
1786#undef __entity_check_STRING
1787#undef __entity_check_ENDPOINT
1788
1789 return length;
1790}
1791
1792static int __must_check ffs_do_descs(unsigned count, char *data, unsigned len,
1793 ffs_entity_callback entity, void *priv)
1794{
1795 const unsigned _len = len;
1796 unsigned long num = 0;
1797
1798 ENTER();
1799
1800 for (;;) {
1801 int ret;
1802
1803 if (num == count)
1804 data = NULL;
1805
1806 /* Record "descriptor" entity */
1807 ret = entity(FFS_DESCRIPTOR, (u8 *)num, (void *)data, priv);
1808 if (unlikely(ret < 0)) {
1809 pr_debug("entity DESCRIPTOR(%02lx); ret = %d\n",
1810 num, ret);
1811 return ret;
1812 }
1813
1814 if (!data)
1815 return _len - len;
1816
1817 ret = ffs_do_single_desc(data, len, entity, priv);
1818 if (unlikely(ret < 0)) {
1819 pr_debug("%s returns %d\n", __func__, ret);
1820 return ret;
1821 }
1822
1823 len -= ret;
1824 data += ret;
1825 ++num;
1826 }
1827}
1828
1829static int __ffs_data_do_entity(enum ffs_entity_type type,
1830 u8 *valuep, struct usb_descriptor_header *desc,
1831 void *priv)
1832{
1833 struct ffs_data *ffs = priv;
1834
1835 ENTER();
1836
1837 switch (type) {
1838 case FFS_DESCRIPTOR:
1839 break;
1840
1841 case FFS_INTERFACE:
1842 /*
1843 * Interfaces are indexed from zero so if we
1844 * encountered interface "n" then there are at least
1845 * "n+1" interfaces.
1846 */
1847 if (*valuep >= ffs->interfaces_count)
1848 ffs->interfaces_count = *valuep + 1;
1849 break;
1850
1851 case FFS_STRING:
1852 /*
1853 * Strings are indexed from 1 (0 is magic ;) reserved
1854 * for languages list or some such)
1855 */
1856 if (*valuep > ffs->strings_count)
1857 ffs->strings_count = *valuep;
1858 break;
1859
1860 case FFS_ENDPOINT:
1861 /* Endpoints are indexed from 1 as well. */
1862 if ((*valuep & USB_ENDPOINT_NUMBER_MASK) > ffs->eps_count)
1863 ffs->eps_count = (*valuep & USB_ENDPOINT_NUMBER_MASK);
1864 break;
1865 }
1866
1867 return 0;
1868}
1869
1870static int __ffs_do_os_desc_header(enum ffs_os_desc_type *next_type,
1871 struct usb_os_desc_header *desc)
1872{
1873 u16 bcd_version = le16_to_cpu(desc->bcdVersion);
1874 u16 w_index = le16_to_cpu(desc->wIndex);
1875
1876 if (bcd_version != 1) {
1877 pr_vdebug("unsupported os descriptors version: %d",
1878 bcd_version);
1879 return -EINVAL;
1880 }
1881 switch (w_index) {
1882 case 0x4:
1883 *next_type = FFS_OS_DESC_EXT_COMPAT;
1884 break;
1885 case 0x5:
1886 *next_type = FFS_OS_DESC_EXT_PROP;
1887 break;
1888 default:
1889 pr_vdebug("unsupported os descriptor type: %d", w_index);
1890 return -EINVAL;
1891 }
1892
1893 return sizeof(*desc);
1894}
1895
1896/*
1897 * Process all extended compatibility/extended property descriptors
1898 * of a feature descriptor
1899 */
1900static int __must_check ffs_do_single_os_desc(char *data, unsigned len,
1901 enum ffs_os_desc_type type,
1902 u16 feature_count,
1903 ffs_os_desc_callback entity,
1904 void *priv,
1905 struct usb_os_desc_header *h)
1906{
1907 int ret;
1908 const unsigned _len = len;
1909
1910 ENTER();
1911
1912 /* loop over all ext compat/ext prop descriptors */
1913 while (feature_count--) {
1914 ret = entity(type, h, data, len, priv);
1915 if (unlikely(ret < 0)) {
1916 pr_debug("bad OS descriptor, type: %d\n", type);
1917 return ret;
1918 }
1919 data += ret;
1920 len -= ret;
1921 }
1922 return _len - len;
1923}
1924
1925/* Process a number of complete Feature Descriptors (Ext Compat or Ext Prop) */
1926static int __must_check ffs_do_os_descs(unsigned count,
1927 char *data, unsigned len,
1928 ffs_os_desc_callback entity, void *priv)
1929{
1930 const unsigned _len = len;
1931 unsigned long num = 0;
1932
1933 ENTER();
1934
1935 for (num = 0; num < count; ++num) {
1936 int ret;
1937 enum ffs_os_desc_type type;
1938 u16 feature_count;
1939 struct usb_os_desc_header *desc = (void *)data;
1940
1941 if (len < sizeof(*desc))
1942 return -EINVAL;
1943
1944 /*
1945 * Record "descriptor" entity.
1946 * Process dwLength, bcdVersion, wIndex, get b/wCount.
1947 * Move the data pointer to the beginning of extended
1948 * compatibilities proper or extended properties proper
1949 * portions of the data
1950 */
1951 if (le32_to_cpu(desc->dwLength) > len)
1952 return -EINVAL;
1953
1954 ret = __ffs_do_os_desc_header(&type, desc);
1955 if (unlikely(ret < 0)) {
1956 pr_debug("entity OS_DESCRIPTOR(%02lx); ret = %d\n",
1957 num, ret);
1958 return ret;
1959 }
1960 /*
1961 * 16-bit hex "?? 00" Little Endian looks like 8-bit hex "??"
1962 */
1963 feature_count = le16_to_cpu(desc->wCount);
1964 if (type == FFS_OS_DESC_EXT_COMPAT &&
1965 (feature_count > 255 || desc->Reserved))
1966 return -EINVAL;
1967 len -= ret;
1968 data += ret;
1969
1970 /*
1971 * Process all function/property descriptors
1972 * of this Feature Descriptor
1973 */
1974 ret = ffs_do_single_os_desc(data, len, type,
1975 feature_count, entity, priv, desc);
1976 if (unlikely(ret < 0)) {
1977 pr_debug("%s returns %d\n", __func__, ret);
1978 return ret;
1979 }
1980
1981 len -= ret;
1982 data += ret;
1983 }
1984 return _len - len;
1985}
1986
1987/**
1988 * Validate contents of the buffer from userspace related to OS descriptors.
1989 */
1990static int __ffs_data_do_os_desc(enum ffs_os_desc_type type,
1991 struct usb_os_desc_header *h, void *data,
1992 unsigned len, void *priv)
1993{
1994 struct ffs_data *ffs = priv;
1995 u8 length;
1996
1997 ENTER();
1998
1999 switch (type) {
2000 case FFS_OS_DESC_EXT_COMPAT: {
2001 struct usb_ext_compat_desc *d = data;
2002 int i;
2003
2004 if (len < sizeof(*d) ||
2005 d->bFirstInterfaceNumber >= ffs->interfaces_count ||
2006 d->Reserved1)
2007 return -EINVAL;
2008 for (i = 0; i < ARRAY_SIZE(d->Reserved2); ++i)
2009 if (d->Reserved2[i])
2010 return -EINVAL;
2011
2012 length = sizeof(struct usb_ext_compat_desc);
2013 }
2014 break;
2015 case FFS_OS_DESC_EXT_PROP: {
2016 struct usb_ext_prop_desc *d = data;
2017 u32 type, pdl;
2018 u16 pnl;
2019
2020 if (len < sizeof(*d) || h->interface >= ffs->interfaces_count)
2021 return -EINVAL;
2022 length = le32_to_cpu(d->dwSize);
2023 type = le32_to_cpu(d->dwPropertyDataType);
2024 if (type < USB_EXT_PROP_UNICODE ||
2025 type > USB_EXT_PROP_UNICODE_MULTI) {
2026 pr_vdebug("unsupported os descriptor property type: %d",
2027 type);
2028 return -EINVAL;
2029 }
2030 pnl = le16_to_cpu(d->wPropertyNameLength);
2031 pdl = le32_to_cpu(*(u32 *)((u8 *)data + 10 + pnl));
2032 if (length != 14 + pnl + pdl) {
2033 pr_vdebug("invalid os descriptor length: %d pnl:%d pdl:%d (descriptor %d)\n",
2034 length, pnl, pdl, type);
2035 return -EINVAL;
2036 }
2037 ++ffs->ms_os_descs_ext_prop_count;
2038 /* property name reported to the host as "WCHAR"s */
2039 ffs->ms_os_descs_ext_prop_name_len += pnl * 2;
2040 ffs->ms_os_descs_ext_prop_data_len += pdl;
2041 }
2042 break;
2043 default:
2044 pr_vdebug("unknown descriptor: %d\n", type);
2045 return -EINVAL;
2046 }
2047 return length;
2048}
2049
2050static int __ffs_data_got_descs(struct ffs_data *ffs,
2051 char *const _data, size_t len)
2052{
2053 char *data = _data, *raw_descs;
2054 unsigned os_descs_count = 0, counts[3], flags;
2055 int ret = -EINVAL, i;
2056
2057 ENTER();
2058
2059 if (get_unaligned_le32(data + 4) != len)
2060 goto error;
2061
2062 switch (get_unaligned_le32(data)) {
2063 case FUNCTIONFS_DESCRIPTORS_MAGIC:
2064 flags = FUNCTIONFS_HAS_FS_DESC | FUNCTIONFS_HAS_HS_DESC;
2065 data += 8;
2066 len -= 8;
2067 break;
2068 case FUNCTIONFS_DESCRIPTORS_MAGIC_V2:
2069 flags = get_unaligned_le32(data + 8);
2070 if (flags & ~(FUNCTIONFS_HAS_FS_DESC |
2071 FUNCTIONFS_HAS_HS_DESC |
2072 FUNCTIONFS_HAS_SS_DESC |
2073 FUNCTIONFS_HAS_MS_OS_DESC)) {
2074 ret = -ENOSYS;
2075 goto error;
2076 }
2077 data += 12;
2078 len -= 12;
2079 break;
2080 default:
2081 goto error;
2082 }
2083
2084 /* Read fs_count, hs_count and ss_count (if present) */
2085 for (i = 0; i < 3; ++i) {
2086 if (!(flags & (1 << i))) {
2087 counts[i] = 0;
2088 } else if (len < 4) {
2089 goto error;
2090 } else {
2091 counts[i] = get_unaligned_le32(data);
2092 data += 4;
2093 len -= 4;
2094 }
2095 }
2096 if (flags & (1 << i)) {
2097 os_descs_count = get_unaligned_le32(data);
2098 data += 4;
2099 len -= 4;
2100 };
2101
2102 /* Read descriptors */
2103 raw_descs = data;
2104 for (i = 0; i < 3; ++i) {
2105 if (!counts[i])
2106 continue;
2107 ret = ffs_do_descs(counts[i], data, len,
2108 __ffs_data_do_entity, ffs);
2109 if (ret < 0)
2110 goto error;
2111 data += ret;
2112 len -= ret;
2113 }
2114 if (os_descs_count) {
2115 ret = ffs_do_os_descs(os_descs_count, data, len,
2116 __ffs_data_do_os_desc, ffs);
2117 if (ret < 0)
2118 goto error;
2119 data += ret;
2120 len -= ret;
2121 }
2122
2123 if (raw_descs == data || len) {
2124 ret = -EINVAL;
2125 goto error;
2126 }
2127
2128 ffs->raw_descs_data = _data;
2129 ffs->raw_descs = raw_descs;
2130 ffs->raw_descs_length = data - raw_descs;
2131 ffs->fs_descs_count = counts[0];
2132 ffs->hs_descs_count = counts[1];
2133 ffs->ss_descs_count = counts[2];
2134 ffs->ms_os_descs_count = os_descs_count;
2135
2136 return 0;
2137
2138error:
2139 kfree(_data);
2140 return ret;
2141}
2142
2143static int __ffs_data_got_strings(struct ffs_data *ffs,
2144 char *const _data, size_t len)
2145{
2146 u32 str_count, needed_count, lang_count;
2147 struct usb_gadget_strings **stringtabs, *t;
2148 struct usb_string *strings, *s;
2149 const char *data = _data;
2150
2151 ENTER();
2152
2153 if (unlikely(get_unaligned_le32(data) != FUNCTIONFS_STRINGS_MAGIC ||
2154 get_unaligned_le32(data + 4) != len))
2155 goto error;
2156 str_count = get_unaligned_le32(data + 8);
2157 lang_count = get_unaligned_le32(data + 12);
2158
2159 /* if one is zero the other must be zero */
2160 if (unlikely(!str_count != !lang_count))
2161 goto error;
2162
2163 /* Do we have at least as many strings as descriptors need? */
2164 needed_count = ffs->strings_count;
2165 if (unlikely(str_count < needed_count))
2166 goto error;
2167
2168 /*
2169 * If we don't need any strings just return and free all
2170 * memory.
2171 */
2172 if (!needed_count) {
2173 kfree(_data);
2174 return 0;
2175 }
2176
2177 /* Allocate everything in one chunk so there's less maintenance. */
2178 {
2179 unsigned i = 0;
2180 vla_group(d);
2181 vla_item(d, struct usb_gadget_strings *, stringtabs,
2182 lang_count + 1);
2183 vla_item(d, struct usb_gadget_strings, stringtab, lang_count);
2184 vla_item(d, struct usb_string, strings,
2185 lang_count*(needed_count+1));
2186
2187 char *vlabuf = kmalloc(vla_group_size(d), GFP_KERNEL);
2188
2189 if (unlikely(!vlabuf)) {
2190 kfree(_data);
2191 return -ENOMEM;
2192 }
2193
2194 /* Initialize the VLA pointers */
2195 stringtabs = vla_ptr(vlabuf, d, stringtabs);
2196 t = vla_ptr(vlabuf, d, stringtab);
2197 i = lang_count;
2198 do {
2199 *stringtabs++ = t++;
2200 } while (--i);
2201 *stringtabs = NULL;
2202
2203 /* stringtabs = vlabuf = d_stringtabs for later kfree */
2204 stringtabs = vla_ptr(vlabuf, d, stringtabs);
2205 t = vla_ptr(vlabuf, d, stringtab);
2206 s = vla_ptr(vlabuf, d, strings);
2207 strings = s;
2208 }
2209
2210 /* For each language */
2211 data += 16;
2212 len -= 16;
2213
2214 do { /* lang_count > 0 so we can use do-while */
2215 unsigned needed = needed_count;
2216
2217 if (unlikely(len < 3))
2218 goto error_free;
2219 t->language = get_unaligned_le16(data);
2220 t->strings = s;
2221 ++t;
2222
2223 data += 2;
2224 len -= 2;
2225
2226 /* For each string */
2227 do { /* str_count > 0 so we can use do-while */
2228 size_t length = strnlen(data, len);
2229
2230 if (unlikely(length == len))
2231 goto error_free;
2232
2233 /*
2234 * User may provide more strings then we need,
2235 * if that's the case we simply ignore the
2236 * rest
2237 */
2238 if (likely(needed)) {
2239 /*
2240 * s->id will be set while adding
2241 * function to configuration so for
2242 * now just leave garbage here.
2243 */
2244 s->s = data;
2245 --needed;
2246 ++s;
2247 }
2248
2249 data += length + 1;
2250 len -= length + 1;
2251 } while (--str_count);
2252
2253 s->id = 0; /* terminator */
2254 s->s = NULL;
2255 ++s;
2256
2257 } while (--lang_count);
2258
2259 /* Some garbage left? */
2260 if (unlikely(len))
2261 goto error_free;
2262
2263 /* Done! */
2264 ffs->stringtabs = stringtabs;
2265 ffs->raw_strings = _data;
2266
2267 return 0;
2268
2269error_free:
2270 kfree(stringtabs);
2271error:
2272 kfree(_data);
2273 return -EINVAL;
2274}
2275
2276
2277/* Events handling and management *******************************************/
2278
2279static void __ffs_event_add(struct ffs_data *ffs,
2280 enum usb_functionfs_event_type type)
2281{
2282 enum usb_functionfs_event_type rem_type1, rem_type2 = type;
2283 int neg = 0;
2284
2285 /*
2286 * Abort any unhandled setup
2287 *
2288 * We do not need to worry about some cmpxchg() changing value
2289 * of ffs->setup_state without holding the lock because when
2290 * state is FFS_SETUP_PENDING cmpxchg() in several places in
2291 * the source does nothing.
2292 */
2293 if (ffs->setup_state == FFS_SETUP_PENDING)
2294 ffs->setup_state = FFS_SETUP_CANCELLED;
2295
2296 switch (type) {
2297 case FUNCTIONFS_RESUME:
2298 rem_type2 = FUNCTIONFS_SUSPEND;
2299 /* FALL THROUGH */
2300 case FUNCTIONFS_SUSPEND:
2301 case FUNCTIONFS_SETUP:
2302 rem_type1 = type;
2303 /* Discard all similar events */
2304 break;
2305
2306 case FUNCTIONFS_BIND:
2307 case FUNCTIONFS_UNBIND:
2308 case FUNCTIONFS_DISABLE:
2309 case FUNCTIONFS_ENABLE:
2310 /* Discard everything other then power management. */
2311 rem_type1 = FUNCTIONFS_SUSPEND;
2312 rem_type2 = FUNCTIONFS_RESUME;
2313 neg = 1;
2314 break;
2315
2316 default:
2317 BUG();
2318 }
2319
2320 {
2321 u8 *ev = ffs->ev.types, *out = ev;
2322 unsigned n = ffs->ev.count;
2323 for (; n; --n, ++ev)
2324 if ((*ev == rem_type1 || *ev == rem_type2) == neg)
2325 *out++ = *ev;
2326 else
2327 pr_vdebug("purging event %d\n", *ev);
2328 ffs->ev.count = out - ffs->ev.types;
2329 }
2330
2331 pr_vdebug("adding event %d\n", type);
2332 ffs->ev.types[ffs->ev.count++] = type;
2333 wake_up_locked(&ffs->ev.waitq);
2334}
2335
2336static void ffs_event_add(struct ffs_data *ffs,
2337 enum usb_functionfs_event_type type)
2338{
2339 unsigned long flags;
2340 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2341 __ffs_event_add(ffs, type);
2342 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2343}
2344
2345
2346/* Bind/unbind USB function hooks *******************************************/
2347
2348static int __ffs_func_bind_do_descs(enum ffs_entity_type type, u8 *valuep,
2349 struct usb_descriptor_header *desc,
2350 void *priv)
2351{
2352 struct usb_endpoint_descriptor *ds = (void *)desc;
2353 struct ffs_function *func = priv;
2354 struct ffs_ep *ffs_ep;
2355 unsigned ep_desc_id, idx;
2356 static const char *speed_names[] = { "full", "high", "super" };
2357
2358 if (type != FFS_DESCRIPTOR)
2359 return 0;
2360
2361 /*
2362 * If ss_descriptors is not NULL, we are reading super speed
2363 * descriptors; if hs_descriptors is not NULL, we are reading high
2364 * speed descriptors; otherwise, we are reading full speed
2365 * descriptors.
2366 */
2367 if (func->function.ss_descriptors) {
2368 ep_desc_id = 2;
2369 func->function.ss_descriptors[(long)valuep] = desc;
2370 } else if (func->function.hs_descriptors) {
2371 ep_desc_id = 1;
2372 func->function.hs_descriptors[(long)valuep] = desc;
2373 } else {
2374 ep_desc_id = 0;
2375 func->function.fs_descriptors[(long)valuep] = desc;
2376 }
2377
2378 if (!desc || desc->bDescriptorType != USB_DT_ENDPOINT)
2379 return 0;
2380
2381 idx = (ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK) - 1;
2382 ffs_ep = func->eps + idx;
2383
2384 if (unlikely(ffs_ep->descs[ep_desc_id])) {
2385 pr_err("two %sspeed descriptors for EP %d\n",
2386 speed_names[ep_desc_id],
2387 ds->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
2388 return -EINVAL;
2389 }
2390 ffs_ep->descs[ep_desc_id] = ds;
2391
2392 ffs_dump_mem(": Original ep desc", ds, ds->bLength);
2393 if (ffs_ep->ep) {
2394 ds->bEndpointAddress = ffs_ep->descs[0]->bEndpointAddress;
2395 if (!ds->wMaxPacketSize)
2396 ds->wMaxPacketSize = ffs_ep->descs[0]->wMaxPacketSize;
2397 } else {
2398 struct usb_request *req;
2399 struct usb_ep *ep;
2400
2401 pr_vdebug("autoconfig\n");
2402 ep = usb_ep_autoconfig(func->gadget, ds);
2403 if (unlikely(!ep))
2404 return -ENOTSUPP;
2405 ep->driver_data = func->eps + idx;
2406
2407 req = usb_ep_alloc_request(ep, GFP_KERNEL);
2408 if (unlikely(!req))
2409 return -ENOMEM;
2410
2411 ffs_ep->ep = ep;
2412 ffs_ep->req = req;
2413 func->eps_revmap[ds->bEndpointAddress &
2414 USB_ENDPOINT_NUMBER_MASK] = idx + 1;
2415 }
2416 ffs_dump_mem(": Rewritten ep desc", ds, ds->bLength);
2417
2418 return 0;
2419}
2420
2421static int __ffs_func_bind_do_nums(enum ffs_entity_type type, u8 *valuep,
2422 struct usb_descriptor_header *desc,
2423 void *priv)
2424{
2425 struct ffs_function *func = priv;
2426 unsigned idx;
2427 u8 newValue;
2428
2429 switch (type) {
2430 default:
2431 case FFS_DESCRIPTOR:
2432 /* Handled in previous pass by __ffs_func_bind_do_descs() */
2433 return 0;
2434
2435 case FFS_INTERFACE:
2436 idx = *valuep;
2437 if (func->interfaces_nums[idx] < 0) {
2438 int id = usb_interface_id(func->conf, &func->function);
2439 if (unlikely(id < 0))
2440 return id;
2441 func->interfaces_nums[idx] = id;
2442 }
2443 newValue = func->interfaces_nums[idx];
2444 break;
2445
2446 case FFS_STRING:
2447 /* String' IDs are allocated when fsf_data is bound to cdev */
2448 newValue = func->ffs->stringtabs[0]->strings[*valuep - 1].id;
2449 break;
2450
2451 case FFS_ENDPOINT:
2452 /*
2453 * USB_DT_ENDPOINT are handled in
2454 * __ffs_func_bind_do_descs().
2455 */
2456 if (desc->bDescriptorType == USB_DT_ENDPOINT)
2457 return 0;
2458
2459 idx = (*valuep & USB_ENDPOINT_NUMBER_MASK) - 1;
2460 if (unlikely(!func->eps[idx].ep))
2461 return -EINVAL;
2462
2463 {
2464 struct usb_endpoint_descriptor **descs;
2465 descs = func->eps[idx].descs;
2466 newValue = descs[descs[0] ? 0 : 1]->bEndpointAddress;
2467 }
2468 break;
2469 }
2470
2471 pr_vdebug("%02x -> %02x\n", *valuep, newValue);
2472 *valuep = newValue;
2473 return 0;
2474}
2475
2476static int __ffs_func_bind_do_os_desc(enum ffs_os_desc_type type,
2477 struct usb_os_desc_header *h, void *data,
2478 unsigned len, void *priv)
2479{
2480 struct ffs_function *func = priv;
2481 u8 length = 0;
2482
2483 switch (type) {
2484 case FFS_OS_DESC_EXT_COMPAT: {
2485 struct usb_ext_compat_desc *desc = data;
2486 struct usb_os_desc_table *t;
2487
2488 t = &func->function.os_desc_table[desc->bFirstInterfaceNumber];
2489 t->if_id = func->interfaces_nums[desc->bFirstInterfaceNumber];
2490 memcpy(t->os_desc->ext_compat_id, &desc->CompatibleID,
2491 ARRAY_SIZE(desc->CompatibleID) +
2492 ARRAY_SIZE(desc->SubCompatibleID));
2493 length = sizeof(*desc);
2494 }
2495 break;
2496 case FFS_OS_DESC_EXT_PROP: {
2497 struct usb_ext_prop_desc *desc = data;
2498 struct usb_os_desc_table *t;
2499 struct usb_os_desc_ext_prop *ext_prop;
2500 char *ext_prop_name;
2501 char *ext_prop_data;
2502
2503 t = &func->function.os_desc_table[h->interface];
2504 t->if_id = func->interfaces_nums[h->interface];
2505
2506 ext_prop = func->ffs->ms_os_descs_ext_prop_avail;
2507 func->ffs->ms_os_descs_ext_prop_avail += sizeof(*ext_prop);
2508
2509 ext_prop->type = le32_to_cpu(desc->dwPropertyDataType);
2510 ext_prop->name_len = le16_to_cpu(desc->wPropertyNameLength);
2511 ext_prop->data_len = le32_to_cpu(*(u32 *)
2512 usb_ext_prop_data_len_ptr(data, ext_prop->name_len));
2513 length = ext_prop->name_len + ext_prop->data_len + 14;
2514
2515 ext_prop_name = func->ffs->ms_os_descs_ext_prop_name_avail;
2516 func->ffs->ms_os_descs_ext_prop_name_avail +=
2517 ext_prop->name_len;
2518
2519 ext_prop_data = func->ffs->ms_os_descs_ext_prop_data_avail;
2520 func->ffs->ms_os_descs_ext_prop_data_avail +=
2521 ext_prop->data_len;
2522 memcpy(ext_prop_data,
2523 usb_ext_prop_data_ptr(data, ext_prop->name_len),
2524 ext_prop->data_len);
2525 /* unicode data reported to the host as "WCHAR"s */
2526 switch (ext_prop->type) {
2527 case USB_EXT_PROP_UNICODE:
2528 case USB_EXT_PROP_UNICODE_ENV:
2529 case USB_EXT_PROP_UNICODE_LINK:
2530 case USB_EXT_PROP_UNICODE_MULTI:
2531 ext_prop->data_len *= 2;
2532 break;
2533 }
2534 ext_prop->data = ext_prop_data;
2535
2536 memcpy(ext_prop_name, usb_ext_prop_name_ptr(data),
2537 ext_prop->name_len);
2538 /* property name reported to the host as "WCHAR"s */
2539 ext_prop->name_len *= 2;
2540 ext_prop->name = ext_prop_name;
2541
2542 t->os_desc->ext_prop_len +=
2543 ext_prop->name_len + ext_prop->data_len + 14;
2544 ++t->os_desc->ext_prop_count;
2545 list_add_tail(&ext_prop->entry, &t->os_desc->ext_prop);
2546 }
2547 break;
2548 default:
2549 pr_vdebug("unknown descriptor: %d\n", type);
2550 }
2551
2552 return length;
2553}
2554
2555static inline struct f_fs_opts *ffs_do_functionfs_bind(struct usb_function *f,
2556 struct usb_configuration *c)
2557{
2558 struct ffs_function *func = ffs_func_from_usb(f);
2559 struct f_fs_opts *ffs_opts =
2560 container_of(f->fi, struct f_fs_opts, func_inst);
2561 int ret;
2562
2563 ENTER();
2564
2565 /*
2566 * Legacy gadget triggers binding in functionfs_ready_callback,
2567 * which already uses locking; taking the same lock here would
2568 * cause a deadlock.
2569 *
2570 * Configfs-enabled gadgets however do need ffs_dev_lock.
2571 */
2572 if (!ffs_opts->no_configfs)
2573 ffs_dev_lock();
2574 ret = ffs_opts->dev->desc_ready ? 0 : -ENODEV;
2575 func->ffs = ffs_opts->dev->ffs_data;
2576 if (!ffs_opts->no_configfs)
2577 ffs_dev_unlock();
2578 if (ret)
2579 return ERR_PTR(ret);
2580
2581 func->conf = c;
2582 func->gadget = c->cdev->gadget;
2583
2584 ffs_data_get(func->ffs);
2585
2586 /*
2587 * in drivers/usb/gadget/configfs.c:configfs_composite_bind()
2588 * configurations are bound in sequence with list_for_each_entry,
2589 * in each configuration its functions are bound in sequence
2590 * with list_for_each_entry, so we assume no race condition
2591 * with regard to ffs_opts->bound access
2592 */
2593 if (!ffs_opts->refcnt) {
2594 ret = functionfs_bind(func->ffs, c->cdev);
2595 if (ret)
2596 return ERR_PTR(ret);
2597 }
2598 ffs_opts->refcnt++;
2599 func->function.strings = func->ffs->stringtabs;
2600
2601 return ffs_opts;
2602}
2603
2604static int _ffs_func_bind(struct usb_configuration *c,
2605 struct usb_function *f)
2606{
2607 struct ffs_function *func = ffs_func_from_usb(f);
2608 struct ffs_data *ffs = func->ffs;
2609
2610 const int full = !!func->ffs->fs_descs_count;
2611 const int high = gadget_is_dualspeed(func->gadget) &&
2612 func->ffs->hs_descs_count;
2613 const int super = gadget_is_superspeed(func->gadget) &&
2614 func->ffs->ss_descs_count;
2615
2616 int fs_len, hs_len, ss_len, ret, i;
2617
2618 /* Make it a single chunk, less management later on */
2619 vla_group(d);
2620 vla_item_with_sz(d, struct ffs_ep, eps, ffs->eps_count);
2621 vla_item_with_sz(d, struct usb_descriptor_header *, fs_descs,
2622 full ? ffs->fs_descs_count + 1 : 0);
2623 vla_item_with_sz(d, struct usb_descriptor_header *, hs_descs,
2624 high ? ffs->hs_descs_count + 1 : 0);
2625 vla_item_with_sz(d, struct usb_descriptor_header *, ss_descs,
2626 super ? ffs->ss_descs_count + 1 : 0);
2627 vla_item_with_sz(d, short, inums, ffs->interfaces_count);
2628 vla_item_with_sz(d, struct usb_os_desc_table, os_desc_table,
2629 c->cdev->use_os_string ? ffs->interfaces_count : 0);
2630 vla_item_with_sz(d, char[16], ext_compat,
2631 c->cdev->use_os_string ? ffs->interfaces_count : 0);
2632 vla_item_with_sz(d, struct usb_os_desc, os_desc,
2633 c->cdev->use_os_string ? ffs->interfaces_count : 0);
2634 vla_item_with_sz(d, struct usb_os_desc_ext_prop, ext_prop,
2635 ffs->ms_os_descs_ext_prop_count);
2636 vla_item_with_sz(d, char, ext_prop_name,
2637 ffs->ms_os_descs_ext_prop_name_len);
2638 vla_item_with_sz(d, char, ext_prop_data,
2639 ffs->ms_os_descs_ext_prop_data_len);
2640 vla_item_with_sz(d, char, raw_descs, ffs->raw_descs_length);
2641 char *vlabuf;
2642
2643 ENTER();
2644
2645 /* Has descriptors only for speeds gadget does not support */
2646 if (unlikely(!(full | high | super)))
2647 return -ENOTSUPP;
2648
2649 /* Allocate a single chunk, less management later on */
2650 vlabuf = kzalloc(vla_group_size(d), GFP_KERNEL);
2651 if (unlikely(!vlabuf))
2652 return -ENOMEM;
2653
2654 ffs->ms_os_descs_ext_prop_avail = vla_ptr(vlabuf, d, ext_prop);
2655 ffs->ms_os_descs_ext_prop_name_avail =
2656 vla_ptr(vlabuf, d, ext_prop_name);
2657 ffs->ms_os_descs_ext_prop_data_avail =
2658 vla_ptr(vlabuf, d, ext_prop_data);
2659
2660 /* Copy descriptors */
2661 memcpy(vla_ptr(vlabuf, d, raw_descs), ffs->raw_descs,
2662 ffs->raw_descs_length);
2663
2664 memset(vla_ptr(vlabuf, d, inums), 0xff, d_inums__sz);
2665 for (ret = ffs->eps_count; ret; --ret) {
2666 struct ffs_ep *ptr;
2667
2668 ptr = vla_ptr(vlabuf, d, eps);
2669 ptr[ret].num = -1;
2670 }
2671
2672 /* Save pointers
2673 * d_eps == vlabuf, func->eps used to kfree vlabuf later
2674 */
2675 func->eps = vla_ptr(vlabuf, d, eps);
2676 func->interfaces_nums = vla_ptr(vlabuf, d, inums);
2677
2678 /*
2679 * Go through all the endpoint descriptors and allocate
2680 * endpoints first, so that later we can rewrite the endpoint
2681 * numbers without worrying that it may be described later on.
2682 */
2683 if (likely(full)) {
2684 func->function.fs_descriptors = vla_ptr(vlabuf, d, fs_descs);
2685 fs_len = ffs_do_descs(ffs->fs_descs_count,
2686 vla_ptr(vlabuf, d, raw_descs),
2687 d_raw_descs__sz,
2688 __ffs_func_bind_do_descs, func);
2689 if (unlikely(fs_len < 0)) {
2690 ret = fs_len;
2691 goto error;
2692 }
2693 } else {
2694 fs_len = 0;
2695 }
2696
2697 if (likely(high)) {
2698 func->function.hs_descriptors = vla_ptr(vlabuf, d, hs_descs);
2699 hs_len = ffs_do_descs(ffs->hs_descs_count,
2700 vla_ptr(vlabuf, d, raw_descs) + fs_len,
2701 d_raw_descs__sz - fs_len,
2702 __ffs_func_bind_do_descs, func);
2703 if (unlikely(hs_len < 0)) {
2704 ret = hs_len;
2705 goto error;
2706 }
2707 } else {
2708 hs_len = 0;
2709 }
2710
2711 if (likely(super)) {
2712 func->function.ss_descriptors = vla_ptr(vlabuf, d, ss_descs);
2713 ss_len = ffs_do_descs(ffs->ss_descs_count,
2714 vla_ptr(vlabuf, d, raw_descs) + fs_len + hs_len,
2715 d_raw_descs__sz - fs_len - hs_len,
2716 __ffs_func_bind_do_descs, func);
2717 if (unlikely(ss_len < 0)) {
2718 ret = ss_len;
2719 goto error;
2720 }
2721 } else {
2722 ss_len = 0;
2723 }
2724
2725 /*
2726 * Now handle interface numbers allocation and interface and
2727 * endpoint numbers rewriting. We can do that in one go
2728 * now.
2729 */
2730 ret = ffs_do_descs(ffs->fs_descs_count +
2731 (high ? ffs->hs_descs_count : 0) +
2732 (super ? ffs->ss_descs_count : 0),
2733 vla_ptr(vlabuf, d, raw_descs), d_raw_descs__sz,
2734 __ffs_func_bind_do_nums, func);
2735 if (unlikely(ret < 0))
2736 goto error;
2737
2738 func->function.os_desc_table = vla_ptr(vlabuf, d, os_desc_table);
2739 if (c->cdev->use_os_string)
2740 for (i = 0; i < ffs->interfaces_count; ++i) {
2741 struct usb_os_desc *desc;
2742
2743 desc = func->function.os_desc_table[i].os_desc =
2744 vla_ptr(vlabuf, d, os_desc) +
2745 i * sizeof(struct usb_os_desc);
2746 desc->ext_compat_id =
2747 vla_ptr(vlabuf, d, ext_compat) + i * 16;
2748 INIT_LIST_HEAD(&desc->ext_prop);
2749 }
2750 ret = ffs_do_os_descs(ffs->ms_os_descs_count,
2751 vla_ptr(vlabuf, d, raw_descs) +
2752 fs_len + hs_len + ss_len,
2753 d_raw_descs__sz - fs_len - hs_len - ss_len,
2754 __ffs_func_bind_do_os_desc, func);
2755 if (unlikely(ret < 0))
2756 goto error;
2757 func->function.os_desc_n =
2758 c->cdev->use_os_string ? ffs->interfaces_count : 0;
2759
2760 /* And we're done */
2761 ffs_event_add(ffs, FUNCTIONFS_BIND);
2762 return 0;
2763
2764error:
2765 /* XXX Do we need to release all claimed endpoints here? */
2766 return ret;
2767}
2768
2769static int ffs_func_bind(struct usb_configuration *c,
2770 struct usb_function *f)
2771{
2772 struct f_fs_opts *ffs_opts = ffs_do_functionfs_bind(f, c);
2773
2774 if (IS_ERR(ffs_opts))
2775 return PTR_ERR(ffs_opts);
2776
2777 return _ffs_func_bind(c, f);
2778}
2779
2780
2781/* Other USB function hooks *************************************************/
2782
2783static int ffs_func_set_alt(struct usb_function *f,
2784 unsigned interface, unsigned alt)
2785{
2786 struct ffs_function *func = ffs_func_from_usb(f);
2787 struct ffs_data *ffs = func->ffs;
2788 int ret = 0, intf;
2789
2790 if (alt != (unsigned)-1) {
2791 intf = ffs_func_revmap_intf(func, interface);
2792 if (unlikely(intf < 0))
2793 return intf;
2794 }
2795
2796 if (ffs->func)
2797 ffs_func_eps_disable(ffs->func);
2798
2799 if (ffs->state != FFS_ACTIVE)
2800 return -ENODEV;
2801
2802 if (alt == (unsigned)-1) {
2803 ffs->func = NULL;
2804 ffs_event_add(ffs, FUNCTIONFS_DISABLE);
2805 return 0;
2806 }
2807
2808 ffs->func = func;
2809 ret = ffs_func_eps_enable(func);
2810 if (likely(ret >= 0))
2811 ffs_event_add(ffs, FUNCTIONFS_ENABLE);
2812 return ret;
2813}
2814
2815static void ffs_func_disable(struct usb_function *f)
2816{
2817 ffs_func_set_alt(f, 0, (unsigned)-1);
2818}
2819
2820static int ffs_func_setup(struct usb_function *f,
2821 const struct usb_ctrlrequest *creq)
2822{
2823 struct ffs_function *func = ffs_func_from_usb(f);
2824 struct ffs_data *ffs = func->ffs;
2825 unsigned long flags;
2826 int ret;
2827
2828 ENTER();
2829
2830 pr_vdebug("creq->bRequestType = %02x\n", creq->bRequestType);
2831 pr_vdebug("creq->bRequest = %02x\n", creq->bRequest);
2832 pr_vdebug("creq->wValue = %04x\n", le16_to_cpu(creq->wValue));
2833 pr_vdebug("creq->wIndex = %04x\n", le16_to_cpu(creq->wIndex));
2834 pr_vdebug("creq->wLength = %04x\n", le16_to_cpu(creq->wLength));
2835
2836 /*
2837 * Most requests directed to interface go through here
2838 * (notable exceptions are set/get interface) so we need to
2839 * handle them. All other either handled by composite or
2840 * passed to usb_configuration->setup() (if one is set). No
2841 * matter, we will handle requests directed to endpoint here
2842 * as well (as it's straightforward) but what to do with any
2843 * other request?
2844 */
2845 if (ffs->state != FFS_ACTIVE)
2846 return -ENODEV;
2847
2848 switch (creq->bRequestType & USB_RECIP_MASK) {
2849 case USB_RECIP_INTERFACE:
2850 ret = ffs_func_revmap_intf(func, le16_to_cpu(creq->wIndex));
2851 if (unlikely(ret < 0))
2852 return ret;
2853 break;
2854
2855 case USB_RECIP_ENDPOINT:
2856 ret = ffs_func_revmap_ep(func, le16_to_cpu(creq->wIndex));
2857 if (unlikely(ret < 0))
2858 return ret;
2859 break;
2860
2861 default:
2862 return -EOPNOTSUPP;
2863 }
2864
2865 spin_lock_irqsave(&ffs->ev.waitq.lock, flags);
2866 ffs->ev.setup = *creq;
2867 ffs->ev.setup.wIndex = cpu_to_le16(ret);
2868 __ffs_event_add(ffs, FUNCTIONFS_SETUP);
2869 spin_unlock_irqrestore(&ffs->ev.waitq.lock, flags);
2870
2871 return 0;
2872}
2873
2874static void ffs_func_suspend(struct usb_function *f)
2875{
2876 ENTER();
2877 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_SUSPEND);
2878}
2879
2880static void ffs_func_resume(struct usb_function *f)
2881{
2882 ENTER();
2883 ffs_event_add(ffs_func_from_usb(f)->ffs, FUNCTIONFS_RESUME);
2884}
2885
2886
2887/* Endpoint and interface numbers reverse mapping ***************************/
2888
2889static int ffs_func_revmap_ep(struct ffs_function *func, u8 num)
2890{
2891 num = func->eps_revmap[num & USB_ENDPOINT_NUMBER_MASK];
2892 return num ? num : -EDOM;
2893}
2894
2895static int ffs_func_revmap_intf(struct ffs_function *func, u8 intf)
2896{
2897 short *nums = func->interfaces_nums;
2898 unsigned count = func->ffs->interfaces_count;
2899
2900 for (; count; --count, ++nums) {
2901 if (*nums >= 0 && *nums == intf)
2902 return nums - func->interfaces_nums;
2903 }
2904
2905 return -EDOM;
2906}
2907
2908
2909/* Devices management *******************************************************/
2910
2911static LIST_HEAD(ffs_devices);
2912
2913static struct ffs_dev *_ffs_do_find_dev(const char *name)
2914{
2915 struct ffs_dev *dev;
2916
2917 list_for_each_entry(dev, &ffs_devices, entry) {
2918 if (!dev->name || !name)
2919 continue;
2920 if (strcmp(dev->name, name) == 0)
2921 return dev;
2922 }
2923
2924 return NULL;
2925}
2926
2927/*
2928 * ffs_lock must be taken by the caller of this function
2929 */
2930static struct ffs_dev *_ffs_get_single_dev(void)
2931{
2932 struct ffs_dev *dev;
2933
2934 if (list_is_singular(&ffs_devices)) {
2935 dev = list_first_entry(&ffs_devices, struct ffs_dev, entry);
2936 if (dev->single)
2937 return dev;
2938 }
2939
2940 return NULL;
2941}
2942
2943/*
2944 * ffs_lock must be taken by the caller of this function
2945 */
2946static struct ffs_dev *_ffs_find_dev(const char *name)
2947{
2948 struct ffs_dev *dev;
2949
2950 dev = _ffs_get_single_dev();
2951 if (dev)
2952 return dev;
2953
2954 return _ffs_do_find_dev(name);
2955}
2956
2957/* Configfs support *********************************************************/
2958
2959static inline struct f_fs_opts *to_ffs_opts(struct config_item *item)
2960{
2961 return container_of(to_config_group(item), struct f_fs_opts,
2962 func_inst.group);
2963}
2964
2965static void ffs_attr_release(struct config_item *item)
2966{
2967 struct f_fs_opts *opts = to_ffs_opts(item);
2968
2969 usb_put_function_instance(&opts->func_inst);
2970}
2971
2972static struct configfs_item_operations ffs_item_ops = {
2973 .release = ffs_attr_release,
2974};
2975
2976static struct config_item_type ffs_func_type = {
2977 .ct_item_ops = &ffs_item_ops,
2978 .ct_owner = THIS_MODULE,
2979};
2980
2981
2982/* Function registration interface ******************************************/
2983
2984static void ffs_free_inst(struct usb_function_instance *f)
2985{
2986 struct f_fs_opts *opts;
2987
2988 opts = to_f_fs_opts(f);
2989 ffs_dev_lock();
2990 _ffs_free_dev(opts->dev);
2991 ffs_dev_unlock();
2992 kfree(opts);
2993}
2994
2995#define MAX_INST_NAME_LEN 40
2996
2997static int ffs_set_inst_name(struct usb_function_instance *fi, const char *name)
2998{
2999 struct f_fs_opts *opts;
3000 char *ptr;
3001 const char *tmp;
3002 int name_len, ret;
3003
3004 name_len = strlen(name) + 1;
3005 if (name_len > MAX_INST_NAME_LEN)
3006 return -ENAMETOOLONG;
3007
3008 ptr = kstrndup(name, name_len, GFP_KERNEL);
3009 if (!ptr)
3010 return -ENOMEM;
3011
3012 opts = to_f_fs_opts(fi);
3013 tmp = NULL;
3014
3015 ffs_dev_lock();
3016
3017 tmp = opts->dev->name_allocated ? opts->dev->name : NULL;
3018 ret = _ffs_name_dev(opts->dev, ptr);
3019 if (ret) {
3020 kfree(ptr);
3021 ffs_dev_unlock();
3022 return ret;
3023 }
3024 opts->dev->name_allocated = true;
3025
3026 ffs_dev_unlock();
3027
3028 kfree(tmp);
3029
3030 return 0;
3031}
3032
3033static struct usb_function_instance *ffs_alloc_inst(void)
3034{
3035 struct f_fs_opts *opts;
3036 struct ffs_dev *dev;
3037
3038 opts = kzalloc(sizeof(*opts), GFP_KERNEL);
3039 if (!opts)
3040 return ERR_PTR(-ENOMEM);
3041
3042 opts->func_inst.set_inst_name = ffs_set_inst_name;
3043 opts->func_inst.free_func_inst = ffs_free_inst;
3044 ffs_dev_lock();
3045 dev = _ffs_alloc_dev();
3046 ffs_dev_unlock();
3047 if (IS_ERR(dev)) {
3048 kfree(opts);
3049 return ERR_CAST(dev);
3050 }
3051 opts->dev = dev;
3052 dev->opts = opts;
3053
3054 config_group_init_type_name(&opts->func_inst.group, "",
3055 &ffs_func_type);
3056 return &opts->func_inst;
3057}
3058
3059static void ffs_free(struct usb_function *f)
3060{
3061 kfree(ffs_func_from_usb(f));
3062}
3063
3064static void ffs_func_unbind(struct usb_configuration *c,
3065 struct usb_function *f)
3066{
3067 struct ffs_function *func = ffs_func_from_usb(f);
3068 struct ffs_data *ffs = func->ffs;
3069 struct f_fs_opts *opts =
3070 container_of(f->fi, struct f_fs_opts, func_inst);
3071 struct ffs_ep *ep = func->eps;
3072 unsigned count = ffs->eps_count;
3073 unsigned long flags;
3074
3075 ENTER();
3076 if (ffs->func == func) {
3077 ffs_func_eps_disable(func);
3078 ffs->func = NULL;
3079 }
3080
3081 if (!--opts->refcnt)
3082 functionfs_unbind(ffs);
3083
3084 /* cleanup after autoconfig */
3085 spin_lock_irqsave(&func->ffs->eps_lock, flags);
3086 do {
3087 if (ep->ep && ep->req)
3088 usb_ep_free_request(ep->ep, ep->req);
3089 ep->req = NULL;
3090 ++ep;
3091 } while (--count);
3092 spin_unlock_irqrestore(&func->ffs->eps_lock, flags);
3093 kfree(func->eps);
3094 func->eps = NULL;
3095 /*
3096 * eps, descriptors and interfaces_nums are allocated in the
3097 * same chunk so only one free is required.
3098 */
3099 func->function.fs_descriptors = NULL;
3100 func->function.hs_descriptors = NULL;
3101 func->function.ss_descriptors = NULL;
3102 func->interfaces_nums = NULL;
3103
3104 ffs_event_add(ffs, FUNCTIONFS_UNBIND);
3105}
3106
3107static struct usb_function *ffs_alloc(struct usb_function_instance *fi)
3108{
3109 struct ffs_function *func;
3110
3111 ENTER();
3112
3113 func = kzalloc(sizeof(*func), GFP_KERNEL);
3114 if (unlikely(!func))
3115 return ERR_PTR(-ENOMEM);
3116
3117 func->function.name = "Function FS Gadget";
3118
3119 func->function.bind = ffs_func_bind;
3120 func->function.unbind = ffs_func_unbind;
3121 func->function.set_alt = ffs_func_set_alt;
3122 func->function.disable = ffs_func_disable;
3123 func->function.setup = ffs_func_setup;
3124 func->function.suspend = ffs_func_suspend;
3125 func->function.resume = ffs_func_resume;
3126 func->function.free_func = ffs_free;
3127
3128 return &func->function;
3129}
3130
3131/*
3132 * ffs_lock must be taken by the caller of this function
3133 */
3134static struct ffs_dev *_ffs_alloc_dev(void)
3135{
3136 struct ffs_dev *dev;
3137 int ret;
3138
3139 if (_ffs_get_single_dev())
3140 return ERR_PTR(-EBUSY);
3141
3142 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
3143 if (!dev)
3144 return ERR_PTR(-ENOMEM);
3145
3146 if (list_empty(&ffs_devices)) {
3147 ret = functionfs_init();
3148 if (ret) {
3149 kfree(dev);
3150 return ERR_PTR(ret);
3151 }
3152 }
3153
3154 list_add(&dev->entry, &ffs_devices);
3155
3156 return dev;
3157}
3158
3159/*
3160 * ffs_lock must be taken by the caller of this function
3161 * The caller is responsible for "name" being available whenever f_fs needs it
3162 */
3163static int _ffs_name_dev(struct ffs_dev *dev, const char *name)
3164{
3165 struct ffs_dev *existing;
3166
3167 existing = _ffs_do_find_dev(name);
3168 if (existing)
3169 return -EBUSY;
3170
3171 dev->name = name;
3172
3173 return 0;
3174}
3175
3176/*
3177 * The caller is responsible for "name" being available whenever f_fs needs it
3178 */
3179int ffs_name_dev(struct ffs_dev *dev, const char *name)
3180{
3181 int ret;
3182
3183 ffs_dev_lock();
3184 ret = _ffs_name_dev(dev, name);
3185 ffs_dev_unlock();
3186
3187 return ret;
3188}
3189EXPORT_SYMBOL_GPL(ffs_name_dev);
3190
3191int ffs_single_dev(struct ffs_dev *dev)
3192{
3193 int ret;
3194
3195 ret = 0;
3196 ffs_dev_lock();
3197
3198 if (!list_is_singular(&ffs_devices))
3199 ret = -EBUSY;
3200 else
3201 dev->single = true;
3202
3203 ffs_dev_unlock();
3204 return ret;
3205}
3206EXPORT_SYMBOL_GPL(ffs_single_dev);
3207
3208/*
3209 * ffs_lock must be taken by the caller of this function
3210 */
3211static void _ffs_free_dev(struct ffs_dev *dev)
3212{
3213 list_del(&dev->entry);
3214 if (dev->name_allocated)
3215 kfree(dev->name);
3216 kfree(dev);
3217 if (list_empty(&ffs_devices))
3218 functionfs_cleanup();
3219}
3220
3221static void *ffs_acquire_dev(const char *dev_name)
3222{
3223 struct ffs_dev *ffs_dev;
3224
3225 ENTER();
3226 ffs_dev_lock();
3227
3228 ffs_dev = _ffs_find_dev(dev_name);
3229 if (!ffs_dev)
3230 ffs_dev = ERR_PTR(-ENOENT);
3231 else if (ffs_dev->mounted)
3232 ffs_dev = ERR_PTR(-EBUSY);
3233 else if (ffs_dev->ffs_acquire_dev_callback &&
3234 ffs_dev->ffs_acquire_dev_callback(ffs_dev))
3235 ffs_dev = ERR_PTR(-ENOENT);
3236 else
3237 ffs_dev->mounted = true;
3238
3239 ffs_dev_unlock();
3240 return ffs_dev;
3241}
3242
3243static void ffs_release_dev(struct ffs_data *ffs_data)
3244{
3245 struct ffs_dev *ffs_dev;
3246
3247 ENTER();
3248 ffs_dev_lock();
3249
3250 ffs_dev = ffs_data->private_data;
3251 if (ffs_dev) {
3252 ffs_dev->mounted = false;
3253
3254 if (ffs_dev->ffs_release_dev_callback)
3255 ffs_dev->ffs_release_dev_callback(ffs_dev);
3256 }
3257
3258 ffs_dev_unlock();
3259}
3260
3261static int ffs_ready(struct ffs_data *ffs)
3262{
3263 struct ffs_dev *ffs_obj;
3264 int ret = 0;
3265
3266 ENTER();
3267 ffs_dev_lock();
3268
3269 ffs_obj = ffs->private_data;
3270 if (!ffs_obj) {
3271 ret = -EINVAL;
3272 goto done;
3273 }
3274 if (WARN_ON(ffs_obj->desc_ready)) {
3275 ret = -EBUSY;
3276 goto done;
3277 }
3278
3279 ffs_obj->desc_ready = true;
3280 ffs_obj->ffs_data = ffs;
3281
3282 if (ffs_obj->ffs_ready_callback)
3283 ret = ffs_obj->ffs_ready_callback(ffs);
3284
3285done:
3286 ffs_dev_unlock();
3287 return ret;
3288}
3289
3290static void ffs_closed(struct ffs_data *ffs)
3291{
3292 struct ffs_dev *ffs_obj;
3293
3294 ENTER();
3295 ffs_dev_lock();
3296
3297 ffs_obj = ffs->private_data;
3298 if (!ffs_obj)
3299 goto done;
3300
3301 ffs_obj->desc_ready = false;
3302
3303 if (ffs_obj->ffs_closed_callback)
3304 ffs_obj->ffs_closed_callback(ffs);
3305
3306 if (!ffs_obj->opts || ffs_obj->opts->no_configfs
3307 || !ffs_obj->opts->func_inst.group.cg_item.ci_parent)
3308 goto done;
3309
3310 unregister_gadget_item(ffs_obj->opts->
3311 func_inst.group.cg_item.ci_parent->ci_parent);
3312done:
3313 ffs_dev_unlock();
3314}
3315
3316/* Misc helper functions ****************************************************/
3317
3318static int ffs_mutex_lock(struct mutex *mutex, unsigned nonblock)
3319{
3320 return nonblock
3321 ? likely(mutex_trylock(mutex)) ? 0 : -EAGAIN
3322 : mutex_lock_interruptible(mutex);
3323}
3324
3325static char *ffs_prepare_buffer(const char __user *buf, size_t len)
3326{
3327 char *data;
3328
3329 if (unlikely(!len))
3330 return NULL;
3331
3332 data = kmalloc(len, GFP_KERNEL);
3333 if (unlikely(!data))
3334 return ERR_PTR(-ENOMEM);
3335
3336 if (unlikely(__copy_from_user(data, buf, len))) {
3337 kfree(data);
3338 return ERR_PTR(-EFAULT);
3339 }
3340
3341 pr_vdebug("Buffer from user space:\n");
3342 ffs_dump_mem("", data, len);
3343
3344 return data;
3345}
3346
3347DECLARE_USB_FUNCTION_INIT(ffs, ffs_alloc_inst, ffs_alloc);
3348MODULE_LICENSE("GPL");
3349MODULE_AUTHOR("Michal Nazarewicz");
diff --git a/drivers/usb/gadget/function/f_hid.c b/drivers/usb/gadget/function/f_hid.c
new file mode 100644
index 000000000000..a95290a1289f
--- /dev/null
+++ b/drivers/usb/gadget/function/f_hid.c
@@ -0,0 +1,763 @@
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/cdev.h>
16#include <linux/mutex.h>
17#include <linux/poll.h>
18#include <linux/uaccess.h>
19#include <linux/wait.h>
20#include <linux/sched.h>
21#include <linux/usb/g_hid.h>
22
23#include "u_f.h"
24
25static int major, minors;
26static struct class *hidg_class;
27
28/*-------------------------------------------------------------------------*/
29/* HID gadget struct */
30
31struct f_hidg_req_list {
32 struct usb_request *req;
33 unsigned int pos;
34 struct list_head list;
35};
36
37struct f_hidg {
38 /* configuration */
39 unsigned char bInterfaceSubClass;
40 unsigned char bInterfaceProtocol;
41 unsigned short report_desc_length;
42 char *report_desc;
43 unsigned short report_length;
44
45 /* recv report */
46 struct list_head completed_out_req;
47 spinlock_t spinlock;
48 wait_queue_head_t read_queue;
49 unsigned int qlen;
50
51 /* send report */
52 struct mutex lock;
53 bool write_pending;
54 wait_queue_head_t write_queue;
55 struct usb_request *req;
56
57 int minor;
58 struct cdev cdev;
59 struct usb_function func;
60
61 struct usb_ep *in_ep;
62 struct usb_ep *out_ep;
63};
64
65static inline struct f_hidg *func_to_hidg(struct usb_function *f)
66{
67 return container_of(f, struct f_hidg, func);
68}
69
70/*-------------------------------------------------------------------------*/
71/* Static descriptors */
72
73static struct usb_interface_descriptor hidg_interface_desc = {
74 .bLength = sizeof hidg_interface_desc,
75 .bDescriptorType = USB_DT_INTERFACE,
76 /* .bInterfaceNumber = DYNAMIC */
77 .bAlternateSetting = 0,
78 .bNumEndpoints = 2,
79 .bInterfaceClass = USB_CLASS_HID,
80 /* .bInterfaceSubClass = DYNAMIC */
81 /* .bInterfaceProtocol = DYNAMIC */
82 /* .iInterface = DYNAMIC */
83};
84
85static struct hid_descriptor hidg_desc = {
86 .bLength = sizeof hidg_desc,
87 .bDescriptorType = HID_DT_HID,
88 .bcdHID = 0x0101,
89 .bCountryCode = 0x00,
90 .bNumDescriptors = 0x1,
91 /*.desc[0].bDescriptorType = DYNAMIC */
92 /*.desc[0].wDescriptorLenght = DYNAMIC */
93};
94
95/* High-Speed Support */
96
97static struct usb_endpoint_descriptor hidg_hs_in_ep_desc = {
98 .bLength = USB_DT_ENDPOINT_SIZE,
99 .bDescriptorType = USB_DT_ENDPOINT,
100 .bEndpointAddress = USB_DIR_IN,
101 .bmAttributes = USB_ENDPOINT_XFER_INT,
102 /*.wMaxPacketSize = DYNAMIC */
103 .bInterval = 4, /* FIXME: Add this field in the
104 * HID gadget configuration?
105 * (struct hidg_func_descriptor)
106 */
107};
108
109static struct usb_endpoint_descriptor hidg_hs_out_ep_desc = {
110 .bLength = USB_DT_ENDPOINT_SIZE,
111 .bDescriptorType = USB_DT_ENDPOINT,
112 .bEndpointAddress = USB_DIR_OUT,
113 .bmAttributes = USB_ENDPOINT_XFER_INT,
114 /*.wMaxPacketSize = DYNAMIC */
115 .bInterval = 4, /* FIXME: Add this field in the
116 * HID gadget configuration?
117 * (struct hidg_func_descriptor)
118 */
119};
120
121static struct usb_descriptor_header *hidg_hs_descriptors[] = {
122 (struct usb_descriptor_header *)&hidg_interface_desc,
123 (struct usb_descriptor_header *)&hidg_desc,
124 (struct usb_descriptor_header *)&hidg_hs_in_ep_desc,
125 (struct usb_descriptor_header *)&hidg_hs_out_ep_desc,
126 NULL,
127};
128
129/* Full-Speed Support */
130
131static struct usb_endpoint_descriptor hidg_fs_in_ep_desc = {
132 .bLength = USB_DT_ENDPOINT_SIZE,
133 .bDescriptorType = USB_DT_ENDPOINT,
134 .bEndpointAddress = USB_DIR_IN,
135 .bmAttributes = USB_ENDPOINT_XFER_INT,
136 /*.wMaxPacketSize = DYNAMIC */
137 .bInterval = 10, /* FIXME: Add this field in the
138 * HID gadget configuration?
139 * (struct hidg_func_descriptor)
140 */
141};
142
143static struct usb_endpoint_descriptor hidg_fs_out_ep_desc = {
144 .bLength = USB_DT_ENDPOINT_SIZE,
145 .bDescriptorType = USB_DT_ENDPOINT,
146 .bEndpointAddress = USB_DIR_OUT,
147 .bmAttributes = USB_ENDPOINT_XFER_INT,
148 /*.wMaxPacketSize = DYNAMIC */
149 .bInterval = 10, /* FIXME: Add this field in the
150 * HID gadget configuration?
151 * (struct hidg_func_descriptor)
152 */
153};
154
155static struct usb_descriptor_header *hidg_fs_descriptors[] = {
156 (struct usb_descriptor_header *)&hidg_interface_desc,
157 (struct usb_descriptor_header *)&hidg_desc,
158 (struct usb_descriptor_header *)&hidg_fs_in_ep_desc,
159 (struct usb_descriptor_header *)&hidg_fs_out_ep_desc,
160 NULL,
161};
162
163/*-------------------------------------------------------------------------*/
164/* Char Device */
165
166static ssize_t f_hidg_read(struct file *file, char __user *buffer,
167 size_t count, loff_t *ptr)
168{
169 struct f_hidg *hidg = file->private_data;
170 struct f_hidg_req_list *list;
171 struct usb_request *req;
172 unsigned long flags;
173 int ret;
174
175 if (!count)
176 return 0;
177
178 if (!access_ok(VERIFY_WRITE, buffer, count))
179 return -EFAULT;
180
181 spin_lock_irqsave(&hidg->spinlock, flags);
182
183#define READ_COND (!list_empty(&hidg->completed_out_req))
184
185 /* wait for at least one buffer to complete */
186 while (!READ_COND) {
187 spin_unlock_irqrestore(&hidg->spinlock, flags);
188 if (file->f_flags & O_NONBLOCK)
189 return -EAGAIN;
190
191 if (wait_event_interruptible(hidg->read_queue, READ_COND))
192 return -ERESTARTSYS;
193
194 spin_lock_irqsave(&hidg->spinlock, flags);
195 }
196
197 /* pick the first one */
198 list = list_first_entry(&hidg->completed_out_req,
199 struct f_hidg_req_list, list);
200 req = list->req;
201 count = min_t(unsigned int, count, req->actual - list->pos);
202 spin_unlock_irqrestore(&hidg->spinlock, flags);
203
204 /* copy to user outside spinlock */
205 count -= copy_to_user(buffer, req->buf + list->pos, count);
206 list->pos += count;
207
208 /*
209 * if this request is completely handled and transfered to
210 * userspace, remove its entry from the list and requeue it
211 * again. Otherwise, we will revisit it again upon the next
212 * call, taking into account its current read position.
213 */
214 if (list->pos == req->actual) {
215 spin_lock_irqsave(&hidg->spinlock, flags);
216 list_del(&list->list);
217 kfree(list);
218 spin_unlock_irqrestore(&hidg->spinlock, flags);
219
220 req->length = hidg->report_length;
221 ret = usb_ep_queue(hidg->out_ep, req, GFP_KERNEL);
222 if (ret < 0)
223 return ret;
224 }
225
226 return count;
227}
228
229static void f_hidg_req_complete(struct usb_ep *ep, struct usb_request *req)
230{
231 struct f_hidg *hidg = (struct f_hidg *)ep->driver_data;
232
233 if (req->status != 0) {
234 ERROR(hidg->func.config->cdev,
235 "End Point Request ERROR: %d\n", req->status);
236 }
237
238 hidg->write_pending = 0;
239 wake_up(&hidg->write_queue);
240}
241
242static ssize_t f_hidg_write(struct file *file, const char __user *buffer,
243 size_t count, loff_t *offp)
244{
245 struct f_hidg *hidg = file->private_data;
246 ssize_t status = -ENOMEM;
247
248 if (!access_ok(VERIFY_READ, buffer, count))
249 return -EFAULT;
250
251 mutex_lock(&hidg->lock);
252
253#define WRITE_COND (!hidg->write_pending)
254
255 /* write queue */
256 while (!WRITE_COND) {
257 mutex_unlock(&hidg->lock);
258 if (file->f_flags & O_NONBLOCK)
259 return -EAGAIN;
260
261 if (wait_event_interruptible_exclusive(
262 hidg->write_queue, WRITE_COND))
263 return -ERESTARTSYS;
264
265 mutex_lock(&hidg->lock);
266 }
267
268 count = min_t(unsigned, count, hidg->report_length);
269 status = copy_from_user(hidg->req->buf, buffer, count);
270
271 if (status != 0) {
272 ERROR(hidg->func.config->cdev,
273 "copy_from_user error\n");
274 mutex_unlock(&hidg->lock);
275 return -EINVAL;
276 }
277
278 hidg->req->status = 0;
279 hidg->req->zero = 0;
280 hidg->req->length = count;
281 hidg->req->complete = f_hidg_req_complete;
282 hidg->req->context = hidg;
283 hidg->write_pending = 1;
284
285 status = usb_ep_queue(hidg->in_ep, hidg->req, GFP_ATOMIC);
286 if (status < 0) {
287 ERROR(hidg->func.config->cdev,
288 "usb_ep_queue error on int endpoint %zd\n", status);
289 hidg->write_pending = 0;
290 wake_up(&hidg->write_queue);
291 } else {
292 status = count;
293 }
294
295 mutex_unlock(&hidg->lock);
296
297 return status;
298}
299
300static unsigned int f_hidg_poll(struct file *file, poll_table *wait)
301{
302 struct f_hidg *hidg = file->private_data;
303 unsigned int ret = 0;
304
305 poll_wait(file, &hidg->read_queue, wait);
306 poll_wait(file, &hidg->write_queue, wait);
307
308 if (WRITE_COND)
309 ret |= POLLOUT | POLLWRNORM;
310
311 if (READ_COND)
312 ret |= POLLIN | POLLRDNORM;
313
314 return ret;
315}
316
317#undef WRITE_COND
318#undef READ_COND
319
320static int f_hidg_release(struct inode *inode, struct file *fd)
321{
322 fd->private_data = NULL;
323 return 0;
324}
325
326static int f_hidg_open(struct inode *inode, struct file *fd)
327{
328 struct f_hidg *hidg =
329 container_of(inode->i_cdev, struct f_hidg, cdev);
330
331 fd->private_data = hidg;
332
333 return 0;
334}
335
336/*-------------------------------------------------------------------------*/
337/* usb_function */
338
339static inline struct usb_request *hidg_alloc_ep_req(struct usb_ep *ep,
340 unsigned length)
341{
342 return alloc_ep_req(ep, length, length);
343}
344
345static void hidg_set_report_complete(struct usb_ep *ep, struct usb_request *req)
346{
347 struct f_hidg *hidg = (struct f_hidg *) req->context;
348 struct f_hidg_req_list *req_list;
349 unsigned long flags;
350
351 req_list = kzalloc(sizeof(*req_list), GFP_ATOMIC);
352 if (!req_list)
353 return;
354
355 req_list->req = req;
356
357 spin_lock_irqsave(&hidg->spinlock, flags);
358 list_add_tail(&req_list->list, &hidg->completed_out_req);
359 spin_unlock_irqrestore(&hidg->spinlock, flags);
360
361 wake_up(&hidg->read_queue);
362}
363
364static int hidg_setup(struct usb_function *f,
365 const struct usb_ctrlrequest *ctrl)
366{
367 struct f_hidg *hidg = func_to_hidg(f);
368 struct usb_composite_dev *cdev = f->config->cdev;
369 struct usb_request *req = cdev->req;
370 int status = 0;
371 __u16 value, length;
372
373 value = __le16_to_cpu(ctrl->wValue);
374 length = __le16_to_cpu(ctrl->wLength);
375
376 VDBG(cdev, "hid_setup crtl_request : bRequestType:0x%x bRequest:0x%x "
377 "Value:0x%x\n", ctrl->bRequestType, ctrl->bRequest, value);
378
379 switch ((ctrl->bRequestType << 8) | ctrl->bRequest) {
380 case ((USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8
381 | HID_REQ_GET_REPORT):
382 VDBG(cdev, "get_report\n");
383
384 /* send an empty report */
385 length = min_t(unsigned, length, hidg->report_length);
386 memset(req->buf, 0x0, length);
387
388 goto respond;
389 break;
390
391 case ((USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8
392 | HID_REQ_GET_PROTOCOL):
393 VDBG(cdev, "get_protocol\n");
394 goto stall;
395 break;
396
397 case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8
398 | HID_REQ_SET_REPORT):
399 VDBG(cdev, "set_report | wLenght=%d\n", ctrl->wLength);
400 goto stall;
401 break;
402
403 case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8
404 | HID_REQ_SET_PROTOCOL):
405 VDBG(cdev, "set_protocol\n");
406 goto stall;
407 break;
408
409 case ((USB_DIR_IN | USB_TYPE_STANDARD | USB_RECIP_INTERFACE) << 8
410 | USB_REQ_GET_DESCRIPTOR):
411 switch (value >> 8) {
412 case HID_DT_HID:
413 VDBG(cdev, "USB_REQ_GET_DESCRIPTOR: HID\n");
414 length = min_t(unsigned short, length,
415 hidg_desc.bLength);
416 memcpy(req->buf, &hidg_desc, length);
417 goto respond;
418 break;
419 case HID_DT_REPORT:
420 VDBG(cdev, "USB_REQ_GET_DESCRIPTOR: REPORT\n");
421 length = min_t(unsigned short, length,
422 hidg->report_desc_length);
423 memcpy(req->buf, hidg->report_desc, length);
424 goto respond;
425 break;
426
427 default:
428 VDBG(cdev, "Unknown descriptor request 0x%x\n",
429 value >> 8);
430 goto stall;
431 break;
432 }
433 break;
434
435 default:
436 VDBG(cdev, "Unknown request 0x%x\n",
437 ctrl->bRequest);
438 goto stall;
439 break;
440 }
441
442stall:
443 return -EOPNOTSUPP;
444
445respond:
446 req->zero = 0;
447 req->length = length;
448 status = usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC);
449 if (status < 0)
450 ERROR(cdev, "usb_ep_queue error on ep0 %d\n", value);
451 return status;
452}
453
454static void hidg_disable(struct usb_function *f)
455{
456 struct f_hidg *hidg = func_to_hidg(f);
457 struct f_hidg_req_list *list, *next;
458
459 usb_ep_disable(hidg->in_ep);
460 hidg->in_ep->driver_data = NULL;
461
462 usb_ep_disable(hidg->out_ep);
463 hidg->out_ep->driver_data = NULL;
464
465 list_for_each_entry_safe(list, next, &hidg->completed_out_req, list) {
466 list_del(&list->list);
467 kfree(list);
468 }
469}
470
471static int hidg_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
472{
473 struct usb_composite_dev *cdev = f->config->cdev;
474 struct f_hidg *hidg = func_to_hidg(f);
475 int i, status = 0;
476
477 VDBG(cdev, "hidg_set_alt intf:%d alt:%d\n", intf, alt);
478
479 if (hidg->in_ep != NULL) {
480 /* restart endpoint */
481 if (hidg->in_ep->driver_data != NULL)
482 usb_ep_disable(hidg->in_ep);
483
484 status = config_ep_by_speed(f->config->cdev->gadget, f,
485 hidg->in_ep);
486 if (status) {
487 ERROR(cdev, "config_ep_by_speed FAILED!\n");
488 goto fail;
489 }
490 status = usb_ep_enable(hidg->in_ep);
491 if (status < 0) {
492 ERROR(cdev, "Enable IN endpoint FAILED!\n");
493 goto fail;
494 }
495 hidg->in_ep->driver_data = hidg;
496 }
497
498
499 if (hidg->out_ep != NULL) {
500 /* restart endpoint */
501 if (hidg->out_ep->driver_data != NULL)
502 usb_ep_disable(hidg->out_ep);
503
504 status = config_ep_by_speed(f->config->cdev->gadget, f,
505 hidg->out_ep);
506 if (status) {
507 ERROR(cdev, "config_ep_by_speed FAILED!\n");
508 goto fail;
509 }
510 status = usb_ep_enable(hidg->out_ep);
511 if (status < 0) {
512 ERROR(cdev, "Enable IN endpoint FAILED!\n");
513 goto fail;
514 }
515 hidg->out_ep->driver_data = hidg;
516
517 /*
518 * allocate a bunch of read buffers and queue them all at once.
519 */
520 for (i = 0; i < hidg->qlen && status == 0; i++) {
521 struct usb_request *req =
522 hidg_alloc_ep_req(hidg->out_ep,
523 hidg->report_length);
524 if (req) {
525 req->complete = hidg_set_report_complete;
526 req->context = hidg;
527 status = usb_ep_queue(hidg->out_ep, req,
528 GFP_ATOMIC);
529 if (status)
530 ERROR(cdev, "%s queue req --> %d\n",
531 hidg->out_ep->name, status);
532 } else {
533 usb_ep_disable(hidg->out_ep);
534 hidg->out_ep->driver_data = NULL;
535 status = -ENOMEM;
536 goto fail;
537 }
538 }
539 }
540
541fail:
542 return status;
543}
544
545const struct file_operations f_hidg_fops = {
546 .owner = THIS_MODULE,
547 .open = f_hidg_open,
548 .release = f_hidg_release,
549 .write = f_hidg_write,
550 .read = f_hidg_read,
551 .poll = f_hidg_poll,
552 .llseek = noop_llseek,
553};
554
555static int __init hidg_bind(struct usb_configuration *c, struct usb_function *f)
556{
557 struct usb_ep *ep;
558 struct f_hidg *hidg = func_to_hidg(f);
559 int status;
560 dev_t dev;
561
562 /* allocate instance-specific interface IDs, and patch descriptors */
563 status = usb_interface_id(c, f);
564 if (status < 0)
565 goto fail;
566 hidg_interface_desc.bInterfaceNumber = status;
567
568 /* allocate instance-specific endpoints */
569 status = -ENODEV;
570 ep = usb_ep_autoconfig(c->cdev->gadget, &hidg_fs_in_ep_desc);
571 if (!ep)
572 goto fail;
573 ep->driver_data = c->cdev; /* claim */
574 hidg->in_ep = ep;
575
576 ep = usb_ep_autoconfig(c->cdev->gadget, &hidg_fs_out_ep_desc);
577 if (!ep)
578 goto fail;
579 ep->driver_data = c->cdev; /* claim */
580 hidg->out_ep = ep;
581
582 /* preallocate request and buffer */
583 status = -ENOMEM;
584 hidg->req = usb_ep_alloc_request(hidg->in_ep, GFP_KERNEL);
585 if (!hidg->req)
586 goto fail;
587
588 hidg->req->buf = kmalloc(hidg->report_length, GFP_KERNEL);
589 if (!hidg->req->buf)
590 goto fail;
591
592 /* set descriptor dynamic values */
593 hidg_interface_desc.bInterfaceSubClass = hidg->bInterfaceSubClass;
594 hidg_interface_desc.bInterfaceProtocol = hidg->bInterfaceProtocol;
595 hidg_hs_in_ep_desc.wMaxPacketSize = cpu_to_le16(hidg->report_length);
596 hidg_fs_in_ep_desc.wMaxPacketSize = cpu_to_le16(hidg->report_length);
597 hidg_hs_out_ep_desc.wMaxPacketSize = cpu_to_le16(hidg->report_length);
598 hidg_fs_out_ep_desc.wMaxPacketSize = cpu_to_le16(hidg->report_length);
599 hidg_desc.desc[0].bDescriptorType = HID_DT_REPORT;
600 hidg_desc.desc[0].wDescriptorLength =
601 cpu_to_le16(hidg->report_desc_length);
602
603 hidg_hs_in_ep_desc.bEndpointAddress =
604 hidg_fs_in_ep_desc.bEndpointAddress;
605 hidg_hs_out_ep_desc.bEndpointAddress =
606 hidg_fs_out_ep_desc.bEndpointAddress;
607
608 status = usb_assign_descriptors(f, hidg_fs_descriptors,
609 hidg_hs_descriptors, NULL);
610 if (status)
611 goto fail;
612
613 mutex_init(&hidg->lock);
614 spin_lock_init(&hidg->spinlock);
615 init_waitqueue_head(&hidg->write_queue);
616 init_waitqueue_head(&hidg->read_queue);
617 INIT_LIST_HEAD(&hidg->completed_out_req);
618
619 /* create char device */
620 cdev_init(&hidg->cdev, &f_hidg_fops);
621 dev = MKDEV(major, hidg->minor);
622 status = cdev_add(&hidg->cdev, dev, 1);
623 if (status)
624 goto fail;
625
626 device_create(hidg_class, NULL, dev, NULL, "%s%d", "hidg", hidg->minor);
627
628 return 0;
629
630fail:
631 ERROR(f->config->cdev, "hidg_bind FAILED\n");
632 if (hidg->req != NULL) {
633 kfree(hidg->req->buf);
634 if (hidg->in_ep != NULL)
635 usb_ep_free_request(hidg->in_ep, hidg->req);
636 }
637
638 usb_free_all_descriptors(f);
639 return status;
640}
641
642static void hidg_unbind(struct usb_configuration *c, struct usb_function *f)
643{
644 struct f_hidg *hidg = func_to_hidg(f);
645
646 device_destroy(hidg_class, MKDEV(major, hidg->minor));
647 cdev_del(&hidg->cdev);
648
649 /* disable/free request and end point */
650 usb_ep_disable(hidg->in_ep);
651 usb_ep_dequeue(hidg->in_ep, hidg->req);
652 kfree(hidg->req->buf);
653 usb_ep_free_request(hidg->in_ep, hidg->req);
654
655 usb_free_all_descriptors(f);
656
657 kfree(hidg->report_desc);
658 kfree(hidg);
659}
660
661/*-------------------------------------------------------------------------*/
662/* Strings */
663
664#define CT_FUNC_HID_IDX 0
665
666static struct usb_string ct_func_string_defs[] = {
667 [CT_FUNC_HID_IDX].s = "HID Interface",
668 {}, /* end of list */
669};
670
671static struct usb_gadget_strings ct_func_string_table = {
672 .language = 0x0409, /* en-US */
673 .strings = ct_func_string_defs,
674};
675
676static struct usb_gadget_strings *ct_func_strings[] = {
677 &ct_func_string_table,
678 NULL,
679};
680
681/*-------------------------------------------------------------------------*/
682/* usb_configuration */
683
684int __init hidg_bind_config(struct usb_configuration *c,
685 struct hidg_func_descriptor *fdesc, int index)
686{
687 struct f_hidg *hidg;
688 int status;
689
690 if (index >= minors)
691 return -ENOENT;
692
693 /* maybe allocate device-global string IDs, and patch descriptors */
694 if (ct_func_string_defs[CT_FUNC_HID_IDX].id == 0) {
695 status = usb_string_id(c->cdev);
696 if (status < 0)
697 return status;
698 ct_func_string_defs[CT_FUNC_HID_IDX].id = status;
699 hidg_interface_desc.iInterface = status;
700 }
701
702 /* allocate and initialize one new instance */
703 hidg = kzalloc(sizeof *hidg, GFP_KERNEL);
704 if (!hidg)
705 return -ENOMEM;
706
707 hidg->minor = index;
708 hidg->bInterfaceSubClass = fdesc->subclass;
709 hidg->bInterfaceProtocol = fdesc->protocol;
710 hidg->report_length = fdesc->report_length;
711 hidg->report_desc_length = fdesc->report_desc_length;
712 hidg->report_desc = kmemdup(fdesc->report_desc,
713 fdesc->report_desc_length,
714 GFP_KERNEL);
715 if (!hidg->report_desc) {
716 kfree(hidg);
717 return -ENOMEM;
718 }
719
720 hidg->func.name = "hid";
721 hidg->func.strings = ct_func_strings;
722 hidg->func.bind = hidg_bind;
723 hidg->func.unbind = hidg_unbind;
724 hidg->func.set_alt = hidg_set_alt;
725 hidg->func.disable = hidg_disable;
726 hidg->func.setup = hidg_setup;
727
728 /* this could me made configurable at some point */
729 hidg->qlen = 4;
730
731 status = usb_add_function(c, &hidg->func);
732 if (status)
733 kfree(hidg);
734
735 return status;
736}
737
738int __init ghid_setup(struct usb_gadget *g, int count)
739{
740 int status;
741 dev_t dev;
742
743 hidg_class = class_create(THIS_MODULE, "hidg");
744
745 status = alloc_chrdev_region(&dev, 0, count, "hidg");
746 if (!status) {
747 major = MAJOR(dev);
748 minors = count;
749 }
750
751 return status;
752}
753
754void ghid_cleanup(void)
755{
756 if (major) {
757 unregister_chrdev_region(MKDEV(major, 0), minors);
758 major = minors = 0;
759 }
760
761 class_destroy(hidg_class);
762 hidg_class = NULL;
763}
diff --git a/drivers/usb/gadget/function/f_loopback.c b/drivers/usb/gadget/function/f_loopback.c
new file mode 100644
index 000000000000..4557cd03f0b1
--- /dev/null
+++ b/drivers/usb/gadget/function/f_loopback.c
@@ -0,0 +1,571 @@
1/*
2 * f_loopback.c - USB peripheral loopback configuration driver
3 *
4 * Copyright (C) 2003-2008 David Brownell
5 * Copyright (C) 2008 by Nokia Corporation
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 */
12
13/* #define VERBOSE_DEBUG */
14
15#include <linux/slab.h>
16#include <linux/kernel.h>
17#include <linux/device.h>
18#include <linux/module.h>
19#include <linux/err.h>
20#include <linux/usb/composite.h>
21
22#include "g_zero.h"
23#include "u_f.h"
24
25/*
26 * LOOPBACK FUNCTION ... a testing vehicle for USB peripherals,
27 *
28 * This takes messages of various sizes written OUT to a device, and loops
29 * them back so they can be read IN from it. It has been used by certain
30 * test applications. It supports limited testing of data queueing logic.
31 *
32 *
33 * This is currently packaged as a configuration driver, which can't be
34 * combined with other functions to make composite devices. However, it
35 * can be combined with other independent configurations.
36 */
37struct f_loopback {
38 struct usb_function function;
39
40 struct usb_ep *in_ep;
41 struct usb_ep *out_ep;
42};
43
44static inline struct f_loopback *func_to_loop(struct usb_function *f)
45{
46 return container_of(f, struct f_loopback, function);
47}
48
49static unsigned qlen;
50static unsigned buflen;
51
52/*-------------------------------------------------------------------------*/
53
54static struct usb_interface_descriptor loopback_intf = {
55 .bLength = sizeof loopback_intf,
56 .bDescriptorType = USB_DT_INTERFACE,
57
58 .bNumEndpoints = 2,
59 .bInterfaceClass = USB_CLASS_VENDOR_SPEC,
60 /* .iInterface = DYNAMIC */
61};
62
63/* full speed support: */
64
65static struct usb_endpoint_descriptor fs_loop_source_desc = {
66 .bLength = USB_DT_ENDPOINT_SIZE,
67 .bDescriptorType = USB_DT_ENDPOINT,
68
69 .bEndpointAddress = USB_DIR_IN,
70 .bmAttributes = USB_ENDPOINT_XFER_BULK,
71};
72
73static struct usb_endpoint_descriptor fs_loop_sink_desc = {
74 .bLength = USB_DT_ENDPOINT_SIZE,
75 .bDescriptorType = USB_DT_ENDPOINT,
76
77 .bEndpointAddress = USB_DIR_OUT,
78 .bmAttributes = USB_ENDPOINT_XFER_BULK,
79};
80
81static struct usb_descriptor_header *fs_loopback_descs[] = {
82 (struct usb_descriptor_header *) &loopback_intf,
83 (struct usb_descriptor_header *) &fs_loop_sink_desc,
84 (struct usb_descriptor_header *) &fs_loop_source_desc,
85 NULL,
86};
87
88/* high speed support: */
89
90static struct usb_endpoint_descriptor hs_loop_source_desc = {
91 .bLength = USB_DT_ENDPOINT_SIZE,
92 .bDescriptorType = USB_DT_ENDPOINT,
93
94 .bmAttributes = USB_ENDPOINT_XFER_BULK,
95 .wMaxPacketSize = cpu_to_le16(512),
96};
97
98static struct usb_endpoint_descriptor hs_loop_sink_desc = {
99 .bLength = USB_DT_ENDPOINT_SIZE,
100 .bDescriptorType = USB_DT_ENDPOINT,
101
102 .bmAttributes = USB_ENDPOINT_XFER_BULK,
103 .wMaxPacketSize = cpu_to_le16(512),
104};
105
106static struct usb_descriptor_header *hs_loopback_descs[] = {
107 (struct usb_descriptor_header *) &loopback_intf,
108 (struct usb_descriptor_header *) &hs_loop_source_desc,
109 (struct usb_descriptor_header *) &hs_loop_sink_desc,
110 NULL,
111};
112
113/* super speed support: */
114
115static struct usb_endpoint_descriptor ss_loop_source_desc = {
116 .bLength = USB_DT_ENDPOINT_SIZE,
117 .bDescriptorType = USB_DT_ENDPOINT,
118
119 .bmAttributes = USB_ENDPOINT_XFER_BULK,
120 .wMaxPacketSize = cpu_to_le16(1024),
121};
122
123static struct usb_ss_ep_comp_descriptor ss_loop_source_comp_desc = {
124 .bLength = USB_DT_SS_EP_COMP_SIZE,
125 .bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
126 .bMaxBurst = 0,
127 .bmAttributes = 0,
128 .wBytesPerInterval = 0,
129};
130
131static struct usb_endpoint_descriptor ss_loop_sink_desc = {
132 .bLength = USB_DT_ENDPOINT_SIZE,
133 .bDescriptorType = USB_DT_ENDPOINT,
134
135 .bmAttributes = USB_ENDPOINT_XFER_BULK,
136 .wMaxPacketSize = cpu_to_le16(1024),
137};
138
139static struct usb_ss_ep_comp_descriptor ss_loop_sink_comp_desc = {
140 .bLength = USB_DT_SS_EP_COMP_SIZE,
141 .bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
142 .bMaxBurst = 0,
143 .bmAttributes = 0,
144 .wBytesPerInterval = 0,
145};
146
147static struct usb_descriptor_header *ss_loopback_descs[] = {
148 (struct usb_descriptor_header *) &loopback_intf,
149 (struct usb_descriptor_header *) &ss_loop_source_desc,
150 (struct usb_descriptor_header *) &ss_loop_source_comp_desc,
151 (struct usb_descriptor_header *) &ss_loop_sink_desc,
152 (struct usb_descriptor_header *) &ss_loop_sink_comp_desc,
153 NULL,
154};
155
156/* function-specific strings: */
157
158static struct usb_string strings_loopback[] = {
159 [0].s = "loop input to output",
160 { } /* end of list */
161};
162
163static struct usb_gadget_strings stringtab_loop = {
164 .language = 0x0409, /* en-us */
165 .strings = strings_loopback,
166};
167
168static struct usb_gadget_strings *loopback_strings[] = {
169 &stringtab_loop,
170 NULL,
171};
172
173/*-------------------------------------------------------------------------*/
174
175static int loopback_bind(struct usb_configuration *c, struct usb_function *f)
176{
177 struct usb_composite_dev *cdev = c->cdev;
178 struct f_loopback *loop = func_to_loop(f);
179 int id;
180 int ret;
181
182 /* allocate interface ID(s) */
183 id = usb_interface_id(c, f);
184 if (id < 0)
185 return id;
186 loopback_intf.bInterfaceNumber = id;
187
188 id = usb_string_id(cdev);
189 if (id < 0)
190 return id;
191 strings_loopback[0].id = id;
192 loopback_intf.iInterface = id;
193
194 /* allocate endpoints */
195
196 loop->in_ep = usb_ep_autoconfig(cdev->gadget, &fs_loop_source_desc);
197 if (!loop->in_ep) {
198autoconf_fail:
199 ERROR(cdev, "%s: can't autoconfigure on %s\n",
200 f->name, cdev->gadget->name);
201 return -ENODEV;
202 }
203 loop->in_ep->driver_data = cdev; /* claim */
204
205 loop->out_ep = usb_ep_autoconfig(cdev->gadget, &fs_loop_sink_desc);
206 if (!loop->out_ep)
207 goto autoconf_fail;
208 loop->out_ep->driver_data = cdev; /* claim */
209
210 /* support high speed hardware */
211 hs_loop_source_desc.bEndpointAddress =
212 fs_loop_source_desc.bEndpointAddress;
213 hs_loop_sink_desc.bEndpointAddress = fs_loop_sink_desc.bEndpointAddress;
214
215 /* support super speed hardware */
216 ss_loop_source_desc.bEndpointAddress =
217 fs_loop_source_desc.bEndpointAddress;
218 ss_loop_sink_desc.bEndpointAddress = fs_loop_sink_desc.bEndpointAddress;
219
220 ret = usb_assign_descriptors(f, fs_loopback_descs, hs_loopback_descs,
221 ss_loopback_descs);
222 if (ret)
223 return ret;
224
225 DBG(cdev, "%s speed %s: IN/%s, OUT/%s\n",
226 (gadget_is_superspeed(c->cdev->gadget) ? "super" :
227 (gadget_is_dualspeed(c->cdev->gadget) ? "dual" : "full")),
228 f->name, loop->in_ep->name, loop->out_ep->name);
229 return 0;
230}
231
232static void lb_free_func(struct usb_function *f)
233{
234 struct f_lb_opts *opts;
235
236 opts = container_of(f->fi, struct f_lb_opts, func_inst);
237
238 mutex_lock(&opts->lock);
239 opts->refcnt--;
240 mutex_unlock(&opts->lock);
241
242 usb_free_all_descriptors(f);
243 kfree(func_to_loop(f));
244}
245
246static void loopback_complete(struct usb_ep *ep, struct usb_request *req)
247{
248 struct f_loopback *loop = ep->driver_data;
249 struct usb_composite_dev *cdev = loop->function.config->cdev;
250 int status = req->status;
251
252 switch (status) {
253
254 case 0: /* normal completion? */
255 if (ep == loop->out_ep) {
256 /* loop this OUT packet back IN to the host */
257 req->zero = (req->actual < req->length);
258 req->length = req->actual;
259 status = usb_ep_queue(loop->in_ep, req, GFP_ATOMIC);
260 if (status == 0)
261 return;
262
263 /* "should never get here" */
264 ERROR(cdev, "can't loop %s to %s: %d\n",
265 ep->name, loop->in_ep->name,
266 status);
267 }
268
269 /* queue the buffer for some later OUT packet */
270 req->length = buflen;
271 status = usb_ep_queue(loop->out_ep, req, GFP_ATOMIC);
272 if (status == 0)
273 return;
274
275 /* "should never get here" */
276 /* FALLTHROUGH */
277
278 default:
279 ERROR(cdev, "%s loop complete --> %d, %d/%d\n", ep->name,
280 status, req->actual, req->length);
281 /* FALLTHROUGH */
282
283 /* NOTE: since this driver doesn't maintain an explicit record
284 * of requests it submitted (just maintains qlen count), we
285 * rely on the hardware driver to clean up on disconnect or
286 * endpoint disable.
287 */
288 case -ECONNABORTED: /* hardware forced ep reset */
289 case -ECONNRESET: /* request dequeued */
290 case -ESHUTDOWN: /* disconnect from host */
291 free_ep_req(ep, req);
292 return;
293 }
294}
295
296static void disable_loopback(struct f_loopback *loop)
297{
298 struct usb_composite_dev *cdev;
299
300 cdev = loop->function.config->cdev;
301 disable_endpoints(cdev, loop->in_ep, loop->out_ep, NULL, NULL);
302 VDBG(cdev, "%s disabled\n", loop->function.name);
303}
304
305static inline struct usb_request *lb_alloc_ep_req(struct usb_ep *ep, int len)
306{
307 return alloc_ep_req(ep, len, buflen);
308}
309
310static int
311enable_loopback(struct usb_composite_dev *cdev, struct f_loopback *loop)
312{
313 int result = 0;
314 struct usb_ep *ep;
315 struct usb_request *req;
316 unsigned i;
317
318 /* one endpoint writes data back IN to the host */
319 ep = loop->in_ep;
320 result = config_ep_by_speed(cdev->gadget, &(loop->function), ep);
321 if (result)
322 return result;
323 result = usb_ep_enable(ep);
324 if (result < 0)
325 return result;
326 ep->driver_data = loop;
327
328 /* one endpoint just reads OUT packets */
329 ep = loop->out_ep;
330 result = config_ep_by_speed(cdev->gadget, &(loop->function), ep);
331 if (result)
332 goto fail0;
333
334 result = usb_ep_enable(ep);
335 if (result < 0) {
336fail0:
337 ep = loop->in_ep;
338 usb_ep_disable(ep);
339 ep->driver_data = NULL;
340 return result;
341 }
342 ep->driver_data = loop;
343
344 /* allocate a bunch of read buffers and queue them all at once.
345 * we buffer at most 'qlen' transfers; fewer if any need more
346 * than 'buflen' bytes each.
347 */
348 for (i = 0; i < qlen && result == 0; i++) {
349 req = lb_alloc_ep_req(ep, 0);
350 if (req) {
351 req->complete = loopback_complete;
352 result = usb_ep_queue(ep, req, GFP_ATOMIC);
353 if (result)
354 ERROR(cdev, "%s queue req --> %d\n",
355 ep->name, result);
356 } else {
357 usb_ep_disable(ep);
358 ep->driver_data = NULL;
359 result = -ENOMEM;
360 goto fail0;
361 }
362 }
363
364 DBG(cdev, "%s enabled\n", loop->function.name);
365 return result;
366}
367
368static int loopback_set_alt(struct usb_function *f,
369 unsigned intf, unsigned alt)
370{
371 struct f_loopback *loop = func_to_loop(f);
372 struct usb_composite_dev *cdev = f->config->cdev;
373
374 /* we know alt is zero */
375 if (loop->in_ep->driver_data)
376 disable_loopback(loop);
377 return enable_loopback(cdev, loop);
378}
379
380static void loopback_disable(struct usb_function *f)
381{
382 struct f_loopback *loop = func_to_loop(f);
383
384 disable_loopback(loop);
385}
386
387static struct usb_function *loopback_alloc(struct usb_function_instance *fi)
388{
389 struct f_loopback *loop;
390 struct f_lb_opts *lb_opts;
391
392 loop = kzalloc(sizeof *loop, GFP_KERNEL);
393 if (!loop)
394 return ERR_PTR(-ENOMEM);
395
396 lb_opts = container_of(fi, struct f_lb_opts, func_inst);
397
398 mutex_lock(&lb_opts->lock);
399 lb_opts->refcnt++;
400 mutex_unlock(&lb_opts->lock);
401
402 buflen = lb_opts->bulk_buflen;
403 qlen = lb_opts->qlen;
404 if (!qlen)
405 qlen = 32;
406
407 loop->function.name = "loopback";
408 loop->function.bind = loopback_bind;
409 loop->function.set_alt = loopback_set_alt;
410 loop->function.disable = loopback_disable;
411 loop->function.strings = loopback_strings;
412
413 loop->function.free_func = lb_free_func;
414
415 return &loop->function;
416}
417
418static inline struct f_lb_opts *to_f_lb_opts(struct config_item *item)
419{
420 return container_of(to_config_group(item), struct f_lb_opts,
421 func_inst.group);
422}
423
424CONFIGFS_ATTR_STRUCT(f_lb_opts);
425CONFIGFS_ATTR_OPS(f_lb_opts);
426
427static void lb_attr_release(struct config_item *item)
428{
429 struct f_lb_opts *lb_opts = to_f_lb_opts(item);
430
431 usb_put_function_instance(&lb_opts->func_inst);
432}
433
434static struct configfs_item_operations lb_item_ops = {
435 .release = lb_attr_release,
436 .show_attribute = f_lb_opts_attr_show,
437 .store_attribute = f_lb_opts_attr_store,
438};
439
440static ssize_t f_lb_opts_qlen_show(struct f_lb_opts *opts, char *page)
441{
442 int result;
443
444 mutex_lock(&opts->lock);
445 result = sprintf(page, "%d", opts->qlen);
446 mutex_unlock(&opts->lock);
447
448 return result;
449}
450
451static ssize_t f_lb_opts_qlen_store(struct f_lb_opts *opts,
452 const char *page, size_t len)
453{
454 int ret;
455 u32 num;
456
457 mutex_lock(&opts->lock);
458 if (opts->refcnt) {
459 ret = -EBUSY;
460 goto end;
461 }
462
463 ret = kstrtou32(page, 0, &num);
464 if (ret)
465 goto end;
466
467 opts->qlen = num;
468 ret = len;
469end:
470 mutex_unlock(&opts->lock);
471 return ret;
472}
473
474static struct f_lb_opts_attribute f_lb_opts_qlen =
475 __CONFIGFS_ATTR(qlen, S_IRUGO | S_IWUSR,
476 f_lb_opts_qlen_show,
477 f_lb_opts_qlen_store);
478
479static ssize_t f_lb_opts_bulk_buflen_show(struct f_lb_opts *opts, char *page)
480{
481 int result;
482
483 mutex_lock(&opts->lock);
484 result = sprintf(page, "%d", opts->bulk_buflen);
485 mutex_unlock(&opts->lock);
486
487 return result;
488}
489
490static ssize_t f_lb_opts_bulk_buflen_store(struct f_lb_opts *opts,
491 const char *page, size_t len)
492{
493 int ret;
494 u32 num;
495
496 mutex_lock(&opts->lock);
497 if (opts->refcnt) {
498 ret = -EBUSY;
499 goto end;
500 }
501
502 ret = kstrtou32(page, 0, &num);
503 if (ret)
504 goto end;
505
506 opts->bulk_buflen = num;
507 ret = len;
508end:
509 mutex_unlock(&opts->lock);
510 return ret;
511}
512
513static struct f_lb_opts_attribute f_lb_opts_bulk_buflen =
514 __CONFIGFS_ATTR(buflen, S_IRUGO | S_IWUSR,
515 f_lb_opts_bulk_buflen_show,
516 f_lb_opts_bulk_buflen_store);
517
518static struct configfs_attribute *lb_attrs[] = {
519 &f_lb_opts_qlen.attr,
520 &f_lb_opts_bulk_buflen.attr,
521 NULL,
522};
523
524static struct config_item_type lb_func_type = {
525 .ct_item_ops = &lb_item_ops,
526 .ct_attrs = lb_attrs,
527 .ct_owner = THIS_MODULE,
528};
529
530static void lb_free_instance(struct usb_function_instance *fi)
531{
532 struct f_lb_opts *lb_opts;
533
534 lb_opts = container_of(fi, struct f_lb_opts, func_inst);
535 kfree(lb_opts);
536}
537
538static struct usb_function_instance *loopback_alloc_instance(void)
539{
540 struct f_lb_opts *lb_opts;
541
542 lb_opts = kzalloc(sizeof(*lb_opts), GFP_KERNEL);
543 if (!lb_opts)
544 return ERR_PTR(-ENOMEM);
545 mutex_init(&lb_opts->lock);
546 lb_opts->func_inst.free_func_inst = lb_free_instance;
547 lb_opts->bulk_buflen = GZERO_BULK_BUFLEN;
548 lb_opts->qlen = GZERO_QLEN;
549
550 config_group_init_type_name(&lb_opts->func_inst.group, "",
551 &lb_func_type);
552
553 return &lb_opts->func_inst;
554}
555DECLARE_USB_FUNCTION(Loopback, loopback_alloc_instance, loopback_alloc);
556
557int __init lb_modinit(void)
558{
559 int ret;
560
561 ret = usb_function_register(&Loopbackusb_func);
562 if (ret)
563 return ret;
564 return ret;
565}
566void __exit lb_modexit(void)
567{
568 usb_function_unregister(&Loopbackusb_func);
569}
570
571MODULE_LICENSE("GPL");
diff --git a/drivers/usb/gadget/function/f_mass_storage.c b/drivers/usb/gadget/function/f_mass_storage.c
new file mode 100644
index 000000000000..b96393908860
--- /dev/null
+++ b/drivers/usb/gadget/function/f_mass_storage.c
@@ -0,0 +1,3668 @@
1/*
2 * f_mass_storage.c -- Mass Storage USB Composite Function
3 *
4 * Copyright (C) 2003-2008 Alan Stern
5 * Copyright (C) 2009 Samsung Electronics
6 * Author: Michal Nazarewicz <mina86@mina86.com>
7 * All rights reserved.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions, and the following disclaimer,
14 * without modification.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. The names of the above-listed copyright holders may not be used
19 * to endorse or promote products derived from this software without
20 * specific prior written permission.
21 *
22 * ALTERNATIVELY, this software may be distributed under the terms of the
23 * GNU General Public License ("GPL") as published by the Free Software
24 * Foundation, either version 2 of that License or (at your option) any
25 * later version.
26 *
27 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
28 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
29 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
30 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
31 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
32 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
33 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
34 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
35 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
36 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
37 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 */
39
40/*
41 * The Mass Storage Function acts as a USB Mass Storage device,
42 * appearing to the host as a disk drive or as a CD-ROM drive. In
43 * addition to providing an example of a genuinely useful composite
44 * function for a USB device, it also illustrates a technique of
45 * double-buffering for increased throughput.
46 *
47 * For more information about MSF and in particular its module
48 * parameters and sysfs interface read the
49 * <Documentation/usb/mass-storage.txt> file.
50 */
51
52/*
53 * MSF is configured by specifying a fsg_config structure. It has the
54 * following fields:
55 *
56 * nluns Number of LUNs function have (anywhere from 1
57 * to FSG_MAX_LUNS which is 8).
58 * luns An array of LUN configuration values. This
59 * should be filled for each LUN that
60 * function will include (ie. for "nluns"
61 * LUNs). Each element of the array has
62 * the following fields:
63 * ->filename The path to the backing file for the LUN.
64 * Required if LUN is not marked as
65 * removable.
66 * ->ro Flag specifying access to the LUN shall be
67 * read-only. This is implied if CD-ROM
68 * emulation is enabled as well as when
69 * it was impossible to open "filename"
70 * in R/W mode.
71 * ->removable Flag specifying that LUN shall be indicated as
72 * being removable.
73 * ->cdrom Flag specifying that LUN shall be reported as
74 * being a CD-ROM.
75 * ->nofua Flag specifying that FUA flag in SCSI WRITE(10,12)
76 * commands for this LUN shall be ignored.
77 *
78 * vendor_name
79 * product_name
80 * release Information used as a reply to INQUIRY
81 * request. To use default set to NULL,
82 * NULL, 0xffff respectively. The first
83 * field should be 8 and the second 16
84 * characters or less.
85 *
86 * can_stall Set to permit function to halt bulk endpoints.
87 * Disabled on some USB devices known not
88 * to work correctly. You should set it
89 * to true.
90 *
91 * If "removable" is not set for a LUN then a backing file must be
92 * specified. If it is set, then NULL filename means the LUN's medium
93 * is not loaded (an empty string as "filename" in the fsg_config
94 * structure causes error). The CD-ROM emulation includes a single
95 * data track and no audio tracks; hence there need be only one
96 * backing file per LUN.
97 *
98 * This function is heavily based on "File-backed Storage Gadget" by
99 * Alan Stern which in turn is heavily based on "Gadget Zero" by David
100 * Brownell. The driver's SCSI command interface was based on the
101 * "Information technology - Small Computer System Interface - 2"
102 * document from X3T9.2 Project 375D, Revision 10L, 7-SEP-93,
103 * available at <http://www.t10.org/ftp/t10/drafts/s2/s2-r10l.pdf>.
104 * The single exception is opcode 0x23 (READ FORMAT CAPACITIES), which
105 * was based on the "Universal Serial Bus Mass Storage Class UFI
106 * Command Specification" document, Revision 1.0, December 14, 1998,
107 * available at
108 * <http://www.usb.org/developers/devclass_docs/usbmass-ufi10.pdf>.
109 */
110
111/*
112 * Driver Design
113 *
114 * The MSF is fairly straightforward. There is a main kernel
115 * thread that handles most of the work. Interrupt routines field
116 * callbacks from the controller driver: bulk- and interrupt-request
117 * completion notifications, endpoint-0 events, and disconnect events.
118 * Completion events are passed to the main thread by wakeup calls. Many
119 * ep0 requests are handled at interrupt time, but SetInterface,
120 * SetConfiguration, and device reset requests are forwarded to the
121 * thread in the form of "exceptions" using SIGUSR1 signals (since they
122 * should interrupt any ongoing file I/O operations).
123 *
124 * The thread's main routine implements the standard command/data/status
125 * parts of a SCSI interaction. It and its subroutines are full of tests
126 * for pending signals/exceptions -- all this polling is necessary since
127 * the kernel has no setjmp/longjmp equivalents. (Maybe this is an
128 * indication that the driver really wants to be running in userspace.)
129 * An important point is that so long as the thread is alive it keeps an
130 * open reference to the backing file. This will prevent unmounting
131 * the backing file's underlying filesystem and could cause problems
132 * during system shutdown, for example. To prevent such problems, the
133 * thread catches INT, TERM, and KILL signals and converts them into
134 * an EXIT exception.
135 *
136 * In normal operation the main thread is started during the gadget's
137 * fsg_bind() callback and stopped during fsg_unbind(). But it can
138 * also exit when it receives a signal, and there's no point leaving
139 * the gadget running when the thread is dead. As of this moment, MSF
140 * provides no way to deregister the gadget when thread dies -- maybe
141 * a callback functions is needed.
142 *
143 * To provide maximum throughput, the driver uses a circular pipeline of
144 * buffer heads (struct fsg_buffhd). In principle the pipeline can be
145 * arbitrarily long; in practice the benefits don't justify having more
146 * than 2 stages (i.e., double buffering). But it helps to think of the
147 * pipeline as being a long one. Each buffer head contains a bulk-in and
148 * a bulk-out request pointer (since the buffer can be used for both
149 * output and input -- directions always are given from the host's
150 * point of view) as well as a pointer to the buffer and various state
151 * variables.
152 *
153 * Use of the pipeline follows a simple protocol. There is a variable
154 * (fsg->next_buffhd_to_fill) that points to the next buffer head to use.
155 * At any time that buffer head may still be in use from an earlier
156 * request, so each buffer head has a state variable indicating whether
157 * it is EMPTY, FULL, or BUSY. Typical use involves waiting for the
158 * buffer head to be EMPTY, filling the buffer either by file I/O or by
159 * USB I/O (during which the buffer head is BUSY), and marking the buffer
160 * head FULL when the I/O is complete. Then the buffer will be emptied
161 * (again possibly by USB I/O, during which it is marked BUSY) and
162 * finally marked EMPTY again (possibly by a completion routine).
163 *
164 * A module parameter tells the driver to avoid stalling the bulk
165 * endpoints wherever the transport specification allows. This is
166 * necessary for some UDCs like the SuperH, which cannot reliably clear a
167 * halt on a bulk endpoint. However, under certain circumstances the
168 * Bulk-only specification requires a stall. In such cases the driver
169 * will halt the endpoint and set a flag indicating that it should clear
170 * the halt in software during the next device reset. Hopefully this
171 * will permit everything to work correctly. Furthermore, although the
172 * specification allows the bulk-out endpoint to halt when the host sends
173 * too much data, implementing this would cause an unavoidable race.
174 * The driver will always use the "no-stall" approach for OUT transfers.
175 *
176 * One subtle point concerns sending status-stage responses for ep0
177 * requests. Some of these requests, such as device reset, can involve
178 * interrupting an ongoing file I/O operation, which might take an
179 * arbitrarily long time. During that delay the host might give up on
180 * the original ep0 request and issue a new one. When that happens the
181 * driver should not notify the host about completion of the original
182 * request, as the host will no longer be waiting for it. So the driver
183 * assigns to each ep0 request a unique tag, and it keeps track of the
184 * tag value of the request associated with a long-running exception
185 * (device-reset, interface-change, or configuration-change). When the
186 * exception handler is finished, the status-stage response is submitted
187 * only if the current ep0 request tag is equal to the exception request
188 * tag. Thus only the most recently received ep0 request will get a
189 * status-stage response.
190 *
191 * Warning: This driver source file is too long. It ought to be split up
192 * into a header file plus about 3 separate .c files, to handle the details
193 * of the Gadget, USB Mass Storage, and SCSI protocols.
194 */
195
196
197/* #define VERBOSE_DEBUG */
198/* #define DUMP_MSGS */
199
200#include <linux/blkdev.h>
201#include <linux/completion.h>
202#include <linux/dcache.h>
203#include <linux/delay.h>
204#include <linux/device.h>
205#include <linux/fcntl.h>
206#include <linux/file.h>
207#include <linux/fs.h>
208#include <linux/kref.h>
209#include <linux/kthread.h>
210#include <linux/limits.h>
211#include <linux/rwsem.h>
212#include <linux/slab.h>
213#include <linux/spinlock.h>
214#include <linux/string.h>
215#include <linux/freezer.h>
216#include <linux/module.h>
217
218#include <linux/usb/ch9.h>
219#include <linux/usb/gadget.h>
220#include <linux/usb/composite.h>
221
222#include "gadget_chips.h"
223#include "configfs.h"
224
225
226/*------------------------------------------------------------------------*/
227
228#define FSG_DRIVER_DESC "Mass Storage Function"
229#define FSG_DRIVER_VERSION "2009/09/11"
230
231static const char fsg_string_interface[] = "Mass Storage";
232
233#include "storage_common.h"
234#include "f_mass_storage.h"
235
236/* Static strings, in UTF-8 (for simplicity we use only ASCII characters) */
237static struct usb_string fsg_strings[] = {
238 {FSG_STRING_INTERFACE, fsg_string_interface},
239 {}
240};
241
242static struct usb_gadget_strings fsg_stringtab = {
243 .language = 0x0409, /* en-us */
244 .strings = fsg_strings,
245};
246
247static struct usb_gadget_strings *fsg_strings_array[] = {
248 &fsg_stringtab,
249 NULL,
250};
251
252/*-------------------------------------------------------------------------*/
253
254struct fsg_dev;
255struct fsg_common;
256
257/* Data shared by all the FSG instances. */
258struct fsg_common {
259 struct usb_gadget *gadget;
260 struct usb_composite_dev *cdev;
261 struct fsg_dev *fsg, *new_fsg;
262 wait_queue_head_t fsg_wait;
263
264 /* filesem protects: backing files in use */
265 struct rw_semaphore filesem;
266
267 /* lock protects: state, all the req_busy's */
268 spinlock_t lock;
269
270 struct usb_ep *ep0; /* Copy of gadget->ep0 */
271 struct usb_request *ep0req; /* Copy of cdev->req */
272 unsigned int ep0_req_tag;
273
274 struct fsg_buffhd *next_buffhd_to_fill;
275 struct fsg_buffhd *next_buffhd_to_drain;
276 struct fsg_buffhd *buffhds;
277 unsigned int fsg_num_buffers;
278
279 int cmnd_size;
280 u8 cmnd[MAX_COMMAND_SIZE];
281
282 unsigned int nluns;
283 unsigned int lun;
284 struct fsg_lun **luns;
285 struct fsg_lun *curlun;
286
287 unsigned int bulk_out_maxpacket;
288 enum fsg_state state; /* For exception handling */
289 unsigned int exception_req_tag;
290
291 enum data_direction data_dir;
292 u32 data_size;
293 u32 data_size_from_cmnd;
294 u32 tag;
295 u32 residue;
296 u32 usb_amount_left;
297
298 unsigned int can_stall:1;
299 unsigned int free_storage_on_release:1;
300 unsigned int phase_error:1;
301 unsigned int short_packet_received:1;
302 unsigned int bad_lun_okay:1;
303 unsigned int running:1;
304 unsigned int sysfs:1;
305
306 int thread_wakeup_needed;
307 struct completion thread_notifier;
308 struct task_struct *thread_task;
309
310 /* Callback functions. */
311 const struct fsg_operations *ops;
312 /* Gadget's private data. */
313 void *private_data;
314
315 /*
316 * Vendor (8 chars), product (16 chars), release (4
317 * hexadecimal digits) and NUL byte
318 */
319 char inquiry_string[8 + 16 + 4 + 1];
320
321 struct kref ref;
322};
323
324struct fsg_dev {
325 struct usb_function function;
326 struct usb_gadget *gadget; /* Copy of cdev->gadget */
327 struct fsg_common *common;
328
329 u16 interface_number;
330
331 unsigned int bulk_in_enabled:1;
332 unsigned int bulk_out_enabled:1;
333
334 unsigned long atomic_bitflags;
335#define IGNORE_BULK_OUT 0
336
337 struct usb_ep *bulk_in;
338 struct usb_ep *bulk_out;
339};
340
341static inline int __fsg_is_set(struct fsg_common *common,
342 const char *func, unsigned line)
343{
344 if (common->fsg)
345 return 1;
346 ERROR(common, "common->fsg is NULL in %s at %u\n", func, line);
347 WARN_ON(1);
348 return 0;
349}
350
351#define fsg_is_set(common) likely(__fsg_is_set(common, __func__, __LINE__))
352
353static inline struct fsg_dev *fsg_from_func(struct usb_function *f)
354{
355 return container_of(f, struct fsg_dev, function);
356}
357
358typedef void (*fsg_routine_t)(struct fsg_dev *);
359
360static int exception_in_progress(struct fsg_common *common)
361{
362 return common->state > FSG_STATE_IDLE;
363}
364
365/* Make bulk-out requests be divisible by the maxpacket size */
366static void set_bulk_out_req_length(struct fsg_common *common,
367 struct fsg_buffhd *bh, unsigned int length)
368{
369 unsigned int rem;
370
371 bh->bulk_out_intended_length = length;
372 rem = length % common->bulk_out_maxpacket;
373 if (rem > 0)
374 length += common->bulk_out_maxpacket - rem;
375 bh->outreq->length = length;
376}
377
378
379/*-------------------------------------------------------------------------*/
380
381static int fsg_set_halt(struct fsg_dev *fsg, struct usb_ep *ep)
382{
383 const char *name;
384
385 if (ep == fsg->bulk_in)
386 name = "bulk-in";
387 else if (ep == fsg->bulk_out)
388 name = "bulk-out";
389 else
390 name = ep->name;
391 DBG(fsg, "%s set halt\n", name);
392 return usb_ep_set_halt(ep);
393}
394
395
396/*-------------------------------------------------------------------------*/
397
398/* These routines may be called in process context or in_irq */
399
400/* Caller must hold fsg->lock */
401static void wakeup_thread(struct fsg_common *common)
402{
403 smp_wmb(); /* ensure the write of bh->state is complete */
404 /* Tell the main thread that something has happened */
405 common->thread_wakeup_needed = 1;
406 if (common->thread_task)
407 wake_up_process(common->thread_task);
408}
409
410static void raise_exception(struct fsg_common *common, enum fsg_state new_state)
411{
412 unsigned long flags;
413
414 /*
415 * Do nothing if a higher-priority exception is already in progress.
416 * If a lower-or-equal priority exception is in progress, preempt it
417 * and notify the main thread by sending it a signal.
418 */
419 spin_lock_irqsave(&common->lock, flags);
420 if (common->state <= new_state) {
421 common->exception_req_tag = common->ep0_req_tag;
422 common->state = new_state;
423 if (common->thread_task)
424 send_sig_info(SIGUSR1, SEND_SIG_FORCED,
425 common->thread_task);
426 }
427 spin_unlock_irqrestore(&common->lock, flags);
428}
429
430
431/*-------------------------------------------------------------------------*/
432
433static int ep0_queue(struct fsg_common *common)
434{
435 int rc;
436
437 rc = usb_ep_queue(common->ep0, common->ep0req, GFP_ATOMIC);
438 common->ep0->driver_data = common;
439 if (rc != 0 && rc != -ESHUTDOWN) {
440 /* We can't do much more than wait for a reset */
441 WARNING(common, "error in submission: %s --> %d\n",
442 common->ep0->name, rc);
443 }
444 return rc;
445}
446
447
448/*-------------------------------------------------------------------------*/
449
450/* Completion handlers. These always run in_irq. */
451
452static void bulk_in_complete(struct usb_ep *ep, struct usb_request *req)
453{
454 struct fsg_common *common = ep->driver_data;
455 struct fsg_buffhd *bh = req->context;
456
457 if (req->status || req->actual != req->length)
458 DBG(common, "%s --> %d, %u/%u\n", __func__,
459 req->status, req->actual, req->length);
460 if (req->status == -ECONNRESET) /* Request was cancelled */
461 usb_ep_fifo_flush(ep);
462
463 /* Hold the lock while we update the request and buffer states */
464 smp_wmb();
465 spin_lock(&common->lock);
466 bh->inreq_busy = 0;
467 bh->state = BUF_STATE_EMPTY;
468 wakeup_thread(common);
469 spin_unlock(&common->lock);
470}
471
472static void bulk_out_complete(struct usb_ep *ep, struct usb_request *req)
473{
474 struct fsg_common *common = ep->driver_data;
475 struct fsg_buffhd *bh = req->context;
476
477 dump_msg(common, "bulk-out", req->buf, req->actual);
478 if (req->status || req->actual != bh->bulk_out_intended_length)
479 DBG(common, "%s --> %d, %u/%u\n", __func__,
480 req->status, req->actual, bh->bulk_out_intended_length);
481 if (req->status == -ECONNRESET) /* Request was cancelled */
482 usb_ep_fifo_flush(ep);
483
484 /* Hold the lock while we update the request and buffer states */
485 smp_wmb();
486 spin_lock(&common->lock);
487 bh->outreq_busy = 0;
488 bh->state = BUF_STATE_FULL;
489 wakeup_thread(common);
490 spin_unlock(&common->lock);
491}
492
493static int fsg_setup(struct usb_function *f,
494 const struct usb_ctrlrequest *ctrl)
495{
496 struct fsg_dev *fsg = fsg_from_func(f);
497 struct usb_request *req = fsg->common->ep0req;
498 u16 w_index = le16_to_cpu(ctrl->wIndex);
499 u16 w_value = le16_to_cpu(ctrl->wValue);
500 u16 w_length = le16_to_cpu(ctrl->wLength);
501
502 if (!fsg_is_set(fsg->common))
503 return -EOPNOTSUPP;
504
505 ++fsg->common->ep0_req_tag; /* Record arrival of a new request */
506 req->context = NULL;
507 req->length = 0;
508 dump_msg(fsg, "ep0-setup", (u8 *) ctrl, sizeof(*ctrl));
509
510 switch (ctrl->bRequest) {
511
512 case US_BULK_RESET_REQUEST:
513 if (ctrl->bRequestType !=
514 (USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
515 break;
516 if (w_index != fsg->interface_number || w_value != 0 ||
517 w_length != 0)
518 return -EDOM;
519
520 /*
521 * Raise an exception to stop the current operation
522 * and reinitialize our state.
523 */
524 DBG(fsg, "bulk reset request\n");
525 raise_exception(fsg->common, FSG_STATE_RESET);
526 return USB_GADGET_DELAYED_STATUS;
527
528 case US_BULK_GET_MAX_LUN:
529 if (ctrl->bRequestType !=
530 (USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE))
531 break;
532 if (w_index != fsg->interface_number || w_value != 0 ||
533 w_length != 1)
534 return -EDOM;
535 VDBG(fsg, "get max LUN\n");
536 *(u8 *)req->buf = fsg->common->nluns - 1;
537
538 /* Respond with data/status */
539 req->length = min((u16)1, w_length);
540 return ep0_queue(fsg->common);
541 }
542
543 VDBG(fsg,
544 "unknown class-specific control req %02x.%02x v%04x i%04x l%u\n",
545 ctrl->bRequestType, ctrl->bRequest,
546 le16_to_cpu(ctrl->wValue), w_index, w_length);
547 return -EOPNOTSUPP;
548}
549
550
551/*-------------------------------------------------------------------------*/
552
553/* All the following routines run in process context */
554
555/* Use this for bulk or interrupt transfers, not ep0 */
556static void start_transfer(struct fsg_dev *fsg, struct usb_ep *ep,
557 struct usb_request *req, int *pbusy,
558 enum fsg_buffer_state *state)
559{
560 int rc;
561
562 if (ep == fsg->bulk_in)
563 dump_msg(fsg, "bulk-in", req->buf, req->length);
564
565 spin_lock_irq(&fsg->common->lock);
566 *pbusy = 1;
567 *state = BUF_STATE_BUSY;
568 spin_unlock_irq(&fsg->common->lock);
569 rc = usb_ep_queue(ep, req, GFP_KERNEL);
570 if (rc != 0) {
571 *pbusy = 0;
572 *state = BUF_STATE_EMPTY;
573
574 /* We can't do much more than wait for a reset */
575
576 /*
577 * Note: currently the net2280 driver fails zero-length
578 * submissions if DMA is enabled.
579 */
580 if (rc != -ESHUTDOWN &&
581 !(rc == -EOPNOTSUPP && req->length == 0))
582 WARNING(fsg, "error in submission: %s --> %d\n",
583 ep->name, rc);
584 }
585}
586
587static bool start_in_transfer(struct fsg_common *common, struct fsg_buffhd *bh)
588{
589 if (!fsg_is_set(common))
590 return false;
591 start_transfer(common->fsg, common->fsg->bulk_in,
592 bh->inreq, &bh->inreq_busy, &bh->state);
593 return true;
594}
595
596static bool start_out_transfer(struct fsg_common *common, struct fsg_buffhd *bh)
597{
598 if (!fsg_is_set(common))
599 return false;
600 start_transfer(common->fsg, common->fsg->bulk_out,
601 bh->outreq, &bh->outreq_busy, &bh->state);
602 return true;
603}
604
605static int sleep_thread(struct fsg_common *common, bool can_freeze)
606{
607 int rc = 0;
608
609 /* Wait until a signal arrives or we are woken up */
610 for (;;) {
611 if (can_freeze)
612 try_to_freeze();
613 set_current_state(TASK_INTERRUPTIBLE);
614 if (signal_pending(current)) {
615 rc = -EINTR;
616 break;
617 }
618 if (common->thread_wakeup_needed)
619 break;
620 schedule();
621 }
622 __set_current_state(TASK_RUNNING);
623 common->thread_wakeup_needed = 0;
624 smp_rmb(); /* ensure the latest bh->state is visible */
625 return rc;
626}
627
628
629/*-------------------------------------------------------------------------*/
630
631static int do_read(struct fsg_common *common)
632{
633 struct fsg_lun *curlun = common->curlun;
634 u32 lba;
635 struct fsg_buffhd *bh;
636 int rc;
637 u32 amount_left;
638 loff_t file_offset, file_offset_tmp;
639 unsigned int amount;
640 ssize_t nread;
641
642 /*
643 * Get the starting Logical Block Address and check that it's
644 * not too big.
645 */
646 if (common->cmnd[0] == READ_6)
647 lba = get_unaligned_be24(&common->cmnd[1]);
648 else {
649 lba = get_unaligned_be32(&common->cmnd[2]);
650
651 /*
652 * We allow DPO (Disable Page Out = don't save data in the
653 * cache) and FUA (Force Unit Access = don't read from the
654 * cache), but we don't implement them.
655 */
656 if ((common->cmnd[1] & ~0x18) != 0) {
657 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
658 return -EINVAL;
659 }
660 }
661 if (lba >= curlun->num_sectors) {
662 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
663 return -EINVAL;
664 }
665 file_offset = ((loff_t) lba) << curlun->blkbits;
666
667 /* Carry out the file reads */
668 amount_left = common->data_size_from_cmnd;
669 if (unlikely(amount_left == 0))
670 return -EIO; /* No default reply */
671
672 for (;;) {
673 /*
674 * Figure out how much we need to read:
675 * Try to read the remaining amount.
676 * But don't read more than the buffer size.
677 * And don't try to read past the end of the file.
678 */
679 amount = min(amount_left, FSG_BUFLEN);
680 amount = min((loff_t)amount,
681 curlun->file_length - file_offset);
682
683 /* Wait for the next buffer to become available */
684 bh = common->next_buffhd_to_fill;
685 while (bh->state != BUF_STATE_EMPTY) {
686 rc = sleep_thread(common, false);
687 if (rc)
688 return rc;
689 }
690
691 /*
692 * If we were asked to read past the end of file,
693 * end with an empty buffer.
694 */
695 if (amount == 0) {
696 curlun->sense_data =
697 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
698 curlun->sense_data_info =
699 file_offset >> curlun->blkbits;
700 curlun->info_valid = 1;
701 bh->inreq->length = 0;
702 bh->state = BUF_STATE_FULL;
703 break;
704 }
705
706 /* Perform the read */
707 file_offset_tmp = file_offset;
708 nread = vfs_read(curlun->filp,
709 (char __user *)bh->buf,
710 amount, &file_offset_tmp);
711 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
712 (unsigned long long)file_offset, (int)nread);
713 if (signal_pending(current))
714 return -EINTR;
715
716 if (nread < 0) {
717 LDBG(curlun, "error in file read: %d\n", (int)nread);
718 nread = 0;
719 } else if (nread < amount) {
720 LDBG(curlun, "partial file read: %d/%u\n",
721 (int)nread, amount);
722 nread = round_down(nread, curlun->blksize);
723 }
724 file_offset += nread;
725 amount_left -= nread;
726 common->residue -= nread;
727
728 /*
729 * Except at the end of the transfer, nread will be
730 * equal to the buffer size, which is divisible by the
731 * bulk-in maxpacket size.
732 */
733 bh->inreq->length = nread;
734 bh->state = BUF_STATE_FULL;
735
736 /* If an error occurred, report it and its position */
737 if (nread < amount) {
738 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
739 curlun->sense_data_info =
740 file_offset >> curlun->blkbits;
741 curlun->info_valid = 1;
742 break;
743 }
744
745 if (amount_left == 0)
746 break; /* No more left to read */
747
748 /* Send this buffer and go read some more */
749 bh->inreq->zero = 0;
750 if (!start_in_transfer(common, bh))
751 /* Don't know what to do if common->fsg is NULL */
752 return -EIO;
753 common->next_buffhd_to_fill = bh->next;
754 }
755
756 return -EIO; /* No default reply */
757}
758
759
760/*-------------------------------------------------------------------------*/
761
762static int do_write(struct fsg_common *common)
763{
764 struct fsg_lun *curlun = common->curlun;
765 u32 lba;
766 struct fsg_buffhd *bh;
767 int get_some_more;
768 u32 amount_left_to_req, amount_left_to_write;
769 loff_t usb_offset, file_offset, file_offset_tmp;
770 unsigned int amount;
771 ssize_t nwritten;
772 int rc;
773
774 if (curlun->ro) {
775 curlun->sense_data = SS_WRITE_PROTECTED;
776 return -EINVAL;
777 }
778 spin_lock(&curlun->filp->f_lock);
779 curlun->filp->f_flags &= ~O_SYNC; /* Default is not to wait */
780 spin_unlock(&curlun->filp->f_lock);
781
782 /*
783 * Get the starting Logical Block Address and check that it's
784 * not too big
785 */
786 if (common->cmnd[0] == WRITE_6)
787 lba = get_unaligned_be24(&common->cmnd[1]);
788 else {
789 lba = get_unaligned_be32(&common->cmnd[2]);
790
791 /*
792 * We allow DPO (Disable Page Out = don't save data in the
793 * cache) and FUA (Force Unit Access = write directly to the
794 * medium). We don't implement DPO; we implement FUA by
795 * performing synchronous output.
796 */
797 if (common->cmnd[1] & ~0x18) {
798 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
799 return -EINVAL;
800 }
801 if (!curlun->nofua && (common->cmnd[1] & 0x08)) { /* FUA */
802 spin_lock(&curlun->filp->f_lock);
803 curlun->filp->f_flags |= O_SYNC;
804 spin_unlock(&curlun->filp->f_lock);
805 }
806 }
807 if (lba >= curlun->num_sectors) {
808 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
809 return -EINVAL;
810 }
811
812 /* Carry out the file writes */
813 get_some_more = 1;
814 file_offset = usb_offset = ((loff_t) lba) << curlun->blkbits;
815 amount_left_to_req = common->data_size_from_cmnd;
816 amount_left_to_write = common->data_size_from_cmnd;
817
818 while (amount_left_to_write > 0) {
819
820 /* Queue a request for more data from the host */
821 bh = common->next_buffhd_to_fill;
822 if (bh->state == BUF_STATE_EMPTY && get_some_more) {
823
824 /*
825 * Figure out how much we want to get:
826 * Try to get the remaining amount,
827 * but not more than the buffer size.
828 */
829 amount = min(amount_left_to_req, FSG_BUFLEN);
830
831 /* Beyond the end of the backing file? */
832 if (usb_offset >= curlun->file_length) {
833 get_some_more = 0;
834 curlun->sense_data =
835 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
836 curlun->sense_data_info =
837 usb_offset >> curlun->blkbits;
838 curlun->info_valid = 1;
839 continue;
840 }
841
842 /* Get the next buffer */
843 usb_offset += amount;
844 common->usb_amount_left -= amount;
845 amount_left_to_req -= amount;
846 if (amount_left_to_req == 0)
847 get_some_more = 0;
848
849 /*
850 * Except at the end of the transfer, amount will be
851 * equal to the buffer size, which is divisible by
852 * the bulk-out maxpacket size.
853 */
854 set_bulk_out_req_length(common, bh, amount);
855 if (!start_out_transfer(common, bh))
856 /* Dunno what to do if common->fsg is NULL */
857 return -EIO;
858 common->next_buffhd_to_fill = bh->next;
859 continue;
860 }
861
862 /* Write the received data to the backing file */
863 bh = common->next_buffhd_to_drain;
864 if (bh->state == BUF_STATE_EMPTY && !get_some_more)
865 break; /* We stopped early */
866 if (bh->state == BUF_STATE_FULL) {
867 smp_rmb();
868 common->next_buffhd_to_drain = bh->next;
869 bh->state = BUF_STATE_EMPTY;
870
871 /* Did something go wrong with the transfer? */
872 if (bh->outreq->status != 0) {
873 curlun->sense_data = SS_COMMUNICATION_FAILURE;
874 curlun->sense_data_info =
875 file_offset >> curlun->blkbits;
876 curlun->info_valid = 1;
877 break;
878 }
879
880 amount = bh->outreq->actual;
881 if (curlun->file_length - file_offset < amount) {
882 LERROR(curlun,
883 "write %u @ %llu beyond end %llu\n",
884 amount, (unsigned long long)file_offset,
885 (unsigned long long)curlun->file_length);
886 amount = curlun->file_length - file_offset;
887 }
888
889 /* Don't accept excess data. The spec doesn't say
890 * what to do in this case. We'll ignore the error.
891 */
892 amount = min(amount, bh->bulk_out_intended_length);
893
894 /* Don't write a partial block */
895 amount = round_down(amount, curlun->blksize);
896 if (amount == 0)
897 goto empty_write;
898
899 /* Perform the write */
900 file_offset_tmp = file_offset;
901 nwritten = vfs_write(curlun->filp,
902 (char __user *)bh->buf,
903 amount, &file_offset_tmp);
904 VLDBG(curlun, "file write %u @ %llu -> %d\n", amount,
905 (unsigned long long)file_offset, (int)nwritten);
906 if (signal_pending(current))
907 return -EINTR; /* Interrupted! */
908
909 if (nwritten < 0) {
910 LDBG(curlun, "error in file write: %d\n",
911 (int)nwritten);
912 nwritten = 0;
913 } else if (nwritten < amount) {
914 LDBG(curlun, "partial file write: %d/%u\n",
915 (int)nwritten, amount);
916 nwritten = round_down(nwritten, curlun->blksize);
917 }
918 file_offset += nwritten;
919 amount_left_to_write -= nwritten;
920 common->residue -= nwritten;
921
922 /* If an error occurred, report it and its position */
923 if (nwritten < amount) {
924 curlun->sense_data = SS_WRITE_ERROR;
925 curlun->sense_data_info =
926 file_offset >> curlun->blkbits;
927 curlun->info_valid = 1;
928 break;
929 }
930
931 empty_write:
932 /* Did the host decide to stop early? */
933 if (bh->outreq->actual < bh->bulk_out_intended_length) {
934 common->short_packet_received = 1;
935 break;
936 }
937 continue;
938 }
939
940 /* Wait for something to happen */
941 rc = sleep_thread(common, false);
942 if (rc)
943 return rc;
944 }
945
946 return -EIO; /* No default reply */
947}
948
949
950/*-------------------------------------------------------------------------*/
951
952static int do_synchronize_cache(struct fsg_common *common)
953{
954 struct fsg_lun *curlun = common->curlun;
955 int rc;
956
957 /* We ignore the requested LBA and write out all file's
958 * dirty data buffers. */
959 rc = fsg_lun_fsync_sub(curlun);
960 if (rc)
961 curlun->sense_data = SS_WRITE_ERROR;
962 return 0;
963}
964
965
966/*-------------------------------------------------------------------------*/
967
968static void invalidate_sub(struct fsg_lun *curlun)
969{
970 struct file *filp = curlun->filp;
971 struct inode *inode = file_inode(filp);
972 unsigned long rc;
973
974 rc = invalidate_mapping_pages(inode->i_mapping, 0, -1);
975 VLDBG(curlun, "invalidate_mapping_pages -> %ld\n", rc);
976}
977
978static int do_verify(struct fsg_common *common)
979{
980 struct fsg_lun *curlun = common->curlun;
981 u32 lba;
982 u32 verification_length;
983 struct fsg_buffhd *bh = common->next_buffhd_to_fill;
984 loff_t file_offset, file_offset_tmp;
985 u32 amount_left;
986 unsigned int amount;
987 ssize_t nread;
988
989 /*
990 * Get the starting Logical Block Address and check that it's
991 * not too big.
992 */
993 lba = get_unaligned_be32(&common->cmnd[2]);
994 if (lba >= curlun->num_sectors) {
995 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
996 return -EINVAL;
997 }
998
999 /*
1000 * We allow DPO (Disable Page Out = don't save data in the
1001 * cache) but we don't implement it.
1002 */
1003 if (common->cmnd[1] & ~0x10) {
1004 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1005 return -EINVAL;
1006 }
1007
1008 verification_length = get_unaligned_be16(&common->cmnd[7]);
1009 if (unlikely(verification_length == 0))
1010 return -EIO; /* No default reply */
1011
1012 /* Prepare to carry out the file verify */
1013 amount_left = verification_length << curlun->blkbits;
1014 file_offset = ((loff_t) lba) << curlun->blkbits;
1015
1016 /* Write out all the dirty buffers before invalidating them */
1017 fsg_lun_fsync_sub(curlun);
1018 if (signal_pending(current))
1019 return -EINTR;
1020
1021 invalidate_sub(curlun);
1022 if (signal_pending(current))
1023 return -EINTR;
1024
1025 /* Just try to read the requested blocks */
1026 while (amount_left > 0) {
1027 /*
1028 * Figure out how much we need to read:
1029 * Try to read the remaining amount, but not more than
1030 * the buffer size.
1031 * And don't try to read past the end of the file.
1032 */
1033 amount = min(amount_left, FSG_BUFLEN);
1034 amount = min((loff_t)amount,
1035 curlun->file_length - file_offset);
1036 if (amount == 0) {
1037 curlun->sense_data =
1038 SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1039 curlun->sense_data_info =
1040 file_offset >> curlun->blkbits;
1041 curlun->info_valid = 1;
1042 break;
1043 }
1044
1045 /* Perform the read */
1046 file_offset_tmp = file_offset;
1047 nread = vfs_read(curlun->filp,
1048 (char __user *) bh->buf,
1049 amount, &file_offset_tmp);
1050 VLDBG(curlun, "file read %u @ %llu -> %d\n", amount,
1051 (unsigned long long) file_offset,
1052 (int) nread);
1053 if (signal_pending(current))
1054 return -EINTR;
1055
1056 if (nread < 0) {
1057 LDBG(curlun, "error in file verify: %d\n", (int)nread);
1058 nread = 0;
1059 } else if (nread < amount) {
1060 LDBG(curlun, "partial file verify: %d/%u\n",
1061 (int)nread, amount);
1062 nread = round_down(nread, curlun->blksize);
1063 }
1064 if (nread == 0) {
1065 curlun->sense_data = SS_UNRECOVERED_READ_ERROR;
1066 curlun->sense_data_info =
1067 file_offset >> curlun->blkbits;
1068 curlun->info_valid = 1;
1069 break;
1070 }
1071 file_offset += nread;
1072 amount_left -= nread;
1073 }
1074 return 0;
1075}
1076
1077
1078/*-------------------------------------------------------------------------*/
1079
1080static int do_inquiry(struct fsg_common *common, struct fsg_buffhd *bh)
1081{
1082 struct fsg_lun *curlun = common->curlun;
1083 u8 *buf = (u8 *) bh->buf;
1084
1085 if (!curlun) { /* Unsupported LUNs are okay */
1086 common->bad_lun_okay = 1;
1087 memset(buf, 0, 36);
1088 buf[0] = 0x7f; /* Unsupported, no device-type */
1089 buf[4] = 31; /* Additional length */
1090 return 36;
1091 }
1092
1093 buf[0] = curlun->cdrom ? TYPE_ROM : TYPE_DISK;
1094 buf[1] = curlun->removable ? 0x80 : 0;
1095 buf[2] = 2; /* ANSI SCSI level 2 */
1096 buf[3] = 2; /* SCSI-2 INQUIRY data format */
1097 buf[4] = 31; /* Additional length */
1098 buf[5] = 0; /* No special options */
1099 buf[6] = 0;
1100 buf[7] = 0;
1101 memcpy(buf + 8, common->inquiry_string, sizeof common->inquiry_string);
1102 return 36;
1103}
1104
1105static int do_request_sense(struct fsg_common *common, struct fsg_buffhd *bh)
1106{
1107 struct fsg_lun *curlun = common->curlun;
1108 u8 *buf = (u8 *) bh->buf;
1109 u32 sd, sdinfo;
1110 int valid;
1111
1112 /*
1113 * From the SCSI-2 spec., section 7.9 (Unit attention condition):
1114 *
1115 * If a REQUEST SENSE command is received from an initiator
1116 * with a pending unit attention condition (before the target
1117 * generates the contingent allegiance condition), then the
1118 * target shall either:
1119 * a) report any pending sense data and preserve the unit
1120 * attention condition on the logical unit, or,
1121 * b) report the unit attention condition, may discard any
1122 * pending sense data, and clear the unit attention
1123 * condition on the logical unit for that initiator.
1124 *
1125 * FSG normally uses option a); enable this code to use option b).
1126 */
1127#if 0
1128 if (curlun && curlun->unit_attention_data != SS_NO_SENSE) {
1129 curlun->sense_data = curlun->unit_attention_data;
1130 curlun->unit_attention_data = SS_NO_SENSE;
1131 }
1132#endif
1133
1134 if (!curlun) { /* Unsupported LUNs are okay */
1135 common->bad_lun_okay = 1;
1136 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1137 sdinfo = 0;
1138 valid = 0;
1139 } else {
1140 sd = curlun->sense_data;
1141 sdinfo = curlun->sense_data_info;
1142 valid = curlun->info_valid << 7;
1143 curlun->sense_data = SS_NO_SENSE;
1144 curlun->sense_data_info = 0;
1145 curlun->info_valid = 0;
1146 }
1147
1148 memset(buf, 0, 18);
1149 buf[0] = valid | 0x70; /* Valid, current error */
1150 buf[2] = SK(sd);
1151 put_unaligned_be32(sdinfo, &buf[3]); /* Sense information */
1152 buf[7] = 18 - 8; /* Additional sense length */
1153 buf[12] = ASC(sd);
1154 buf[13] = ASCQ(sd);
1155 return 18;
1156}
1157
1158static int do_read_capacity(struct fsg_common *common, struct fsg_buffhd *bh)
1159{
1160 struct fsg_lun *curlun = common->curlun;
1161 u32 lba = get_unaligned_be32(&common->cmnd[2]);
1162 int pmi = common->cmnd[8];
1163 u8 *buf = (u8 *)bh->buf;
1164
1165 /* Check the PMI and LBA fields */
1166 if (pmi > 1 || (pmi == 0 && lba != 0)) {
1167 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1168 return -EINVAL;
1169 }
1170
1171 put_unaligned_be32(curlun->num_sectors - 1, &buf[0]);
1172 /* Max logical block */
1173 put_unaligned_be32(curlun->blksize, &buf[4]);/* Block length */
1174 return 8;
1175}
1176
1177static int do_read_header(struct fsg_common *common, struct fsg_buffhd *bh)
1178{
1179 struct fsg_lun *curlun = common->curlun;
1180 int msf = common->cmnd[1] & 0x02;
1181 u32 lba = get_unaligned_be32(&common->cmnd[2]);
1182 u8 *buf = (u8 *)bh->buf;
1183
1184 if (common->cmnd[1] & ~0x02) { /* Mask away MSF */
1185 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1186 return -EINVAL;
1187 }
1188 if (lba >= curlun->num_sectors) {
1189 curlun->sense_data = SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE;
1190 return -EINVAL;
1191 }
1192
1193 memset(buf, 0, 8);
1194 buf[0] = 0x01; /* 2048 bytes of user data, rest is EC */
1195 store_cdrom_address(&buf[4], msf, lba);
1196 return 8;
1197}
1198
1199static int do_read_toc(struct fsg_common *common, struct fsg_buffhd *bh)
1200{
1201 struct fsg_lun *curlun = common->curlun;
1202 int msf = common->cmnd[1] & 0x02;
1203 int start_track = common->cmnd[6];
1204 u8 *buf = (u8 *)bh->buf;
1205
1206 if ((common->cmnd[1] & ~0x02) != 0 || /* Mask away MSF */
1207 start_track > 1) {
1208 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1209 return -EINVAL;
1210 }
1211
1212 memset(buf, 0, 20);
1213 buf[1] = (20-2); /* TOC data length */
1214 buf[2] = 1; /* First track number */
1215 buf[3] = 1; /* Last track number */
1216 buf[5] = 0x16; /* Data track, copying allowed */
1217 buf[6] = 0x01; /* Only track is number 1 */
1218 store_cdrom_address(&buf[8], msf, 0);
1219
1220 buf[13] = 0x16; /* Lead-out track is data */
1221 buf[14] = 0xAA; /* Lead-out track number */
1222 store_cdrom_address(&buf[16], msf, curlun->num_sectors);
1223 return 20;
1224}
1225
1226static int do_mode_sense(struct fsg_common *common, struct fsg_buffhd *bh)
1227{
1228 struct fsg_lun *curlun = common->curlun;
1229 int mscmnd = common->cmnd[0];
1230 u8 *buf = (u8 *) bh->buf;
1231 u8 *buf0 = buf;
1232 int pc, page_code;
1233 int changeable_values, all_pages;
1234 int valid_page = 0;
1235 int len, limit;
1236
1237 if ((common->cmnd[1] & ~0x08) != 0) { /* Mask away DBD */
1238 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1239 return -EINVAL;
1240 }
1241 pc = common->cmnd[2] >> 6;
1242 page_code = common->cmnd[2] & 0x3f;
1243 if (pc == 3) {
1244 curlun->sense_data = SS_SAVING_PARAMETERS_NOT_SUPPORTED;
1245 return -EINVAL;
1246 }
1247 changeable_values = (pc == 1);
1248 all_pages = (page_code == 0x3f);
1249
1250 /*
1251 * Write the mode parameter header. Fixed values are: default
1252 * medium type, no cache control (DPOFUA), and no block descriptors.
1253 * The only variable value is the WriteProtect bit. We will fill in
1254 * the mode data length later.
1255 */
1256 memset(buf, 0, 8);
1257 if (mscmnd == MODE_SENSE) {
1258 buf[2] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */
1259 buf += 4;
1260 limit = 255;
1261 } else { /* MODE_SENSE_10 */
1262 buf[3] = (curlun->ro ? 0x80 : 0x00); /* WP, DPOFUA */
1263 buf += 8;
1264 limit = 65535; /* Should really be FSG_BUFLEN */
1265 }
1266
1267 /* No block descriptors */
1268
1269 /*
1270 * The mode pages, in numerical order. The only page we support
1271 * is the Caching page.
1272 */
1273 if (page_code == 0x08 || all_pages) {
1274 valid_page = 1;
1275 buf[0] = 0x08; /* Page code */
1276 buf[1] = 10; /* Page length */
1277 memset(buf+2, 0, 10); /* None of the fields are changeable */
1278
1279 if (!changeable_values) {
1280 buf[2] = 0x04; /* Write cache enable, */
1281 /* Read cache not disabled */
1282 /* No cache retention priorities */
1283 put_unaligned_be16(0xffff, &buf[4]);
1284 /* Don't disable prefetch */
1285 /* Minimum prefetch = 0 */
1286 put_unaligned_be16(0xffff, &buf[8]);
1287 /* Maximum prefetch */
1288 put_unaligned_be16(0xffff, &buf[10]);
1289 /* Maximum prefetch ceiling */
1290 }
1291 buf += 12;
1292 }
1293
1294 /*
1295 * Check that a valid page was requested and the mode data length
1296 * isn't too long.
1297 */
1298 len = buf - buf0;
1299 if (!valid_page || len > limit) {
1300 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1301 return -EINVAL;
1302 }
1303
1304 /* Store the mode data length */
1305 if (mscmnd == MODE_SENSE)
1306 buf0[0] = len - 1;
1307 else
1308 put_unaligned_be16(len - 2, buf0);
1309 return len;
1310}
1311
1312static int do_start_stop(struct fsg_common *common)
1313{
1314 struct fsg_lun *curlun = common->curlun;
1315 int loej, start;
1316
1317 if (!curlun) {
1318 return -EINVAL;
1319 } else if (!curlun->removable) {
1320 curlun->sense_data = SS_INVALID_COMMAND;
1321 return -EINVAL;
1322 } else if ((common->cmnd[1] & ~0x01) != 0 || /* Mask away Immed */
1323 (common->cmnd[4] & ~0x03) != 0) { /* Mask LoEj, Start */
1324 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1325 return -EINVAL;
1326 }
1327
1328 loej = common->cmnd[4] & 0x02;
1329 start = common->cmnd[4] & 0x01;
1330
1331 /*
1332 * Our emulation doesn't support mounting; the medium is
1333 * available for use as soon as it is loaded.
1334 */
1335 if (start) {
1336 if (!fsg_lun_is_open(curlun)) {
1337 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
1338 return -EINVAL;
1339 }
1340 return 0;
1341 }
1342
1343 /* Are we allowed to unload the media? */
1344 if (curlun->prevent_medium_removal) {
1345 LDBG(curlun, "unload attempt prevented\n");
1346 curlun->sense_data = SS_MEDIUM_REMOVAL_PREVENTED;
1347 return -EINVAL;
1348 }
1349
1350 if (!loej)
1351 return 0;
1352
1353 up_read(&common->filesem);
1354 down_write(&common->filesem);
1355 fsg_lun_close(curlun);
1356 up_write(&common->filesem);
1357 down_read(&common->filesem);
1358
1359 return 0;
1360}
1361
1362static int do_prevent_allow(struct fsg_common *common)
1363{
1364 struct fsg_lun *curlun = common->curlun;
1365 int prevent;
1366
1367 if (!common->curlun) {
1368 return -EINVAL;
1369 } else if (!common->curlun->removable) {
1370 common->curlun->sense_data = SS_INVALID_COMMAND;
1371 return -EINVAL;
1372 }
1373
1374 prevent = common->cmnd[4] & 0x01;
1375 if ((common->cmnd[4] & ~0x01) != 0) { /* Mask away Prevent */
1376 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1377 return -EINVAL;
1378 }
1379
1380 if (curlun->prevent_medium_removal && !prevent)
1381 fsg_lun_fsync_sub(curlun);
1382 curlun->prevent_medium_removal = prevent;
1383 return 0;
1384}
1385
1386static int do_read_format_capacities(struct fsg_common *common,
1387 struct fsg_buffhd *bh)
1388{
1389 struct fsg_lun *curlun = common->curlun;
1390 u8 *buf = (u8 *) bh->buf;
1391
1392 buf[0] = buf[1] = buf[2] = 0;
1393 buf[3] = 8; /* Only the Current/Maximum Capacity Descriptor */
1394 buf += 4;
1395
1396 put_unaligned_be32(curlun->num_sectors, &buf[0]);
1397 /* Number of blocks */
1398 put_unaligned_be32(curlun->blksize, &buf[4]);/* Block length */
1399 buf[4] = 0x02; /* Current capacity */
1400 return 12;
1401}
1402
1403static int do_mode_select(struct fsg_common *common, struct fsg_buffhd *bh)
1404{
1405 struct fsg_lun *curlun = common->curlun;
1406
1407 /* We don't support MODE SELECT */
1408 if (curlun)
1409 curlun->sense_data = SS_INVALID_COMMAND;
1410 return -EINVAL;
1411}
1412
1413
1414/*-------------------------------------------------------------------------*/
1415
1416static int halt_bulk_in_endpoint(struct fsg_dev *fsg)
1417{
1418 int rc;
1419
1420 rc = fsg_set_halt(fsg, fsg->bulk_in);
1421 if (rc == -EAGAIN)
1422 VDBG(fsg, "delayed bulk-in endpoint halt\n");
1423 while (rc != 0) {
1424 if (rc != -EAGAIN) {
1425 WARNING(fsg, "usb_ep_set_halt -> %d\n", rc);
1426 rc = 0;
1427 break;
1428 }
1429
1430 /* Wait for a short time and then try again */
1431 if (msleep_interruptible(100) != 0)
1432 return -EINTR;
1433 rc = usb_ep_set_halt(fsg->bulk_in);
1434 }
1435 return rc;
1436}
1437
1438static int wedge_bulk_in_endpoint(struct fsg_dev *fsg)
1439{
1440 int rc;
1441
1442 DBG(fsg, "bulk-in set wedge\n");
1443 rc = usb_ep_set_wedge(fsg->bulk_in);
1444 if (rc == -EAGAIN)
1445 VDBG(fsg, "delayed bulk-in endpoint wedge\n");
1446 while (rc != 0) {
1447 if (rc != -EAGAIN) {
1448 WARNING(fsg, "usb_ep_set_wedge -> %d\n", rc);
1449 rc = 0;
1450 break;
1451 }
1452
1453 /* Wait for a short time and then try again */
1454 if (msleep_interruptible(100) != 0)
1455 return -EINTR;
1456 rc = usb_ep_set_wedge(fsg->bulk_in);
1457 }
1458 return rc;
1459}
1460
1461static int throw_away_data(struct fsg_common *common)
1462{
1463 struct fsg_buffhd *bh;
1464 u32 amount;
1465 int rc;
1466
1467 for (bh = common->next_buffhd_to_drain;
1468 bh->state != BUF_STATE_EMPTY || common->usb_amount_left > 0;
1469 bh = common->next_buffhd_to_drain) {
1470
1471 /* Throw away the data in a filled buffer */
1472 if (bh->state == BUF_STATE_FULL) {
1473 smp_rmb();
1474 bh->state = BUF_STATE_EMPTY;
1475 common->next_buffhd_to_drain = bh->next;
1476
1477 /* A short packet or an error ends everything */
1478 if (bh->outreq->actual < bh->bulk_out_intended_length ||
1479 bh->outreq->status != 0) {
1480 raise_exception(common,
1481 FSG_STATE_ABORT_BULK_OUT);
1482 return -EINTR;
1483 }
1484 continue;
1485 }
1486
1487 /* Try to submit another request if we need one */
1488 bh = common->next_buffhd_to_fill;
1489 if (bh->state == BUF_STATE_EMPTY
1490 && common->usb_amount_left > 0) {
1491 amount = min(common->usb_amount_left, FSG_BUFLEN);
1492
1493 /*
1494 * Except at the end of the transfer, amount will be
1495 * equal to the buffer size, which is divisible by
1496 * the bulk-out maxpacket size.
1497 */
1498 set_bulk_out_req_length(common, bh, amount);
1499 if (!start_out_transfer(common, bh))
1500 /* Dunno what to do if common->fsg is NULL */
1501 return -EIO;
1502 common->next_buffhd_to_fill = bh->next;
1503 common->usb_amount_left -= amount;
1504 continue;
1505 }
1506
1507 /* Otherwise wait for something to happen */
1508 rc = sleep_thread(common, true);
1509 if (rc)
1510 return rc;
1511 }
1512 return 0;
1513}
1514
1515static int finish_reply(struct fsg_common *common)
1516{
1517 struct fsg_buffhd *bh = common->next_buffhd_to_fill;
1518 int rc = 0;
1519
1520 switch (common->data_dir) {
1521 case DATA_DIR_NONE:
1522 break; /* Nothing to send */
1523
1524 /*
1525 * If we don't know whether the host wants to read or write,
1526 * this must be CB or CBI with an unknown command. We mustn't
1527 * try to send or receive any data. So stall both bulk pipes
1528 * if we can and wait for a reset.
1529 */
1530 case DATA_DIR_UNKNOWN:
1531 if (!common->can_stall) {
1532 /* Nothing */
1533 } else if (fsg_is_set(common)) {
1534 fsg_set_halt(common->fsg, common->fsg->bulk_out);
1535 rc = halt_bulk_in_endpoint(common->fsg);
1536 } else {
1537 /* Don't know what to do if common->fsg is NULL */
1538 rc = -EIO;
1539 }
1540 break;
1541
1542 /* All but the last buffer of data must have already been sent */
1543 case DATA_DIR_TO_HOST:
1544 if (common->data_size == 0) {
1545 /* Nothing to send */
1546
1547 /* Don't know what to do if common->fsg is NULL */
1548 } else if (!fsg_is_set(common)) {
1549 rc = -EIO;
1550
1551 /* If there's no residue, simply send the last buffer */
1552 } else if (common->residue == 0) {
1553 bh->inreq->zero = 0;
1554 if (!start_in_transfer(common, bh))
1555 return -EIO;
1556 common->next_buffhd_to_fill = bh->next;
1557
1558 /*
1559 * For Bulk-only, mark the end of the data with a short
1560 * packet. If we are allowed to stall, halt the bulk-in
1561 * endpoint. (Note: This violates the Bulk-Only Transport
1562 * specification, which requires us to pad the data if we
1563 * don't halt the endpoint. Presumably nobody will mind.)
1564 */
1565 } else {
1566 bh->inreq->zero = 1;
1567 if (!start_in_transfer(common, bh))
1568 rc = -EIO;
1569 common->next_buffhd_to_fill = bh->next;
1570 if (common->can_stall)
1571 rc = halt_bulk_in_endpoint(common->fsg);
1572 }
1573 break;
1574
1575 /*
1576 * We have processed all we want from the data the host has sent.
1577 * There may still be outstanding bulk-out requests.
1578 */
1579 case DATA_DIR_FROM_HOST:
1580 if (common->residue == 0) {
1581 /* Nothing to receive */
1582
1583 /* Did the host stop sending unexpectedly early? */
1584 } else if (common->short_packet_received) {
1585 raise_exception(common, FSG_STATE_ABORT_BULK_OUT);
1586 rc = -EINTR;
1587
1588 /*
1589 * We haven't processed all the incoming data. Even though
1590 * we may be allowed to stall, doing so would cause a race.
1591 * The controller may already have ACK'ed all the remaining
1592 * bulk-out packets, in which case the host wouldn't see a
1593 * STALL. Not realizing the endpoint was halted, it wouldn't
1594 * clear the halt -- leading to problems later on.
1595 */
1596#if 0
1597 } else if (common->can_stall) {
1598 if (fsg_is_set(common))
1599 fsg_set_halt(common->fsg,
1600 common->fsg->bulk_out);
1601 raise_exception(common, FSG_STATE_ABORT_BULK_OUT);
1602 rc = -EINTR;
1603#endif
1604
1605 /*
1606 * We can't stall. Read in the excess data and throw it
1607 * all away.
1608 */
1609 } else {
1610 rc = throw_away_data(common);
1611 }
1612 break;
1613 }
1614 return rc;
1615}
1616
1617static int send_status(struct fsg_common *common)
1618{
1619 struct fsg_lun *curlun = common->curlun;
1620 struct fsg_buffhd *bh;
1621 struct bulk_cs_wrap *csw;
1622 int rc;
1623 u8 status = US_BULK_STAT_OK;
1624 u32 sd, sdinfo = 0;
1625
1626 /* Wait for the next buffer to become available */
1627 bh = common->next_buffhd_to_fill;
1628 while (bh->state != BUF_STATE_EMPTY) {
1629 rc = sleep_thread(common, true);
1630 if (rc)
1631 return rc;
1632 }
1633
1634 if (curlun) {
1635 sd = curlun->sense_data;
1636 sdinfo = curlun->sense_data_info;
1637 } else if (common->bad_lun_okay)
1638 sd = SS_NO_SENSE;
1639 else
1640 sd = SS_LOGICAL_UNIT_NOT_SUPPORTED;
1641
1642 if (common->phase_error) {
1643 DBG(common, "sending phase-error status\n");
1644 status = US_BULK_STAT_PHASE;
1645 sd = SS_INVALID_COMMAND;
1646 } else if (sd != SS_NO_SENSE) {
1647 DBG(common, "sending command-failure status\n");
1648 status = US_BULK_STAT_FAIL;
1649 VDBG(common, " sense data: SK x%02x, ASC x%02x, ASCQ x%02x;"
1650 " info x%x\n",
1651 SK(sd), ASC(sd), ASCQ(sd), sdinfo);
1652 }
1653
1654 /* Store and send the Bulk-only CSW */
1655 csw = (void *)bh->buf;
1656
1657 csw->Signature = cpu_to_le32(US_BULK_CS_SIGN);
1658 csw->Tag = common->tag;
1659 csw->Residue = cpu_to_le32(common->residue);
1660 csw->Status = status;
1661
1662 bh->inreq->length = US_BULK_CS_WRAP_LEN;
1663 bh->inreq->zero = 0;
1664 if (!start_in_transfer(common, bh))
1665 /* Don't know what to do if common->fsg is NULL */
1666 return -EIO;
1667
1668 common->next_buffhd_to_fill = bh->next;
1669 return 0;
1670}
1671
1672
1673/*-------------------------------------------------------------------------*/
1674
1675/*
1676 * Check whether the command is properly formed and whether its data size
1677 * and direction agree with the values we already have.
1678 */
1679static int check_command(struct fsg_common *common, int cmnd_size,
1680 enum data_direction data_dir, unsigned int mask,
1681 int needs_medium, const char *name)
1682{
1683 int i;
1684 unsigned int lun = common->cmnd[1] >> 5;
1685 static const char dirletter[4] = {'u', 'o', 'i', 'n'};
1686 char hdlen[20];
1687 struct fsg_lun *curlun;
1688
1689 hdlen[0] = 0;
1690 if (common->data_dir != DATA_DIR_UNKNOWN)
1691 sprintf(hdlen, ", H%c=%u", dirletter[(int) common->data_dir],
1692 common->data_size);
1693 VDBG(common, "SCSI command: %s; Dc=%d, D%c=%u; Hc=%d%s\n",
1694 name, cmnd_size, dirletter[(int) data_dir],
1695 common->data_size_from_cmnd, common->cmnd_size, hdlen);
1696
1697 /*
1698 * We can't reply at all until we know the correct data direction
1699 * and size.
1700 */
1701 if (common->data_size_from_cmnd == 0)
1702 data_dir = DATA_DIR_NONE;
1703 if (common->data_size < common->data_size_from_cmnd) {
1704 /*
1705 * Host data size < Device data size is a phase error.
1706 * Carry out the command, but only transfer as much as
1707 * we are allowed.
1708 */
1709 common->data_size_from_cmnd = common->data_size;
1710 common->phase_error = 1;
1711 }
1712 common->residue = common->data_size;
1713 common->usb_amount_left = common->data_size;
1714
1715 /* Conflicting data directions is a phase error */
1716 if (common->data_dir != data_dir && common->data_size_from_cmnd > 0) {
1717 common->phase_error = 1;
1718 return -EINVAL;
1719 }
1720
1721 /* Verify the length of the command itself */
1722 if (cmnd_size != common->cmnd_size) {
1723
1724 /*
1725 * Special case workaround: There are plenty of buggy SCSI
1726 * implementations. Many have issues with cbw->Length
1727 * field passing a wrong command size. For those cases we
1728 * always try to work around the problem by using the length
1729 * sent by the host side provided it is at least as large
1730 * as the correct command length.
1731 * Examples of such cases would be MS-Windows, which issues
1732 * REQUEST SENSE with cbw->Length == 12 where it should
1733 * be 6, and xbox360 issuing INQUIRY, TEST UNIT READY and
1734 * REQUEST SENSE with cbw->Length == 10 where it should
1735 * be 6 as well.
1736 */
1737 if (cmnd_size <= common->cmnd_size) {
1738 DBG(common, "%s is buggy! Expected length %d "
1739 "but we got %d\n", name,
1740 cmnd_size, common->cmnd_size);
1741 cmnd_size = common->cmnd_size;
1742 } else {
1743 common->phase_error = 1;
1744 return -EINVAL;
1745 }
1746 }
1747
1748 /* Check that the LUN values are consistent */
1749 if (common->lun != lun)
1750 DBG(common, "using LUN %u from CBW, not LUN %u from CDB\n",
1751 common->lun, lun);
1752
1753 /* Check the LUN */
1754 curlun = common->curlun;
1755 if (curlun) {
1756 if (common->cmnd[0] != REQUEST_SENSE) {
1757 curlun->sense_data = SS_NO_SENSE;
1758 curlun->sense_data_info = 0;
1759 curlun->info_valid = 0;
1760 }
1761 } else {
1762 common->bad_lun_okay = 0;
1763
1764 /*
1765 * INQUIRY and REQUEST SENSE commands are explicitly allowed
1766 * to use unsupported LUNs; all others may not.
1767 */
1768 if (common->cmnd[0] != INQUIRY &&
1769 common->cmnd[0] != REQUEST_SENSE) {
1770 DBG(common, "unsupported LUN %u\n", common->lun);
1771 return -EINVAL;
1772 }
1773 }
1774
1775 /*
1776 * If a unit attention condition exists, only INQUIRY and
1777 * REQUEST SENSE commands are allowed; anything else must fail.
1778 */
1779 if (curlun && curlun->unit_attention_data != SS_NO_SENSE &&
1780 common->cmnd[0] != INQUIRY &&
1781 common->cmnd[0] != REQUEST_SENSE) {
1782 curlun->sense_data = curlun->unit_attention_data;
1783 curlun->unit_attention_data = SS_NO_SENSE;
1784 return -EINVAL;
1785 }
1786
1787 /* Check that only command bytes listed in the mask are non-zero */
1788 common->cmnd[1] &= 0x1f; /* Mask away the LUN */
1789 for (i = 1; i < cmnd_size; ++i) {
1790 if (common->cmnd[i] && !(mask & (1 << i))) {
1791 if (curlun)
1792 curlun->sense_data = SS_INVALID_FIELD_IN_CDB;
1793 return -EINVAL;
1794 }
1795 }
1796
1797 /* If the medium isn't mounted and the command needs to access
1798 * it, return an error. */
1799 if (curlun && !fsg_lun_is_open(curlun) && needs_medium) {
1800 curlun->sense_data = SS_MEDIUM_NOT_PRESENT;
1801 return -EINVAL;
1802 }
1803
1804 return 0;
1805}
1806
1807/* wrapper of check_command for data size in blocks handling */
1808static int check_command_size_in_blocks(struct fsg_common *common,
1809 int cmnd_size, enum data_direction data_dir,
1810 unsigned int mask, int needs_medium, const char *name)
1811{
1812 if (common->curlun)
1813 common->data_size_from_cmnd <<= common->curlun->blkbits;
1814 return check_command(common, cmnd_size, data_dir,
1815 mask, needs_medium, name);
1816}
1817
1818static int do_scsi_command(struct fsg_common *common)
1819{
1820 struct fsg_buffhd *bh;
1821 int rc;
1822 int reply = -EINVAL;
1823 int i;
1824 static char unknown[16];
1825
1826 dump_cdb(common);
1827
1828 /* Wait for the next buffer to become available for data or status */
1829 bh = common->next_buffhd_to_fill;
1830 common->next_buffhd_to_drain = bh;
1831 while (bh->state != BUF_STATE_EMPTY) {
1832 rc = sleep_thread(common, true);
1833 if (rc)
1834 return rc;
1835 }
1836 common->phase_error = 0;
1837 common->short_packet_received = 0;
1838
1839 down_read(&common->filesem); /* We're using the backing file */
1840 switch (common->cmnd[0]) {
1841
1842 case INQUIRY:
1843 common->data_size_from_cmnd = common->cmnd[4];
1844 reply = check_command(common, 6, DATA_DIR_TO_HOST,
1845 (1<<4), 0,
1846 "INQUIRY");
1847 if (reply == 0)
1848 reply = do_inquiry(common, bh);
1849 break;
1850
1851 case MODE_SELECT:
1852 common->data_size_from_cmnd = common->cmnd[4];
1853 reply = check_command(common, 6, DATA_DIR_FROM_HOST,
1854 (1<<1) | (1<<4), 0,
1855 "MODE SELECT(6)");
1856 if (reply == 0)
1857 reply = do_mode_select(common, bh);
1858 break;
1859
1860 case MODE_SELECT_10:
1861 common->data_size_from_cmnd =
1862 get_unaligned_be16(&common->cmnd[7]);
1863 reply = check_command(common, 10, DATA_DIR_FROM_HOST,
1864 (1<<1) | (3<<7), 0,
1865 "MODE SELECT(10)");
1866 if (reply == 0)
1867 reply = do_mode_select(common, bh);
1868 break;
1869
1870 case MODE_SENSE:
1871 common->data_size_from_cmnd = common->cmnd[4];
1872 reply = check_command(common, 6, DATA_DIR_TO_HOST,
1873 (1<<1) | (1<<2) | (1<<4), 0,
1874 "MODE SENSE(6)");
1875 if (reply == 0)
1876 reply = do_mode_sense(common, bh);
1877 break;
1878
1879 case MODE_SENSE_10:
1880 common->data_size_from_cmnd =
1881 get_unaligned_be16(&common->cmnd[7]);
1882 reply = check_command(common, 10, DATA_DIR_TO_HOST,
1883 (1<<1) | (1<<2) | (3<<7), 0,
1884 "MODE SENSE(10)");
1885 if (reply == 0)
1886 reply = do_mode_sense(common, bh);
1887 break;
1888
1889 case ALLOW_MEDIUM_REMOVAL:
1890 common->data_size_from_cmnd = 0;
1891 reply = check_command(common, 6, DATA_DIR_NONE,
1892 (1<<4), 0,
1893 "PREVENT-ALLOW MEDIUM REMOVAL");
1894 if (reply == 0)
1895 reply = do_prevent_allow(common);
1896 break;
1897
1898 case READ_6:
1899 i = common->cmnd[4];
1900 common->data_size_from_cmnd = (i == 0) ? 256 : i;
1901 reply = check_command_size_in_blocks(common, 6,
1902 DATA_DIR_TO_HOST,
1903 (7<<1) | (1<<4), 1,
1904 "READ(6)");
1905 if (reply == 0)
1906 reply = do_read(common);
1907 break;
1908
1909 case READ_10:
1910 common->data_size_from_cmnd =
1911 get_unaligned_be16(&common->cmnd[7]);
1912 reply = check_command_size_in_blocks(common, 10,
1913 DATA_DIR_TO_HOST,
1914 (1<<1) | (0xf<<2) | (3<<7), 1,
1915 "READ(10)");
1916 if (reply == 0)
1917 reply = do_read(common);
1918 break;
1919
1920 case READ_12:
1921 common->data_size_from_cmnd =
1922 get_unaligned_be32(&common->cmnd[6]);
1923 reply = check_command_size_in_blocks(common, 12,
1924 DATA_DIR_TO_HOST,
1925 (1<<1) | (0xf<<2) | (0xf<<6), 1,
1926 "READ(12)");
1927 if (reply == 0)
1928 reply = do_read(common);
1929 break;
1930
1931 case READ_CAPACITY:
1932 common->data_size_from_cmnd = 8;
1933 reply = check_command(common, 10, DATA_DIR_TO_HOST,
1934 (0xf<<2) | (1<<8), 1,
1935 "READ CAPACITY");
1936 if (reply == 0)
1937 reply = do_read_capacity(common, bh);
1938 break;
1939
1940 case READ_HEADER:
1941 if (!common->curlun || !common->curlun->cdrom)
1942 goto unknown_cmnd;
1943 common->data_size_from_cmnd =
1944 get_unaligned_be16(&common->cmnd[7]);
1945 reply = check_command(common, 10, DATA_DIR_TO_HOST,
1946 (3<<7) | (0x1f<<1), 1,
1947 "READ HEADER");
1948 if (reply == 0)
1949 reply = do_read_header(common, bh);
1950 break;
1951
1952 case READ_TOC:
1953 if (!common->curlun || !common->curlun->cdrom)
1954 goto unknown_cmnd;
1955 common->data_size_from_cmnd =
1956 get_unaligned_be16(&common->cmnd[7]);
1957 reply = check_command(common, 10, DATA_DIR_TO_HOST,
1958 (7<<6) | (1<<1), 1,
1959 "READ TOC");
1960 if (reply == 0)
1961 reply = do_read_toc(common, bh);
1962 break;
1963
1964 case READ_FORMAT_CAPACITIES:
1965 common->data_size_from_cmnd =
1966 get_unaligned_be16(&common->cmnd[7]);
1967 reply = check_command(common, 10, DATA_DIR_TO_HOST,
1968 (3<<7), 1,
1969 "READ FORMAT CAPACITIES");
1970 if (reply == 0)
1971 reply = do_read_format_capacities(common, bh);
1972 break;
1973
1974 case REQUEST_SENSE:
1975 common->data_size_from_cmnd = common->cmnd[4];
1976 reply = check_command(common, 6, DATA_DIR_TO_HOST,
1977 (1<<4), 0,
1978 "REQUEST SENSE");
1979 if (reply == 0)
1980 reply = do_request_sense(common, bh);
1981 break;
1982
1983 case START_STOP:
1984 common->data_size_from_cmnd = 0;
1985 reply = check_command(common, 6, DATA_DIR_NONE,
1986 (1<<1) | (1<<4), 0,
1987 "START-STOP UNIT");
1988 if (reply == 0)
1989 reply = do_start_stop(common);
1990 break;
1991
1992 case SYNCHRONIZE_CACHE:
1993 common->data_size_from_cmnd = 0;
1994 reply = check_command(common, 10, DATA_DIR_NONE,
1995 (0xf<<2) | (3<<7), 1,
1996 "SYNCHRONIZE CACHE");
1997 if (reply == 0)
1998 reply = do_synchronize_cache(common);
1999 break;
2000
2001 case TEST_UNIT_READY:
2002 common->data_size_from_cmnd = 0;
2003 reply = check_command(common, 6, DATA_DIR_NONE,
2004 0, 1,
2005 "TEST UNIT READY");
2006 break;
2007
2008 /*
2009 * Although optional, this command is used by MS-Windows. We
2010 * support a minimal version: BytChk must be 0.
2011 */
2012 case VERIFY:
2013 common->data_size_from_cmnd = 0;
2014 reply = check_command(common, 10, DATA_DIR_NONE,
2015 (1<<1) | (0xf<<2) | (3<<7), 1,
2016 "VERIFY");
2017 if (reply == 0)
2018 reply = do_verify(common);
2019 break;
2020
2021 case WRITE_6:
2022 i = common->cmnd[4];
2023 common->data_size_from_cmnd = (i == 0) ? 256 : i;
2024 reply = check_command_size_in_blocks(common, 6,
2025 DATA_DIR_FROM_HOST,
2026 (7<<1) | (1<<4), 1,
2027 "WRITE(6)");
2028 if (reply == 0)
2029 reply = do_write(common);
2030 break;
2031
2032 case WRITE_10:
2033 common->data_size_from_cmnd =
2034 get_unaligned_be16(&common->cmnd[7]);
2035 reply = check_command_size_in_blocks(common, 10,
2036 DATA_DIR_FROM_HOST,
2037 (1<<1) | (0xf<<2) | (3<<7), 1,
2038 "WRITE(10)");
2039 if (reply == 0)
2040 reply = do_write(common);
2041 break;
2042
2043 case WRITE_12:
2044 common->data_size_from_cmnd =
2045 get_unaligned_be32(&common->cmnd[6]);
2046 reply = check_command_size_in_blocks(common, 12,
2047 DATA_DIR_FROM_HOST,
2048 (1<<1) | (0xf<<2) | (0xf<<6), 1,
2049 "WRITE(12)");
2050 if (reply == 0)
2051 reply = do_write(common);
2052 break;
2053
2054 /*
2055 * Some mandatory commands that we recognize but don't implement.
2056 * They don't mean much in this setting. It's left as an exercise
2057 * for anyone interested to implement RESERVE and RELEASE in terms
2058 * of Posix locks.
2059 */
2060 case FORMAT_UNIT:
2061 case RELEASE:
2062 case RESERVE:
2063 case SEND_DIAGNOSTIC:
2064 /* Fall through */
2065
2066 default:
2067unknown_cmnd:
2068 common->data_size_from_cmnd = 0;
2069 sprintf(unknown, "Unknown x%02x", common->cmnd[0]);
2070 reply = check_command(common, common->cmnd_size,
2071 DATA_DIR_UNKNOWN, ~0, 0, unknown);
2072 if (reply == 0) {
2073 common->curlun->sense_data = SS_INVALID_COMMAND;
2074 reply = -EINVAL;
2075 }
2076 break;
2077 }
2078 up_read(&common->filesem);
2079
2080 if (reply == -EINTR || signal_pending(current))
2081 return -EINTR;
2082
2083 /* Set up the single reply buffer for finish_reply() */
2084 if (reply == -EINVAL)
2085 reply = 0; /* Error reply length */
2086 if (reply >= 0 && common->data_dir == DATA_DIR_TO_HOST) {
2087 reply = min((u32)reply, common->data_size_from_cmnd);
2088 bh->inreq->length = reply;
2089 bh->state = BUF_STATE_FULL;
2090 common->residue -= reply;
2091 } /* Otherwise it's already set */
2092
2093 return 0;
2094}
2095
2096
2097/*-------------------------------------------------------------------------*/
2098
2099static int received_cbw(struct fsg_dev *fsg, struct fsg_buffhd *bh)
2100{
2101 struct usb_request *req = bh->outreq;
2102 struct bulk_cb_wrap *cbw = req->buf;
2103 struct fsg_common *common = fsg->common;
2104
2105 /* Was this a real packet? Should it be ignored? */
2106 if (req->status || test_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags))
2107 return -EINVAL;
2108
2109 /* Is the CBW valid? */
2110 if (req->actual != US_BULK_CB_WRAP_LEN ||
2111 cbw->Signature != cpu_to_le32(
2112 US_BULK_CB_SIGN)) {
2113 DBG(fsg, "invalid CBW: len %u sig 0x%x\n",
2114 req->actual,
2115 le32_to_cpu(cbw->Signature));
2116
2117 /*
2118 * The Bulk-only spec says we MUST stall the IN endpoint
2119 * (6.6.1), so it's unavoidable. It also says we must
2120 * retain this state until the next reset, but there's
2121 * no way to tell the controller driver it should ignore
2122 * Clear-Feature(HALT) requests.
2123 *
2124 * We aren't required to halt the OUT endpoint; instead
2125 * we can simply accept and discard any data received
2126 * until the next reset.
2127 */
2128 wedge_bulk_in_endpoint(fsg);
2129 set_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2130 return -EINVAL;
2131 }
2132
2133 /* Is the CBW meaningful? */
2134 if (cbw->Lun >= FSG_MAX_LUNS || cbw->Flags & ~US_BULK_FLAG_IN ||
2135 cbw->Length <= 0 || cbw->Length > MAX_COMMAND_SIZE) {
2136 DBG(fsg, "non-meaningful CBW: lun = %u, flags = 0x%x, "
2137 "cmdlen %u\n",
2138 cbw->Lun, cbw->Flags, cbw->Length);
2139
2140 /*
2141 * We can do anything we want here, so let's stall the
2142 * bulk pipes if we are allowed to.
2143 */
2144 if (common->can_stall) {
2145 fsg_set_halt(fsg, fsg->bulk_out);
2146 halt_bulk_in_endpoint(fsg);
2147 }
2148 return -EINVAL;
2149 }
2150
2151 /* Save the command for later */
2152 common->cmnd_size = cbw->Length;
2153 memcpy(common->cmnd, cbw->CDB, common->cmnd_size);
2154 if (cbw->Flags & US_BULK_FLAG_IN)
2155 common->data_dir = DATA_DIR_TO_HOST;
2156 else
2157 common->data_dir = DATA_DIR_FROM_HOST;
2158 common->data_size = le32_to_cpu(cbw->DataTransferLength);
2159 if (common->data_size == 0)
2160 common->data_dir = DATA_DIR_NONE;
2161 common->lun = cbw->Lun;
2162 if (common->lun < common->nluns)
2163 common->curlun = common->luns[common->lun];
2164 else
2165 common->curlun = NULL;
2166 common->tag = cbw->Tag;
2167 return 0;
2168}
2169
2170static int get_next_command(struct fsg_common *common)
2171{
2172 struct fsg_buffhd *bh;
2173 int rc = 0;
2174
2175 /* Wait for the next buffer to become available */
2176 bh = common->next_buffhd_to_fill;
2177 while (bh->state != BUF_STATE_EMPTY) {
2178 rc = sleep_thread(common, true);
2179 if (rc)
2180 return rc;
2181 }
2182
2183 /* Queue a request to read a Bulk-only CBW */
2184 set_bulk_out_req_length(common, bh, US_BULK_CB_WRAP_LEN);
2185 if (!start_out_transfer(common, bh))
2186 /* Don't know what to do if common->fsg is NULL */
2187 return -EIO;
2188
2189 /*
2190 * We will drain the buffer in software, which means we
2191 * can reuse it for the next filling. No need to advance
2192 * next_buffhd_to_fill.
2193 */
2194
2195 /* Wait for the CBW to arrive */
2196 while (bh->state != BUF_STATE_FULL) {
2197 rc = sleep_thread(common, true);
2198 if (rc)
2199 return rc;
2200 }
2201 smp_rmb();
2202 rc = fsg_is_set(common) ? received_cbw(common->fsg, bh) : -EIO;
2203 bh->state = BUF_STATE_EMPTY;
2204
2205 return rc;
2206}
2207
2208
2209/*-------------------------------------------------------------------------*/
2210
2211static int alloc_request(struct fsg_common *common, struct usb_ep *ep,
2212 struct usb_request **preq)
2213{
2214 *preq = usb_ep_alloc_request(ep, GFP_ATOMIC);
2215 if (*preq)
2216 return 0;
2217 ERROR(common, "can't allocate request for %s\n", ep->name);
2218 return -ENOMEM;
2219}
2220
2221/* Reset interface setting and re-init endpoint state (toggle etc). */
2222static int do_set_interface(struct fsg_common *common, struct fsg_dev *new_fsg)
2223{
2224 struct fsg_dev *fsg;
2225 int i, rc = 0;
2226
2227 if (common->running)
2228 DBG(common, "reset interface\n");
2229
2230reset:
2231 /* Deallocate the requests */
2232 if (common->fsg) {
2233 fsg = common->fsg;
2234
2235 for (i = 0; i < common->fsg_num_buffers; ++i) {
2236 struct fsg_buffhd *bh = &common->buffhds[i];
2237
2238 if (bh->inreq) {
2239 usb_ep_free_request(fsg->bulk_in, bh->inreq);
2240 bh->inreq = NULL;
2241 }
2242 if (bh->outreq) {
2243 usb_ep_free_request(fsg->bulk_out, bh->outreq);
2244 bh->outreq = NULL;
2245 }
2246 }
2247
2248 /* Disable the endpoints */
2249 if (fsg->bulk_in_enabled) {
2250 usb_ep_disable(fsg->bulk_in);
2251 fsg->bulk_in->driver_data = NULL;
2252 fsg->bulk_in_enabled = 0;
2253 }
2254 if (fsg->bulk_out_enabled) {
2255 usb_ep_disable(fsg->bulk_out);
2256 fsg->bulk_out->driver_data = NULL;
2257 fsg->bulk_out_enabled = 0;
2258 }
2259
2260 common->fsg = NULL;
2261 wake_up(&common->fsg_wait);
2262 }
2263
2264 common->running = 0;
2265 if (!new_fsg || rc)
2266 return rc;
2267
2268 common->fsg = new_fsg;
2269 fsg = common->fsg;
2270
2271 /* Enable the endpoints */
2272 rc = config_ep_by_speed(common->gadget, &(fsg->function), fsg->bulk_in);
2273 if (rc)
2274 goto reset;
2275 rc = usb_ep_enable(fsg->bulk_in);
2276 if (rc)
2277 goto reset;
2278 fsg->bulk_in->driver_data = common;
2279 fsg->bulk_in_enabled = 1;
2280
2281 rc = config_ep_by_speed(common->gadget, &(fsg->function),
2282 fsg->bulk_out);
2283 if (rc)
2284 goto reset;
2285 rc = usb_ep_enable(fsg->bulk_out);
2286 if (rc)
2287 goto reset;
2288 fsg->bulk_out->driver_data = common;
2289 fsg->bulk_out_enabled = 1;
2290 common->bulk_out_maxpacket = usb_endpoint_maxp(fsg->bulk_out->desc);
2291 clear_bit(IGNORE_BULK_OUT, &fsg->atomic_bitflags);
2292
2293 /* Allocate the requests */
2294 for (i = 0; i < common->fsg_num_buffers; ++i) {
2295 struct fsg_buffhd *bh = &common->buffhds[i];
2296
2297 rc = alloc_request(common, fsg->bulk_in, &bh->inreq);
2298 if (rc)
2299 goto reset;
2300 rc = alloc_request(common, fsg->bulk_out, &bh->outreq);
2301 if (rc)
2302 goto reset;
2303 bh->inreq->buf = bh->outreq->buf = bh->buf;
2304 bh->inreq->context = bh->outreq->context = bh;
2305 bh->inreq->complete = bulk_in_complete;
2306 bh->outreq->complete = bulk_out_complete;
2307 }
2308
2309 common->running = 1;
2310 for (i = 0; i < common->nluns; ++i)
2311 if (common->luns[i])
2312 common->luns[i]->unit_attention_data =
2313 SS_RESET_OCCURRED;
2314 return rc;
2315}
2316
2317
2318/****************************** ALT CONFIGS ******************************/
2319
2320static int fsg_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
2321{
2322 struct fsg_dev *fsg = fsg_from_func(f);
2323 fsg->common->new_fsg = fsg;
2324 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
2325 return USB_GADGET_DELAYED_STATUS;
2326}
2327
2328static void fsg_disable(struct usb_function *f)
2329{
2330 struct fsg_dev *fsg = fsg_from_func(f);
2331 fsg->common->new_fsg = NULL;
2332 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
2333}
2334
2335
2336/*-------------------------------------------------------------------------*/
2337
2338static void handle_exception(struct fsg_common *common)
2339{
2340 siginfo_t info;
2341 int i;
2342 struct fsg_buffhd *bh;
2343 enum fsg_state old_state;
2344 struct fsg_lun *curlun;
2345 unsigned int exception_req_tag;
2346
2347 /*
2348 * Clear the existing signals. Anything but SIGUSR1 is converted
2349 * into a high-priority EXIT exception.
2350 */
2351 for (;;) {
2352 int sig =
2353 dequeue_signal_lock(current, &current->blocked, &info);
2354 if (!sig)
2355 break;
2356 if (sig != SIGUSR1) {
2357 if (common->state < FSG_STATE_EXIT)
2358 DBG(common, "Main thread exiting on signal\n");
2359 raise_exception(common, FSG_STATE_EXIT);
2360 }
2361 }
2362
2363 /* Cancel all the pending transfers */
2364 if (likely(common->fsg)) {
2365 for (i = 0; i < common->fsg_num_buffers; ++i) {
2366 bh = &common->buffhds[i];
2367 if (bh->inreq_busy)
2368 usb_ep_dequeue(common->fsg->bulk_in, bh->inreq);
2369 if (bh->outreq_busy)
2370 usb_ep_dequeue(common->fsg->bulk_out,
2371 bh->outreq);
2372 }
2373
2374 /* Wait until everything is idle */
2375 for (;;) {
2376 int num_active = 0;
2377 for (i = 0; i < common->fsg_num_buffers; ++i) {
2378 bh = &common->buffhds[i];
2379 num_active += bh->inreq_busy + bh->outreq_busy;
2380 }
2381 if (num_active == 0)
2382 break;
2383 if (sleep_thread(common, true))
2384 return;
2385 }
2386
2387 /* Clear out the controller's fifos */
2388 if (common->fsg->bulk_in_enabled)
2389 usb_ep_fifo_flush(common->fsg->bulk_in);
2390 if (common->fsg->bulk_out_enabled)
2391 usb_ep_fifo_flush(common->fsg->bulk_out);
2392 }
2393
2394 /*
2395 * Reset the I/O buffer states and pointers, the SCSI
2396 * state, and the exception. Then invoke the handler.
2397 */
2398 spin_lock_irq(&common->lock);
2399
2400 for (i = 0; i < common->fsg_num_buffers; ++i) {
2401 bh = &common->buffhds[i];
2402 bh->state = BUF_STATE_EMPTY;
2403 }
2404 common->next_buffhd_to_fill = &common->buffhds[0];
2405 common->next_buffhd_to_drain = &common->buffhds[0];
2406 exception_req_tag = common->exception_req_tag;
2407 old_state = common->state;
2408
2409 if (old_state == FSG_STATE_ABORT_BULK_OUT)
2410 common->state = FSG_STATE_STATUS_PHASE;
2411 else {
2412 for (i = 0; i < common->nluns; ++i) {
2413 curlun = common->luns[i];
2414 if (!curlun)
2415 continue;
2416 curlun->prevent_medium_removal = 0;
2417 curlun->sense_data = SS_NO_SENSE;
2418 curlun->unit_attention_data = SS_NO_SENSE;
2419 curlun->sense_data_info = 0;
2420 curlun->info_valid = 0;
2421 }
2422 common->state = FSG_STATE_IDLE;
2423 }
2424 spin_unlock_irq(&common->lock);
2425
2426 /* Carry out any extra actions required for the exception */
2427 switch (old_state) {
2428 case FSG_STATE_ABORT_BULK_OUT:
2429 send_status(common);
2430 spin_lock_irq(&common->lock);
2431 if (common->state == FSG_STATE_STATUS_PHASE)
2432 common->state = FSG_STATE_IDLE;
2433 spin_unlock_irq(&common->lock);
2434 break;
2435
2436 case FSG_STATE_RESET:
2437 /*
2438 * In case we were forced against our will to halt a
2439 * bulk endpoint, clear the halt now. (The SuperH UDC
2440 * requires this.)
2441 */
2442 if (!fsg_is_set(common))
2443 break;
2444 if (test_and_clear_bit(IGNORE_BULK_OUT,
2445 &common->fsg->atomic_bitflags))
2446 usb_ep_clear_halt(common->fsg->bulk_in);
2447
2448 if (common->ep0_req_tag == exception_req_tag)
2449 ep0_queue(common); /* Complete the status stage */
2450
2451 /*
2452 * Technically this should go here, but it would only be
2453 * a waste of time. Ditto for the INTERFACE_CHANGE and
2454 * CONFIG_CHANGE cases.
2455 */
2456 /* for (i = 0; i < common->nluns; ++i) */
2457 /* if (common->luns[i]) */
2458 /* common->luns[i]->unit_attention_data = */
2459 /* SS_RESET_OCCURRED; */
2460 break;
2461
2462 case FSG_STATE_CONFIG_CHANGE:
2463 do_set_interface(common, common->new_fsg);
2464 if (common->new_fsg)
2465 usb_composite_setup_continue(common->cdev);
2466 break;
2467
2468 case FSG_STATE_EXIT:
2469 case FSG_STATE_TERMINATED:
2470 do_set_interface(common, NULL); /* Free resources */
2471 spin_lock_irq(&common->lock);
2472 common->state = FSG_STATE_TERMINATED; /* Stop the thread */
2473 spin_unlock_irq(&common->lock);
2474 break;
2475
2476 case FSG_STATE_INTERFACE_CHANGE:
2477 case FSG_STATE_DISCONNECT:
2478 case FSG_STATE_COMMAND_PHASE:
2479 case FSG_STATE_DATA_PHASE:
2480 case FSG_STATE_STATUS_PHASE:
2481 case FSG_STATE_IDLE:
2482 break;
2483 }
2484}
2485
2486
2487/*-------------------------------------------------------------------------*/
2488
2489static int fsg_main_thread(void *common_)
2490{
2491 struct fsg_common *common = common_;
2492
2493 /*
2494 * Allow the thread to be killed by a signal, but set the signal mask
2495 * to block everything but INT, TERM, KILL, and USR1.
2496 */
2497 allow_signal(SIGINT);
2498 allow_signal(SIGTERM);
2499 allow_signal(SIGKILL);
2500 allow_signal(SIGUSR1);
2501
2502 /* Allow the thread to be frozen */
2503 set_freezable();
2504
2505 /*
2506 * Arrange for userspace references to be interpreted as kernel
2507 * pointers. That way we can pass a kernel pointer to a routine
2508 * that expects a __user pointer and it will work okay.
2509 */
2510 set_fs(get_ds());
2511
2512 /* The main loop */
2513 while (common->state != FSG_STATE_TERMINATED) {
2514 if (exception_in_progress(common) || signal_pending(current)) {
2515 handle_exception(common);
2516 continue;
2517 }
2518
2519 if (!common->running) {
2520 sleep_thread(common, true);
2521 continue;
2522 }
2523
2524 if (get_next_command(common))
2525 continue;
2526
2527 spin_lock_irq(&common->lock);
2528 if (!exception_in_progress(common))
2529 common->state = FSG_STATE_DATA_PHASE;
2530 spin_unlock_irq(&common->lock);
2531
2532 if (do_scsi_command(common) || finish_reply(common))
2533 continue;
2534
2535 spin_lock_irq(&common->lock);
2536 if (!exception_in_progress(common))
2537 common->state = FSG_STATE_STATUS_PHASE;
2538 spin_unlock_irq(&common->lock);
2539
2540 if (send_status(common))
2541 continue;
2542
2543 spin_lock_irq(&common->lock);
2544 if (!exception_in_progress(common))
2545 common->state = FSG_STATE_IDLE;
2546 spin_unlock_irq(&common->lock);
2547 }
2548
2549 spin_lock_irq(&common->lock);
2550 common->thread_task = NULL;
2551 spin_unlock_irq(&common->lock);
2552
2553 if (!common->ops || !common->ops->thread_exits
2554 || common->ops->thread_exits(common) < 0) {
2555 struct fsg_lun **curlun_it = common->luns;
2556 unsigned i = common->nluns;
2557
2558 down_write(&common->filesem);
2559 for (; i--; ++curlun_it) {
2560 struct fsg_lun *curlun = *curlun_it;
2561 if (!curlun || !fsg_lun_is_open(curlun))
2562 continue;
2563
2564 fsg_lun_close(curlun);
2565 curlun->unit_attention_data = SS_MEDIUM_NOT_PRESENT;
2566 }
2567 up_write(&common->filesem);
2568 }
2569
2570 /* Let fsg_unbind() know the thread has exited */
2571 complete_and_exit(&common->thread_notifier, 0);
2572}
2573
2574
2575/*************************** DEVICE ATTRIBUTES ***************************/
2576
2577static ssize_t ro_show(struct device *dev, struct device_attribute *attr, char *buf)
2578{
2579 struct fsg_lun *curlun = fsg_lun_from_dev(dev);
2580
2581 return fsg_show_ro(curlun, buf);
2582}
2583
2584static ssize_t nofua_show(struct device *dev, struct device_attribute *attr,
2585 char *buf)
2586{
2587 struct fsg_lun *curlun = fsg_lun_from_dev(dev);
2588
2589 return fsg_show_nofua(curlun, buf);
2590}
2591
2592static ssize_t file_show(struct device *dev, struct device_attribute *attr,
2593 char *buf)
2594{
2595 struct fsg_lun *curlun = fsg_lun_from_dev(dev);
2596 struct rw_semaphore *filesem = dev_get_drvdata(dev);
2597
2598 return fsg_show_file(curlun, filesem, buf);
2599}
2600
2601static ssize_t ro_store(struct device *dev, struct device_attribute *attr,
2602 const char *buf, size_t count)
2603{
2604 struct fsg_lun *curlun = fsg_lun_from_dev(dev);
2605 struct rw_semaphore *filesem = dev_get_drvdata(dev);
2606
2607 return fsg_store_ro(curlun, filesem, buf, count);
2608}
2609
2610static ssize_t nofua_store(struct device *dev, struct device_attribute *attr,
2611 const char *buf, size_t count)
2612{
2613 struct fsg_lun *curlun = fsg_lun_from_dev(dev);
2614
2615 return fsg_store_nofua(curlun, buf, count);
2616}
2617
2618static ssize_t file_store(struct device *dev, struct device_attribute *attr,
2619 const char *buf, size_t count)
2620{
2621 struct fsg_lun *curlun = fsg_lun_from_dev(dev);
2622 struct rw_semaphore *filesem = dev_get_drvdata(dev);
2623
2624 return fsg_store_file(curlun, filesem, buf, count);
2625}
2626
2627static DEVICE_ATTR_RW(ro);
2628static DEVICE_ATTR_RW(nofua);
2629static DEVICE_ATTR_RW(file);
2630
2631static struct device_attribute dev_attr_ro_cdrom = __ATTR_RO(ro);
2632static struct device_attribute dev_attr_file_nonremovable = __ATTR_RO(file);
2633
2634
2635/****************************** FSG COMMON ******************************/
2636
2637static void fsg_common_release(struct kref *ref);
2638
2639static void fsg_lun_release(struct device *dev)
2640{
2641 /* Nothing needs to be done */
2642}
2643
2644void fsg_common_get(struct fsg_common *common)
2645{
2646 kref_get(&common->ref);
2647}
2648EXPORT_SYMBOL_GPL(fsg_common_get);
2649
2650void fsg_common_put(struct fsg_common *common)
2651{
2652 kref_put(&common->ref, fsg_common_release);
2653}
2654EXPORT_SYMBOL_GPL(fsg_common_put);
2655
2656/* check if fsg_num_buffers is within a valid range */
2657static inline int fsg_num_buffers_validate(unsigned int fsg_num_buffers)
2658{
2659 if (fsg_num_buffers >= 2 && fsg_num_buffers <= 4)
2660 return 0;
2661 pr_err("fsg_num_buffers %u is out of range (%d to %d)\n",
2662 fsg_num_buffers, 2, 4);
2663 return -EINVAL;
2664}
2665
2666static struct fsg_common *fsg_common_setup(struct fsg_common *common)
2667{
2668 if (!common) {
2669 common = kzalloc(sizeof(*common), GFP_KERNEL);
2670 if (!common)
2671 return ERR_PTR(-ENOMEM);
2672 common->free_storage_on_release = 1;
2673 } else {
2674 common->free_storage_on_release = 0;
2675 }
2676 init_rwsem(&common->filesem);
2677 spin_lock_init(&common->lock);
2678 kref_init(&common->ref);
2679 init_completion(&common->thread_notifier);
2680 init_waitqueue_head(&common->fsg_wait);
2681 common->state = FSG_STATE_TERMINATED;
2682
2683 return common;
2684}
2685
2686void fsg_common_set_sysfs(struct fsg_common *common, bool sysfs)
2687{
2688 common->sysfs = sysfs;
2689}
2690EXPORT_SYMBOL_GPL(fsg_common_set_sysfs);
2691
2692static void _fsg_common_free_buffers(struct fsg_buffhd *buffhds, unsigned n)
2693{
2694 if (buffhds) {
2695 struct fsg_buffhd *bh = buffhds;
2696 while (n--) {
2697 kfree(bh->buf);
2698 ++bh;
2699 }
2700 kfree(buffhds);
2701 }
2702}
2703
2704int fsg_common_set_num_buffers(struct fsg_common *common, unsigned int n)
2705{
2706 struct fsg_buffhd *bh, *buffhds;
2707 int i, rc;
2708
2709 rc = fsg_num_buffers_validate(n);
2710 if (rc != 0)
2711 return rc;
2712
2713 buffhds = kcalloc(n, sizeof(*buffhds), GFP_KERNEL);
2714 if (!buffhds)
2715 return -ENOMEM;
2716
2717 /* Data buffers cyclic list */
2718 bh = buffhds;
2719 i = n;
2720 goto buffhds_first_it;
2721 do {
2722 bh->next = bh + 1;
2723 ++bh;
2724buffhds_first_it:
2725 bh->buf = kmalloc(FSG_BUFLEN, GFP_KERNEL);
2726 if (unlikely(!bh->buf))
2727 goto error_release;
2728 } while (--i);
2729 bh->next = buffhds;
2730
2731 _fsg_common_free_buffers(common->buffhds, common->fsg_num_buffers);
2732 common->fsg_num_buffers = n;
2733 common->buffhds = buffhds;
2734
2735 return 0;
2736
2737error_release:
2738 /*
2739 * "buf"s pointed to by heads after n - i are NULL
2740 * so releasing them won't hurt
2741 */
2742 _fsg_common_free_buffers(buffhds, n);
2743
2744 return -ENOMEM;
2745}
2746EXPORT_SYMBOL_GPL(fsg_common_set_num_buffers);
2747
2748static inline void fsg_common_remove_sysfs(struct fsg_lun *lun)
2749{
2750 device_remove_file(&lun->dev, &dev_attr_nofua);
2751 /*
2752 * device_remove_file() =>
2753 *
2754 * here the attr (e.g. dev_attr_ro) is only used to be passed to:
2755 *
2756 * sysfs_remove_file() =>
2757 *
2758 * here e.g. both dev_attr_ro_cdrom and dev_attr_ro are in
2759 * the same namespace and
2760 * from here only attr->name is passed to:
2761 *
2762 * sysfs_hash_and_remove()
2763 *
2764 * attr->name is the same for dev_attr_ro_cdrom and
2765 * dev_attr_ro
2766 * attr->name is the same for dev_attr_file and
2767 * dev_attr_file_nonremovable
2768 *
2769 * so we don't differentiate between removing e.g. dev_attr_ro_cdrom
2770 * and dev_attr_ro
2771 */
2772 device_remove_file(&lun->dev, &dev_attr_ro);
2773 device_remove_file(&lun->dev, &dev_attr_file);
2774}
2775
2776void fsg_common_remove_lun(struct fsg_lun *lun, bool sysfs)
2777{
2778 if (sysfs) {
2779 fsg_common_remove_sysfs(lun);
2780 device_unregister(&lun->dev);
2781 }
2782 fsg_lun_close(lun);
2783 kfree(lun);
2784}
2785EXPORT_SYMBOL_GPL(fsg_common_remove_lun);
2786
2787static void _fsg_common_remove_luns(struct fsg_common *common, int n)
2788{
2789 int i;
2790
2791 for (i = 0; i < n; ++i)
2792 if (common->luns[i]) {
2793 fsg_common_remove_lun(common->luns[i], common->sysfs);
2794 common->luns[i] = NULL;
2795 }
2796}
2797EXPORT_SYMBOL_GPL(fsg_common_remove_luns);
2798
2799void fsg_common_remove_luns(struct fsg_common *common)
2800{
2801 _fsg_common_remove_luns(common, common->nluns);
2802}
2803
2804void fsg_common_free_luns(struct fsg_common *common)
2805{
2806 fsg_common_remove_luns(common);
2807 kfree(common->luns);
2808 common->luns = NULL;
2809}
2810EXPORT_SYMBOL_GPL(fsg_common_free_luns);
2811
2812int fsg_common_set_nluns(struct fsg_common *common, int nluns)
2813{
2814 struct fsg_lun **curlun;
2815
2816 /* Find out how many LUNs there should be */
2817 if (nluns < 1 || nluns > FSG_MAX_LUNS) {
2818 pr_err("invalid number of LUNs: %u\n", nluns);
2819 return -EINVAL;
2820 }
2821
2822 curlun = kcalloc(nluns, sizeof(*curlun), GFP_KERNEL);
2823 if (unlikely(!curlun))
2824 return -ENOMEM;
2825
2826 if (common->luns)
2827 fsg_common_free_luns(common);
2828
2829 common->luns = curlun;
2830 common->nluns = nluns;
2831
2832 pr_info("Number of LUNs=%d\n", common->nluns);
2833
2834 return 0;
2835}
2836EXPORT_SYMBOL_GPL(fsg_common_set_nluns);
2837
2838void fsg_common_set_ops(struct fsg_common *common,
2839 const struct fsg_operations *ops)
2840{
2841 common->ops = ops;
2842}
2843EXPORT_SYMBOL_GPL(fsg_common_set_ops);
2844
2845void fsg_common_free_buffers(struct fsg_common *common)
2846{
2847 _fsg_common_free_buffers(common->buffhds, common->fsg_num_buffers);
2848 common->buffhds = NULL;
2849}
2850EXPORT_SYMBOL_GPL(fsg_common_free_buffers);
2851
2852int fsg_common_set_cdev(struct fsg_common *common,
2853 struct usb_composite_dev *cdev, bool can_stall)
2854{
2855 struct usb_string *us;
2856
2857 common->gadget = cdev->gadget;
2858 common->ep0 = cdev->gadget->ep0;
2859 common->ep0req = cdev->req;
2860 common->cdev = cdev;
2861
2862 us = usb_gstrings_attach(cdev, fsg_strings_array,
2863 ARRAY_SIZE(fsg_strings));
2864 if (IS_ERR(us))
2865 return PTR_ERR(us);
2866
2867 fsg_intf_desc.iInterface = us[FSG_STRING_INTERFACE].id;
2868
2869 /*
2870 * Some peripheral controllers are known not to be able to
2871 * halt bulk endpoints correctly. If one of them is present,
2872 * disable stalls.
2873 */
2874 common->can_stall = can_stall && !(gadget_is_at91(common->gadget));
2875
2876 return 0;
2877}
2878EXPORT_SYMBOL_GPL(fsg_common_set_cdev);
2879
2880static inline int fsg_common_add_sysfs(struct fsg_common *common,
2881 struct fsg_lun *lun)
2882{
2883 int rc;
2884
2885 rc = device_register(&lun->dev);
2886 if (rc) {
2887 put_device(&lun->dev);
2888 return rc;
2889 }
2890
2891 rc = device_create_file(&lun->dev,
2892 lun->cdrom
2893 ? &dev_attr_ro_cdrom
2894 : &dev_attr_ro);
2895 if (rc)
2896 goto error;
2897 rc = device_create_file(&lun->dev,
2898 lun->removable
2899 ? &dev_attr_file
2900 : &dev_attr_file_nonremovable);
2901 if (rc)
2902 goto error;
2903 rc = device_create_file(&lun->dev, &dev_attr_nofua);
2904 if (rc)
2905 goto error;
2906
2907 return 0;
2908
2909error:
2910 /* removing nonexistent files is a no-op */
2911 fsg_common_remove_sysfs(lun);
2912 device_unregister(&lun->dev);
2913 return rc;
2914}
2915
2916int fsg_common_create_lun(struct fsg_common *common, struct fsg_lun_config *cfg,
2917 unsigned int id, const char *name,
2918 const char **name_pfx)
2919{
2920 struct fsg_lun *lun;
2921 char *pathbuf, *p;
2922 int rc = -ENOMEM;
2923
2924 if (!common->nluns || !common->luns)
2925 return -ENODEV;
2926
2927 if (common->luns[id])
2928 return -EBUSY;
2929
2930 if (!cfg->filename && !cfg->removable) {
2931 pr_err("no file given for LUN%d\n", id);
2932 return -EINVAL;
2933 }
2934
2935 lun = kzalloc(sizeof(*lun), GFP_KERNEL);
2936 if (!lun)
2937 return -ENOMEM;
2938
2939 lun->name_pfx = name_pfx;
2940
2941 lun->cdrom = !!cfg->cdrom;
2942 lun->ro = cfg->cdrom || cfg->ro;
2943 lun->initially_ro = lun->ro;
2944 lun->removable = !!cfg->removable;
2945
2946 if (!common->sysfs) {
2947 /* we DON'T own the name!*/
2948 lun->name = name;
2949 } else {
2950 lun->dev.release = fsg_lun_release;
2951 lun->dev.parent = &common->gadget->dev;
2952 dev_set_drvdata(&lun->dev, &common->filesem);
2953 dev_set_name(&lun->dev, "%s", name);
2954 lun->name = dev_name(&lun->dev);
2955
2956 rc = fsg_common_add_sysfs(common, lun);
2957 if (rc) {
2958 pr_info("failed to register LUN%d: %d\n", id, rc);
2959 goto error_sysfs;
2960 }
2961 }
2962
2963 common->luns[id] = lun;
2964
2965 if (cfg->filename) {
2966 rc = fsg_lun_open(lun, cfg->filename);
2967 if (rc)
2968 goto error_lun;
2969 }
2970
2971 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
2972 p = "(no medium)";
2973 if (fsg_lun_is_open(lun)) {
2974 p = "(error)";
2975 if (pathbuf) {
2976 p = d_path(&lun->filp->f_path, pathbuf, PATH_MAX);
2977 if (IS_ERR(p))
2978 p = "(error)";
2979 }
2980 }
2981 pr_info("LUN: %s%s%sfile: %s\n",
2982 lun->removable ? "removable " : "",
2983 lun->ro ? "read only " : "",
2984 lun->cdrom ? "CD-ROM " : "",
2985 p);
2986 kfree(pathbuf);
2987
2988 return 0;
2989
2990error_lun:
2991 if (common->sysfs) {
2992 fsg_common_remove_sysfs(lun);
2993 device_unregister(&lun->dev);
2994 }
2995 fsg_lun_close(lun);
2996 common->luns[id] = NULL;
2997error_sysfs:
2998 kfree(lun);
2999 return rc;
3000}
3001EXPORT_SYMBOL_GPL(fsg_common_create_lun);
3002
3003int fsg_common_create_luns(struct fsg_common *common, struct fsg_config *cfg)
3004{
3005 char buf[8]; /* enough for 100000000 different numbers, decimal */
3006 int i, rc;
3007
3008 for (i = 0; i < common->nluns; ++i) {
3009 snprintf(buf, sizeof(buf), "lun%d", i);
3010 rc = fsg_common_create_lun(common, &cfg->luns[i], i, buf, NULL);
3011 if (rc)
3012 goto fail;
3013 }
3014
3015 pr_info("Number of LUNs=%d\n", common->nluns);
3016
3017 return 0;
3018
3019fail:
3020 _fsg_common_remove_luns(common, i);
3021 return rc;
3022}
3023EXPORT_SYMBOL_GPL(fsg_common_create_luns);
3024
3025void fsg_common_set_inquiry_string(struct fsg_common *common, const char *vn,
3026 const char *pn)
3027{
3028 int i;
3029
3030 /* Prepare inquiryString */
3031 i = get_default_bcdDevice();
3032 snprintf(common->inquiry_string, sizeof(common->inquiry_string),
3033 "%-8s%-16s%04x", vn ?: "Linux",
3034 /* Assume product name dependent on the first LUN */
3035 pn ?: ((*common->luns)->cdrom
3036 ? "File-CD Gadget"
3037 : "File-Stor Gadget"),
3038 i);
3039}
3040EXPORT_SYMBOL_GPL(fsg_common_set_inquiry_string);
3041
3042int fsg_common_run_thread(struct fsg_common *common)
3043{
3044 common->state = FSG_STATE_IDLE;
3045 /* Tell the thread to start working */
3046 common->thread_task =
3047 kthread_create(fsg_main_thread, common, "file-storage");
3048 if (IS_ERR(common->thread_task)) {
3049 common->state = FSG_STATE_TERMINATED;
3050 return PTR_ERR(common->thread_task);
3051 }
3052
3053 DBG(common, "I/O thread pid: %d\n", task_pid_nr(common->thread_task));
3054
3055 wake_up_process(common->thread_task);
3056
3057 return 0;
3058}
3059EXPORT_SYMBOL_GPL(fsg_common_run_thread);
3060
3061static void fsg_common_release(struct kref *ref)
3062{
3063 struct fsg_common *common = container_of(ref, struct fsg_common, ref);
3064
3065 /* If the thread isn't already dead, tell it to exit now */
3066 if (common->state != FSG_STATE_TERMINATED) {
3067 raise_exception(common, FSG_STATE_EXIT);
3068 wait_for_completion(&common->thread_notifier);
3069 }
3070
3071 if (likely(common->luns)) {
3072 struct fsg_lun **lun_it = common->luns;
3073 unsigned i = common->nluns;
3074
3075 /* In error recovery common->nluns may be zero. */
3076 for (; i; --i, ++lun_it) {
3077 struct fsg_lun *lun = *lun_it;
3078 if (!lun)
3079 continue;
3080 if (common->sysfs)
3081 fsg_common_remove_sysfs(lun);
3082 fsg_lun_close(lun);
3083 if (common->sysfs)
3084 device_unregister(&lun->dev);
3085 kfree(lun);
3086 }
3087
3088 kfree(common->luns);
3089 }
3090
3091 _fsg_common_free_buffers(common->buffhds, common->fsg_num_buffers);
3092 if (common->free_storage_on_release)
3093 kfree(common);
3094}
3095
3096
3097/*-------------------------------------------------------------------------*/
3098
3099static int fsg_bind(struct usb_configuration *c, struct usb_function *f)
3100{
3101 struct fsg_dev *fsg = fsg_from_func(f);
3102 struct usb_gadget *gadget = c->cdev->gadget;
3103 int i;
3104 struct usb_ep *ep;
3105 unsigned max_burst;
3106 int ret;
3107 struct fsg_opts *opts;
3108
3109 opts = fsg_opts_from_func_inst(f->fi);
3110 if (!opts->no_configfs) {
3111 ret = fsg_common_set_cdev(fsg->common, c->cdev,
3112 fsg->common->can_stall);
3113 if (ret)
3114 return ret;
3115 fsg_common_set_inquiry_string(fsg->common, NULL, NULL);
3116 ret = fsg_common_run_thread(fsg->common);
3117 if (ret)
3118 return ret;
3119 }
3120
3121 fsg->gadget = gadget;
3122
3123 /* New interface */
3124 i = usb_interface_id(c, f);
3125 if (i < 0)
3126 return i;
3127 fsg_intf_desc.bInterfaceNumber = i;
3128 fsg->interface_number = i;
3129
3130 /* Find all the endpoints we will use */
3131 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_in_desc);
3132 if (!ep)
3133 goto autoconf_fail;
3134 ep->driver_data = fsg->common; /* claim the endpoint */
3135 fsg->bulk_in = ep;
3136
3137 ep = usb_ep_autoconfig(gadget, &fsg_fs_bulk_out_desc);
3138 if (!ep)
3139 goto autoconf_fail;
3140 ep->driver_data = fsg->common; /* claim the endpoint */
3141 fsg->bulk_out = ep;
3142
3143 /* Assume endpoint addresses are the same for both speeds */
3144 fsg_hs_bulk_in_desc.bEndpointAddress =
3145 fsg_fs_bulk_in_desc.bEndpointAddress;
3146 fsg_hs_bulk_out_desc.bEndpointAddress =
3147 fsg_fs_bulk_out_desc.bEndpointAddress;
3148
3149 /* Calculate bMaxBurst, we know packet size is 1024 */
3150 max_burst = min_t(unsigned, FSG_BUFLEN / 1024, 15);
3151
3152 fsg_ss_bulk_in_desc.bEndpointAddress =
3153 fsg_fs_bulk_in_desc.bEndpointAddress;
3154 fsg_ss_bulk_in_comp_desc.bMaxBurst = max_burst;
3155
3156 fsg_ss_bulk_out_desc.bEndpointAddress =
3157 fsg_fs_bulk_out_desc.bEndpointAddress;
3158 fsg_ss_bulk_out_comp_desc.bMaxBurst = max_burst;
3159
3160 ret = usb_assign_descriptors(f, fsg_fs_function, fsg_hs_function,
3161 fsg_ss_function);
3162 if (ret)
3163 goto autoconf_fail;
3164
3165 return 0;
3166
3167autoconf_fail:
3168 ERROR(fsg, "unable to autoconfigure all endpoints\n");
3169 return -ENOTSUPP;
3170}
3171
3172/****************************** ALLOCATE FUNCTION *************************/
3173
3174static void fsg_unbind(struct usb_configuration *c, struct usb_function *f)
3175{
3176 struct fsg_dev *fsg = fsg_from_func(f);
3177 struct fsg_common *common = fsg->common;
3178
3179 DBG(fsg, "unbind\n");
3180 if (fsg->common->fsg == fsg) {
3181 fsg->common->new_fsg = NULL;
3182 raise_exception(fsg->common, FSG_STATE_CONFIG_CHANGE);
3183 /* FIXME: make interruptible or killable somehow? */
3184 wait_event(common->fsg_wait, common->fsg != fsg);
3185 }
3186
3187 usb_free_all_descriptors(&fsg->function);
3188}
3189
3190static inline struct fsg_lun_opts *to_fsg_lun_opts(struct config_item *item)
3191{
3192 return container_of(to_config_group(item), struct fsg_lun_opts, group);
3193}
3194
3195static inline struct fsg_opts *to_fsg_opts(struct config_item *item)
3196{
3197 return container_of(to_config_group(item), struct fsg_opts,
3198 func_inst.group);
3199}
3200
3201CONFIGFS_ATTR_STRUCT(fsg_lun_opts);
3202CONFIGFS_ATTR_OPS(fsg_lun_opts);
3203
3204static void fsg_lun_attr_release(struct config_item *item)
3205{
3206 struct fsg_lun_opts *lun_opts;
3207
3208 lun_opts = to_fsg_lun_opts(item);
3209 kfree(lun_opts);
3210}
3211
3212static struct configfs_item_operations fsg_lun_item_ops = {
3213 .release = fsg_lun_attr_release,
3214 .show_attribute = fsg_lun_opts_attr_show,
3215 .store_attribute = fsg_lun_opts_attr_store,
3216};
3217
3218static ssize_t fsg_lun_opts_file_show(struct fsg_lun_opts *opts, char *page)
3219{
3220 struct fsg_opts *fsg_opts;
3221
3222 fsg_opts = to_fsg_opts(opts->group.cg_item.ci_parent);
3223
3224 return fsg_show_file(opts->lun, &fsg_opts->common->filesem, page);
3225}
3226
3227static ssize_t fsg_lun_opts_file_store(struct fsg_lun_opts *opts,
3228 const char *page, size_t len)
3229{
3230 struct fsg_opts *fsg_opts;
3231
3232 fsg_opts = to_fsg_opts(opts->group.cg_item.ci_parent);
3233
3234 return fsg_store_file(opts->lun, &fsg_opts->common->filesem, page, len);
3235}
3236
3237static struct fsg_lun_opts_attribute fsg_lun_opts_file =
3238 __CONFIGFS_ATTR(file, S_IRUGO | S_IWUSR, fsg_lun_opts_file_show,
3239 fsg_lun_opts_file_store);
3240
3241static ssize_t fsg_lun_opts_ro_show(struct fsg_lun_opts *opts, char *page)
3242{
3243 return fsg_show_ro(opts->lun, page);
3244}
3245
3246static ssize_t fsg_lun_opts_ro_store(struct fsg_lun_opts *opts,
3247 const char *page, size_t len)
3248{
3249 struct fsg_opts *fsg_opts;
3250
3251 fsg_opts = to_fsg_opts(opts->group.cg_item.ci_parent);
3252
3253 return fsg_store_ro(opts->lun, &fsg_opts->common->filesem, page, len);
3254}
3255
3256static struct fsg_lun_opts_attribute fsg_lun_opts_ro =
3257 __CONFIGFS_ATTR(ro, S_IRUGO | S_IWUSR, fsg_lun_opts_ro_show,
3258 fsg_lun_opts_ro_store);
3259
3260static ssize_t fsg_lun_opts_removable_show(struct fsg_lun_opts *opts,
3261 char *page)
3262{
3263 return fsg_show_removable(opts->lun, page);
3264}
3265
3266static ssize_t fsg_lun_opts_removable_store(struct fsg_lun_opts *opts,
3267 const char *page, size_t len)
3268{
3269 return fsg_store_removable(opts->lun, page, len);
3270}
3271
3272static struct fsg_lun_opts_attribute fsg_lun_opts_removable =
3273 __CONFIGFS_ATTR(removable, S_IRUGO | S_IWUSR,
3274 fsg_lun_opts_removable_show,
3275 fsg_lun_opts_removable_store);
3276
3277static ssize_t fsg_lun_opts_cdrom_show(struct fsg_lun_opts *opts, char *page)
3278{
3279 return fsg_show_cdrom(opts->lun, page);
3280}
3281
3282static ssize_t fsg_lun_opts_cdrom_store(struct fsg_lun_opts *opts,
3283 const char *page, size_t len)
3284{
3285 struct fsg_opts *fsg_opts;
3286
3287 fsg_opts = to_fsg_opts(opts->group.cg_item.ci_parent);
3288
3289 return fsg_store_cdrom(opts->lun, &fsg_opts->common->filesem, page,
3290 len);
3291}
3292
3293static struct fsg_lun_opts_attribute fsg_lun_opts_cdrom =
3294 __CONFIGFS_ATTR(cdrom, S_IRUGO | S_IWUSR, fsg_lun_opts_cdrom_show,
3295 fsg_lun_opts_cdrom_store);
3296
3297static ssize_t fsg_lun_opts_nofua_show(struct fsg_lun_opts *opts, char *page)
3298{
3299 return fsg_show_nofua(opts->lun, page);
3300}
3301
3302static ssize_t fsg_lun_opts_nofua_store(struct fsg_lun_opts *opts,
3303 const char *page, size_t len)
3304{
3305 return fsg_store_nofua(opts->lun, page, len);
3306}
3307
3308static struct fsg_lun_opts_attribute fsg_lun_opts_nofua =
3309 __CONFIGFS_ATTR(nofua, S_IRUGO | S_IWUSR, fsg_lun_opts_nofua_show,
3310 fsg_lun_opts_nofua_store);
3311
3312static struct configfs_attribute *fsg_lun_attrs[] = {
3313 &fsg_lun_opts_file.attr,
3314 &fsg_lun_opts_ro.attr,
3315 &fsg_lun_opts_removable.attr,
3316 &fsg_lun_opts_cdrom.attr,
3317 &fsg_lun_opts_nofua.attr,
3318 NULL,
3319};
3320
3321static struct config_item_type fsg_lun_type = {
3322 .ct_item_ops = &fsg_lun_item_ops,
3323 .ct_attrs = fsg_lun_attrs,
3324 .ct_owner = THIS_MODULE,
3325};
3326
3327static struct config_group *fsg_lun_make(struct config_group *group,
3328 const char *name)
3329{
3330 struct fsg_lun_opts *opts;
3331 struct fsg_opts *fsg_opts;
3332 struct fsg_lun_config config;
3333 char *num_str;
3334 u8 num;
3335 int ret;
3336
3337 num_str = strchr(name, '.');
3338 if (!num_str) {
3339 pr_err("Unable to locate . in LUN.NUMBER\n");
3340 return ERR_PTR(-EINVAL);
3341 }
3342 num_str++;
3343
3344 ret = kstrtou8(num_str, 0, &num);
3345 if (ret)
3346 return ERR_PTR(ret);
3347
3348 fsg_opts = to_fsg_opts(&group->cg_item);
3349 if (num >= FSG_MAX_LUNS)
3350 return ERR_PTR(-ERANGE);
3351
3352 mutex_lock(&fsg_opts->lock);
3353 if (fsg_opts->refcnt || fsg_opts->common->luns[num]) {
3354 ret = -EBUSY;
3355 goto out;
3356 }
3357
3358 opts = kzalloc(sizeof(*opts), GFP_KERNEL);
3359 if (!opts) {
3360 ret = -ENOMEM;
3361 goto out;
3362 }
3363
3364 memset(&config, 0, sizeof(config));
3365 config.removable = true;
3366
3367 ret = fsg_common_create_lun(fsg_opts->common, &config, num, name,
3368 (const char **)&group->cg_item.ci_name);
3369 if (ret) {
3370 kfree(opts);
3371 goto out;
3372 }
3373 opts->lun = fsg_opts->common->luns[num];
3374 opts->lun_id = num;
3375 mutex_unlock(&fsg_opts->lock);
3376
3377 config_group_init_type_name(&opts->group, name, &fsg_lun_type);
3378
3379 return &opts->group;
3380out:
3381 mutex_unlock(&fsg_opts->lock);
3382 return ERR_PTR(ret);
3383}
3384
3385static void fsg_lun_drop(struct config_group *group, struct config_item *item)
3386{
3387 struct fsg_lun_opts *lun_opts;
3388 struct fsg_opts *fsg_opts;
3389
3390 lun_opts = to_fsg_lun_opts(item);
3391 fsg_opts = to_fsg_opts(&group->cg_item);
3392
3393 mutex_lock(&fsg_opts->lock);
3394 if (fsg_opts->refcnt) {
3395 struct config_item *gadget;
3396
3397 gadget = group->cg_item.ci_parent->ci_parent;
3398 unregister_gadget_item(gadget);
3399 }
3400
3401 fsg_common_remove_lun(lun_opts->lun, fsg_opts->common->sysfs);
3402 fsg_opts->common->luns[lun_opts->lun_id] = NULL;
3403 lun_opts->lun_id = 0;
3404 mutex_unlock(&fsg_opts->lock);
3405
3406 config_item_put(item);
3407}
3408
3409CONFIGFS_ATTR_STRUCT(fsg_opts);
3410CONFIGFS_ATTR_OPS(fsg_opts);
3411
3412static void fsg_attr_release(struct config_item *item)
3413{
3414 struct fsg_opts *opts = to_fsg_opts(item);
3415
3416 usb_put_function_instance(&opts->func_inst);
3417}
3418
3419static struct configfs_item_operations fsg_item_ops = {
3420 .release = fsg_attr_release,
3421 .show_attribute = fsg_opts_attr_show,
3422 .store_attribute = fsg_opts_attr_store,
3423};
3424
3425static ssize_t fsg_opts_stall_show(struct fsg_opts *opts, char *page)
3426{
3427 int result;
3428
3429 mutex_lock(&opts->lock);
3430 result = sprintf(page, "%d", opts->common->can_stall);
3431 mutex_unlock(&opts->lock);
3432
3433 return result;
3434}
3435
3436static ssize_t fsg_opts_stall_store(struct fsg_opts *opts, const char *page,
3437 size_t len)
3438{
3439 int ret;
3440 bool stall;
3441
3442 mutex_lock(&opts->lock);
3443
3444 if (opts->refcnt) {
3445 mutex_unlock(&opts->lock);
3446 return -EBUSY;
3447 }
3448
3449 ret = strtobool(page, &stall);
3450 if (!ret) {
3451 opts->common->can_stall = stall;
3452 ret = len;
3453 }
3454
3455 mutex_unlock(&opts->lock);
3456
3457 return ret;
3458}
3459
3460static struct fsg_opts_attribute fsg_opts_stall =
3461 __CONFIGFS_ATTR(stall, S_IRUGO | S_IWUSR, fsg_opts_stall_show,
3462 fsg_opts_stall_store);
3463
3464#ifdef CONFIG_USB_GADGET_DEBUG_FILES
3465static ssize_t fsg_opts_num_buffers_show(struct fsg_opts *opts, char *page)
3466{
3467 int result;
3468
3469 mutex_lock(&opts->lock);
3470 result = sprintf(page, "%d", opts->common->fsg_num_buffers);
3471 mutex_unlock(&opts->lock);
3472
3473 return result;
3474}
3475
3476static ssize_t fsg_opts_num_buffers_store(struct fsg_opts *opts,
3477 const char *page, size_t len)
3478{
3479 int ret;
3480 u8 num;
3481
3482 mutex_lock(&opts->lock);
3483 if (opts->refcnt) {
3484 ret = -EBUSY;
3485 goto end;
3486 }
3487 ret = kstrtou8(page, 0, &num);
3488 if (ret)
3489 goto end;
3490
3491 ret = fsg_num_buffers_validate(num);
3492 if (ret)
3493 goto end;
3494
3495 fsg_common_set_num_buffers(opts->common, num);
3496 ret = len;
3497
3498end:
3499 mutex_unlock(&opts->lock);
3500 return ret;
3501}
3502
3503static struct fsg_opts_attribute fsg_opts_num_buffers =
3504 __CONFIGFS_ATTR(num_buffers, S_IRUGO | S_IWUSR,
3505 fsg_opts_num_buffers_show,
3506 fsg_opts_num_buffers_store);
3507
3508#endif
3509
3510static struct configfs_attribute *fsg_attrs[] = {
3511 &fsg_opts_stall.attr,
3512#ifdef CONFIG_USB_GADGET_DEBUG_FILES
3513 &fsg_opts_num_buffers.attr,
3514#endif
3515 NULL,
3516};
3517
3518static struct configfs_group_operations fsg_group_ops = {
3519 .make_group = fsg_lun_make,
3520 .drop_item = fsg_lun_drop,
3521};
3522
3523static struct config_item_type fsg_func_type = {
3524 .ct_item_ops = &fsg_item_ops,
3525 .ct_group_ops = &fsg_group_ops,
3526 .ct_attrs = fsg_attrs,
3527 .ct_owner = THIS_MODULE,
3528};
3529
3530static void fsg_free_inst(struct usb_function_instance *fi)
3531{
3532 struct fsg_opts *opts;
3533
3534 opts = fsg_opts_from_func_inst(fi);
3535 fsg_common_put(opts->common);
3536 kfree(opts);
3537}
3538
3539static struct usb_function_instance *fsg_alloc_inst(void)
3540{
3541 struct fsg_opts *opts;
3542 struct fsg_lun_config config;
3543 int rc;
3544
3545 opts = kzalloc(sizeof(*opts), GFP_KERNEL);
3546 if (!opts)
3547 return ERR_PTR(-ENOMEM);
3548 mutex_init(&opts->lock);
3549 opts->func_inst.free_func_inst = fsg_free_inst;
3550 opts->common = fsg_common_setup(opts->common);
3551 if (IS_ERR(opts->common)) {
3552 rc = PTR_ERR(opts->common);
3553 goto release_opts;
3554 }
3555 rc = fsg_common_set_nluns(opts->common, FSG_MAX_LUNS);
3556 if (rc)
3557 goto release_opts;
3558
3559 rc = fsg_common_set_num_buffers(opts->common,
3560 CONFIG_USB_GADGET_STORAGE_NUM_BUFFERS);
3561 if (rc)
3562 goto release_luns;
3563
3564 pr_info(FSG_DRIVER_DESC ", version: " FSG_DRIVER_VERSION "\n");
3565
3566 memset(&config, 0, sizeof(config));
3567 config.removable = true;
3568 rc = fsg_common_create_lun(opts->common, &config, 0, "lun.0",
3569 (const char **)&opts->func_inst.group.cg_item.ci_name);
3570 opts->lun0.lun = opts->common->luns[0];
3571 opts->lun0.lun_id = 0;
3572 config_group_init_type_name(&opts->lun0.group, "lun.0", &fsg_lun_type);
3573 opts->default_groups[0] = &opts->lun0.group;
3574 opts->func_inst.group.default_groups = opts->default_groups;
3575
3576 config_group_init_type_name(&opts->func_inst.group, "", &fsg_func_type);
3577
3578 return &opts->func_inst;
3579
3580release_luns:
3581 kfree(opts->common->luns);
3582release_opts:
3583 kfree(opts);
3584 return ERR_PTR(rc);
3585}
3586
3587static void fsg_free(struct usb_function *f)
3588{
3589 struct fsg_dev *fsg;
3590 struct fsg_opts *opts;
3591
3592 fsg = container_of(f, struct fsg_dev, function);
3593 opts = container_of(f->fi, struct fsg_opts, func_inst);
3594
3595 mutex_lock(&opts->lock);
3596 opts->refcnt--;
3597 mutex_unlock(&opts->lock);
3598
3599 kfree(fsg);
3600}
3601
3602static struct usb_function *fsg_alloc(struct usb_function_instance *fi)
3603{
3604 struct fsg_opts *opts = fsg_opts_from_func_inst(fi);
3605 struct fsg_common *common = opts->common;
3606 struct fsg_dev *fsg;
3607
3608 fsg = kzalloc(sizeof(*fsg), GFP_KERNEL);
3609 if (unlikely(!fsg))
3610 return ERR_PTR(-ENOMEM);
3611
3612 mutex_lock(&opts->lock);
3613 opts->refcnt++;
3614 mutex_unlock(&opts->lock);
3615 fsg->function.name = FSG_DRIVER_DESC;
3616 fsg->function.bind = fsg_bind;
3617 fsg->function.unbind = fsg_unbind;
3618 fsg->function.setup = fsg_setup;
3619 fsg->function.set_alt = fsg_set_alt;
3620 fsg->function.disable = fsg_disable;
3621 fsg->function.free_func = fsg_free;
3622
3623 fsg->common = common;
3624
3625 return &fsg->function;
3626}
3627
3628DECLARE_USB_FUNCTION_INIT(mass_storage, fsg_alloc_inst, fsg_alloc);
3629MODULE_LICENSE("GPL");
3630MODULE_AUTHOR("Michal Nazarewicz");
3631
3632/************************* Module parameters *************************/
3633
3634
3635void fsg_config_from_params(struct fsg_config *cfg,
3636 const struct fsg_module_parameters *params,
3637 unsigned int fsg_num_buffers)
3638{
3639 struct fsg_lun_config *lun;
3640 unsigned i;
3641
3642 /* Configure LUNs */
3643 cfg->nluns =
3644 min(params->luns ?: (params->file_count ?: 1u),
3645 (unsigned)FSG_MAX_LUNS);
3646 for (i = 0, lun = cfg->luns; i < cfg->nluns; ++i, ++lun) {
3647 lun->ro = !!params->ro[i];
3648 lun->cdrom = !!params->cdrom[i];
3649 lun->removable = !!params->removable[i];
3650 lun->filename =
3651 params->file_count > i && params->file[i][0]
3652 ? params->file[i]
3653 : NULL;
3654 }
3655
3656 /* Let MSF use defaults */
3657 cfg->vendor_name = NULL;
3658 cfg->product_name = NULL;
3659
3660 cfg->ops = NULL;
3661 cfg->private_data = NULL;
3662
3663 /* Finalise */
3664 cfg->can_stall = params->stall;
3665 cfg->fsg_num_buffers = fsg_num_buffers;
3666}
3667EXPORT_SYMBOL_GPL(fsg_config_from_params);
3668
diff --git a/drivers/usb/gadget/function/f_mass_storage.h b/drivers/usb/gadget/function/f_mass_storage.h
new file mode 100644
index 000000000000..b4866fcef30b
--- /dev/null
+++ b/drivers/usb/gadget/function/f_mass_storage.h
@@ -0,0 +1,166 @@
1#ifndef USB_F_MASS_STORAGE_H
2#define USB_F_MASS_STORAGE_H
3
4#include <linux/usb/composite.h>
5#include "storage_common.h"
6
7struct fsg_module_parameters {
8 char *file[FSG_MAX_LUNS];
9 bool ro[FSG_MAX_LUNS];
10 bool removable[FSG_MAX_LUNS];
11 bool cdrom[FSG_MAX_LUNS];
12 bool nofua[FSG_MAX_LUNS];
13
14 unsigned int file_count, ro_count, removable_count, cdrom_count;
15 unsigned int nofua_count;
16 unsigned int luns; /* nluns */
17 bool stall; /* can_stall */
18};
19
20#define _FSG_MODULE_PARAM_ARRAY(prefix, params, name, type, desc) \
21 module_param_array_named(prefix ## name, params.name, type, \
22 &prefix ## params.name ## _count, \
23 S_IRUGO); \
24 MODULE_PARM_DESC(prefix ## name, desc)
25
26#define _FSG_MODULE_PARAM(prefix, params, name, type, desc) \
27 module_param_named(prefix ## name, params.name, type, \
28 S_IRUGO); \
29 MODULE_PARM_DESC(prefix ## name, desc)
30
31#define __FSG_MODULE_PARAMETERS(prefix, params) \
32 _FSG_MODULE_PARAM_ARRAY(prefix, params, file, charp, \
33 "names of backing files or devices"); \
34 _FSG_MODULE_PARAM_ARRAY(prefix, params, ro, bool, \
35 "true to force read-only"); \
36 _FSG_MODULE_PARAM_ARRAY(prefix, params, removable, bool, \
37 "true to simulate removable media"); \
38 _FSG_MODULE_PARAM_ARRAY(prefix, params, cdrom, bool, \
39 "true to simulate CD-ROM instead of disk"); \
40 _FSG_MODULE_PARAM_ARRAY(prefix, params, nofua, bool, \
41 "true to ignore SCSI WRITE(10,12) FUA bit"); \
42 _FSG_MODULE_PARAM(prefix, params, luns, uint, \
43 "number of LUNs"); \
44 _FSG_MODULE_PARAM(prefix, params, stall, bool, \
45 "false to prevent bulk stalls")
46
47#ifdef CONFIG_USB_GADGET_DEBUG_FILES
48
49#define FSG_MODULE_PARAMETERS(prefix, params) \
50 __FSG_MODULE_PARAMETERS(prefix, params); \
51 module_param_named(num_buffers, fsg_num_buffers, uint, S_IRUGO);\
52 MODULE_PARM_DESC(num_buffers, "Number of pipeline buffers")
53#else
54
55#define FSG_MODULE_PARAMETERS(prefix, params) \
56 __FSG_MODULE_PARAMETERS(prefix, params)
57
58#endif
59
60struct fsg_common;
61
62/* FSF callback functions */
63struct fsg_operations {
64 /*
65 * Callback function to call when thread exits. If no
66 * callback is set or it returns value lower then zero MSF
67 * will force eject all LUNs it operates on (including those
68 * marked as non-removable or with prevent_medium_removal flag
69 * set).
70 */
71 int (*thread_exits)(struct fsg_common *common);
72};
73
74struct fsg_lun_opts {
75 struct config_group group;
76 struct fsg_lun *lun;
77 int lun_id;
78};
79
80struct fsg_opts {
81 struct fsg_common *common;
82 struct usb_function_instance func_inst;
83 struct fsg_lun_opts lun0;
84 struct config_group *default_groups[2];
85 bool no_configfs; /* for legacy gadgets */
86
87 /*
88 * Read/write access to configfs attributes is handled by configfs.
89 *
90 * This is to protect the data from concurrent access by read/write
91 * and create symlink/remove symlink.
92 */
93 struct mutex lock;
94 int refcnt;
95};
96
97struct fsg_lun_config {
98 const char *filename;
99 char ro;
100 char removable;
101 char cdrom;
102 char nofua;
103};
104
105struct fsg_config {
106 unsigned nluns;
107 struct fsg_lun_config luns[FSG_MAX_LUNS];
108
109 /* Callback functions. */
110 const struct fsg_operations *ops;
111 /* Gadget's private data. */
112 void *private_data;
113
114 const char *vendor_name; /* 8 characters or less */
115 const char *product_name; /* 16 characters or less */
116
117 char can_stall;
118 unsigned int fsg_num_buffers;
119};
120
121static inline struct fsg_opts *
122fsg_opts_from_func_inst(const struct usb_function_instance *fi)
123{
124 return container_of(fi, struct fsg_opts, func_inst);
125}
126
127void fsg_common_get(struct fsg_common *common);
128
129void fsg_common_put(struct fsg_common *common);
130
131void fsg_common_set_sysfs(struct fsg_common *common, bool sysfs);
132
133int fsg_common_set_num_buffers(struct fsg_common *common, unsigned int n);
134
135void fsg_common_free_buffers(struct fsg_common *common);
136
137int fsg_common_set_cdev(struct fsg_common *common,
138 struct usb_composite_dev *cdev, bool can_stall);
139
140void fsg_common_remove_lun(struct fsg_lun *lun, bool sysfs);
141
142void fsg_common_remove_luns(struct fsg_common *common);
143
144void fsg_common_free_luns(struct fsg_common *common);
145
146int fsg_common_set_nluns(struct fsg_common *common, int nluns);
147
148void fsg_common_set_ops(struct fsg_common *common,
149 const struct fsg_operations *ops);
150
151int fsg_common_create_lun(struct fsg_common *common, struct fsg_lun_config *cfg,
152 unsigned int id, const char *name,
153 const char **name_pfx);
154
155int fsg_common_create_luns(struct fsg_common *common, struct fsg_config *cfg);
156
157void fsg_common_set_inquiry_string(struct fsg_common *common, const char *vn,
158 const char *pn);
159
160int fsg_common_run_thread(struct fsg_common *common);
161
162void fsg_config_from_params(struct fsg_config *cfg,
163 const struct fsg_module_parameters *params,
164 unsigned int fsg_num_buffers);
165
166#endif /* USB_F_MASS_STORAGE_H */
diff --git a/drivers/usb/gadget/function/f_midi.c b/drivers/usb/gadget/function/f_midi.c
new file mode 100644
index 000000000000..807b31c0edc3
--- /dev/null
+++ b/drivers/usb/gadget/function/f_midi.c
@@ -0,0 +1,986 @@
1/*
2 * f_midi.c -- USB MIDI class function driver
3 *
4 * Copyright (C) 2006 Thumtronics Pty Ltd.
5 * Developed for Thumtronics by Grey Innovation
6 * Ben Williamson <ben.williamson@greyinnovation.com>
7 *
8 * Rewritten for the composite framework
9 * Copyright (C) 2011 Daniel Mack <zonque@gmail.com>
10 *
11 * Based on drivers/usb/gadget/f_audio.c,
12 * Copyright (C) 2008 Bryan Wu <cooloney@kernel.org>
13 * Copyright (C) 2008 Analog Devices, Inc
14 *
15 * and drivers/usb/gadget/midi.c,
16 * Copyright (C) 2006 Thumtronics Pty Ltd.
17 * Ben Williamson <ben.williamson@greyinnovation.com>
18 *
19 * Licensed under the GPL-2 or later.
20 */
21
22#include <linux/kernel.h>
23#include <linux/slab.h>
24#include <linux/device.h>
25
26#include <sound/core.h>
27#include <sound/initval.h>
28#include <sound/rawmidi.h>
29
30#include <linux/usb/ch9.h>
31#include <linux/usb/gadget.h>
32#include <linux/usb/audio.h>
33#include <linux/usb/midi.h>
34
35#include "u_f.h"
36
37MODULE_AUTHOR("Ben Williamson");
38MODULE_LICENSE("GPL v2");
39
40static const char f_midi_shortname[] = "f_midi";
41static const char f_midi_longname[] = "MIDI Gadget";
42
43/*
44 * We can only handle 16 cables on one single endpoint, as cable numbers are
45 * stored in 4-bit fields. And as the interface currently only holds one
46 * single endpoint, this is the maximum number of ports we can allow.
47 */
48#define MAX_PORTS 16
49
50/*
51 * This is a gadget, and the IN/OUT naming is from the host's perspective.
52 * USB -> OUT endpoint -> rawmidi
53 * USB <- IN endpoint <- rawmidi
54 */
55struct gmidi_in_port {
56 struct f_midi *midi;
57 int active;
58 uint8_t cable;
59 uint8_t state;
60#define STATE_UNKNOWN 0
61#define STATE_1PARAM 1
62#define STATE_2PARAM_1 2
63#define STATE_2PARAM_2 3
64#define STATE_SYSEX_0 4
65#define STATE_SYSEX_1 5
66#define STATE_SYSEX_2 6
67 uint8_t data[2];
68};
69
70struct f_midi {
71 struct usb_function func;
72 struct usb_gadget *gadget;
73 struct usb_ep *in_ep, *out_ep;
74 struct snd_card *card;
75 struct snd_rawmidi *rmidi;
76
77 struct snd_rawmidi_substream *in_substream[MAX_PORTS];
78 struct snd_rawmidi_substream *out_substream[MAX_PORTS];
79 struct gmidi_in_port *in_port[MAX_PORTS];
80
81 unsigned long out_triggered;
82 struct tasklet_struct tasklet;
83 unsigned int in_ports;
84 unsigned int out_ports;
85 int index;
86 char *id;
87 unsigned int buflen, qlen;
88};
89
90static inline struct f_midi *func_to_midi(struct usb_function *f)
91{
92 return container_of(f, struct f_midi, func);
93}
94
95static void f_midi_transmit(struct f_midi *midi, struct usb_request *req);
96
97DECLARE_UAC_AC_HEADER_DESCRIPTOR(1);
98DECLARE_USB_MIDI_OUT_JACK_DESCRIPTOR(1);
99DECLARE_USB_MS_ENDPOINT_DESCRIPTOR(16);
100
101/* B.3.1 Standard AC Interface Descriptor */
102static struct usb_interface_descriptor ac_interface_desc __initdata = {
103 .bLength = USB_DT_INTERFACE_SIZE,
104 .bDescriptorType = USB_DT_INTERFACE,
105 /* .bInterfaceNumber = DYNAMIC */
106 /* .bNumEndpoints = DYNAMIC */
107 .bInterfaceClass = USB_CLASS_AUDIO,
108 .bInterfaceSubClass = USB_SUBCLASS_AUDIOCONTROL,
109 /* .iInterface = DYNAMIC */
110};
111
112/* B.3.2 Class-Specific AC Interface Descriptor */
113static struct uac1_ac_header_descriptor_1 ac_header_desc __initdata = {
114 .bLength = UAC_DT_AC_HEADER_SIZE(1),
115 .bDescriptorType = USB_DT_CS_INTERFACE,
116 .bDescriptorSubtype = USB_MS_HEADER,
117 .bcdADC = cpu_to_le16(0x0100),
118 .wTotalLength = cpu_to_le16(UAC_DT_AC_HEADER_SIZE(1)),
119 .bInCollection = 1,
120 /* .baInterfaceNr = DYNAMIC */
121};
122
123/* B.4.1 Standard MS Interface Descriptor */
124static struct usb_interface_descriptor ms_interface_desc __initdata = {
125 .bLength = USB_DT_INTERFACE_SIZE,
126 .bDescriptorType = USB_DT_INTERFACE,
127 /* .bInterfaceNumber = DYNAMIC */
128 .bNumEndpoints = 2,
129 .bInterfaceClass = USB_CLASS_AUDIO,
130 .bInterfaceSubClass = USB_SUBCLASS_MIDISTREAMING,
131 /* .iInterface = DYNAMIC */
132};
133
134/* B.4.2 Class-Specific MS Interface Descriptor */
135static struct usb_ms_header_descriptor ms_header_desc __initdata = {
136 .bLength = USB_DT_MS_HEADER_SIZE,
137 .bDescriptorType = USB_DT_CS_INTERFACE,
138 .bDescriptorSubtype = USB_MS_HEADER,
139 .bcdMSC = cpu_to_le16(0x0100),
140 /* .wTotalLength = DYNAMIC */
141};
142
143/* B.5.1 Standard Bulk OUT Endpoint Descriptor */
144static struct usb_endpoint_descriptor bulk_out_desc = {
145 .bLength = USB_DT_ENDPOINT_AUDIO_SIZE,
146 .bDescriptorType = USB_DT_ENDPOINT,
147 .bEndpointAddress = USB_DIR_OUT,
148 .bmAttributes = USB_ENDPOINT_XFER_BULK,
149};
150
151/* B.5.2 Class-specific MS Bulk OUT Endpoint Descriptor */
152static struct usb_ms_endpoint_descriptor_16 ms_out_desc = {
153 /* .bLength = DYNAMIC */
154 .bDescriptorType = USB_DT_CS_ENDPOINT,
155 .bDescriptorSubtype = USB_MS_GENERAL,
156 /* .bNumEmbMIDIJack = DYNAMIC */
157 /* .baAssocJackID = DYNAMIC */
158};
159
160/* B.6.1 Standard Bulk IN Endpoint Descriptor */
161static struct usb_endpoint_descriptor bulk_in_desc = {
162 .bLength = USB_DT_ENDPOINT_AUDIO_SIZE,
163 .bDescriptorType = USB_DT_ENDPOINT,
164 .bEndpointAddress = USB_DIR_IN,
165 .bmAttributes = USB_ENDPOINT_XFER_BULK,
166};
167
168/* B.6.2 Class-specific MS Bulk IN Endpoint Descriptor */
169static struct usb_ms_endpoint_descriptor_16 ms_in_desc = {
170 /* .bLength = DYNAMIC */
171 .bDescriptorType = USB_DT_CS_ENDPOINT,
172 .bDescriptorSubtype = USB_MS_GENERAL,
173 /* .bNumEmbMIDIJack = DYNAMIC */
174 /* .baAssocJackID = DYNAMIC */
175};
176
177/* string IDs are assigned dynamically */
178
179#define STRING_FUNC_IDX 0
180
181static struct usb_string midi_string_defs[] = {
182 [STRING_FUNC_IDX].s = "MIDI function",
183 { } /* end of list */
184};
185
186static struct usb_gadget_strings midi_stringtab = {
187 .language = 0x0409, /* en-us */
188 .strings = midi_string_defs,
189};
190
191static struct usb_gadget_strings *midi_strings[] = {
192 &midi_stringtab,
193 NULL,
194};
195
196static inline struct usb_request *midi_alloc_ep_req(struct usb_ep *ep,
197 unsigned length)
198{
199 return alloc_ep_req(ep, length, length);
200}
201
202static void free_ep_req(struct usb_ep *ep, struct usb_request *req)
203{
204 kfree(req->buf);
205 usb_ep_free_request(ep, req);
206}
207
208static const uint8_t f_midi_cin_length[] = {
209 0, 0, 2, 3, 3, 1, 2, 3, 3, 3, 3, 3, 2, 2, 3, 1
210};
211
212/*
213 * Receives a chunk of MIDI data.
214 */
215static void f_midi_read_data(struct usb_ep *ep, int cable,
216 uint8_t *data, int length)
217{
218 struct f_midi *midi = ep->driver_data;
219 struct snd_rawmidi_substream *substream = midi->out_substream[cable];
220
221 if (!substream)
222 /* Nobody is listening - throw it on the floor. */
223 return;
224
225 if (!test_bit(cable, &midi->out_triggered))
226 return;
227
228 snd_rawmidi_receive(substream, data, length);
229}
230
231static void f_midi_handle_out_data(struct usb_ep *ep, struct usb_request *req)
232{
233 unsigned int i;
234 u8 *buf = req->buf;
235
236 for (i = 0; i + 3 < req->actual; i += 4)
237 if (buf[i] != 0) {
238 int cable = buf[i] >> 4;
239 int length = f_midi_cin_length[buf[i] & 0x0f];
240 f_midi_read_data(ep, cable, &buf[i + 1], length);
241 }
242}
243
244static void
245f_midi_complete(struct usb_ep *ep, struct usb_request *req)
246{
247 struct f_midi *midi = ep->driver_data;
248 struct usb_composite_dev *cdev = midi->func.config->cdev;
249 int status = req->status;
250
251 switch (status) {
252 case 0: /* normal completion */
253 if (ep == midi->out_ep) {
254 /* We received stuff. req is queued again, below */
255 f_midi_handle_out_data(ep, req);
256 } else if (ep == midi->in_ep) {
257 /* Our transmit completed. See if there's more to go.
258 * f_midi_transmit eats req, don't queue it again. */
259 f_midi_transmit(midi, req);
260 return;
261 }
262 break;
263
264 /* this endpoint is normally active while we're configured */
265 case -ECONNABORTED: /* hardware forced ep reset */
266 case -ECONNRESET: /* request dequeued */
267 case -ESHUTDOWN: /* disconnect from host */
268 VDBG(cdev, "%s gone (%d), %d/%d\n", ep->name, status,
269 req->actual, req->length);
270 if (ep == midi->out_ep)
271 f_midi_handle_out_data(ep, req);
272
273 free_ep_req(ep, req);
274 return;
275
276 case -EOVERFLOW: /* buffer overrun on read means that
277 * we didn't provide a big enough buffer.
278 */
279 default:
280 DBG(cdev, "%s complete --> %d, %d/%d\n", ep->name,
281 status, req->actual, req->length);
282 break;
283 case -EREMOTEIO: /* short read */
284 break;
285 }
286
287 status = usb_ep_queue(ep, req, GFP_ATOMIC);
288 if (status) {
289 ERROR(cdev, "kill %s: resubmit %d bytes --> %d\n",
290 ep->name, req->length, status);
291 usb_ep_set_halt(ep);
292 /* FIXME recover later ... somehow */
293 }
294}
295
296static int f_midi_start_ep(struct f_midi *midi,
297 struct usb_function *f,
298 struct usb_ep *ep)
299{
300 int err;
301 struct usb_composite_dev *cdev = f->config->cdev;
302
303 if (ep->driver_data)
304 usb_ep_disable(ep);
305
306 err = config_ep_by_speed(midi->gadget, f, ep);
307 if (err) {
308 ERROR(cdev, "can't configure %s: %d\n", ep->name, err);
309 return err;
310 }
311
312 err = usb_ep_enable(ep);
313 if (err) {
314 ERROR(cdev, "can't start %s: %d\n", ep->name, err);
315 return err;
316 }
317
318 ep->driver_data = midi;
319
320 return 0;
321}
322
323static int f_midi_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
324{
325 struct f_midi *midi = func_to_midi(f);
326 struct usb_composite_dev *cdev = f->config->cdev;
327 unsigned i;
328 int err;
329
330 err = f_midi_start_ep(midi, f, midi->in_ep);
331 if (err)
332 return err;
333
334 err = f_midi_start_ep(midi, f, midi->out_ep);
335 if (err)
336 return err;
337
338 if (midi->out_ep->driver_data)
339 usb_ep_disable(midi->out_ep);
340
341 err = config_ep_by_speed(midi->gadget, f, midi->out_ep);
342 if (err) {
343 ERROR(cdev, "can't configure %s: %d\n",
344 midi->out_ep->name, err);
345 return err;
346 }
347
348 err = usb_ep_enable(midi->out_ep);
349 if (err) {
350 ERROR(cdev, "can't start %s: %d\n",
351 midi->out_ep->name, err);
352 return err;
353 }
354
355 midi->out_ep->driver_data = midi;
356
357 /* allocate a bunch of read buffers and queue them all at once. */
358 for (i = 0; i < midi->qlen && err == 0; i++) {
359 struct usb_request *req =
360 midi_alloc_ep_req(midi->out_ep, midi->buflen);
361 if (req == NULL)
362 return -ENOMEM;
363
364 req->complete = f_midi_complete;
365 err = usb_ep_queue(midi->out_ep, req, GFP_ATOMIC);
366 if (err) {
367 ERROR(midi, "%s queue req: %d\n",
368 midi->out_ep->name, err);
369 }
370 }
371
372 return 0;
373}
374
375static void f_midi_disable(struct usb_function *f)
376{
377 struct f_midi *midi = func_to_midi(f);
378 struct usb_composite_dev *cdev = f->config->cdev;
379
380 DBG(cdev, "disable\n");
381
382 /*
383 * just disable endpoints, forcing completion of pending i/o.
384 * all our completion handlers free their requests in this case.
385 */
386 usb_ep_disable(midi->in_ep);
387 usb_ep_disable(midi->out_ep);
388}
389
390static void f_midi_unbind(struct usb_configuration *c, struct usb_function *f)
391{
392 struct usb_composite_dev *cdev = f->config->cdev;
393 struct f_midi *midi = func_to_midi(f);
394 struct snd_card *card;
395
396 DBG(cdev, "unbind\n");
397
398 /* just to be sure */
399 f_midi_disable(f);
400
401 card = midi->card;
402 midi->card = NULL;
403 if (card)
404 snd_card_free(card);
405
406 kfree(midi->id);
407 midi->id = NULL;
408
409 usb_free_all_descriptors(f);
410 kfree(midi);
411}
412
413static int f_midi_snd_free(struct snd_device *device)
414{
415 return 0;
416}
417
418static void f_midi_transmit_packet(struct usb_request *req, uint8_t p0,
419 uint8_t p1, uint8_t p2, uint8_t p3)
420{
421 unsigned length = req->length;
422 u8 *buf = (u8 *)req->buf + length;
423
424 buf[0] = p0;
425 buf[1] = p1;
426 buf[2] = p2;
427 buf[3] = p3;
428 req->length = length + 4;
429}
430
431/*
432 * Converts MIDI commands to USB MIDI packets.
433 */
434static void f_midi_transmit_byte(struct usb_request *req,
435 struct gmidi_in_port *port, uint8_t b)
436{
437 uint8_t p0 = port->cable << 4;
438
439 if (b >= 0xf8) {
440 f_midi_transmit_packet(req, p0 | 0x0f, b, 0, 0);
441 } else if (b >= 0xf0) {
442 switch (b) {
443 case 0xf0:
444 port->data[0] = b;
445 port->state = STATE_SYSEX_1;
446 break;
447 case 0xf1:
448 case 0xf3:
449 port->data[0] = b;
450 port->state = STATE_1PARAM;
451 break;
452 case 0xf2:
453 port->data[0] = b;
454 port->state = STATE_2PARAM_1;
455 break;
456 case 0xf4:
457 case 0xf5:
458 port->state = STATE_UNKNOWN;
459 break;
460 case 0xf6:
461 f_midi_transmit_packet(req, p0 | 0x05, 0xf6, 0, 0);
462 port->state = STATE_UNKNOWN;
463 break;
464 case 0xf7:
465 switch (port->state) {
466 case STATE_SYSEX_0:
467 f_midi_transmit_packet(req,
468 p0 | 0x05, 0xf7, 0, 0);
469 break;
470 case STATE_SYSEX_1:
471 f_midi_transmit_packet(req,
472 p0 | 0x06, port->data[0], 0xf7, 0);
473 break;
474 case STATE_SYSEX_2:
475 f_midi_transmit_packet(req,
476 p0 | 0x07, port->data[0],
477 port->data[1], 0xf7);
478 break;
479 }
480 port->state = STATE_UNKNOWN;
481 break;
482 }
483 } else if (b >= 0x80) {
484 port->data[0] = b;
485 if (b >= 0xc0 && b <= 0xdf)
486 port->state = STATE_1PARAM;
487 else
488 port->state = STATE_2PARAM_1;
489 } else { /* b < 0x80 */
490 switch (port->state) {
491 case STATE_1PARAM:
492 if (port->data[0] < 0xf0) {
493 p0 |= port->data[0] >> 4;
494 } else {
495 p0 |= 0x02;
496 port->state = STATE_UNKNOWN;
497 }
498 f_midi_transmit_packet(req, p0, port->data[0], b, 0);
499 break;
500 case STATE_2PARAM_1:
501 port->data[1] = b;
502 port->state = STATE_2PARAM_2;
503 break;
504 case STATE_2PARAM_2:
505 if (port->data[0] < 0xf0) {
506 p0 |= port->data[0] >> 4;
507 port->state = STATE_2PARAM_1;
508 } else {
509 p0 |= 0x03;
510 port->state = STATE_UNKNOWN;
511 }
512 f_midi_transmit_packet(req,
513 p0, port->data[0], port->data[1], b);
514 break;
515 case STATE_SYSEX_0:
516 port->data[0] = b;
517 port->state = STATE_SYSEX_1;
518 break;
519 case STATE_SYSEX_1:
520 port->data[1] = b;
521 port->state = STATE_SYSEX_2;
522 break;
523 case STATE_SYSEX_2:
524 f_midi_transmit_packet(req,
525 p0 | 0x04, port->data[0], port->data[1], b);
526 port->state = STATE_SYSEX_0;
527 break;
528 }
529 }
530}
531
532static void f_midi_transmit(struct f_midi *midi, struct usb_request *req)
533{
534 struct usb_ep *ep = midi->in_ep;
535 int i;
536
537 if (!ep)
538 return;
539
540 if (!req)
541 req = midi_alloc_ep_req(ep, midi->buflen);
542
543 if (!req) {
544 ERROR(midi, "gmidi_transmit: alloc_ep_request failed\n");
545 return;
546 }
547 req->length = 0;
548 req->complete = f_midi_complete;
549
550 for (i = 0; i < MAX_PORTS; i++) {
551 struct gmidi_in_port *port = midi->in_port[i];
552 struct snd_rawmidi_substream *substream = midi->in_substream[i];
553
554 if (!port || !port->active || !substream)
555 continue;
556
557 while (req->length + 3 < midi->buflen) {
558 uint8_t b;
559 if (snd_rawmidi_transmit(substream, &b, 1) != 1) {
560 port->active = 0;
561 break;
562 }
563 f_midi_transmit_byte(req, port, b);
564 }
565 }
566
567 if (req->length > 0)
568 usb_ep_queue(ep, req, GFP_ATOMIC);
569 else
570 free_ep_req(ep, req);
571}
572
573static void f_midi_in_tasklet(unsigned long data)
574{
575 struct f_midi *midi = (struct f_midi *) data;
576 f_midi_transmit(midi, NULL);
577}
578
579static int f_midi_in_open(struct snd_rawmidi_substream *substream)
580{
581 struct f_midi *midi = substream->rmidi->private_data;
582
583 if (!midi->in_port[substream->number])
584 return -EINVAL;
585
586 VDBG(midi, "%s()\n", __func__);
587 midi->in_substream[substream->number] = substream;
588 midi->in_port[substream->number]->state = STATE_UNKNOWN;
589 return 0;
590}
591
592static int f_midi_in_close(struct snd_rawmidi_substream *substream)
593{
594 struct f_midi *midi = substream->rmidi->private_data;
595
596 VDBG(midi, "%s()\n", __func__);
597 return 0;
598}
599
600static void f_midi_in_trigger(struct snd_rawmidi_substream *substream, int up)
601{
602 struct f_midi *midi = substream->rmidi->private_data;
603
604 if (!midi->in_port[substream->number])
605 return;
606
607 VDBG(midi, "%s() %d\n", __func__, up);
608 midi->in_port[substream->number]->active = up;
609 if (up)
610 tasklet_hi_schedule(&midi->tasklet);
611}
612
613static int f_midi_out_open(struct snd_rawmidi_substream *substream)
614{
615 struct f_midi *midi = substream->rmidi->private_data;
616
617 if (substream->number >= MAX_PORTS)
618 return -EINVAL;
619
620 VDBG(midi, "%s()\n", __func__);
621 midi->out_substream[substream->number] = substream;
622 return 0;
623}
624
625static int f_midi_out_close(struct snd_rawmidi_substream *substream)
626{
627 struct f_midi *midi = substream->rmidi->private_data;
628
629 VDBG(midi, "%s()\n", __func__);
630 return 0;
631}
632
633static void f_midi_out_trigger(struct snd_rawmidi_substream *substream, int up)
634{
635 struct f_midi *midi = substream->rmidi->private_data;
636
637 VDBG(midi, "%s()\n", __func__);
638
639 if (up)
640 set_bit(substream->number, &midi->out_triggered);
641 else
642 clear_bit(substream->number, &midi->out_triggered);
643}
644
645static struct snd_rawmidi_ops gmidi_in_ops = {
646 .open = f_midi_in_open,
647 .close = f_midi_in_close,
648 .trigger = f_midi_in_trigger,
649};
650
651static struct snd_rawmidi_ops gmidi_out_ops = {
652 .open = f_midi_out_open,
653 .close = f_midi_out_close,
654 .trigger = f_midi_out_trigger
655};
656
657/* register as a sound "card" */
658static int f_midi_register_card(struct f_midi *midi)
659{
660 struct snd_card *card;
661 struct snd_rawmidi *rmidi;
662 int err;
663 static struct snd_device_ops ops = {
664 .dev_free = f_midi_snd_free,
665 };
666
667 err = snd_card_new(&midi->gadget->dev, midi->index, midi->id,
668 THIS_MODULE, 0, &card);
669 if (err < 0) {
670 ERROR(midi, "snd_card_new() failed\n");
671 goto fail;
672 }
673 midi->card = card;
674
675 err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, midi, &ops);
676 if (err < 0) {
677 ERROR(midi, "snd_device_new() failed: error %d\n", err);
678 goto fail;
679 }
680
681 strcpy(card->driver, f_midi_longname);
682 strcpy(card->longname, f_midi_longname);
683 strcpy(card->shortname, f_midi_shortname);
684
685 /* Set up rawmidi */
686 snd_component_add(card, "MIDI");
687 err = snd_rawmidi_new(card, card->longname, 0,
688 midi->out_ports, midi->in_ports, &rmidi);
689 if (err < 0) {
690 ERROR(midi, "snd_rawmidi_new() failed: error %d\n", err);
691 goto fail;
692 }
693 midi->rmidi = rmidi;
694 strcpy(rmidi->name, card->shortname);
695 rmidi->info_flags = SNDRV_RAWMIDI_INFO_OUTPUT |
696 SNDRV_RAWMIDI_INFO_INPUT |
697 SNDRV_RAWMIDI_INFO_DUPLEX;
698 rmidi->private_data = midi;
699
700 /*
701 * Yes, rawmidi OUTPUT = USB IN, and rawmidi INPUT = USB OUT.
702 * It's an upside-down world being a gadget.
703 */
704 snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_OUTPUT, &gmidi_in_ops);
705 snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_INPUT, &gmidi_out_ops);
706
707 /* register it - we're ready to go */
708 err = snd_card_register(card);
709 if (err < 0) {
710 ERROR(midi, "snd_card_register() failed\n");
711 goto fail;
712 }
713
714 VDBG(midi, "%s() finished ok\n", __func__);
715 return 0;
716
717fail:
718 if (midi->card) {
719 snd_card_free(midi->card);
720 midi->card = NULL;
721 }
722 return err;
723}
724
725/* MIDI function driver setup/binding */
726
727static int __init
728f_midi_bind(struct usb_configuration *c, struct usb_function *f)
729{
730 struct usb_descriptor_header **midi_function;
731 struct usb_midi_in_jack_descriptor jack_in_ext_desc[MAX_PORTS];
732 struct usb_midi_in_jack_descriptor jack_in_emb_desc[MAX_PORTS];
733 struct usb_midi_out_jack_descriptor_1 jack_out_ext_desc[MAX_PORTS];
734 struct usb_midi_out_jack_descriptor_1 jack_out_emb_desc[MAX_PORTS];
735 struct usb_composite_dev *cdev = c->cdev;
736 struct f_midi *midi = func_to_midi(f);
737 int status, n, jack = 1, i = 0;
738
739 /* maybe allocate device-global string ID */
740 if (midi_string_defs[0].id == 0) {
741 status = usb_string_id(c->cdev);
742 if (status < 0)
743 goto fail;
744 midi_string_defs[0].id = status;
745 }
746
747 /* We have two interfaces, AudioControl and MIDIStreaming */
748 status = usb_interface_id(c, f);
749 if (status < 0)
750 goto fail;
751 ac_interface_desc.bInterfaceNumber = status;
752
753 status = usb_interface_id(c, f);
754 if (status < 0)
755 goto fail;
756 ms_interface_desc.bInterfaceNumber = status;
757 ac_header_desc.baInterfaceNr[0] = status;
758
759 status = -ENODEV;
760
761 /* allocate instance-specific endpoints */
762 midi->in_ep = usb_ep_autoconfig(cdev->gadget, &bulk_in_desc);
763 if (!midi->in_ep)
764 goto fail;
765 midi->in_ep->driver_data = cdev; /* claim */
766
767 midi->out_ep = usb_ep_autoconfig(cdev->gadget, &bulk_out_desc);
768 if (!midi->out_ep)
769 goto fail;
770 midi->out_ep->driver_data = cdev; /* claim */
771
772 /* allocate temporary function list */
773 midi_function = kcalloc((MAX_PORTS * 4) + 9, sizeof(*midi_function),
774 GFP_KERNEL);
775 if (!midi_function) {
776 status = -ENOMEM;
777 goto fail;
778 }
779
780 /*
781 * construct the function's descriptor set. As the number of
782 * input and output MIDI ports is configurable, we have to do
783 * it that way.
784 */
785
786 /* add the headers - these are always the same */
787 midi_function[i++] = (struct usb_descriptor_header *) &ac_interface_desc;
788 midi_function[i++] = (struct usb_descriptor_header *) &ac_header_desc;
789 midi_function[i++] = (struct usb_descriptor_header *) &ms_interface_desc;
790
791 /* calculate the header's wTotalLength */
792 n = USB_DT_MS_HEADER_SIZE
793 + (midi->in_ports + midi->out_ports) *
794 (USB_DT_MIDI_IN_SIZE + USB_DT_MIDI_OUT_SIZE(1));
795 ms_header_desc.wTotalLength = cpu_to_le16(n);
796
797 midi_function[i++] = (struct usb_descriptor_header *) &ms_header_desc;
798
799 /* configure the external IN jacks, each linked to an embedded OUT jack */
800 for (n = 0; n < midi->in_ports; n++) {
801 struct usb_midi_in_jack_descriptor *in_ext = &jack_in_ext_desc[n];
802 struct usb_midi_out_jack_descriptor_1 *out_emb = &jack_out_emb_desc[n];
803
804 in_ext->bLength = USB_DT_MIDI_IN_SIZE;
805 in_ext->bDescriptorType = USB_DT_CS_INTERFACE;
806 in_ext->bDescriptorSubtype = USB_MS_MIDI_IN_JACK;
807 in_ext->bJackType = USB_MS_EXTERNAL;
808 in_ext->bJackID = jack++;
809 in_ext->iJack = 0;
810 midi_function[i++] = (struct usb_descriptor_header *) in_ext;
811
812 out_emb->bLength = USB_DT_MIDI_OUT_SIZE(1);
813 out_emb->bDescriptorType = USB_DT_CS_INTERFACE;
814 out_emb->bDescriptorSubtype = USB_MS_MIDI_OUT_JACK;
815 out_emb->bJackType = USB_MS_EMBEDDED;
816 out_emb->bJackID = jack++;
817 out_emb->bNrInputPins = 1;
818 out_emb->pins[0].baSourcePin = 1;
819 out_emb->pins[0].baSourceID = in_ext->bJackID;
820 out_emb->iJack = 0;
821 midi_function[i++] = (struct usb_descriptor_header *) out_emb;
822
823 /* link it to the endpoint */
824 ms_in_desc.baAssocJackID[n] = out_emb->bJackID;
825 }
826
827 /* configure the external OUT jacks, each linked to an embedded IN jack */
828 for (n = 0; n < midi->out_ports; n++) {
829 struct usb_midi_in_jack_descriptor *in_emb = &jack_in_emb_desc[n];
830 struct usb_midi_out_jack_descriptor_1 *out_ext = &jack_out_ext_desc[n];
831
832 in_emb->bLength = USB_DT_MIDI_IN_SIZE;
833 in_emb->bDescriptorType = USB_DT_CS_INTERFACE;
834 in_emb->bDescriptorSubtype = USB_MS_MIDI_IN_JACK;
835 in_emb->bJackType = USB_MS_EMBEDDED;
836 in_emb->bJackID = jack++;
837 in_emb->iJack = 0;
838 midi_function[i++] = (struct usb_descriptor_header *) in_emb;
839
840 out_ext->bLength = USB_DT_MIDI_OUT_SIZE(1);
841 out_ext->bDescriptorType = USB_DT_CS_INTERFACE;
842 out_ext->bDescriptorSubtype = USB_MS_MIDI_OUT_JACK;
843 out_ext->bJackType = USB_MS_EXTERNAL;
844 out_ext->bJackID = jack++;
845 out_ext->bNrInputPins = 1;
846 out_ext->iJack = 0;
847 out_ext->pins[0].baSourceID = in_emb->bJackID;
848 out_ext->pins[0].baSourcePin = 1;
849 midi_function[i++] = (struct usb_descriptor_header *) out_ext;
850
851 /* link it to the endpoint */
852 ms_out_desc.baAssocJackID[n] = in_emb->bJackID;
853 }
854
855 /* configure the endpoint descriptors ... */
856 ms_out_desc.bLength = USB_DT_MS_ENDPOINT_SIZE(midi->in_ports);
857 ms_out_desc.bNumEmbMIDIJack = midi->in_ports;
858
859 ms_in_desc.bLength = USB_DT_MS_ENDPOINT_SIZE(midi->out_ports);
860 ms_in_desc.bNumEmbMIDIJack = midi->out_ports;
861
862 /* ... and add them to the list */
863 midi_function[i++] = (struct usb_descriptor_header *) &bulk_out_desc;
864 midi_function[i++] = (struct usb_descriptor_header *) &ms_out_desc;
865 midi_function[i++] = (struct usb_descriptor_header *) &bulk_in_desc;
866 midi_function[i++] = (struct usb_descriptor_header *) &ms_in_desc;
867 midi_function[i++] = NULL;
868
869 /*
870 * support all relevant hardware speeds... we expect that when
871 * hardware is dual speed, all bulk-capable endpoints work at
872 * both speeds
873 */
874 /* copy descriptors, and track endpoint copies */
875 f->fs_descriptors = usb_copy_descriptors(midi_function);
876 if (!f->fs_descriptors)
877 goto fail_f_midi;
878
879 if (gadget_is_dualspeed(c->cdev->gadget)) {
880 bulk_in_desc.wMaxPacketSize = cpu_to_le16(512);
881 bulk_out_desc.wMaxPacketSize = cpu_to_le16(512);
882 f->hs_descriptors = usb_copy_descriptors(midi_function);
883 if (!f->hs_descriptors)
884 goto fail_f_midi;
885 }
886
887 kfree(midi_function);
888
889 return 0;
890
891fail_f_midi:
892 kfree(midi_function);
893 usb_free_descriptors(f->hs_descriptors);
894fail:
895 /* we might as well release our claims on endpoints */
896 if (midi->out_ep)
897 midi->out_ep->driver_data = NULL;
898 if (midi->in_ep)
899 midi->in_ep->driver_data = NULL;
900
901 ERROR(cdev, "%s: can't bind, err %d\n", f->name, status);
902
903 return status;
904}
905
906/**
907 * f_midi_bind_config - add USB MIDI function to a configuration
908 * @c: the configuration to supcard the USB audio function
909 * @index: the soundcard index to use for the ALSA device creation
910 * @id: the soundcard id to use for the ALSA device creation
911 * @buflen: the buffer length to use
912 * @qlen the number of read requests to pre-allocate
913 * Context: single threaded during gadget setup
914 *
915 * Returns zero on success, else negative errno.
916 */
917int __init f_midi_bind_config(struct usb_configuration *c,
918 int index, char *id,
919 unsigned int in_ports,
920 unsigned int out_ports,
921 unsigned int buflen,
922 unsigned int qlen)
923{
924 struct f_midi *midi;
925 int status, i;
926
927 /* sanity check */
928 if (in_ports > MAX_PORTS || out_ports > MAX_PORTS)
929 return -EINVAL;
930
931 /* allocate and initialize one new instance */
932 midi = kzalloc(sizeof *midi, GFP_KERNEL);
933 if (!midi) {
934 status = -ENOMEM;
935 goto fail;
936 }
937
938 for (i = 0; i < in_ports; i++) {
939 struct gmidi_in_port *port = kzalloc(sizeof(*port), GFP_KERNEL);
940 if (!port) {
941 status = -ENOMEM;
942 goto setup_fail;
943 }
944
945 port->midi = midi;
946 port->active = 0;
947 port->cable = i;
948 midi->in_port[i] = port;
949 }
950
951 midi->gadget = c->cdev->gadget;
952 tasklet_init(&midi->tasklet, f_midi_in_tasklet, (unsigned long) midi);
953
954 /* set up ALSA midi devices */
955 midi->in_ports = in_ports;
956 midi->out_ports = out_ports;
957 status = f_midi_register_card(midi);
958 if (status < 0)
959 goto setup_fail;
960
961 midi->func.name = "gmidi function";
962 midi->func.strings = midi_strings;
963 midi->func.bind = f_midi_bind;
964 midi->func.unbind = f_midi_unbind;
965 midi->func.set_alt = f_midi_set_alt;
966 midi->func.disable = f_midi_disable;
967
968 midi->id = kstrdup(id, GFP_KERNEL);
969 midi->index = index;
970 midi->buflen = buflen;
971 midi->qlen = qlen;
972
973 status = usb_add_function(c, &midi->func);
974 if (status)
975 goto setup_fail;
976
977 return 0;
978
979setup_fail:
980 for (--i; i >= 0; i--)
981 kfree(midi->in_port[i]);
982 kfree(midi);
983fail:
984 return status;
985}
986
diff --git a/drivers/usb/gadget/function/f_ncm.c b/drivers/usb/gadget/function/f_ncm.c
new file mode 100644
index 000000000000..bcdc882cd415
--- /dev/null
+++ b/drivers/usb/gadget/function/f_ncm.c
@@ -0,0 +1,1622 @@
1/*
2 * f_ncm.c -- USB CDC Network (NCM) link function driver
3 *
4 * Copyright (C) 2010 Nokia Corporation
5 * Contact: Yauheni Kaliuta <yauheni.kaliuta@nokia.com>
6 *
7 * The driver borrows from f_ecm.c which is:
8 *
9 * Copyright (C) 2003-2005,2008 David Brownell
10 * Copyright (C) 2008 Nokia Corporation
11 *
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
16 */
17
18#include <linux/kernel.h>
19#include <linux/module.h>
20#include <linux/device.h>
21#include <linux/etherdevice.h>
22#include <linux/crc32.h>
23
24#include <linux/usb/cdc.h>
25
26#include "u_ether.h"
27#include "u_ether_configfs.h"
28#include "u_ncm.h"
29
30/*
31 * This function is a "CDC Network Control Model" (CDC NCM) Ethernet link.
32 * NCM is intended to be used with high-speed network attachments.
33 *
34 * Note that NCM requires the use of "alternate settings" for its data
35 * interface. This means that the set_alt() method has real work to do,
36 * and also means that a get_alt() method is required.
37 */
38
39/* to trigger crc/non-crc ndp signature */
40
41#define NCM_NDP_HDR_CRC_MASK 0x01000000
42#define NCM_NDP_HDR_CRC 0x01000000
43#define NCM_NDP_HDR_NOCRC 0x00000000
44
45enum ncm_notify_state {
46 NCM_NOTIFY_NONE, /* don't notify */
47 NCM_NOTIFY_CONNECT, /* issue CONNECT next */
48 NCM_NOTIFY_SPEED, /* issue SPEED_CHANGE next */
49};
50
51struct f_ncm {
52 struct gether port;
53 u8 ctrl_id, data_id;
54
55 char ethaddr[14];
56
57 struct usb_ep *notify;
58 struct usb_request *notify_req;
59 u8 notify_state;
60 bool is_open;
61
62 const struct ndp_parser_opts *parser_opts;
63 bool is_crc;
64 u32 ndp_sign;
65
66 /*
67 * for notification, it is accessed from both
68 * callback and ethernet open/close
69 */
70 spinlock_t lock;
71
72 struct net_device *netdev;
73
74 /* For multi-frame NDP TX */
75 struct sk_buff *skb_tx_data;
76 struct sk_buff *skb_tx_ndp;
77 u16 ndp_dgram_count;
78 bool timer_force_tx;
79 struct tasklet_struct tx_tasklet;
80 struct hrtimer task_timer;
81
82 bool timer_stopping;
83};
84
85static inline struct f_ncm *func_to_ncm(struct usb_function *f)
86{
87 return container_of(f, struct f_ncm, port.func);
88}
89
90/* peak (theoretical) bulk transfer rate in bits-per-second */
91static inline unsigned ncm_bitrate(struct usb_gadget *g)
92{
93 if (gadget_is_dualspeed(g) && g->speed == USB_SPEED_HIGH)
94 return 13 * 512 * 8 * 1000 * 8;
95 else
96 return 19 * 64 * 1 * 1000 * 8;
97}
98
99/*-------------------------------------------------------------------------*/
100
101/*
102 * We cannot group frames so use just the minimal size which ok to put
103 * one max-size ethernet frame.
104 * If the host can group frames, allow it to do that, 16K is selected,
105 * because it's used by default by the current linux host driver
106 */
107#define NTB_DEFAULT_IN_SIZE 16384
108#define NTB_OUT_SIZE 16384
109
110/* Allocation for storing the NDP, 32 should suffice for a
111 * 16k packet. This allows a maximum of 32 * 507 Byte packets to
112 * be transmitted in a single 16kB skb, though when sending full size
113 * packets this limit will be plenty.
114 * Smaller packets are not likely to be trying to maximize the
115 * throughput and will be mstly sending smaller infrequent frames.
116 */
117#define TX_MAX_NUM_DPE 32
118
119/* Delay for the transmit to wait before sending an unfilled NTB frame. */
120#define TX_TIMEOUT_NSECS 300000
121
122#define FORMATS_SUPPORTED (USB_CDC_NCM_NTB16_SUPPORTED | \
123 USB_CDC_NCM_NTB32_SUPPORTED)
124
125static struct usb_cdc_ncm_ntb_parameters ntb_parameters = {
126 .wLength = cpu_to_le16(sizeof(ntb_parameters)),
127 .bmNtbFormatsSupported = cpu_to_le16(FORMATS_SUPPORTED),
128 .dwNtbInMaxSize = cpu_to_le32(NTB_DEFAULT_IN_SIZE),
129 .wNdpInDivisor = cpu_to_le16(4),
130 .wNdpInPayloadRemainder = cpu_to_le16(0),
131 .wNdpInAlignment = cpu_to_le16(4),
132
133 .dwNtbOutMaxSize = cpu_to_le32(NTB_OUT_SIZE),
134 .wNdpOutDivisor = cpu_to_le16(4),
135 .wNdpOutPayloadRemainder = cpu_to_le16(0),
136 .wNdpOutAlignment = cpu_to_le16(4),
137};
138
139/*
140 * Use wMaxPacketSize big enough to fit CDC_NOTIFY_SPEED_CHANGE in one
141 * packet, to simplify cancellation; and a big transfer interval, to
142 * waste less bandwidth.
143 */
144
145#define NCM_STATUS_INTERVAL_MS 32
146#define NCM_STATUS_BYTECOUNT 16 /* 8 byte header + data */
147
148static struct usb_interface_assoc_descriptor ncm_iad_desc = {
149 .bLength = sizeof ncm_iad_desc,
150 .bDescriptorType = USB_DT_INTERFACE_ASSOCIATION,
151
152 /* .bFirstInterface = DYNAMIC, */
153 .bInterfaceCount = 2, /* control + data */
154 .bFunctionClass = USB_CLASS_COMM,
155 .bFunctionSubClass = USB_CDC_SUBCLASS_NCM,
156 .bFunctionProtocol = USB_CDC_PROTO_NONE,
157 /* .iFunction = DYNAMIC */
158};
159
160/* interface descriptor: */
161
162static struct usb_interface_descriptor ncm_control_intf = {
163 .bLength = sizeof ncm_control_intf,
164 .bDescriptorType = USB_DT_INTERFACE,
165
166 /* .bInterfaceNumber = DYNAMIC */
167 .bNumEndpoints = 1,
168 .bInterfaceClass = USB_CLASS_COMM,
169 .bInterfaceSubClass = USB_CDC_SUBCLASS_NCM,
170 .bInterfaceProtocol = USB_CDC_PROTO_NONE,
171 /* .iInterface = DYNAMIC */
172};
173
174static struct usb_cdc_header_desc ncm_header_desc = {
175 .bLength = sizeof ncm_header_desc,
176 .bDescriptorType = USB_DT_CS_INTERFACE,
177 .bDescriptorSubType = USB_CDC_HEADER_TYPE,
178
179 .bcdCDC = cpu_to_le16(0x0110),
180};
181
182static struct usb_cdc_union_desc ncm_union_desc = {
183 .bLength = sizeof(ncm_union_desc),
184 .bDescriptorType = USB_DT_CS_INTERFACE,
185 .bDescriptorSubType = USB_CDC_UNION_TYPE,
186 /* .bMasterInterface0 = DYNAMIC */
187 /* .bSlaveInterface0 = DYNAMIC */
188};
189
190static struct usb_cdc_ether_desc ecm_desc = {
191 .bLength = sizeof ecm_desc,
192 .bDescriptorType = USB_DT_CS_INTERFACE,
193 .bDescriptorSubType = USB_CDC_ETHERNET_TYPE,
194
195 /* this descriptor actually adds value, surprise! */
196 /* .iMACAddress = DYNAMIC */
197 .bmEthernetStatistics = cpu_to_le32(0), /* no statistics */
198 .wMaxSegmentSize = cpu_to_le16(ETH_FRAME_LEN),
199 .wNumberMCFilters = cpu_to_le16(0),
200 .bNumberPowerFilters = 0,
201};
202
203#define NCAPS (USB_CDC_NCM_NCAP_ETH_FILTER | USB_CDC_NCM_NCAP_CRC_MODE)
204
205static struct usb_cdc_ncm_desc ncm_desc = {
206 .bLength = sizeof ncm_desc,
207 .bDescriptorType = USB_DT_CS_INTERFACE,
208 .bDescriptorSubType = USB_CDC_NCM_TYPE,
209
210 .bcdNcmVersion = cpu_to_le16(0x0100),
211 /* can process SetEthernetPacketFilter */
212 .bmNetworkCapabilities = NCAPS,
213};
214
215/* the default data interface has no endpoints ... */
216
217static struct usb_interface_descriptor ncm_data_nop_intf = {
218 .bLength = sizeof ncm_data_nop_intf,
219 .bDescriptorType = USB_DT_INTERFACE,
220
221 .bInterfaceNumber = 1,
222 .bAlternateSetting = 0,
223 .bNumEndpoints = 0,
224 .bInterfaceClass = USB_CLASS_CDC_DATA,
225 .bInterfaceSubClass = 0,
226 .bInterfaceProtocol = USB_CDC_NCM_PROTO_NTB,
227 /* .iInterface = DYNAMIC */
228};
229
230/* ... but the "real" data interface has two bulk endpoints */
231
232static struct usb_interface_descriptor ncm_data_intf = {
233 .bLength = sizeof ncm_data_intf,
234 .bDescriptorType = USB_DT_INTERFACE,
235
236 .bInterfaceNumber = 1,
237 .bAlternateSetting = 1,
238 .bNumEndpoints = 2,
239 .bInterfaceClass = USB_CLASS_CDC_DATA,
240 .bInterfaceSubClass = 0,
241 .bInterfaceProtocol = USB_CDC_NCM_PROTO_NTB,
242 /* .iInterface = DYNAMIC */
243};
244
245/* full speed support: */
246
247static struct usb_endpoint_descriptor fs_ncm_notify_desc = {
248 .bLength = USB_DT_ENDPOINT_SIZE,
249 .bDescriptorType = USB_DT_ENDPOINT,
250
251 .bEndpointAddress = USB_DIR_IN,
252 .bmAttributes = USB_ENDPOINT_XFER_INT,
253 .wMaxPacketSize = cpu_to_le16(NCM_STATUS_BYTECOUNT),
254 .bInterval = NCM_STATUS_INTERVAL_MS,
255};
256
257static struct usb_endpoint_descriptor fs_ncm_in_desc = {
258 .bLength = USB_DT_ENDPOINT_SIZE,
259 .bDescriptorType = USB_DT_ENDPOINT,
260
261 .bEndpointAddress = USB_DIR_IN,
262 .bmAttributes = USB_ENDPOINT_XFER_BULK,
263};
264
265static struct usb_endpoint_descriptor fs_ncm_out_desc = {
266 .bLength = USB_DT_ENDPOINT_SIZE,
267 .bDescriptorType = USB_DT_ENDPOINT,
268
269 .bEndpointAddress = USB_DIR_OUT,
270 .bmAttributes = USB_ENDPOINT_XFER_BULK,
271};
272
273static struct usb_descriptor_header *ncm_fs_function[] = {
274 (struct usb_descriptor_header *) &ncm_iad_desc,
275 /* CDC NCM control descriptors */
276 (struct usb_descriptor_header *) &ncm_control_intf,
277 (struct usb_descriptor_header *) &ncm_header_desc,
278 (struct usb_descriptor_header *) &ncm_union_desc,
279 (struct usb_descriptor_header *) &ecm_desc,
280 (struct usb_descriptor_header *) &ncm_desc,
281 (struct usb_descriptor_header *) &fs_ncm_notify_desc,
282 /* data interface, altsettings 0 and 1 */
283 (struct usb_descriptor_header *) &ncm_data_nop_intf,
284 (struct usb_descriptor_header *) &ncm_data_intf,
285 (struct usb_descriptor_header *) &fs_ncm_in_desc,
286 (struct usb_descriptor_header *) &fs_ncm_out_desc,
287 NULL,
288};
289
290/* high speed support: */
291
292static struct usb_endpoint_descriptor hs_ncm_notify_desc = {
293 .bLength = USB_DT_ENDPOINT_SIZE,
294 .bDescriptorType = USB_DT_ENDPOINT,
295
296 .bEndpointAddress = USB_DIR_IN,
297 .bmAttributes = USB_ENDPOINT_XFER_INT,
298 .wMaxPacketSize = cpu_to_le16(NCM_STATUS_BYTECOUNT),
299 .bInterval = USB_MS_TO_HS_INTERVAL(NCM_STATUS_INTERVAL_MS),
300};
301static struct usb_endpoint_descriptor hs_ncm_in_desc = {
302 .bLength = USB_DT_ENDPOINT_SIZE,
303 .bDescriptorType = USB_DT_ENDPOINT,
304
305 .bEndpointAddress = USB_DIR_IN,
306 .bmAttributes = USB_ENDPOINT_XFER_BULK,
307 .wMaxPacketSize = cpu_to_le16(512),
308};
309
310static struct usb_endpoint_descriptor hs_ncm_out_desc = {
311 .bLength = USB_DT_ENDPOINT_SIZE,
312 .bDescriptorType = USB_DT_ENDPOINT,
313
314 .bEndpointAddress = USB_DIR_OUT,
315 .bmAttributes = USB_ENDPOINT_XFER_BULK,
316 .wMaxPacketSize = cpu_to_le16(512),
317};
318
319static struct usb_descriptor_header *ncm_hs_function[] = {
320 (struct usb_descriptor_header *) &ncm_iad_desc,
321 /* CDC NCM control descriptors */
322 (struct usb_descriptor_header *) &ncm_control_intf,
323 (struct usb_descriptor_header *) &ncm_header_desc,
324 (struct usb_descriptor_header *) &ncm_union_desc,
325 (struct usb_descriptor_header *) &ecm_desc,
326 (struct usb_descriptor_header *) &ncm_desc,
327 (struct usb_descriptor_header *) &hs_ncm_notify_desc,
328 /* data interface, altsettings 0 and 1 */
329 (struct usb_descriptor_header *) &ncm_data_nop_intf,
330 (struct usb_descriptor_header *) &ncm_data_intf,
331 (struct usb_descriptor_header *) &hs_ncm_in_desc,
332 (struct usb_descriptor_header *) &hs_ncm_out_desc,
333 NULL,
334};
335
336/* string descriptors: */
337
338#define STRING_CTRL_IDX 0
339#define STRING_MAC_IDX 1
340#define STRING_DATA_IDX 2
341#define STRING_IAD_IDX 3
342
343static struct usb_string ncm_string_defs[] = {
344 [STRING_CTRL_IDX].s = "CDC Network Control Model (NCM)",
345 [STRING_MAC_IDX].s = "",
346 [STRING_DATA_IDX].s = "CDC Network Data",
347 [STRING_IAD_IDX].s = "CDC NCM",
348 { } /* end of list */
349};
350
351static struct usb_gadget_strings ncm_string_table = {
352 .language = 0x0409, /* en-us */
353 .strings = ncm_string_defs,
354};
355
356static struct usb_gadget_strings *ncm_strings[] = {
357 &ncm_string_table,
358 NULL,
359};
360
361/*
362 * Here are options for NCM Datagram Pointer table (NDP) parser.
363 * There are 2 different formats: NDP16 and NDP32 in the spec (ch. 3),
364 * in NDP16 offsets and sizes fields are 1 16bit word wide,
365 * in NDP32 -- 2 16bit words wide. Also signatures are different.
366 * To make the parser code the same, put the differences in the structure,
367 * and switch pointers to the structures when the format is changed.
368 */
369
370struct ndp_parser_opts {
371 u32 nth_sign;
372 u32 ndp_sign;
373 unsigned nth_size;
374 unsigned ndp_size;
375 unsigned dpe_size;
376 unsigned ndplen_align;
377 /* sizes in u16 units */
378 unsigned dgram_item_len; /* index or length */
379 unsigned block_length;
380 unsigned ndp_index;
381 unsigned reserved1;
382 unsigned reserved2;
383 unsigned next_ndp_index;
384};
385
386#define INIT_NDP16_OPTS { \
387 .nth_sign = USB_CDC_NCM_NTH16_SIGN, \
388 .ndp_sign = USB_CDC_NCM_NDP16_NOCRC_SIGN, \
389 .nth_size = sizeof(struct usb_cdc_ncm_nth16), \
390 .ndp_size = sizeof(struct usb_cdc_ncm_ndp16), \
391 .dpe_size = sizeof(struct usb_cdc_ncm_dpe16), \
392 .ndplen_align = 4, \
393 .dgram_item_len = 1, \
394 .block_length = 1, \
395 .ndp_index = 1, \
396 .reserved1 = 0, \
397 .reserved2 = 0, \
398 .next_ndp_index = 1, \
399 }
400
401
402#define INIT_NDP32_OPTS { \
403 .nth_sign = USB_CDC_NCM_NTH32_SIGN, \
404 .ndp_sign = USB_CDC_NCM_NDP32_NOCRC_SIGN, \
405 .nth_size = sizeof(struct usb_cdc_ncm_nth32), \
406 .ndp_size = sizeof(struct usb_cdc_ncm_ndp32), \
407 .dpe_size = sizeof(struct usb_cdc_ncm_dpe32), \
408 .ndplen_align = 8, \
409 .dgram_item_len = 2, \
410 .block_length = 2, \
411 .ndp_index = 2, \
412 .reserved1 = 1, \
413 .reserved2 = 2, \
414 .next_ndp_index = 2, \
415 }
416
417static const struct ndp_parser_opts ndp16_opts = INIT_NDP16_OPTS;
418static const struct ndp_parser_opts ndp32_opts = INIT_NDP32_OPTS;
419
420static inline void put_ncm(__le16 **p, unsigned size, unsigned val)
421{
422 switch (size) {
423 case 1:
424 put_unaligned_le16((u16)val, *p);
425 break;
426 case 2:
427 put_unaligned_le32((u32)val, *p);
428
429 break;
430 default:
431 BUG();
432 }
433
434 *p += size;
435}
436
437static inline unsigned get_ncm(__le16 **p, unsigned size)
438{
439 unsigned tmp;
440
441 switch (size) {
442 case 1:
443 tmp = get_unaligned_le16(*p);
444 break;
445 case 2:
446 tmp = get_unaligned_le32(*p);
447 break;
448 default:
449 BUG();
450 }
451
452 *p += size;
453 return tmp;
454}
455
456/*-------------------------------------------------------------------------*/
457
458static inline void ncm_reset_values(struct f_ncm *ncm)
459{
460 ncm->parser_opts = &ndp16_opts;
461 ncm->is_crc = false;
462 ncm->port.cdc_filter = DEFAULT_FILTER;
463
464 /* doesn't make sense for ncm, fixed size used */
465 ncm->port.header_len = 0;
466
467 ncm->port.fixed_out_len = le32_to_cpu(ntb_parameters.dwNtbOutMaxSize);
468 ncm->port.fixed_in_len = NTB_DEFAULT_IN_SIZE;
469}
470
471/*
472 * Context: ncm->lock held
473 */
474static void ncm_do_notify(struct f_ncm *ncm)
475{
476 struct usb_request *req = ncm->notify_req;
477 struct usb_cdc_notification *event;
478 struct usb_composite_dev *cdev = ncm->port.func.config->cdev;
479 __le32 *data;
480 int status;
481
482 /* notification already in flight? */
483 if (!req)
484 return;
485
486 event = req->buf;
487 switch (ncm->notify_state) {
488 case NCM_NOTIFY_NONE:
489 return;
490
491 case NCM_NOTIFY_CONNECT:
492 event->bNotificationType = USB_CDC_NOTIFY_NETWORK_CONNECTION;
493 if (ncm->is_open)
494 event->wValue = cpu_to_le16(1);
495 else
496 event->wValue = cpu_to_le16(0);
497 event->wLength = 0;
498 req->length = sizeof *event;
499
500 DBG(cdev, "notify connect %s\n",
501 ncm->is_open ? "true" : "false");
502 ncm->notify_state = NCM_NOTIFY_NONE;
503 break;
504
505 case NCM_NOTIFY_SPEED:
506 event->bNotificationType = USB_CDC_NOTIFY_SPEED_CHANGE;
507 event->wValue = cpu_to_le16(0);
508 event->wLength = cpu_to_le16(8);
509 req->length = NCM_STATUS_BYTECOUNT;
510
511 /* SPEED_CHANGE data is up/down speeds in bits/sec */
512 data = req->buf + sizeof *event;
513 data[0] = cpu_to_le32(ncm_bitrate(cdev->gadget));
514 data[1] = data[0];
515
516 DBG(cdev, "notify speed %d\n", ncm_bitrate(cdev->gadget));
517 ncm->notify_state = NCM_NOTIFY_CONNECT;
518 break;
519 }
520 event->bmRequestType = 0xA1;
521 event->wIndex = cpu_to_le16(ncm->ctrl_id);
522
523 ncm->notify_req = NULL;
524 /*
525 * In double buffering if there is a space in FIFO,
526 * completion callback can be called right after the call,
527 * so unlocking
528 */
529 spin_unlock(&ncm->lock);
530 status = usb_ep_queue(ncm->notify, req, GFP_ATOMIC);
531 spin_lock(&ncm->lock);
532 if (status < 0) {
533 ncm->notify_req = req;
534 DBG(cdev, "notify --> %d\n", status);
535 }
536}
537
538/*
539 * Context: ncm->lock held
540 */
541static void ncm_notify(struct f_ncm *ncm)
542{
543 /*
544 * NOTE on most versions of Linux, host side cdc-ethernet
545 * won't listen for notifications until its netdevice opens.
546 * The first notification then sits in the FIFO for a long
547 * time, and the second one is queued.
548 *
549 * If ncm_notify() is called before the second (CONNECT)
550 * notification is sent, then it will reset to send the SPEED
551 * notificaion again (and again, and again), but it's not a problem
552 */
553 ncm->notify_state = NCM_NOTIFY_SPEED;
554 ncm_do_notify(ncm);
555}
556
557static void ncm_notify_complete(struct usb_ep *ep, struct usb_request *req)
558{
559 struct f_ncm *ncm = req->context;
560 struct usb_composite_dev *cdev = ncm->port.func.config->cdev;
561 struct usb_cdc_notification *event = req->buf;
562
563 spin_lock(&ncm->lock);
564 switch (req->status) {
565 case 0:
566 VDBG(cdev, "Notification %02x sent\n",
567 event->bNotificationType);
568 break;
569 case -ECONNRESET:
570 case -ESHUTDOWN:
571 ncm->notify_state = NCM_NOTIFY_NONE;
572 break;
573 default:
574 DBG(cdev, "event %02x --> %d\n",
575 event->bNotificationType, req->status);
576 break;
577 }
578 ncm->notify_req = req;
579 ncm_do_notify(ncm);
580 spin_unlock(&ncm->lock);
581}
582
583static void ncm_ep0out_complete(struct usb_ep *ep, struct usb_request *req)
584{
585 /* now for SET_NTB_INPUT_SIZE only */
586 unsigned in_size;
587 struct usb_function *f = req->context;
588 struct f_ncm *ncm = func_to_ncm(f);
589 struct usb_composite_dev *cdev = ep->driver_data;
590
591 req->context = NULL;
592 if (req->status || req->actual != req->length) {
593 DBG(cdev, "Bad control-OUT transfer\n");
594 goto invalid;
595 }
596
597 in_size = get_unaligned_le32(req->buf);
598 if (in_size < USB_CDC_NCM_NTB_MIN_IN_SIZE ||
599 in_size > le32_to_cpu(ntb_parameters.dwNtbInMaxSize)) {
600 DBG(cdev, "Got wrong INPUT SIZE (%d) from host\n", in_size);
601 goto invalid;
602 }
603
604 ncm->port.fixed_in_len = in_size;
605 VDBG(cdev, "Set NTB INPUT SIZE %d\n", in_size);
606 return;
607
608invalid:
609 usb_ep_set_halt(ep);
610 return;
611}
612
613static int ncm_setup(struct usb_function *f, const struct usb_ctrlrequest *ctrl)
614{
615 struct f_ncm *ncm = func_to_ncm(f);
616 struct usb_composite_dev *cdev = f->config->cdev;
617 struct usb_request *req = cdev->req;
618 int value = -EOPNOTSUPP;
619 u16 w_index = le16_to_cpu(ctrl->wIndex);
620 u16 w_value = le16_to_cpu(ctrl->wValue);
621 u16 w_length = le16_to_cpu(ctrl->wLength);
622
623 /*
624 * composite driver infrastructure handles everything except
625 * CDC class messages; interface activation uses set_alt().
626 */
627 switch ((ctrl->bRequestType << 8) | ctrl->bRequest) {
628 case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
629 | USB_CDC_SET_ETHERNET_PACKET_FILTER:
630 /*
631 * see 6.2.30: no data, wIndex = interface,
632 * wValue = packet filter bitmap
633 */
634 if (w_length != 0 || w_index != ncm->ctrl_id)
635 goto invalid;
636 DBG(cdev, "packet filter %02x\n", w_value);
637 /*
638 * REVISIT locking of cdc_filter. This assumes the UDC
639 * driver won't have a concurrent packet TX irq running on
640 * another CPU; or that if it does, this write is atomic...
641 */
642 ncm->port.cdc_filter = w_value;
643 value = 0;
644 break;
645 /*
646 * and optionally:
647 * case USB_CDC_SEND_ENCAPSULATED_COMMAND:
648 * case USB_CDC_GET_ENCAPSULATED_RESPONSE:
649 * case USB_CDC_SET_ETHERNET_MULTICAST_FILTERS:
650 * case USB_CDC_SET_ETHERNET_PM_PATTERN_FILTER:
651 * case USB_CDC_GET_ETHERNET_PM_PATTERN_FILTER:
652 * case USB_CDC_GET_ETHERNET_STATISTIC:
653 */
654
655 case ((USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
656 | USB_CDC_GET_NTB_PARAMETERS:
657
658 if (w_length == 0 || w_value != 0 || w_index != ncm->ctrl_id)
659 goto invalid;
660 value = w_length > sizeof ntb_parameters ?
661 sizeof ntb_parameters : w_length;
662 memcpy(req->buf, &ntb_parameters, value);
663 VDBG(cdev, "Host asked NTB parameters\n");
664 break;
665
666 case ((USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
667 | USB_CDC_GET_NTB_INPUT_SIZE:
668
669 if (w_length < 4 || w_value != 0 || w_index != ncm->ctrl_id)
670 goto invalid;
671 put_unaligned_le32(ncm->port.fixed_in_len, req->buf);
672 value = 4;
673 VDBG(cdev, "Host asked INPUT SIZE, sending %d\n",
674 ncm->port.fixed_in_len);
675 break;
676
677 case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
678 | USB_CDC_SET_NTB_INPUT_SIZE:
679 {
680 if (w_length != 4 || w_value != 0 || w_index != ncm->ctrl_id)
681 goto invalid;
682 req->complete = ncm_ep0out_complete;
683 req->length = w_length;
684 req->context = f;
685
686 value = req->length;
687 break;
688 }
689
690 case ((USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
691 | USB_CDC_GET_NTB_FORMAT:
692 {
693 uint16_t format;
694
695 if (w_length < 2 || w_value != 0 || w_index != ncm->ctrl_id)
696 goto invalid;
697 format = (ncm->parser_opts == &ndp16_opts) ? 0x0000 : 0x0001;
698 put_unaligned_le16(format, req->buf);
699 value = 2;
700 VDBG(cdev, "Host asked NTB FORMAT, sending %d\n", format);
701 break;
702 }
703
704 case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
705 | USB_CDC_SET_NTB_FORMAT:
706 {
707 if (w_length != 0 || w_index != ncm->ctrl_id)
708 goto invalid;
709 switch (w_value) {
710 case 0x0000:
711 ncm->parser_opts = &ndp16_opts;
712 DBG(cdev, "NCM16 selected\n");
713 break;
714 case 0x0001:
715 ncm->parser_opts = &ndp32_opts;
716 DBG(cdev, "NCM32 selected\n");
717 break;
718 default:
719 goto invalid;
720 }
721 value = 0;
722 break;
723 }
724 case ((USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
725 | USB_CDC_GET_CRC_MODE:
726 {
727 uint16_t is_crc;
728
729 if (w_length < 2 || w_value != 0 || w_index != ncm->ctrl_id)
730 goto invalid;
731 is_crc = ncm->is_crc ? 0x0001 : 0x0000;
732 put_unaligned_le16(is_crc, req->buf);
733 value = 2;
734 VDBG(cdev, "Host asked CRC MODE, sending %d\n", is_crc);
735 break;
736 }
737
738 case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
739 | USB_CDC_SET_CRC_MODE:
740 {
741 int ndp_hdr_crc = 0;
742
743 if (w_length != 0 || w_index != ncm->ctrl_id)
744 goto invalid;
745 switch (w_value) {
746 case 0x0000:
747 ncm->is_crc = false;
748 ndp_hdr_crc = NCM_NDP_HDR_NOCRC;
749 DBG(cdev, "non-CRC mode selected\n");
750 break;
751 case 0x0001:
752 ncm->is_crc = true;
753 ndp_hdr_crc = NCM_NDP_HDR_CRC;
754 DBG(cdev, "CRC mode selected\n");
755 break;
756 default:
757 goto invalid;
758 }
759 ncm->ndp_sign = ncm->parser_opts->ndp_sign | ndp_hdr_crc;
760 value = 0;
761 break;
762 }
763
764 /* and disabled in ncm descriptor: */
765 /* case USB_CDC_GET_NET_ADDRESS: */
766 /* case USB_CDC_SET_NET_ADDRESS: */
767 /* case USB_CDC_GET_MAX_DATAGRAM_SIZE: */
768 /* case USB_CDC_SET_MAX_DATAGRAM_SIZE: */
769
770 default:
771invalid:
772 DBG(cdev, "invalid control req%02x.%02x v%04x i%04x l%d\n",
773 ctrl->bRequestType, ctrl->bRequest,
774 w_value, w_index, w_length);
775 }
776
777 /* respond with data transfer or status phase? */
778 if (value >= 0) {
779 DBG(cdev, "ncm req%02x.%02x v%04x i%04x l%d\n",
780 ctrl->bRequestType, ctrl->bRequest,
781 w_value, w_index, w_length);
782 req->zero = 0;
783 req->length = value;
784 value = usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC);
785 if (value < 0)
786 ERROR(cdev, "ncm req %02x.%02x response err %d\n",
787 ctrl->bRequestType, ctrl->bRequest,
788 value);
789 }
790
791 /* device either stalls (value < 0) or reports success */
792 return value;
793}
794
795
796static int ncm_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
797{
798 struct f_ncm *ncm = func_to_ncm(f);
799 struct usb_composite_dev *cdev = f->config->cdev;
800
801 /* Control interface has only altsetting 0 */
802 if (intf == ncm->ctrl_id) {
803 if (alt != 0)
804 goto fail;
805
806 if (ncm->notify->driver_data) {
807 DBG(cdev, "reset ncm control %d\n", intf);
808 usb_ep_disable(ncm->notify);
809 }
810
811 if (!(ncm->notify->desc)) {
812 DBG(cdev, "init ncm ctrl %d\n", intf);
813 if (config_ep_by_speed(cdev->gadget, f, ncm->notify))
814 goto fail;
815 }
816 usb_ep_enable(ncm->notify);
817 ncm->notify->driver_data = ncm;
818
819 /* Data interface has two altsettings, 0 and 1 */
820 } else if (intf == ncm->data_id) {
821 if (alt > 1)
822 goto fail;
823
824 if (ncm->port.in_ep->driver_data) {
825 DBG(cdev, "reset ncm\n");
826 ncm->timer_stopping = true;
827 ncm->netdev = NULL;
828 gether_disconnect(&ncm->port);
829 ncm_reset_values(ncm);
830 }
831
832 /*
833 * CDC Network only sends data in non-default altsettings.
834 * Changing altsettings resets filters, statistics, etc.
835 */
836 if (alt == 1) {
837 struct net_device *net;
838
839 if (!ncm->port.in_ep->desc ||
840 !ncm->port.out_ep->desc) {
841 DBG(cdev, "init ncm\n");
842 if (config_ep_by_speed(cdev->gadget, f,
843 ncm->port.in_ep) ||
844 config_ep_by_speed(cdev->gadget, f,
845 ncm->port.out_ep)) {
846 ncm->port.in_ep->desc = NULL;
847 ncm->port.out_ep->desc = NULL;
848 goto fail;
849 }
850 }
851
852 /* TODO */
853 /* Enable zlps by default for NCM conformance;
854 * override for musb_hdrc (avoids txdma ovhead)
855 */
856 ncm->port.is_zlp_ok = !(
857 gadget_is_musbhdrc(cdev->gadget)
858 );
859 ncm->port.cdc_filter = DEFAULT_FILTER;
860 DBG(cdev, "activate ncm\n");
861 net = gether_connect(&ncm->port);
862 if (IS_ERR(net))
863 return PTR_ERR(net);
864 ncm->netdev = net;
865 ncm->timer_stopping = false;
866 }
867
868 spin_lock(&ncm->lock);
869 ncm_notify(ncm);
870 spin_unlock(&ncm->lock);
871 } else
872 goto fail;
873
874 return 0;
875fail:
876 return -EINVAL;
877}
878
879/*
880 * Because the data interface supports multiple altsettings,
881 * this NCM function *MUST* implement a get_alt() method.
882 */
883static int ncm_get_alt(struct usb_function *f, unsigned intf)
884{
885 struct f_ncm *ncm = func_to_ncm(f);
886
887 if (intf == ncm->ctrl_id)
888 return 0;
889 return ncm->port.in_ep->driver_data ? 1 : 0;
890}
891
892static struct sk_buff *package_for_tx(struct f_ncm *ncm)
893{
894 __le16 *ntb_iter;
895 struct sk_buff *skb2 = NULL;
896 unsigned ndp_pad;
897 unsigned ndp_index;
898 unsigned new_len;
899
900 const struct ndp_parser_opts *opts = ncm->parser_opts;
901 const int ndp_align = le16_to_cpu(ntb_parameters.wNdpInAlignment);
902 const int dgram_idx_len = 2 * 2 * opts->dgram_item_len;
903
904 /* Stop the timer */
905 hrtimer_try_to_cancel(&ncm->task_timer);
906
907 ndp_pad = ALIGN(ncm->skb_tx_data->len, ndp_align) -
908 ncm->skb_tx_data->len;
909 ndp_index = ncm->skb_tx_data->len + ndp_pad;
910 new_len = ndp_index + dgram_idx_len + ncm->skb_tx_ndp->len;
911
912 /* Set the final BlockLength and wNdpIndex */
913 ntb_iter = (void *) ncm->skb_tx_data->data;
914 /* Increment pointer to BlockLength */
915 ntb_iter += 2 + 1 + 1;
916 put_ncm(&ntb_iter, opts->block_length, new_len);
917 put_ncm(&ntb_iter, opts->ndp_index, ndp_index);
918
919 /* Set the final NDP wLength */
920 new_len = opts->ndp_size +
921 (ncm->ndp_dgram_count * dgram_idx_len);
922 ncm->ndp_dgram_count = 0;
923 /* Increment from start to wLength */
924 ntb_iter = (void *) ncm->skb_tx_ndp->data;
925 ntb_iter += 2;
926 put_unaligned_le16(new_len, ntb_iter);
927
928 /* Merge the skbs */
929 swap(skb2, ncm->skb_tx_data);
930 if (ncm->skb_tx_data) {
931 dev_kfree_skb_any(ncm->skb_tx_data);
932 ncm->skb_tx_data = NULL;
933 }
934
935 /* Insert NDP alignment. */
936 ntb_iter = (void *) skb_put(skb2, ndp_pad);
937 memset(ntb_iter, 0, ndp_pad);
938
939 /* Copy NTB across. */
940 ntb_iter = (void *) skb_put(skb2, ncm->skb_tx_ndp->len);
941 memcpy(ntb_iter, ncm->skb_tx_ndp->data, ncm->skb_tx_ndp->len);
942 dev_kfree_skb_any(ncm->skb_tx_ndp);
943 ncm->skb_tx_ndp = NULL;
944
945 /* Insert zero'd datagram. */
946 ntb_iter = (void *) skb_put(skb2, dgram_idx_len);
947 memset(ntb_iter, 0, dgram_idx_len);
948
949 return skb2;
950}
951
952static struct sk_buff *ncm_wrap_ntb(struct gether *port,
953 struct sk_buff *skb)
954{
955 struct f_ncm *ncm = func_to_ncm(&port->func);
956 struct sk_buff *skb2 = NULL;
957 int ncb_len = 0;
958 __le16 *ntb_data;
959 __le16 *ntb_ndp;
960 int dgram_pad;
961
962 unsigned max_size = ncm->port.fixed_in_len;
963 const struct ndp_parser_opts *opts = ncm->parser_opts;
964 const int ndp_align = le16_to_cpu(ntb_parameters.wNdpInAlignment);
965 const int div = le16_to_cpu(ntb_parameters.wNdpInDivisor);
966 const int rem = le16_to_cpu(ntb_parameters.wNdpInPayloadRemainder);
967 const int dgram_idx_len = 2 * 2 * opts->dgram_item_len;
968
969 if (!skb && !ncm->skb_tx_data)
970 return NULL;
971
972 if (skb) {
973 /* Add the CRC if required up front */
974 if (ncm->is_crc) {
975 uint32_t crc;
976 __le16 *crc_pos;
977
978 crc = ~crc32_le(~0,
979 skb->data,
980 skb->len);
981 crc_pos = (void *) skb_put(skb, sizeof(uint32_t));
982 put_unaligned_le32(crc, crc_pos);
983 }
984
985 /* If the new skb is too big for the current NCM NTB then
986 * set the current stored skb to be sent now and clear it
987 * ready for new data.
988 * NOTE: Assume maximum align for speed of calculation.
989 */
990 if (ncm->skb_tx_data
991 && (ncm->ndp_dgram_count >= TX_MAX_NUM_DPE
992 || (ncm->skb_tx_data->len +
993 div + rem + skb->len +
994 ncm->skb_tx_ndp->len + ndp_align + (2 * dgram_idx_len))
995 > max_size)) {
996 skb2 = package_for_tx(ncm);
997 if (!skb2)
998 goto err;
999 }
1000
1001 if (!ncm->skb_tx_data) {
1002 ncb_len = opts->nth_size;
1003 dgram_pad = ALIGN(ncb_len, div) + rem - ncb_len;
1004 ncb_len += dgram_pad;
1005
1006 /* Create a new skb for the NTH and datagrams. */
1007 ncm->skb_tx_data = alloc_skb(max_size, GFP_ATOMIC);
1008 if (!ncm->skb_tx_data)
1009 goto err;
1010
1011 ntb_data = (void *) skb_put(ncm->skb_tx_data, ncb_len);
1012 memset(ntb_data, 0, ncb_len);
1013 /* dwSignature */
1014 put_unaligned_le32(opts->nth_sign, ntb_data);
1015 ntb_data += 2;
1016 /* wHeaderLength */
1017 put_unaligned_le16(opts->nth_size, ntb_data++);
1018
1019 /* Allocate an skb for storing the NDP,
1020 * TX_MAX_NUM_DPE should easily suffice for a
1021 * 16k packet.
1022 */
1023 ncm->skb_tx_ndp = alloc_skb((int)(opts->ndp_size
1024 + opts->dpe_size
1025 * TX_MAX_NUM_DPE),
1026 GFP_ATOMIC);
1027 if (!ncm->skb_tx_ndp)
1028 goto err;
1029 ntb_ndp = (void *) skb_put(ncm->skb_tx_ndp,
1030 opts->ndp_size);
1031 memset(ntb_ndp, 0, ncb_len);
1032 /* dwSignature */
1033 put_unaligned_le32(ncm->ndp_sign, ntb_ndp);
1034 ntb_ndp += 2;
1035
1036 /* There is always a zeroed entry */
1037 ncm->ndp_dgram_count = 1;
1038
1039 /* Note: we skip opts->next_ndp_index */
1040 }
1041
1042 /* Delay the timer. */
1043 hrtimer_start(&ncm->task_timer,
1044 ktime_set(0, TX_TIMEOUT_NSECS),
1045 HRTIMER_MODE_REL);
1046
1047 /* Add the datagram position entries */
1048 ntb_ndp = (void *) skb_put(ncm->skb_tx_ndp, dgram_idx_len);
1049 memset(ntb_ndp, 0, dgram_idx_len);
1050
1051 ncb_len = ncm->skb_tx_data->len;
1052 dgram_pad = ALIGN(ncb_len, div) + rem - ncb_len;
1053 ncb_len += dgram_pad;
1054
1055 /* (d)wDatagramIndex */
1056 put_ncm(&ntb_ndp, opts->dgram_item_len, ncb_len);
1057 /* (d)wDatagramLength */
1058 put_ncm(&ntb_ndp, opts->dgram_item_len, skb->len);
1059 ncm->ndp_dgram_count++;
1060
1061 /* Add the new data to the skb */
1062 ntb_data = (void *) skb_put(ncm->skb_tx_data, dgram_pad);
1063 memset(ntb_data, 0, dgram_pad);
1064 ntb_data = (void *) skb_put(ncm->skb_tx_data, skb->len);
1065 memcpy(ntb_data, skb->data, skb->len);
1066 dev_kfree_skb_any(skb);
1067 skb = NULL;
1068
1069 } else if (ncm->skb_tx_data && ncm->timer_force_tx) {
1070 /* If the tx was requested because of a timeout then send */
1071 skb2 = package_for_tx(ncm);
1072 if (!skb2)
1073 goto err;
1074 }
1075
1076 return skb2;
1077
1078err:
1079 ncm->netdev->stats.tx_dropped++;
1080
1081 if (skb)
1082 dev_kfree_skb_any(skb);
1083 if (ncm->skb_tx_data)
1084 dev_kfree_skb_any(ncm->skb_tx_data);
1085 if (ncm->skb_tx_ndp)
1086 dev_kfree_skb_any(ncm->skb_tx_ndp);
1087
1088 return NULL;
1089}
1090
1091/*
1092 * This transmits the NTB if there are frames waiting.
1093 */
1094static void ncm_tx_tasklet(unsigned long data)
1095{
1096 struct f_ncm *ncm = (void *)data;
1097
1098 if (ncm->timer_stopping)
1099 return;
1100
1101 /* Only send if data is available. */
1102 if (ncm->skb_tx_data) {
1103 ncm->timer_force_tx = true;
1104 ncm->netdev->netdev_ops->ndo_start_xmit(NULL, ncm->netdev);
1105 ncm->timer_force_tx = false;
1106 }
1107}
1108
1109/*
1110 * The transmit should only be run if no skb data has been sent
1111 * for a certain duration.
1112 */
1113static enum hrtimer_restart ncm_tx_timeout(struct hrtimer *data)
1114{
1115 struct f_ncm *ncm = container_of(data, struct f_ncm, task_timer);
1116 tasklet_schedule(&ncm->tx_tasklet);
1117 return HRTIMER_NORESTART;
1118}
1119
1120static int ncm_unwrap_ntb(struct gether *port,
1121 struct sk_buff *skb,
1122 struct sk_buff_head *list)
1123{
1124 struct f_ncm *ncm = func_to_ncm(&port->func);
1125 __le16 *tmp = (void *) skb->data;
1126 unsigned index, index2;
1127 int ndp_index;
1128 unsigned dg_len, dg_len2;
1129 unsigned ndp_len;
1130 struct sk_buff *skb2;
1131 int ret = -EINVAL;
1132 unsigned max_size = le32_to_cpu(ntb_parameters.dwNtbOutMaxSize);
1133 const struct ndp_parser_opts *opts = ncm->parser_opts;
1134 unsigned crc_len = ncm->is_crc ? sizeof(uint32_t) : 0;
1135 int dgram_counter;
1136
1137 /* dwSignature */
1138 if (get_unaligned_le32(tmp) != opts->nth_sign) {
1139 INFO(port->func.config->cdev, "Wrong NTH SIGN, skblen %d\n",
1140 skb->len);
1141 print_hex_dump(KERN_INFO, "HEAD:", DUMP_PREFIX_ADDRESS, 32, 1,
1142 skb->data, 32, false);
1143
1144 goto err;
1145 }
1146 tmp += 2;
1147 /* wHeaderLength */
1148 if (get_unaligned_le16(tmp++) != opts->nth_size) {
1149 INFO(port->func.config->cdev, "Wrong NTB headersize\n");
1150 goto err;
1151 }
1152 tmp++; /* skip wSequence */
1153
1154 /* (d)wBlockLength */
1155 if (get_ncm(&tmp, opts->block_length) > max_size) {
1156 INFO(port->func.config->cdev, "OUT size exceeded\n");
1157 goto err;
1158 }
1159
1160 ndp_index = get_ncm(&tmp, opts->ndp_index);
1161
1162 /* Run through all the NDP's in the NTB */
1163 do {
1164 /* NCM 3.2 */
1165 if (((ndp_index % 4) != 0) &&
1166 (ndp_index < opts->nth_size)) {
1167 INFO(port->func.config->cdev, "Bad index: %#X\n",
1168 ndp_index);
1169 goto err;
1170 }
1171
1172 /* walk through NDP */
1173 tmp = (void *)(skb->data + ndp_index);
1174 if (get_unaligned_le32(tmp) != ncm->ndp_sign) {
1175 INFO(port->func.config->cdev, "Wrong NDP SIGN\n");
1176 goto err;
1177 }
1178 tmp += 2;
1179
1180 ndp_len = get_unaligned_le16(tmp++);
1181 /*
1182 * NCM 3.3.1
1183 * entry is 2 items
1184 * item size is 16/32 bits, opts->dgram_item_len * 2 bytes
1185 * minimal: struct usb_cdc_ncm_ndpX + normal entry + zero entry
1186 * Each entry is a dgram index and a dgram length.
1187 */
1188 if ((ndp_len < opts->ndp_size
1189 + 2 * 2 * (opts->dgram_item_len * 2))
1190 || (ndp_len % opts->ndplen_align != 0)) {
1191 INFO(port->func.config->cdev, "Bad NDP length: %#X\n",
1192 ndp_len);
1193 goto err;
1194 }
1195 tmp += opts->reserved1;
1196 /* Check for another NDP (d)wNextNdpIndex */
1197 ndp_index = get_ncm(&tmp, opts->next_ndp_index);
1198 tmp += opts->reserved2;
1199
1200 ndp_len -= opts->ndp_size;
1201 index2 = get_ncm(&tmp, opts->dgram_item_len);
1202 dg_len2 = get_ncm(&tmp, opts->dgram_item_len);
1203 dgram_counter = 0;
1204
1205 do {
1206 index = index2;
1207 dg_len = dg_len2;
1208 if (dg_len < 14 + crc_len) { /* ethernet hdr + crc */
1209 INFO(port->func.config->cdev,
1210 "Bad dgram length: %#X\n", dg_len);
1211 goto err;
1212 }
1213 if (ncm->is_crc) {
1214 uint32_t crc, crc2;
1215
1216 crc = get_unaligned_le32(skb->data +
1217 index + dg_len -
1218 crc_len);
1219 crc2 = ~crc32_le(~0,
1220 skb->data + index,
1221 dg_len - crc_len);
1222 if (crc != crc2) {
1223 INFO(port->func.config->cdev,
1224 "Bad CRC\n");
1225 goto err;
1226 }
1227 }
1228
1229 index2 = get_ncm(&tmp, opts->dgram_item_len);
1230 dg_len2 = get_ncm(&tmp, opts->dgram_item_len);
1231
1232 /*
1233 * Copy the data into a new skb.
1234 * This ensures the truesize is correct
1235 */
1236 skb2 = netdev_alloc_skb_ip_align(ncm->netdev,
1237 dg_len - crc_len);
1238 if (skb2 == NULL)
1239 goto err;
1240 memcpy(skb_put(skb2, dg_len - crc_len),
1241 skb->data + index, dg_len - crc_len);
1242
1243 skb_queue_tail(list, skb2);
1244
1245 ndp_len -= 2 * (opts->dgram_item_len * 2);
1246
1247 dgram_counter++;
1248
1249 if (index2 == 0 || dg_len2 == 0)
1250 break;
1251 } while (ndp_len > 2 * (opts->dgram_item_len * 2));
1252 } while (ndp_index);
1253
1254 dev_kfree_skb_any(skb);
1255
1256 VDBG(port->func.config->cdev,
1257 "Parsed NTB with %d frames\n", dgram_counter);
1258 return 0;
1259err:
1260 skb_queue_purge(list);
1261 dev_kfree_skb_any(skb);
1262 return ret;
1263}
1264
1265static void ncm_disable(struct usb_function *f)
1266{
1267 struct f_ncm *ncm = func_to_ncm(f);
1268 struct usb_composite_dev *cdev = f->config->cdev;
1269
1270 DBG(cdev, "ncm deactivated\n");
1271
1272 if (ncm->port.in_ep->driver_data) {
1273 ncm->timer_stopping = true;
1274 ncm->netdev = NULL;
1275 gether_disconnect(&ncm->port);
1276 }
1277
1278 if (ncm->notify->driver_data) {
1279 usb_ep_disable(ncm->notify);
1280 ncm->notify->driver_data = NULL;
1281 ncm->notify->desc = NULL;
1282 }
1283}
1284
1285/*-------------------------------------------------------------------------*/
1286
1287/*
1288 * Callbacks let us notify the host about connect/disconnect when the
1289 * net device is opened or closed.
1290 *
1291 * For testing, note that link states on this side include both opened
1292 * and closed variants of:
1293 *
1294 * - disconnected/unconfigured
1295 * - configured but inactive (data alt 0)
1296 * - configured and active (data alt 1)
1297 *
1298 * Each needs to be tested with unplug, rmmod, SET_CONFIGURATION, and
1299 * SET_INTERFACE (altsetting). Remember also that "configured" doesn't
1300 * imply the host is actually polling the notification endpoint, and
1301 * likewise that "active" doesn't imply it's actually using the data
1302 * endpoints for traffic.
1303 */
1304
1305static void ncm_open(struct gether *geth)
1306{
1307 struct f_ncm *ncm = func_to_ncm(&geth->func);
1308
1309 DBG(ncm->port.func.config->cdev, "%s\n", __func__);
1310
1311 spin_lock(&ncm->lock);
1312 ncm->is_open = true;
1313 ncm_notify(ncm);
1314 spin_unlock(&ncm->lock);
1315}
1316
1317static void ncm_close(struct gether *geth)
1318{
1319 struct f_ncm *ncm = func_to_ncm(&geth->func);
1320
1321 DBG(ncm->port.func.config->cdev, "%s\n", __func__);
1322
1323 spin_lock(&ncm->lock);
1324 ncm->is_open = false;
1325 ncm_notify(ncm);
1326 spin_unlock(&ncm->lock);
1327}
1328
1329/*-------------------------------------------------------------------------*/
1330
1331/* ethernet function driver setup/binding */
1332
1333static int ncm_bind(struct usb_configuration *c, struct usb_function *f)
1334{
1335 struct usb_composite_dev *cdev = c->cdev;
1336 struct f_ncm *ncm = func_to_ncm(f);
1337 struct usb_string *us;
1338 int status;
1339 struct usb_ep *ep;
1340 struct f_ncm_opts *ncm_opts;
1341
1342 if (!can_support_ecm(cdev->gadget))
1343 return -EINVAL;
1344
1345 ncm_opts = container_of(f->fi, struct f_ncm_opts, func_inst);
1346 /*
1347 * in drivers/usb/gadget/configfs.c:configfs_composite_bind()
1348 * configurations are bound in sequence with list_for_each_entry,
1349 * in each configuration its functions are bound in sequence
1350 * with list_for_each_entry, so we assume no race condition
1351 * with regard to ncm_opts->bound access
1352 */
1353 if (!ncm_opts->bound) {
1354 mutex_lock(&ncm_opts->lock);
1355 gether_set_gadget(ncm_opts->net, cdev->gadget);
1356 status = gether_register_netdev(ncm_opts->net);
1357 mutex_unlock(&ncm_opts->lock);
1358 if (status)
1359 return status;
1360 ncm_opts->bound = true;
1361 }
1362 us = usb_gstrings_attach(cdev, ncm_strings,
1363 ARRAY_SIZE(ncm_string_defs));
1364 if (IS_ERR(us))
1365 return PTR_ERR(us);
1366 ncm_control_intf.iInterface = us[STRING_CTRL_IDX].id;
1367 ncm_data_nop_intf.iInterface = us[STRING_DATA_IDX].id;
1368 ncm_data_intf.iInterface = us[STRING_DATA_IDX].id;
1369 ecm_desc.iMACAddress = us[STRING_MAC_IDX].id;
1370 ncm_iad_desc.iFunction = us[STRING_IAD_IDX].id;
1371
1372 /* allocate instance-specific interface IDs */
1373 status = usb_interface_id(c, f);
1374 if (status < 0)
1375 goto fail;
1376 ncm->ctrl_id = status;
1377 ncm_iad_desc.bFirstInterface = status;
1378
1379 ncm_control_intf.bInterfaceNumber = status;
1380 ncm_union_desc.bMasterInterface0 = status;
1381
1382 status = usb_interface_id(c, f);
1383 if (status < 0)
1384 goto fail;
1385 ncm->data_id = status;
1386
1387 ncm_data_nop_intf.bInterfaceNumber = status;
1388 ncm_data_intf.bInterfaceNumber = status;
1389 ncm_union_desc.bSlaveInterface0 = status;
1390
1391 status = -ENODEV;
1392
1393 /* allocate instance-specific endpoints */
1394 ep = usb_ep_autoconfig(cdev->gadget, &fs_ncm_in_desc);
1395 if (!ep)
1396 goto fail;
1397 ncm->port.in_ep = ep;
1398 ep->driver_data = cdev; /* claim */
1399
1400 ep = usb_ep_autoconfig(cdev->gadget, &fs_ncm_out_desc);
1401 if (!ep)
1402 goto fail;
1403 ncm->port.out_ep = ep;
1404 ep->driver_data = cdev; /* claim */
1405
1406 ep = usb_ep_autoconfig(cdev->gadget, &fs_ncm_notify_desc);
1407 if (!ep)
1408 goto fail;
1409 ncm->notify = ep;
1410 ep->driver_data = cdev; /* claim */
1411
1412 status = -ENOMEM;
1413
1414 /* allocate notification request and buffer */
1415 ncm->notify_req = usb_ep_alloc_request(ep, GFP_KERNEL);
1416 if (!ncm->notify_req)
1417 goto fail;
1418 ncm->notify_req->buf = kmalloc(NCM_STATUS_BYTECOUNT, GFP_KERNEL);
1419 if (!ncm->notify_req->buf)
1420 goto fail;
1421 ncm->notify_req->context = ncm;
1422 ncm->notify_req->complete = ncm_notify_complete;
1423
1424 /*
1425 * support all relevant hardware speeds... we expect that when
1426 * hardware is dual speed, all bulk-capable endpoints work at
1427 * both speeds
1428 */
1429 hs_ncm_in_desc.bEndpointAddress = fs_ncm_in_desc.bEndpointAddress;
1430 hs_ncm_out_desc.bEndpointAddress = fs_ncm_out_desc.bEndpointAddress;
1431 hs_ncm_notify_desc.bEndpointAddress =
1432 fs_ncm_notify_desc.bEndpointAddress;
1433
1434 status = usb_assign_descriptors(f, ncm_fs_function, ncm_hs_function,
1435 NULL);
1436 /*
1437 * NOTE: all that is done without knowing or caring about
1438 * the network link ... which is unavailable to this code
1439 * until we're activated via set_alt().
1440 */
1441
1442 ncm->port.open = ncm_open;
1443 ncm->port.close = ncm_close;
1444
1445 tasklet_init(&ncm->tx_tasklet, ncm_tx_tasklet, (unsigned long) ncm);
1446 hrtimer_init(&ncm->task_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1447 ncm->task_timer.function = ncm_tx_timeout;
1448
1449 DBG(cdev, "CDC Network: %s speed IN/%s OUT/%s NOTIFY/%s\n",
1450 gadget_is_dualspeed(c->cdev->gadget) ? "dual" : "full",
1451 ncm->port.in_ep->name, ncm->port.out_ep->name,
1452 ncm->notify->name);
1453 return 0;
1454
1455fail:
1456 usb_free_all_descriptors(f);
1457 if (ncm->notify_req) {
1458 kfree(ncm->notify_req->buf);
1459 usb_ep_free_request(ncm->notify, ncm->notify_req);
1460 }
1461
1462 /* we might as well release our claims on endpoints */
1463 if (ncm->notify)
1464 ncm->notify->driver_data = NULL;
1465 if (ncm->port.out_ep)
1466 ncm->port.out_ep->driver_data = NULL;
1467 if (ncm->port.in_ep)
1468 ncm->port.in_ep->driver_data = NULL;
1469
1470 ERROR(cdev, "%s: can't bind, err %d\n", f->name, status);
1471
1472 return status;
1473}
1474
1475static inline struct f_ncm_opts *to_f_ncm_opts(struct config_item *item)
1476{
1477 return container_of(to_config_group(item), struct f_ncm_opts,
1478 func_inst.group);
1479}
1480
1481/* f_ncm_item_ops */
1482USB_ETHERNET_CONFIGFS_ITEM(ncm);
1483
1484/* f_ncm_opts_dev_addr */
1485USB_ETHERNET_CONFIGFS_ITEM_ATTR_DEV_ADDR(ncm);
1486
1487/* f_ncm_opts_host_addr */
1488USB_ETHERNET_CONFIGFS_ITEM_ATTR_HOST_ADDR(ncm);
1489
1490/* f_ncm_opts_qmult */
1491USB_ETHERNET_CONFIGFS_ITEM_ATTR_QMULT(ncm);
1492
1493/* f_ncm_opts_ifname */
1494USB_ETHERNET_CONFIGFS_ITEM_ATTR_IFNAME(ncm);
1495
1496static struct configfs_attribute *ncm_attrs[] = {
1497 &f_ncm_opts_dev_addr.attr,
1498 &f_ncm_opts_host_addr.attr,
1499 &f_ncm_opts_qmult.attr,
1500 &f_ncm_opts_ifname.attr,
1501 NULL,
1502};
1503
1504static struct config_item_type ncm_func_type = {
1505 .ct_item_ops = &ncm_item_ops,
1506 .ct_attrs = ncm_attrs,
1507 .ct_owner = THIS_MODULE,
1508};
1509
1510static void ncm_free_inst(struct usb_function_instance *f)
1511{
1512 struct f_ncm_opts *opts;
1513
1514 opts = container_of(f, struct f_ncm_opts, func_inst);
1515 if (opts->bound)
1516 gether_cleanup(netdev_priv(opts->net));
1517 else
1518 free_netdev(opts->net);
1519 kfree(opts);
1520}
1521
1522static struct usb_function_instance *ncm_alloc_inst(void)
1523{
1524 struct f_ncm_opts *opts;
1525
1526 opts = kzalloc(sizeof(*opts), GFP_KERNEL);
1527 if (!opts)
1528 return ERR_PTR(-ENOMEM);
1529 mutex_init(&opts->lock);
1530 opts->func_inst.free_func_inst = ncm_free_inst;
1531 opts->net = gether_setup_default();
1532 if (IS_ERR(opts->net)) {
1533 struct net_device *net = opts->net;
1534 kfree(opts);
1535 return ERR_CAST(net);
1536 }
1537
1538 config_group_init_type_name(&opts->func_inst.group, "", &ncm_func_type);
1539
1540 return &opts->func_inst;
1541}
1542
1543static void ncm_free(struct usb_function *f)
1544{
1545 struct f_ncm *ncm;
1546 struct f_ncm_opts *opts;
1547
1548 ncm = func_to_ncm(f);
1549 opts = container_of(f->fi, struct f_ncm_opts, func_inst);
1550 kfree(ncm);
1551 mutex_lock(&opts->lock);
1552 opts->refcnt--;
1553 mutex_unlock(&opts->lock);
1554}
1555
1556static void ncm_unbind(struct usb_configuration *c, struct usb_function *f)
1557{
1558 struct f_ncm *ncm = func_to_ncm(f);
1559
1560 DBG(c->cdev, "ncm unbind\n");
1561
1562 hrtimer_cancel(&ncm->task_timer);
1563 tasklet_kill(&ncm->tx_tasklet);
1564
1565 ncm_string_defs[0].id = 0;
1566 usb_free_all_descriptors(f);
1567
1568 kfree(ncm->notify_req->buf);
1569 usb_ep_free_request(ncm->notify, ncm->notify_req);
1570}
1571
1572static struct usb_function *ncm_alloc(struct usb_function_instance *fi)
1573{
1574 struct f_ncm *ncm;
1575 struct f_ncm_opts *opts;
1576 int status;
1577
1578 /* allocate and initialize one new instance */
1579 ncm = kzalloc(sizeof(*ncm), GFP_KERNEL);
1580 if (!ncm)
1581 return ERR_PTR(-ENOMEM);
1582
1583 opts = container_of(fi, struct f_ncm_opts, func_inst);
1584 mutex_lock(&opts->lock);
1585 opts->refcnt++;
1586
1587 /* export host's Ethernet address in CDC format */
1588 status = gether_get_host_addr_cdc(opts->net, ncm->ethaddr,
1589 sizeof(ncm->ethaddr));
1590 if (status < 12) { /* strlen("01234567890a") */
1591 kfree(ncm);
1592 mutex_unlock(&opts->lock);
1593 return ERR_PTR(-EINVAL);
1594 }
1595 ncm_string_defs[STRING_MAC_IDX].s = ncm->ethaddr;
1596
1597 spin_lock_init(&ncm->lock);
1598 ncm_reset_values(ncm);
1599 ncm->port.ioport = netdev_priv(opts->net);
1600 mutex_unlock(&opts->lock);
1601 ncm->port.is_fixed = true;
1602 ncm->port.supports_multi_frame = true;
1603
1604 ncm->port.func.name = "cdc_network";
1605 /* descriptors are per-instance copies */
1606 ncm->port.func.bind = ncm_bind;
1607 ncm->port.func.unbind = ncm_unbind;
1608 ncm->port.func.set_alt = ncm_set_alt;
1609 ncm->port.func.get_alt = ncm_get_alt;
1610 ncm->port.func.setup = ncm_setup;
1611 ncm->port.func.disable = ncm_disable;
1612 ncm->port.func.free_func = ncm_free;
1613
1614 ncm->port.wrap = ncm_wrap_ntb;
1615 ncm->port.unwrap = ncm_unwrap_ntb;
1616
1617 return &ncm->port.func;
1618}
1619
1620DECLARE_USB_FUNCTION_INIT(ncm, ncm_alloc_inst, ncm_alloc);
1621MODULE_LICENSE("GPL");
1622MODULE_AUTHOR("Yauheni Kaliuta");
diff --git a/drivers/usb/gadget/function/f_obex.c b/drivers/usb/gadget/function/f_obex.c
new file mode 100644
index 000000000000..aebae1853bce
--- /dev/null
+++ b/drivers/usb/gadget/function/f_obex.c
@@ -0,0 +1,533 @@
1/*
2 * f_obex.c -- USB CDC OBEX function driver
3 *
4 * Copyright (C) 2008 Nokia Corporation
5 * Contact: Felipe Balbi <felipe.balbi@nokia.com>
6 *
7 * Based on f_acm.c by Al Borchers and David Brownell.
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 */
14
15/* #define VERBOSE_DEBUG */
16
17#include <linux/slab.h>
18#include <linux/kernel.h>
19#include <linux/device.h>
20#include <linux/module.h>
21
22#include "u_serial.h"
23#include "gadget_chips.h"
24
25
26/*
27 * This CDC OBEX function support just packages a TTY-ish byte stream.
28 * A user mode server will put it into "raw" mode and handle all the
29 * relevant protocol details ... this is just a kernel passthrough.
30 * When possible, we prevent gadget enumeration until that server is
31 * ready to handle the commands.
32 */
33
34struct f_obex {
35 struct gserial port;
36 u8 ctrl_id;
37 u8 data_id;
38 u8 port_num;
39 u8 can_activate;
40};
41
42static inline struct f_obex *func_to_obex(struct usb_function *f)
43{
44 return container_of(f, struct f_obex, port.func);
45}
46
47static inline struct f_obex *port_to_obex(struct gserial *p)
48{
49 return container_of(p, struct f_obex, port);
50}
51
52/*-------------------------------------------------------------------------*/
53
54#define OBEX_CTRL_IDX 0
55#define OBEX_DATA_IDX 1
56
57static struct usb_string obex_string_defs[] = {
58 [OBEX_CTRL_IDX].s = "CDC Object Exchange (OBEX)",
59 [OBEX_DATA_IDX].s = "CDC OBEX Data",
60 { }, /* end of list */
61};
62
63static struct usb_gadget_strings obex_string_table = {
64 .language = 0x0409, /* en-US */
65 .strings = obex_string_defs,
66};
67
68static struct usb_gadget_strings *obex_strings[] = {
69 &obex_string_table,
70 NULL,
71};
72
73/*-------------------------------------------------------------------------*/
74
75static struct usb_interface_descriptor obex_control_intf = {
76 .bLength = sizeof(obex_control_intf),
77 .bDescriptorType = USB_DT_INTERFACE,
78 .bInterfaceNumber = 0,
79
80 .bAlternateSetting = 0,
81 .bNumEndpoints = 0,
82 .bInterfaceClass = USB_CLASS_COMM,
83 .bInterfaceSubClass = USB_CDC_SUBCLASS_OBEX,
84};
85
86static struct usb_interface_descriptor obex_data_nop_intf = {
87 .bLength = sizeof(obex_data_nop_intf),
88 .bDescriptorType = USB_DT_INTERFACE,
89 .bInterfaceNumber = 1,
90
91 .bAlternateSetting = 0,
92 .bNumEndpoints = 0,
93 .bInterfaceClass = USB_CLASS_CDC_DATA,
94};
95
96static struct usb_interface_descriptor obex_data_intf = {
97 .bLength = sizeof(obex_data_intf),
98 .bDescriptorType = USB_DT_INTERFACE,
99 .bInterfaceNumber = 2,
100
101 .bAlternateSetting = 1,
102 .bNumEndpoints = 2,
103 .bInterfaceClass = USB_CLASS_CDC_DATA,
104};
105
106static struct usb_cdc_header_desc obex_cdc_header_desc = {
107 .bLength = sizeof(obex_cdc_header_desc),
108 .bDescriptorType = USB_DT_CS_INTERFACE,
109 .bDescriptorSubType = USB_CDC_HEADER_TYPE,
110 .bcdCDC = cpu_to_le16(0x0120),
111};
112
113static struct usb_cdc_union_desc obex_cdc_union_desc = {
114 .bLength = sizeof(obex_cdc_union_desc),
115 .bDescriptorType = USB_DT_CS_INTERFACE,
116 .bDescriptorSubType = USB_CDC_UNION_TYPE,
117 .bMasterInterface0 = 1,
118 .bSlaveInterface0 = 2,
119};
120
121static struct usb_cdc_obex_desc obex_desc = {
122 .bLength = sizeof(obex_desc),
123 .bDescriptorType = USB_DT_CS_INTERFACE,
124 .bDescriptorSubType = USB_CDC_OBEX_TYPE,
125 .bcdVersion = cpu_to_le16(0x0100),
126};
127
128/* High-Speed Support */
129
130static struct usb_endpoint_descriptor obex_hs_ep_out_desc = {
131 .bLength = USB_DT_ENDPOINT_SIZE,
132 .bDescriptorType = USB_DT_ENDPOINT,
133
134 .bEndpointAddress = USB_DIR_OUT,
135 .bmAttributes = USB_ENDPOINT_XFER_BULK,
136 .wMaxPacketSize = cpu_to_le16(512),
137};
138
139static struct usb_endpoint_descriptor obex_hs_ep_in_desc = {
140 .bLength = USB_DT_ENDPOINT_SIZE,
141 .bDescriptorType = USB_DT_ENDPOINT,
142
143 .bEndpointAddress = USB_DIR_IN,
144 .bmAttributes = USB_ENDPOINT_XFER_BULK,
145 .wMaxPacketSize = cpu_to_le16(512),
146};
147
148static struct usb_descriptor_header *hs_function[] = {
149 (struct usb_descriptor_header *) &obex_control_intf,
150 (struct usb_descriptor_header *) &obex_cdc_header_desc,
151 (struct usb_descriptor_header *) &obex_desc,
152 (struct usb_descriptor_header *) &obex_cdc_union_desc,
153
154 (struct usb_descriptor_header *) &obex_data_nop_intf,
155 (struct usb_descriptor_header *) &obex_data_intf,
156 (struct usb_descriptor_header *) &obex_hs_ep_in_desc,
157 (struct usb_descriptor_header *) &obex_hs_ep_out_desc,
158 NULL,
159};
160
161/* Full-Speed Support */
162
163static struct usb_endpoint_descriptor obex_fs_ep_in_desc = {
164 .bLength = USB_DT_ENDPOINT_SIZE,
165 .bDescriptorType = USB_DT_ENDPOINT,
166
167 .bEndpointAddress = USB_DIR_IN,
168 .bmAttributes = USB_ENDPOINT_XFER_BULK,
169};
170
171static struct usb_endpoint_descriptor obex_fs_ep_out_desc = {
172 .bLength = USB_DT_ENDPOINT_SIZE,
173 .bDescriptorType = USB_DT_ENDPOINT,
174
175 .bEndpointAddress = USB_DIR_OUT,
176 .bmAttributes = USB_ENDPOINT_XFER_BULK,
177};
178
179static struct usb_descriptor_header *fs_function[] = {
180 (struct usb_descriptor_header *) &obex_control_intf,
181 (struct usb_descriptor_header *) &obex_cdc_header_desc,
182 (struct usb_descriptor_header *) &obex_desc,
183 (struct usb_descriptor_header *) &obex_cdc_union_desc,
184
185 (struct usb_descriptor_header *) &obex_data_nop_intf,
186 (struct usb_descriptor_header *) &obex_data_intf,
187 (struct usb_descriptor_header *) &obex_fs_ep_in_desc,
188 (struct usb_descriptor_header *) &obex_fs_ep_out_desc,
189 NULL,
190};
191
192/*-------------------------------------------------------------------------*/
193
194static int obex_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
195{
196 struct f_obex *obex = func_to_obex(f);
197 struct usb_composite_dev *cdev = f->config->cdev;
198
199 if (intf == obex->ctrl_id) {
200 if (alt != 0)
201 goto fail;
202 /* NOP */
203 DBG(cdev, "reset obex ttyGS%d control\n", obex->port_num);
204
205 } else if (intf == obex->data_id) {
206 if (alt > 1)
207 goto fail;
208
209 if (obex->port.in->driver_data) {
210 DBG(cdev, "reset obex ttyGS%d\n", obex->port_num);
211 gserial_disconnect(&obex->port);
212 }
213
214 if (!obex->port.in->desc || !obex->port.out->desc) {
215 DBG(cdev, "init obex ttyGS%d\n", obex->port_num);
216 if (config_ep_by_speed(cdev->gadget, f,
217 obex->port.in) ||
218 config_ep_by_speed(cdev->gadget, f,
219 obex->port.out)) {
220 obex->port.out->desc = NULL;
221 obex->port.in->desc = NULL;
222 goto fail;
223 }
224 }
225
226 if (alt == 1) {
227 DBG(cdev, "activate obex ttyGS%d\n", obex->port_num);
228 gserial_connect(&obex->port, obex->port_num);
229 }
230
231 } else
232 goto fail;
233
234 return 0;
235
236fail:
237 return -EINVAL;
238}
239
240static int obex_get_alt(struct usb_function *f, unsigned intf)
241{
242 struct f_obex *obex = func_to_obex(f);
243
244 if (intf == obex->ctrl_id)
245 return 0;
246
247 return obex->port.in->driver_data ? 1 : 0;
248}
249
250static void obex_disable(struct usb_function *f)
251{
252 struct f_obex *obex = func_to_obex(f);
253 struct usb_composite_dev *cdev = f->config->cdev;
254
255 DBG(cdev, "obex ttyGS%d disable\n", obex->port_num);
256 gserial_disconnect(&obex->port);
257}
258
259/*-------------------------------------------------------------------------*/
260
261static void obex_connect(struct gserial *g)
262{
263 struct f_obex *obex = port_to_obex(g);
264 struct usb_composite_dev *cdev = g->func.config->cdev;
265 int status;
266
267 if (!obex->can_activate)
268 return;
269
270 status = usb_function_activate(&g->func);
271 if (status)
272 DBG(cdev, "obex ttyGS%d function activate --> %d\n",
273 obex->port_num, status);
274}
275
276static void obex_disconnect(struct gserial *g)
277{
278 struct f_obex *obex = port_to_obex(g);
279 struct usb_composite_dev *cdev = g->func.config->cdev;
280 int status;
281
282 if (!obex->can_activate)
283 return;
284
285 status = usb_function_deactivate(&g->func);
286 if (status)
287 DBG(cdev, "obex ttyGS%d function deactivate --> %d\n",
288 obex->port_num, status);
289}
290
291/*-------------------------------------------------------------------------*/
292
293/* Some controllers can't support CDC OBEX ... */
294static inline bool can_support_obex(struct usb_configuration *c)
295{
296 /* Since the first interface is a NOP, we can ignore the
297 * issue of multi-interface support on most controllers.
298 *
299 * Altsettings are mandatory, however...
300 */
301 if (!gadget_supports_altsettings(c->cdev->gadget))
302 return false;
303
304 /* everything else is *probably* fine ... */
305 return true;
306}
307
308static int obex_bind(struct usb_configuration *c, struct usb_function *f)
309{
310 struct usb_composite_dev *cdev = c->cdev;
311 struct f_obex *obex = func_to_obex(f);
312 struct usb_string *us;
313 int status;
314 struct usb_ep *ep;
315
316 if (!can_support_obex(c))
317 return -EINVAL;
318
319 us = usb_gstrings_attach(cdev, obex_strings,
320 ARRAY_SIZE(obex_string_defs));
321 if (IS_ERR(us))
322 return PTR_ERR(us);
323 obex_control_intf.iInterface = us[OBEX_CTRL_IDX].id;
324 obex_data_nop_intf.iInterface = us[OBEX_DATA_IDX].id;
325 obex_data_intf.iInterface = us[OBEX_DATA_IDX].id;
326
327 /* allocate instance-specific interface IDs, and patch descriptors */
328
329 status = usb_interface_id(c, f);
330 if (status < 0)
331 goto fail;
332 obex->ctrl_id = status;
333
334 obex_control_intf.bInterfaceNumber = status;
335 obex_cdc_union_desc.bMasterInterface0 = status;
336
337 status = usb_interface_id(c, f);
338 if (status < 0)
339 goto fail;
340 obex->data_id = status;
341
342 obex_data_nop_intf.bInterfaceNumber = status;
343 obex_data_intf.bInterfaceNumber = status;
344 obex_cdc_union_desc.bSlaveInterface0 = status;
345
346 /* allocate instance-specific endpoints */
347
348 status = -ENODEV;
349 ep = usb_ep_autoconfig(cdev->gadget, &obex_fs_ep_in_desc);
350 if (!ep)
351 goto fail;
352 obex->port.in = ep;
353 ep->driver_data = cdev; /* claim */
354
355 ep = usb_ep_autoconfig(cdev->gadget, &obex_fs_ep_out_desc);
356 if (!ep)
357 goto fail;
358 obex->port.out = ep;
359 ep->driver_data = cdev; /* claim */
360
361 /* support all relevant hardware speeds... we expect that when
362 * hardware is dual speed, all bulk-capable endpoints work at
363 * both speeds
364 */
365
366 obex_hs_ep_in_desc.bEndpointAddress =
367 obex_fs_ep_in_desc.bEndpointAddress;
368 obex_hs_ep_out_desc.bEndpointAddress =
369 obex_fs_ep_out_desc.bEndpointAddress;
370
371 status = usb_assign_descriptors(f, fs_function, hs_function, NULL);
372 if (status)
373 goto fail;
374
375 /* Avoid letting this gadget enumerate until the userspace
376 * OBEX server is active.
377 */
378 status = usb_function_deactivate(f);
379 if (status < 0)
380 WARNING(cdev, "obex ttyGS%d: can't prevent enumeration, %d\n",
381 obex->port_num, status);
382 else
383 obex->can_activate = true;
384
385
386 DBG(cdev, "obex ttyGS%d: %s speed IN/%s OUT/%s\n",
387 obex->port_num,
388 gadget_is_dualspeed(c->cdev->gadget) ? "dual" : "full",
389 obex->port.in->name, obex->port.out->name);
390
391 return 0;
392
393fail:
394 usb_free_all_descriptors(f);
395 /* we might as well release our claims on endpoints */
396 if (obex->port.out)
397 obex->port.out->driver_data = NULL;
398 if (obex->port.in)
399 obex->port.in->driver_data = NULL;
400
401 ERROR(cdev, "%s/%p: can't bind, err %d\n", f->name, f, status);
402
403 return status;
404}
405
406static inline struct f_serial_opts *to_f_serial_opts(struct config_item *item)
407{
408 return container_of(to_config_group(item), struct f_serial_opts,
409 func_inst.group);
410}
411
412CONFIGFS_ATTR_STRUCT(f_serial_opts);
413static ssize_t f_obex_attr_show(struct config_item *item,
414 struct configfs_attribute *attr,
415 char *page)
416{
417 struct f_serial_opts *opts = to_f_serial_opts(item);
418 struct f_serial_opts_attribute *f_serial_opts_attr =
419 container_of(attr, struct f_serial_opts_attribute, attr);
420 ssize_t ret = 0;
421
422 if (f_serial_opts_attr->show)
423 ret = f_serial_opts_attr->show(opts, page);
424
425 return ret;
426}
427
428static void obex_attr_release(struct config_item *item)
429{
430 struct f_serial_opts *opts = to_f_serial_opts(item);
431
432 usb_put_function_instance(&opts->func_inst);
433}
434
435static struct configfs_item_operations obex_item_ops = {
436 .release = obex_attr_release,
437 .show_attribute = f_obex_attr_show,
438};
439
440static ssize_t f_obex_port_num_show(struct f_serial_opts *opts, char *page)
441{
442 return sprintf(page, "%u\n", opts->port_num);
443}
444
445static struct f_serial_opts_attribute f_obex_port_num =
446 __CONFIGFS_ATTR_RO(port_num, f_obex_port_num_show);
447
448static struct configfs_attribute *acm_attrs[] = {
449 &f_obex_port_num.attr,
450 NULL,
451};
452
453static struct config_item_type obex_func_type = {
454 .ct_item_ops = &obex_item_ops,
455 .ct_attrs = acm_attrs,
456 .ct_owner = THIS_MODULE,
457};
458
459static void obex_free_inst(struct usb_function_instance *f)
460{
461 struct f_serial_opts *opts;
462
463 opts = container_of(f, struct f_serial_opts, func_inst);
464 gserial_free_line(opts->port_num);
465 kfree(opts);
466}
467
468static struct usb_function_instance *obex_alloc_inst(void)
469{
470 struct f_serial_opts *opts;
471 int ret;
472
473 opts = kzalloc(sizeof(*opts), GFP_KERNEL);
474 if (!opts)
475 return ERR_PTR(-ENOMEM);
476
477 opts->func_inst.free_func_inst = obex_free_inst;
478 ret = gserial_alloc_line(&opts->port_num);
479 if (ret) {
480 kfree(opts);
481 return ERR_PTR(ret);
482 }
483 config_group_init_type_name(&opts->func_inst.group, "",
484 &obex_func_type);
485
486 return &opts->func_inst;
487}
488
489static void obex_free(struct usb_function *f)
490{
491 struct f_obex *obex;
492
493 obex = func_to_obex(f);
494 kfree(obex);
495}
496
497static void obex_unbind(struct usb_configuration *c, struct usb_function *f)
498{
499 usb_free_all_descriptors(f);
500}
501
502static struct usb_function *obex_alloc(struct usb_function_instance *fi)
503{
504 struct f_obex *obex;
505 struct f_serial_opts *opts;
506
507 /* allocate and initialize one new instance */
508 obex = kzalloc(sizeof(*obex), GFP_KERNEL);
509 if (!obex)
510 return ERR_PTR(-ENOMEM);
511
512 opts = container_of(fi, struct f_serial_opts, func_inst);
513
514 obex->port_num = opts->port_num;
515
516 obex->port.connect = obex_connect;
517 obex->port.disconnect = obex_disconnect;
518
519 obex->port.func.name = "obex";
520 /* descriptors are per-instance copies */
521 obex->port.func.bind = obex_bind;
522 obex->port.func.unbind = obex_unbind;
523 obex->port.func.set_alt = obex_set_alt;
524 obex->port.func.get_alt = obex_get_alt;
525 obex->port.func.disable = obex_disable;
526 obex->port.func.free_func = obex_free;
527
528 return &obex->port.func;
529}
530
531DECLARE_USB_FUNCTION_INIT(obex, obex_alloc_inst, obex_alloc);
532MODULE_AUTHOR("Felipe Balbi");
533MODULE_LICENSE("GPL");
diff --git a/drivers/usb/gadget/function/f_phonet.c b/drivers/usb/gadget/function/f_phonet.c
new file mode 100644
index 000000000000..f2b781773eed
--- /dev/null
+++ b/drivers/usb/gadget/function/f_phonet.c
@@ -0,0 +1,758 @@
1/*
2 * f_phonet.c -- USB CDC Phonet function
3 *
4 * Copyright (C) 2007-2008 Nokia Corporation. All rights reserved.
5 *
6 * Author: Rémi Denis-Courmont
7 *
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License
10 * version 2 as published by the Free Software Foundation.
11 */
12
13#include <linux/mm.h>
14#include <linux/slab.h>
15#include <linux/kernel.h>
16#include <linux/module.h>
17#include <linux/device.h>
18
19#include <linux/netdevice.h>
20#include <linux/if_ether.h>
21#include <linux/if_phonet.h>
22#include <linux/if_arp.h>
23
24#include <linux/usb/ch9.h>
25#include <linux/usb/cdc.h>
26#include <linux/usb/composite.h>
27
28#include "u_phonet.h"
29#include "u_ether.h"
30
31#define PN_MEDIA_USB 0x1B
32#define MAXPACKET 512
33#if (PAGE_SIZE % MAXPACKET)
34#error MAXPACKET must divide PAGE_SIZE!
35#endif
36
37/*-------------------------------------------------------------------------*/
38
39struct phonet_port {
40 struct f_phonet *usb;
41 spinlock_t lock;
42};
43
44struct f_phonet {
45 struct usb_function function;
46 struct {
47 struct sk_buff *skb;
48 spinlock_t lock;
49 } rx;
50 struct net_device *dev;
51 struct usb_ep *in_ep, *out_ep;
52
53 struct usb_request *in_req;
54 struct usb_request *out_reqv[0];
55};
56
57static int phonet_rxq_size = 17;
58
59static inline struct f_phonet *func_to_pn(struct usb_function *f)
60{
61 return container_of(f, struct f_phonet, function);
62}
63
64/*-------------------------------------------------------------------------*/
65
66#define USB_CDC_SUBCLASS_PHONET 0xfe
67#define USB_CDC_PHONET_TYPE 0xab
68
69static struct usb_interface_descriptor
70pn_control_intf_desc = {
71 .bLength = sizeof pn_control_intf_desc,
72 .bDescriptorType = USB_DT_INTERFACE,
73
74 /* .bInterfaceNumber = DYNAMIC, */
75 .bInterfaceClass = USB_CLASS_COMM,
76 .bInterfaceSubClass = USB_CDC_SUBCLASS_PHONET,
77};
78
79static const struct usb_cdc_header_desc
80pn_header_desc = {
81 .bLength = sizeof pn_header_desc,
82 .bDescriptorType = USB_DT_CS_INTERFACE,
83 .bDescriptorSubType = USB_CDC_HEADER_TYPE,
84 .bcdCDC = cpu_to_le16(0x0110),
85};
86
87static const struct usb_cdc_header_desc
88pn_phonet_desc = {
89 .bLength = sizeof pn_phonet_desc,
90 .bDescriptorType = USB_DT_CS_INTERFACE,
91 .bDescriptorSubType = USB_CDC_PHONET_TYPE,
92 .bcdCDC = cpu_to_le16(0x1505), /* ??? */
93};
94
95static struct usb_cdc_union_desc
96pn_union_desc = {
97 .bLength = sizeof pn_union_desc,
98 .bDescriptorType = USB_DT_CS_INTERFACE,
99 .bDescriptorSubType = USB_CDC_UNION_TYPE,
100
101 /* .bMasterInterface0 = DYNAMIC, */
102 /* .bSlaveInterface0 = DYNAMIC, */
103};
104
105static struct usb_interface_descriptor
106pn_data_nop_intf_desc = {
107 .bLength = sizeof pn_data_nop_intf_desc,
108 .bDescriptorType = USB_DT_INTERFACE,
109
110 /* .bInterfaceNumber = DYNAMIC, */
111 .bAlternateSetting = 0,
112 .bNumEndpoints = 0,
113 .bInterfaceClass = USB_CLASS_CDC_DATA,
114};
115
116static struct usb_interface_descriptor
117pn_data_intf_desc = {
118 .bLength = sizeof pn_data_intf_desc,
119 .bDescriptorType = USB_DT_INTERFACE,
120
121 /* .bInterfaceNumber = DYNAMIC, */
122 .bAlternateSetting = 1,
123 .bNumEndpoints = 2,
124 .bInterfaceClass = USB_CLASS_CDC_DATA,
125};
126
127static struct usb_endpoint_descriptor
128pn_fs_sink_desc = {
129 .bLength = USB_DT_ENDPOINT_SIZE,
130 .bDescriptorType = USB_DT_ENDPOINT,
131
132 .bEndpointAddress = USB_DIR_OUT,
133 .bmAttributes = USB_ENDPOINT_XFER_BULK,
134};
135
136static struct usb_endpoint_descriptor
137pn_hs_sink_desc = {
138 .bLength = USB_DT_ENDPOINT_SIZE,
139 .bDescriptorType = USB_DT_ENDPOINT,
140
141 .bEndpointAddress = USB_DIR_OUT,
142 .bmAttributes = USB_ENDPOINT_XFER_BULK,
143 .wMaxPacketSize = cpu_to_le16(MAXPACKET),
144};
145
146static struct usb_endpoint_descriptor
147pn_fs_source_desc = {
148 .bLength = USB_DT_ENDPOINT_SIZE,
149 .bDescriptorType = USB_DT_ENDPOINT,
150
151 .bEndpointAddress = USB_DIR_IN,
152 .bmAttributes = USB_ENDPOINT_XFER_BULK,
153};
154
155static struct usb_endpoint_descriptor
156pn_hs_source_desc = {
157 .bLength = USB_DT_ENDPOINT_SIZE,
158 .bDescriptorType = USB_DT_ENDPOINT,
159
160 .bEndpointAddress = USB_DIR_IN,
161 .bmAttributes = USB_ENDPOINT_XFER_BULK,
162 .wMaxPacketSize = cpu_to_le16(512),
163};
164
165static struct usb_descriptor_header *fs_pn_function[] = {
166 (struct usb_descriptor_header *) &pn_control_intf_desc,
167 (struct usb_descriptor_header *) &pn_header_desc,
168 (struct usb_descriptor_header *) &pn_phonet_desc,
169 (struct usb_descriptor_header *) &pn_union_desc,
170 (struct usb_descriptor_header *) &pn_data_nop_intf_desc,
171 (struct usb_descriptor_header *) &pn_data_intf_desc,
172 (struct usb_descriptor_header *) &pn_fs_sink_desc,
173 (struct usb_descriptor_header *) &pn_fs_source_desc,
174 NULL,
175};
176
177static struct usb_descriptor_header *hs_pn_function[] = {
178 (struct usb_descriptor_header *) &pn_control_intf_desc,
179 (struct usb_descriptor_header *) &pn_header_desc,
180 (struct usb_descriptor_header *) &pn_phonet_desc,
181 (struct usb_descriptor_header *) &pn_union_desc,
182 (struct usb_descriptor_header *) &pn_data_nop_intf_desc,
183 (struct usb_descriptor_header *) &pn_data_intf_desc,
184 (struct usb_descriptor_header *) &pn_hs_sink_desc,
185 (struct usb_descriptor_header *) &pn_hs_source_desc,
186 NULL,
187};
188
189/*-------------------------------------------------------------------------*/
190
191static int pn_net_open(struct net_device *dev)
192{
193 netif_wake_queue(dev);
194 return 0;
195}
196
197static int pn_net_close(struct net_device *dev)
198{
199 netif_stop_queue(dev);
200 return 0;
201}
202
203static void pn_tx_complete(struct usb_ep *ep, struct usb_request *req)
204{
205 struct f_phonet *fp = ep->driver_data;
206 struct net_device *dev = fp->dev;
207 struct sk_buff *skb = req->context;
208
209 switch (req->status) {
210 case 0:
211 dev->stats.tx_packets++;
212 dev->stats.tx_bytes += skb->len;
213 break;
214
215 case -ESHUTDOWN: /* disconnected */
216 case -ECONNRESET: /* disabled */
217 dev->stats.tx_aborted_errors++;
218 default:
219 dev->stats.tx_errors++;
220 }
221
222 dev_kfree_skb_any(skb);
223 netif_wake_queue(dev);
224}
225
226static int pn_net_xmit(struct sk_buff *skb, struct net_device *dev)
227{
228 struct phonet_port *port = netdev_priv(dev);
229 struct f_phonet *fp;
230 struct usb_request *req;
231 unsigned long flags;
232
233 if (skb->protocol != htons(ETH_P_PHONET))
234 goto out;
235
236 spin_lock_irqsave(&port->lock, flags);
237 fp = port->usb;
238 if (unlikely(!fp)) /* race with carrier loss */
239 goto out_unlock;
240
241 req = fp->in_req;
242 req->buf = skb->data;
243 req->length = skb->len;
244 req->complete = pn_tx_complete;
245 req->zero = 1;
246 req->context = skb;
247
248 if (unlikely(usb_ep_queue(fp->in_ep, req, GFP_ATOMIC)))
249 goto out_unlock;
250
251 netif_stop_queue(dev);
252 skb = NULL;
253
254out_unlock:
255 spin_unlock_irqrestore(&port->lock, flags);
256out:
257 if (unlikely(skb)) {
258 dev_kfree_skb(skb);
259 dev->stats.tx_dropped++;
260 }
261 return NETDEV_TX_OK;
262}
263
264static int pn_net_mtu(struct net_device *dev, int new_mtu)
265{
266 if ((new_mtu < PHONET_MIN_MTU) || (new_mtu > PHONET_MAX_MTU))
267 return -EINVAL;
268 dev->mtu = new_mtu;
269 return 0;
270}
271
272static const struct net_device_ops pn_netdev_ops = {
273 .ndo_open = pn_net_open,
274 .ndo_stop = pn_net_close,
275 .ndo_start_xmit = pn_net_xmit,
276 .ndo_change_mtu = pn_net_mtu,
277};
278
279static void pn_net_setup(struct net_device *dev)
280{
281 dev->features = 0;
282 dev->type = ARPHRD_PHONET;
283 dev->flags = IFF_POINTOPOINT | IFF_NOARP;
284 dev->mtu = PHONET_DEV_MTU;
285 dev->hard_header_len = 1;
286 dev->dev_addr[0] = PN_MEDIA_USB;
287 dev->addr_len = 1;
288 dev->tx_queue_len = 1;
289
290 dev->netdev_ops = &pn_netdev_ops;
291 dev->destructor = free_netdev;
292 dev->header_ops = &phonet_header_ops;
293}
294
295/*-------------------------------------------------------------------------*/
296
297/*
298 * Queue buffer for data from the host
299 */
300static int
301pn_rx_submit(struct f_phonet *fp, struct usb_request *req, gfp_t gfp_flags)
302{
303 struct page *page;
304 int err;
305
306 page = __skb_alloc_page(gfp_flags | __GFP_NOMEMALLOC, NULL);
307 if (!page)
308 return -ENOMEM;
309
310 req->buf = page_address(page);
311 req->length = PAGE_SIZE;
312 req->context = page;
313
314 err = usb_ep_queue(fp->out_ep, req, gfp_flags);
315 if (unlikely(err))
316 put_page(page);
317 return err;
318}
319
320static void pn_rx_complete(struct usb_ep *ep, struct usb_request *req)
321{
322 struct f_phonet *fp = ep->driver_data;
323 struct net_device *dev = fp->dev;
324 struct page *page = req->context;
325 struct sk_buff *skb;
326 unsigned long flags;
327 int status = req->status;
328
329 switch (status) {
330 case 0:
331 spin_lock_irqsave(&fp->rx.lock, flags);
332 skb = fp->rx.skb;
333 if (!skb)
334 skb = fp->rx.skb = netdev_alloc_skb(dev, 12);
335 if (req->actual < req->length) /* Last fragment */
336 fp->rx.skb = NULL;
337 spin_unlock_irqrestore(&fp->rx.lock, flags);
338
339 if (unlikely(!skb))
340 break;
341
342 if (skb->len == 0) { /* First fragment */
343 skb->protocol = htons(ETH_P_PHONET);
344 skb_reset_mac_header(skb);
345 /* Can't use pskb_pull() on page in IRQ */
346 memcpy(skb_put(skb, 1), page_address(page), 1);
347 }
348
349 skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags, page,
350 skb->len <= 1, req->actual, PAGE_SIZE);
351 page = NULL;
352
353 if (req->actual < req->length) { /* Last fragment */
354 skb->dev = dev;
355 dev->stats.rx_packets++;
356 dev->stats.rx_bytes += skb->len;
357
358 netif_rx(skb);
359 }
360 break;
361
362 /* Do not resubmit in these cases: */
363 case -ESHUTDOWN: /* disconnect */
364 case -ECONNABORTED: /* hw reset */
365 case -ECONNRESET: /* dequeued (unlink or netif down) */
366 req = NULL;
367 break;
368
369 /* Do resubmit in these cases: */
370 case -EOVERFLOW: /* request buffer overflow */
371 dev->stats.rx_over_errors++;
372 default:
373 dev->stats.rx_errors++;
374 break;
375 }
376
377 if (page)
378 put_page(page);
379 if (req)
380 pn_rx_submit(fp, req, GFP_ATOMIC | __GFP_COLD);
381}
382
383/*-------------------------------------------------------------------------*/
384
385static void __pn_reset(struct usb_function *f)
386{
387 struct f_phonet *fp = func_to_pn(f);
388 struct net_device *dev = fp->dev;
389 struct phonet_port *port = netdev_priv(dev);
390
391 netif_carrier_off(dev);
392 port->usb = NULL;
393
394 usb_ep_disable(fp->out_ep);
395 usb_ep_disable(fp->in_ep);
396 if (fp->rx.skb) {
397 dev_kfree_skb_irq(fp->rx.skb);
398 fp->rx.skb = NULL;
399 }
400}
401
402static int pn_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
403{
404 struct f_phonet *fp = func_to_pn(f);
405 struct usb_gadget *gadget = fp->function.config->cdev->gadget;
406
407 if (intf == pn_control_intf_desc.bInterfaceNumber)
408 /* control interface, no altsetting */
409 return (alt > 0) ? -EINVAL : 0;
410
411 if (intf == pn_data_intf_desc.bInterfaceNumber) {
412 struct net_device *dev = fp->dev;
413 struct phonet_port *port = netdev_priv(dev);
414
415 /* data intf (0: inactive, 1: active) */
416 if (alt > 1)
417 return -EINVAL;
418
419 spin_lock(&port->lock);
420 __pn_reset(f);
421 if (alt == 1) {
422 int i;
423
424 if (config_ep_by_speed(gadget, f, fp->in_ep) ||
425 config_ep_by_speed(gadget, f, fp->out_ep)) {
426 fp->in_ep->desc = NULL;
427 fp->out_ep->desc = NULL;
428 spin_unlock(&port->lock);
429 return -EINVAL;
430 }
431 usb_ep_enable(fp->out_ep);
432 usb_ep_enable(fp->in_ep);
433
434 port->usb = fp;
435 fp->out_ep->driver_data = fp;
436 fp->in_ep->driver_data = fp;
437
438 netif_carrier_on(dev);
439 for (i = 0; i < phonet_rxq_size; i++)
440 pn_rx_submit(fp, fp->out_reqv[i], GFP_ATOMIC | __GFP_COLD);
441 }
442 spin_unlock(&port->lock);
443 return 0;
444 }
445
446 return -EINVAL;
447}
448
449static int pn_get_alt(struct usb_function *f, unsigned intf)
450{
451 struct f_phonet *fp = func_to_pn(f);
452
453 if (intf == pn_control_intf_desc.bInterfaceNumber)
454 return 0;
455
456 if (intf == pn_data_intf_desc.bInterfaceNumber) {
457 struct phonet_port *port = netdev_priv(fp->dev);
458 u8 alt;
459
460 spin_lock(&port->lock);
461 alt = port->usb != NULL;
462 spin_unlock(&port->lock);
463 return alt;
464 }
465
466 return -EINVAL;
467}
468
469static void pn_disconnect(struct usb_function *f)
470{
471 struct f_phonet *fp = func_to_pn(f);
472 struct phonet_port *port = netdev_priv(fp->dev);
473 unsigned long flags;
474
475 /* remain disabled until set_alt */
476 spin_lock_irqsave(&port->lock, flags);
477 __pn_reset(f);
478 spin_unlock_irqrestore(&port->lock, flags);
479}
480
481/*-------------------------------------------------------------------------*/
482
483static int pn_bind(struct usb_configuration *c, struct usb_function *f)
484{
485 struct usb_composite_dev *cdev = c->cdev;
486 struct usb_gadget *gadget = cdev->gadget;
487 struct f_phonet *fp = func_to_pn(f);
488 struct usb_ep *ep;
489 int status, i;
490
491 struct f_phonet_opts *phonet_opts;
492
493 phonet_opts = container_of(f->fi, struct f_phonet_opts, func_inst);
494
495 /*
496 * in drivers/usb/gadget/configfs.c:configfs_composite_bind()
497 * configurations are bound in sequence with list_for_each_entry,
498 * in each configuration its functions are bound in sequence
499 * with list_for_each_entry, so we assume no race condition
500 * with regard to phonet_opts->bound access
501 */
502 if (!phonet_opts->bound) {
503 gphonet_set_gadget(phonet_opts->net, gadget);
504 status = gphonet_register_netdev(phonet_opts->net);
505 if (status)
506 return status;
507 phonet_opts->bound = true;
508 }
509
510 /* Reserve interface IDs */
511 status = usb_interface_id(c, f);
512 if (status < 0)
513 goto err;
514 pn_control_intf_desc.bInterfaceNumber = status;
515 pn_union_desc.bMasterInterface0 = status;
516
517 status = usb_interface_id(c, f);
518 if (status < 0)
519 goto err;
520 pn_data_nop_intf_desc.bInterfaceNumber = status;
521 pn_data_intf_desc.bInterfaceNumber = status;
522 pn_union_desc.bSlaveInterface0 = status;
523
524 /* Reserve endpoints */
525 status = -ENODEV;
526 ep = usb_ep_autoconfig(gadget, &pn_fs_sink_desc);
527 if (!ep)
528 goto err;
529 fp->out_ep = ep;
530 ep->driver_data = fp; /* Claim */
531
532 ep = usb_ep_autoconfig(gadget, &pn_fs_source_desc);
533 if (!ep)
534 goto err;
535 fp->in_ep = ep;
536 ep->driver_data = fp; /* Claim */
537
538 pn_hs_sink_desc.bEndpointAddress = pn_fs_sink_desc.bEndpointAddress;
539 pn_hs_source_desc.bEndpointAddress = pn_fs_source_desc.bEndpointAddress;
540
541 /* Do not try to bind Phonet twice... */
542 status = usb_assign_descriptors(f, fs_pn_function, hs_pn_function,
543 NULL);
544 if (status)
545 goto err;
546
547 /* Incoming USB requests */
548 status = -ENOMEM;
549 for (i = 0; i < phonet_rxq_size; i++) {
550 struct usb_request *req;
551
552 req = usb_ep_alloc_request(fp->out_ep, GFP_KERNEL);
553 if (!req)
554 goto err_req;
555
556 req->complete = pn_rx_complete;
557 fp->out_reqv[i] = req;
558 }
559
560 /* Outgoing USB requests */
561 fp->in_req = usb_ep_alloc_request(fp->in_ep, GFP_KERNEL);
562 if (!fp->in_req)
563 goto err_req;
564
565 INFO(cdev, "USB CDC Phonet function\n");
566 INFO(cdev, "using %s, OUT %s, IN %s\n", cdev->gadget->name,
567 fp->out_ep->name, fp->in_ep->name);
568 return 0;
569
570err_req:
571 for (i = 0; i < phonet_rxq_size && fp->out_reqv[i]; i++)
572 usb_ep_free_request(fp->out_ep, fp->out_reqv[i]);
573err:
574 usb_free_all_descriptors(f);
575 if (fp->out_ep)
576 fp->out_ep->driver_data = NULL;
577 if (fp->in_ep)
578 fp->in_ep->driver_data = NULL;
579 ERROR(cdev, "USB CDC Phonet: cannot autoconfigure\n");
580 return status;
581}
582
583static inline struct f_phonet_opts *to_f_phonet_opts(struct config_item *item)
584{
585 return container_of(to_config_group(item), struct f_phonet_opts,
586 func_inst.group);
587}
588
589CONFIGFS_ATTR_STRUCT(f_phonet_opts);
590static ssize_t f_phonet_attr_show(struct config_item *item,
591 struct configfs_attribute *attr,
592 char *page)
593{
594 struct f_phonet_opts *opts = to_f_phonet_opts(item);
595 struct f_phonet_opts_attribute *f_phonet_opts_attr =
596 container_of(attr, struct f_phonet_opts_attribute, attr);
597 ssize_t ret = 0;
598
599 if (f_phonet_opts_attr->show)
600 ret = f_phonet_opts_attr->show(opts, page);
601 return ret;
602}
603
604static void phonet_attr_release(struct config_item *item)
605{
606 struct f_phonet_opts *opts = to_f_phonet_opts(item);
607
608 usb_put_function_instance(&opts->func_inst);
609}
610
611static struct configfs_item_operations phonet_item_ops = {
612 .release = phonet_attr_release,
613 .show_attribute = f_phonet_attr_show,
614};
615
616static ssize_t f_phonet_ifname_show(struct f_phonet_opts *opts, char *page)
617{
618 return gether_get_ifname(opts->net, page, PAGE_SIZE);
619}
620
621static struct f_phonet_opts_attribute f_phonet_ifname =
622 __CONFIGFS_ATTR_RO(ifname, f_phonet_ifname_show);
623
624static struct configfs_attribute *phonet_attrs[] = {
625 &f_phonet_ifname.attr,
626 NULL,
627};
628
629static struct config_item_type phonet_func_type = {
630 .ct_item_ops = &phonet_item_ops,
631 .ct_attrs = phonet_attrs,
632 .ct_owner = THIS_MODULE,
633};
634
635static void phonet_free_inst(struct usb_function_instance *f)
636{
637 struct f_phonet_opts *opts;
638
639 opts = container_of(f, struct f_phonet_opts, func_inst);
640 if (opts->bound)
641 gphonet_cleanup(opts->net);
642 else
643 free_netdev(opts->net);
644 kfree(opts);
645}
646
647static struct usb_function_instance *phonet_alloc_inst(void)
648{
649 struct f_phonet_opts *opts;
650
651 opts = kzalloc(sizeof(*opts), GFP_KERNEL);
652 if (!opts)
653 return ERR_PTR(-ENOMEM);
654
655 opts->func_inst.free_func_inst = phonet_free_inst;
656 opts->net = gphonet_setup_default();
657 if (IS_ERR(opts->net)) {
658 struct net_device *net = opts->net;
659 kfree(opts);
660 return ERR_CAST(net);
661 }
662
663 config_group_init_type_name(&opts->func_inst.group, "",
664 &phonet_func_type);
665
666 return &opts->func_inst;
667}
668
669static void phonet_free(struct usb_function *f)
670{
671 struct f_phonet *phonet;
672
673 phonet = func_to_pn(f);
674 kfree(phonet);
675}
676
677static void pn_unbind(struct usb_configuration *c, struct usb_function *f)
678{
679 struct f_phonet *fp = func_to_pn(f);
680 int i;
681
682 /* We are already disconnected */
683 if (fp->in_req)
684 usb_ep_free_request(fp->in_ep, fp->in_req);
685 for (i = 0; i < phonet_rxq_size; i++)
686 if (fp->out_reqv[i])
687 usb_ep_free_request(fp->out_ep, fp->out_reqv[i]);
688
689 usb_free_all_descriptors(f);
690}
691
692static struct usb_function *phonet_alloc(struct usb_function_instance *fi)
693{
694 struct f_phonet *fp;
695 struct f_phonet_opts *opts;
696 int size;
697
698 size = sizeof(*fp) + (phonet_rxq_size * sizeof(struct usb_request *));
699 fp = kzalloc(size, GFP_KERNEL);
700 if (!fp)
701 return ERR_PTR(-ENOMEM);
702
703 opts = container_of(fi, struct f_phonet_opts, func_inst);
704
705 fp->dev = opts->net;
706 fp->function.name = "phonet";
707 fp->function.bind = pn_bind;
708 fp->function.unbind = pn_unbind;
709 fp->function.set_alt = pn_set_alt;
710 fp->function.get_alt = pn_get_alt;
711 fp->function.disable = pn_disconnect;
712 fp->function.free_func = phonet_free;
713 spin_lock_init(&fp->rx.lock);
714
715 return &fp->function;
716}
717
718struct net_device *gphonet_setup_default(void)
719{
720 struct net_device *dev;
721 struct phonet_port *port;
722
723 /* Create net device */
724 dev = alloc_netdev(sizeof(*port), "upnlink%d", pn_net_setup);
725 if (!dev)
726 return ERR_PTR(-ENOMEM);
727
728 port = netdev_priv(dev);
729 spin_lock_init(&port->lock);
730 netif_carrier_off(dev);
731
732 return dev;
733}
734
735void gphonet_set_gadget(struct net_device *net, struct usb_gadget *g)
736{
737 SET_NETDEV_DEV(net, &g->dev);
738}
739
740int gphonet_register_netdev(struct net_device *net)
741{
742 int status;
743
744 status = register_netdev(net);
745 if (status)
746 free_netdev(net);
747
748 return status;
749}
750
751void gphonet_cleanup(struct net_device *dev)
752{
753 unregister_netdev(dev);
754}
755
756DECLARE_USB_FUNCTION_INIT(phonet, phonet_alloc_inst, phonet_alloc);
757MODULE_AUTHOR("Rémi Denis-Courmont");
758MODULE_LICENSE("GPL");
diff --git a/drivers/usb/gadget/function/f_rndis.c b/drivers/usb/gadget/function/f_rndis.c
new file mode 100644
index 000000000000..ddb09dc6d1f2
--- /dev/null
+++ b/drivers/usb/gadget/function/f_rndis.c
@@ -0,0 +1,1035 @@
1/*
2 * f_rndis.c -- RNDIS link function driver
3 *
4 * Copyright (C) 2003-2005,2008 David Brownell
5 * Copyright (C) 2003-2004 Robert Schwebel, Benedikt Spranger
6 * Copyright (C) 2008 Nokia Corporation
7 * Copyright (C) 2009 Samsung Electronics
8 * Author: Michal Nazarewicz (mina86@mina86.com)
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 */
15
16/* #define VERBOSE_DEBUG */
17
18#include <linux/slab.h>
19#include <linux/kernel.h>
20#include <linux/module.h>
21#include <linux/device.h>
22#include <linux/etherdevice.h>
23
24#include <linux/atomic.h>
25
26#include "u_ether.h"
27#include "u_ether_configfs.h"
28#include "u_rndis.h"
29#include "rndis.h"
30#include "configfs.h"
31
32/*
33 * This function is an RNDIS Ethernet port -- a Microsoft protocol that's
34 * been promoted instead of the standard CDC Ethernet. The published RNDIS
35 * spec is ambiguous, incomplete, and needlessly complex. Variants such as
36 * ActiveSync have even worse status in terms of specification.
37 *
38 * In short: it's a protocol controlled by (and for) Microsoft, not for an
39 * Open ecosystem or markets. Linux supports it *only* because Microsoft
40 * doesn't support the CDC Ethernet standard.
41 *
42 * The RNDIS data transfer model is complex, with multiple Ethernet packets
43 * per USB message, and out of band data. The control model is built around
44 * what's essentially an "RNDIS RPC" protocol. It's all wrapped in a CDC ACM
45 * (modem, not Ethernet) veneer, with those ACM descriptors being entirely
46 * useless (they're ignored). RNDIS expects to be the only function in its
47 * configuration, so it's no real help if you need composite devices; and
48 * it expects to be the first configuration too.
49 *
50 * There is a single technical advantage of RNDIS over CDC Ethernet, if you
51 * discount the fluff that its RPC can be made to deliver: it doesn't need
52 * a NOP altsetting for the data interface. That lets it work on some of the
53 * "so smart it's stupid" hardware which takes over configuration changes
54 * from the software, and adds restrictions like "no altsettings".
55 *
56 * Unfortunately MSFT's RNDIS drivers are buggy. They hang or oops, and
57 * have all sorts of contrary-to-specification oddities that can prevent
58 * them from working sanely. Since bugfixes (or accurate specs, letting
59 * Linux work around those bugs) are unlikely to ever come from MSFT, you
60 * may want to avoid using RNDIS on purely operational grounds.
61 *
62 * Omissions from the RNDIS 1.0 specification include:
63 *
64 * - Power management ... references data that's scattered around lots
65 * of other documentation, which is incorrect/incomplete there too.
66 *
67 * - There are various undocumented protocol requirements, like the need
68 * to send garbage in some control-OUT messages.
69 *
70 * - MS-Windows drivers sometimes emit undocumented requests.
71 */
72
73struct f_rndis {
74 struct gether port;
75 u8 ctrl_id, data_id;
76 u8 ethaddr[ETH_ALEN];
77 u32 vendorID;
78 const char *manufacturer;
79 int config;
80
81 struct usb_ep *notify;
82 struct usb_request *notify_req;
83 atomic_t notify_count;
84};
85
86static inline struct f_rndis *func_to_rndis(struct usb_function *f)
87{
88 return container_of(f, struct f_rndis, port.func);
89}
90
91/* peak (theoretical) bulk transfer rate in bits-per-second */
92static unsigned int bitrate(struct usb_gadget *g)
93{
94 if (gadget_is_superspeed(g) && g->speed == USB_SPEED_SUPER)
95 return 13 * 1024 * 8 * 1000 * 8;
96 else if (gadget_is_dualspeed(g) && g->speed == USB_SPEED_HIGH)
97 return 13 * 512 * 8 * 1000 * 8;
98 else
99 return 19 * 64 * 1 * 1000 * 8;
100}
101
102/*-------------------------------------------------------------------------*/
103
104/*
105 */
106
107#define RNDIS_STATUS_INTERVAL_MS 32
108#define STATUS_BYTECOUNT 8 /* 8 bytes data */
109
110
111/* interface descriptor: */
112
113static struct usb_interface_descriptor rndis_control_intf = {
114 .bLength = sizeof rndis_control_intf,
115 .bDescriptorType = USB_DT_INTERFACE,
116
117 /* .bInterfaceNumber = DYNAMIC */
118 /* status endpoint is optional; this could be patched later */
119 .bNumEndpoints = 1,
120 .bInterfaceClass = USB_CLASS_COMM,
121 .bInterfaceSubClass = USB_CDC_SUBCLASS_ACM,
122 .bInterfaceProtocol = USB_CDC_ACM_PROTO_VENDOR,
123 /* .iInterface = DYNAMIC */
124};
125
126static struct usb_cdc_header_desc header_desc = {
127 .bLength = sizeof header_desc,
128 .bDescriptorType = USB_DT_CS_INTERFACE,
129 .bDescriptorSubType = USB_CDC_HEADER_TYPE,
130
131 .bcdCDC = cpu_to_le16(0x0110),
132};
133
134static struct usb_cdc_call_mgmt_descriptor call_mgmt_descriptor = {
135 .bLength = sizeof call_mgmt_descriptor,
136 .bDescriptorType = USB_DT_CS_INTERFACE,
137 .bDescriptorSubType = USB_CDC_CALL_MANAGEMENT_TYPE,
138
139 .bmCapabilities = 0x00,
140 .bDataInterface = 0x01,
141};
142
143static struct usb_cdc_acm_descriptor rndis_acm_descriptor = {
144 .bLength = sizeof rndis_acm_descriptor,
145 .bDescriptorType = USB_DT_CS_INTERFACE,
146 .bDescriptorSubType = USB_CDC_ACM_TYPE,
147
148 .bmCapabilities = 0x00,
149};
150
151static struct usb_cdc_union_desc rndis_union_desc = {
152 .bLength = sizeof(rndis_union_desc),
153 .bDescriptorType = USB_DT_CS_INTERFACE,
154 .bDescriptorSubType = USB_CDC_UNION_TYPE,
155 /* .bMasterInterface0 = DYNAMIC */
156 /* .bSlaveInterface0 = DYNAMIC */
157};
158
159/* the data interface has two bulk endpoints */
160
161static struct usb_interface_descriptor rndis_data_intf = {
162 .bLength = sizeof rndis_data_intf,
163 .bDescriptorType = USB_DT_INTERFACE,
164
165 /* .bInterfaceNumber = DYNAMIC */
166 .bNumEndpoints = 2,
167 .bInterfaceClass = USB_CLASS_CDC_DATA,
168 .bInterfaceSubClass = 0,
169 .bInterfaceProtocol = 0,
170 /* .iInterface = DYNAMIC */
171};
172
173
174static struct usb_interface_assoc_descriptor
175rndis_iad_descriptor = {
176 .bLength = sizeof rndis_iad_descriptor,
177 .bDescriptorType = USB_DT_INTERFACE_ASSOCIATION,
178
179 .bFirstInterface = 0, /* XXX, hardcoded */
180 .bInterfaceCount = 2, // control + data
181 .bFunctionClass = USB_CLASS_COMM,
182 .bFunctionSubClass = USB_CDC_SUBCLASS_ETHERNET,
183 .bFunctionProtocol = USB_CDC_PROTO_NONE,
184 /* .iFunction = DYNAMIC */
185};
186
187/* full speed support: */
188
189static struct usb_endpoint_descriptor fs_notify_desc = {
190 .bLength = USB_DT_ENDPOINT_SIZE,
191 .bDescriptorType = USB_DT_ENDPOINT,
192
193 .bEndpointAddress = USB_DIR_IN,
194 .bmAttributes = USB_ENDPOINT_XFER_INT,
195 .wMaxPacketSize = cpu_to_le16(STATUS_BYTECOUNT),
196 .bInterval = RNDIS_STATUS_INTERVAL_MS,
197};
198
199static struct usb_endpoint_descriptor fs_in_desc = {
200 .bLength = USB_DT_ENDPOINT_SIZE,
201 .bDescriptorType = USB_DT_ENDPOINT,
202
203 .bEndpointAddress = USB_DIR_IN,
204 .bmAttributes = USB_ENDPOINT_XFER_BULK,
205};
206
207static struct usb_endpoint_descriptor fs_out_desc = {
208 .bLength = USB_DT_ENDPOINT_SIZE,
209 .bDescriptorType = USB_DT_ENDPOINT,
210
211 .bEndpointAddress = USB_DIR_OUT,
212 .bmAttributes = USB_ENDPOINT_XFER_BULK,
213};
214
215static struct usb_descriptor_header *eth_fs_function[] = {
216 (struct usb_descriptor_header *) &rndis_iad_descriptor,
217
218 /* control interface matches ACM, not Ethernet */
219 (struct usb_descriptor_header *) &rndis_control_intf,
220 (struct usb_descriptor_header *) &header_desc,
221 (struct usb_descriptor_header *) &call_mgmt_descriptor,
222 (struct usb_descriptor_header *) &rndis_acm_descriptor,
223 (struct usb_descriptor_header *) &rndis_union_desc,
224 (struct usb_descriptor_header *) &fs_notify_desc,
225
226 /* data interface has no altsetting */
227 (struct usb_descriptor_header *) &rndis_data_intf,
228 (struct usb_descriptor_header *) &fs_in_desc,
229 (struct usb_descriptor_header *) &fs_out_desc,
230 NULL,
231};
232
233/* high speed support: */
234
235static struct usb_endpoint_descriptor hs_notify_desc = {
236 .bLength = USB_DT_ENDPOINT_SIZE,
237 .bDescriptorType = USB_DT_ENDPOINT,
238
239 .bEndpointAddress = USB_DIR_IN,
240 .bmAttributes = USB_ENDPOINT_XFER_INT,
241 .wMaxPacketSize = cpu_to_le16(STATUS_BYTECOUNT),
242 .bInterval = USB_MS_TO_HS_INTERVAL(RNDIS_STATUS_INTERVAL_MS)
243};
244
245static struct usb_endpoint_descriptor hs_in_desc = {
246 .bLength = USB_DT_ENDPOINT_SIZE,
247 .bDescriptorType = USB_DT_ENDPOINT,
248
249 .bEndpointAddress = USB_DIR_IN,
250 .bmAttributes = USB_ENDPOINT_XFER_BULK,
251 .wMaxPacketSize = cpu_to_le16(512),
252};
253
254static struct usb_endpoint_descriptor hs_out_desc = {
255 .bLength = USB_DT_ENDPOINT_SIZE,
256 .bDescriptorType = USB_DT_ENDPOINT,
257
258 .bEndpointAddress = USB_DIR_OUT,
259 .bmAttributes = USB_ENDPOINT_XFER_BULK,
260 .wMaxPacketSize = cpu_to_le16(512),
261};
262
263static struct usb_descriptor_header *eth_hs_function[] = {
264 (struct usb_descriptor_header *) &rndis_iad_descriptor,
265
266 /* control interface matches ACM, not Ethernet */
267 (struct usb_descriptor_header *) &rndis_control_intf,
268 (struct usb_descriptor_header *) &header_desc,
269 (struct usb_descriptor_header *) &call_mgmt_descriptor,
270 (struct usb_descriptor_header *) &rndis_acm_descriptor,
271 (struct usb_descriptor_header *) &rndis_union_desc,
272 (struct usb_descriptor_header *) &hs_notify_desc,
273
274 /* data interface has no altsetting */
275 (struct usb_descriptor_header *) &rndis_data_intf,
276 (struct usb_descriptor_header *) &hs_in_desc,
277 (struct usb_descriptor_header *) &hs_out_desc,
278 NULL,
279};
280
281/* super speed support: */
282
283static struct usb_endpoint_descriptor ss_notify_desc = {
284 .bLength = USB_DT_ENDPOINT_SIZE,
285 .bDescriptorType = USB_DT_ENDPOINT,
286
287 .bEndpointAddress = USB_DIR_IN,
288 .bmAttributes = USB_ENDPOINT_XFER_INT,
289 .wMaxPacketSize = cpu_to_le16(STATUS_BYTECOUNT),
290 .bInterval = USB_MS_TO_HS_INTERVAL(RNDIS_STATUS_INTERVAL_MS)
291};
292
293static struct usb_ss_ep_comp_descriptor ss_intr_comp_desc = {
294 .bLength = sizeof ss_intr_comp_desc,
295 .bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
296
297 /* the following 3 values can be tweaked if necessary */
298 /* .bMaxBurst = 0, */
299 /* .bmAttributes = 0, */
300 .wBytesPerInterval = cpu_to_le16(STATUS_BYTECOUNT),
301};
302
303static struct usb_endpoint_descriptor ss_in_desc = {
304 .bLength = USB_DT_ENDPOINT_SIZE,
305 .bDescriptorType = USB_DT_ENDPOINT,
306
307 .bEndpointAddress = USB_DIR_IN,
308 .bmAttributes = USB_ENDPOINT_XFER_BULK,
309 .wMaxPacketSize = cpu_to_le16(1024),
310};
311
312static struct usb_endpoint_descriptor ss_out_desc = {
313 .bLength = USB_DT_ENDPOINT_SIZE,
314 .bDescriptorType = USB_DT_ENDPOINT,
315
316 .bEndpointAddress = USB_DIR_OUT,
317 .bmAttributes = USB_ENDPOINT_XFER_BULK,
318 .wMaxPacketSize = cpu_to_le16(1024),
319};
320
321static struct usb_ss_ep_comp_descriptor ss_bulk_comp_desc = {
322 .bLength = sizeof ss_bulk_comp_desc,
323 .bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
324
325 /* the following 2 values can be tweaked if necessary */
326 /* .bMaxBurst = 0, */
327 /* .bmAttributes = 0, */
328};
329
330static struct usb_descriptor_header *eth_ss_function[] = {
331 (struct usb_descriptor_header *) &rndis_iad_descriptor,
332
333 /* control interface matches ACM, not Ethernet */
334 (struct usb_descriptor_header *) &rndis_control_intf,
335 (struct usb_descriptor_header *) &header_desc,
336 (struct usb_descriptor_header *) &call_mgmt_descriptor,
337 (struct usb_descriptor_header *) &rndis_acm_descriptor,
338 (struct usb_descriptor_header *) &rndis_union_desc,
339 (struct usb_descriptor_header *) &ss_notify_desc,
340 (struct usb_descriptor_header *) &ss_intr_comp_desc,
341
342 /* data interface has no altsetting */
343 (struct usb_descriptor_header *) &rndis_data_intf,
344 (struct usb_descriptor_header *) &ss_in_desc,
345 (struct usb_descriptor_header *) &ss_bulk_comp_desc,
346 (struct usb_descriptor_header *) &ss_out_desc,
347 (struct usb_descriptor_header *) &ss_bulk_comp_desc,
348 NULL,
349};
350
351/* string descriptors: */
352
353static struct usb_string rndis_string_defs[] = {
354 [0].s = "RNDIS Communications Control",
355 [1].s = "RNDIS Ethernet Data",
356 [2].s = "RNDIS",
357 { } /* end of list */
358};
359
360static struct usb_gadget_strings rndis_string_table = {
361 .language = 0x0409, /* en-us */
362 .strings = rndis_string_defs,
363};
364
365static struct usb_gadget_strings *rndis_strings[] = {
366 &rndis_string_table,
367 NULL,
368};
369
370/*-------------------------------------------------------------------------*/
371
372static struct sk_buff *rndis_add_header(struct gether *port,
373 struct sk_buff *skb)
374{
375 struct sk_buff *skb2;
376
377 skb2 = skb_realloc_headroom(skb, sizeof(struct rndis_packet_msg_type));
378 if (skb2)
379 rndis_add_hdr(skb2);
380
381 dev_kfree_skb(skb);
382 return skb2;
383}
384
385static void rndis_response_available(void *_rndis)
386{
387 struct f_rndis *rndis = _rndis;
388 struct usb_request *req = rndis->notify_req;
389 struct usb_composite_dev *cdev = rndis->port.func.config->cdev;
390 __le32 *data = req->buf;
391 int status;
392
393 if (atomic_inc_return(&rndis->notify_count) != 1)
394 return;
395
396 /* Send RNDIS RESPONSE_AVAILABLE notification; a
397 * USB_CDC_NOTIFY_RESPONSE_AVAILABLE "should" work too
398 *
399 * This is the only notification defined by RNDIS.
400 */
401 data[0] = cpu_to_le32(1);
402 data[1] = cpu_to_le32(0);
403
404 status = usb_ep_queue(rndis->notify, req, GFP_ATOMIC);
405 if (status) {
406 atomic_dec(&rndis->notify_count);
407 DBG(cdev, "notify/0 --> %d\n", status);
408 }
409}
410
411static void rndis_response_complete(struct usb_ep *ep, struct usb_request *req)
412{
413 struct f_rndis *rndis = req->context;
414 struct usb_composite_dev *cdev = rndis->port.func.config->cdev;
415 int status = req->status;
416
417 /* after TX:
418 * - USB_CDC_GET_ENCAPSULATED_RESPONSE (ep0/control)
419 * - RNDIS_RESPONSE_AVAILABLE (status/irq)
420 */
421 switch (status) {
422 case -ECONNRESET:
423 case -ESHUTDOWN:
424 /* connection gone */
425 atomic_set(&rndis->notify_count, 0);
426 break;
427 default:
428 DBG(cdev, "RNDIS %s response error %d, %d/%d\n",
429 ep->name, status,
430 req->actual, req->length);
431 /* FALLTHROUGH */
432 case 0:
433 if (ep != rndis->notify)
434 break;
435
436 /* handle multiple pending RNDIS_RESPONSE_AVAILABLE
437 * notifications by resending until we're done
438 */
439 if (atomic_dec_and_test(&rndis->notify_count))
440 break;
441 status = usb_ep_queue(rndis->notify, req, GFP_ATOMIC);
442 if (status) {
443 atomic_dec(&rndis->notify_count);
444 DBG(cdev, "notify/1 --> %d\n", status);
445 }
446 break;
447 }
448}
449
450static void rndis_command_complete(struct usb_ep *ep, struct usb_request *req)
451{
452 struct f_rndis *rndis = req->context;
453 int status;
454
455 /* received RNDIS command from USB_CDC_SEND_ENCAPSULATED_COMMAND */
456// spin_lock(&dev->lock);
457 status = rndis_msg_parser(rndis->config, (u8 *) req->buf);
458 if (status < 0)
459 pr_err("RNDIS command error %d, %d/%d\n",
460 status, req->actual, req->length);
461// spin_unlock(&dev->lock);
462}
463
464static int
465rndis_setup(struct usb_function *f, const struct usb_ctrlrequest *ctrl)
466{
467 struct f_rndis *rndis = func_to_rndis(f);
468 struct usb_composite_dev *cdev = f->config->cdev;
469 struct usb_request *req = cdev->req;
470 int value = -EOPNOTSUPP;
471 u16 w_index = le16_to_cpu(ctrl->wIndex);
472 u16 w_value = le16_to_cpu(ctrl->wValue);
473 u16 w_length = le16_to_cpu(ctrl->wLength);
474
475 /* composite driver infrastructure handles everything except
476 * CDC class messages; interface activation uses set_alt().
477 */
478 switch ((ctrl->bRequestType << 8) | ctrl->bRequest) {
479
480 /* RNDIS uses the CDC command encapsulation mechanism to implement
481 * an RPC scheme, with much getting/setting of attributes by OID.
482 */
483 case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
484 | USB_CDC_SEND_ENCAPSULATED_COMMAND:
485 if (w_value || w_index != rndis->ctrl_id)
486 goto invalid;
487 /* read the request; process it later */
488 value = w_length;
489 req->complete = rndis_command_complete;
490 req->context = rndis;
491 /* later, rndis_response_available() sends a notification */
492 break;
493
494 case ((USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
495 | USB_CDC_GET_ENCAPSULATED_RESPONSE:
496 if (w_value || w_index != rndis->ctrl_id)
497 goto invalid;
498 else {
499 u8 *buf;
500 u32 n;
501
502 /* return the result */
503 buf = rndis_get_next_response(rndis->config, &n);
504 if (buf) {
505 memcpy(req->buf, buf, n);
506 req->complete = rndis_response_complete;
507 req->context = rndis;
508 rndis_free_response(rndis->config, buf);
509 value = n;
510 }
511 /* else stalls ... spec says to avoid that */
512 }
513 break;
514
515 default:
516invalid:
517 VDBG(cdev, "invalid control req%02x.%02x v%04x i%04x l%d\n",
518 ctrl->bRequestType, ctrl->bRequest,
519 w_value, w_index, w_length);
520 }
521
522 /* respond with data transfer or status phase? */
523 if (value >= 0) {
524 DBG(cdev, "rndis req%02x.%02x v%04x i%04x l%d\n",
525 ctrl->bRequestType, ctrl->bRequest,
526 w_value, w_index, w_length);
527 req->zero = (value < w_length);
528 req->length = value;
529 value = usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC);
530 if (value < 0)
531 ERROR(cdev, "rndis response on err %d\n", value);
532 }
533
534 /* device either stalls (value < 0) or reports success */
535 return value;
536}
537
538
539static int rndis_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
540{
541 struct f_rndis *rndis = func_to_rndis(f);
542 struct usb_composite_dev *cdev = f->config->cdev;
543
544 /* we know alt == 0 */
545
546 if (intf == rndis->ctrl_id) {
547 if (rndis->notify->driver_data) {
548 VDBG(cdev, "reset rndis control %d\n", intf);
549 usb_ep_disable(rndis->notify);
550 }
551 if (!rndis->notify->desc) {
552 VDBG(cdev, "init rndis ctrl %d\n", intf);
553 if (config_ep_by_speed(cdev->gadget, f, rndis->notify))
554 goto fail;
555 }
556 usb_ep_enable(rndis->notify);
557 rndis->notify->driver_data = rndis;
558
559 } else if (intf == rndis->data_id) {
560 struct net_device *net;
561
562 if (rndis->port.in_ep->driver_data) {
563 DBG(cdev, "reset rndis\n");
564 gether_disconnect(&rndis->port);
565 }
566
567 if (!rndis->port.in_ep->desc || !rndis->port.out_ep->desc) {
568 DBG(cdev, "init rndis\n");
569 if (config_ep_by_speed(cdev->gadget, f,
570 rndis->port.in_ep) ||
571 config_ep_by_speed(cdev->gadget, f,
572 rndis->port.out_ep)) {
573 rndis->port.in_ep->desc = NULL;
574 rndis->port.out_ep->desc = NULL;
575 goto fail;
576 }
577 }
578
579 /* Avoid ZLPs; they can be troublesome. */
580 rndis->port.is_zlp_ok = false;
581
582 /* RNDIS should be in the "RNDIS uninitialized" state,
583 * either never activated or after rndis_uninit().
584 *
585 * We don't want data to flow here until a nonzero packet
586 * filter is set, at which point it enters "RNDIS data
587 * initialized" state ... but we do want the endpoints
588 * to be activated. It's a strange little state.
589 *
590 * REVISIT the RNDIS gadget code has done this wrong for a
591 * very long time. We need another call to the link layer
592 * code -- gether_updown(...bool) maybe -- to do it right.
593 */
594 rndis->port.cdc_filter = 0;
595
596 DBG(cdev, "RNDIS RX/TX early activation ... \n");
597 net = gether_connect(&rndis->port);
598 if (IS_ERR(net))
599 return PTR_ERR(net);
600
601 rndis_set_param_dev(rndis->config, net,
602 &rndis->port.cdc_filter);
603 } else
604 goto fail;
605
606 return 0;
607fail:
608 return -EINVAL;
609}
610
611static void rndis_disable(struct usb_function *f)
612{
613 struct f_rndis *rndis = func_to_rndis(f);
614 struct usb_composite_dev *cdev = f->config->cdev;
615
616 if (!rndis->notify->driver_data)
617 return;
618
619 DBG(cdev, "rndis deactivated\n");
620
621 rndis_uninit(rndis->config);
622 gether_disconnect(&rndis->port);
623
624 usb_ep_disable(rndis->notify);
625 rndis->notify->driver_data = NULL;
626}
627
628/*-------------------------------------------------------------------------*/
629
630/*
631 * This isn't quite the same mechanism as CDC Ethernet, since the
632 * notification scheme passes less data, but the same set of link
633 * states must be tested. A key difference is that altsettings are
634 * not used to tell whether the link should send packets or not.
635 */
636
637static void rndis_open(struct gether *geth)
638{
639 struct f_rndis *rndis = func_to_rndis(&geth->func);
640 struct usb_composite_dev *cdev = geth->func.config->cdev;
641
642 DBG(cdev, "%s\n", __func__);
643
644 rndis_set_param_medium(rndis->config, RNDIS_MEDIUM_802_3,
645 bitrate(cdev->gadget) / 100);
646 rndis_signal_connect(rndis->config);
647}
648
649static void rndis_close(struct gether *geth)
650{
651 struct f_rndis *rndis = func_to_rndis(&geth->func);
652
653 DBG(geth->func.config->cdev, "%s\n", __func__);
654
655 rndis_set_param_medium(rndis->config, RNDIS_MEDIUM_802_3, 0);
656 rndis_signal_disconnect(rndis->config);
657}
658
659/*-------------------------------------------------------------------------*/
660
661/* Some controllers can't support RNDIS ... */
662static inline bool can_support_rndis(struct usb_configuration *c)
663{
664 /* everything else is *presumably* fine */
665 return true;
666}
667
668/* ethernet function driver setup/binding */
669
670static int
671rndis_bind(struct usb_configuration *c, struct usb_function *f)
672{
673 struct usb_composite_dev *cdev = c->cdev;
674 struct f_rndis *rndis = func_to_rndis(f);
675 struct usb_string *us;
676 int status;
677 struct usb_ep *ep;
678
679 struct f_rndis_opts *rndis_opts;
680
681 if (!can_support_rndis(c))
682 return -EINVAL;
683
684 rndis_opts = container_of(f->fi, struct f_rndis_opts, func_inst);
685
686 if (cdev->use_os_string) {
687 f->os_desc_table = kzalloc(sizeof(*f->os_desc_table),
688 GFP_KERNEL);
689 if (!f->os_desc_table)
690 return -ENOMEM;
691 f->os_desc_n = 1;
692 f->os_desc_table[0].os_desc = &rndis_opts->rndis_os_desc;
693 }
694
695 /*
696 * in drivers/usb/gadget/configfs.c:configfs_composite_bind()
697 * configurations are bound in sequence with list_for_each_entry,
698 * in each configuration its functions are bound in sequence
699 * with list_for_each_entry, so we assume no race condition
700 * with regard to rndis_opts->bound access
701 */
702 if (!rndis_opts->bound) {
703 gether_set_gadget(rndis_opts->net, cdev->gadget);
704 status = gether_register_netdev(rndis_opts->net);
705 if (status)
706 goto fail;
707 rndis_opts->bound = true;
708 }
709
710 us = usb_gstrings_attach(cdev, rndis_strings,
711 ARRAY_SIZE(rndis_string_defs));
712 if (IS_ERR(us)) {
713 status = PTR_ERR(us);
714 goto fail;
715 }
716 rndis_control_intf.iInterface = us[0].id;
717 rndis_data_intf.iInterface = us[1].id;
718 rndis_iad_descriptor.iFunction = us[2].id;
719
720 /* allocate instance-specific interface IDs */
721 status = usb_interface_id(c, f);
722 if (status < 0)
723 goto fail;
724 rndis->ctrl_id = status;
725 rndis_iad_descriptor.bFirstInterface = status;
726
727 rndis_control_intf.bInterfaceNumber = status;
728 rndis_union_desc.bMasterInterface0 = status;
729
730 if (cdev->use_os_string)
731 f->os_desc_table[0].if_id =
732 rndis_iad_descriptor.bFirstInterface;
733
734 status = usb_interface_id(c, f);
735 if (status < 0)
736 goto fail;
737 rndis->data_id = status;
738
739 rndis_data_intf.bInterfaceNumber = status;
740 rndis_union_desc.bSlaveInterface0 = status;
741
742 status = -ENODEV;
743
744 /* allocate instance-specific endpoints */
745 ep = usb_ep_autoconfig(cdev->gadget, &fs_in_desc);
746 if (!ep)
747 goto fail;
748 rndis->port.in_ep = ep;
749 ep->driver_data = cdev; /* claim */
750
751 ep = usb_ep_autoconfig(cdev->gadget, &fs_out_desc);
752 if (!ep)
753 goto fail;
754 rndis->port.out_ep = ep;
755 ep->driver_data = cdev; /* claim */
756
757 /* NOTE: a status/notification endpoint is, strictly speaking,
758 * optional. We don't treat it that way though! It's simpler,
759 * and some newer profiles don't treat it as optional.
760 */
761 ep = usb_ep_autoconfig(cdev->gadget, &fs_notify_desc);
762 if (!ep)
763 goto fail;
764 rndis->notify = ep;
765 ep->driver_data = cdev; /* claim */
766
767 status = -ENOMEM;
768
769 /* allocate notification request and buffer */
770 rndis->notify_req = usb_ep_alloc_request(ep, GFP_KERNEL);
771 if (!rndis->notify_req)
772 goto fail;
773 rndis->notify_req->buf = kmalloc(STATUS_BYTECOUNT, GFP_KERNEL);
774 if (!rndis->notify_req->buf)
775 goto fail;
776 rndis->notify_req->length = STATUS_BYTECOUNT;
777 rndis->notify_req->context = rndis;
778 rndis->notify_req->complete = rndis_response_complete;
779
780 /* support all relevant hardware speeds... we expect that when
781 * hardware is dual speed, all bulk-capable endpoints work at
782 * both speeds
783 */
784 hs_in_desc.bEndpointAddress = fs_in_desc.bEndpointAddress;
785 hs_out_desc.bEndpointAddress = fs_out_desc.bEndpointAddress;
786 hs_notify_desc.bEndpointAddress = fs_notify_desc.bEndpointAddress;
787
788 ss_in_desc.bEndpointAddress = fs_in_desc.bEndpointAddress;
789 ss_out_desc.bEndpointAddress = fs_out_desc.bEndpointAddress;
790 ss_notify_desc.bEndpointAddress = fs_notify_desc.bEndpointAddress;
791
792 status = usb_assign_descriptors(f, eth_fs_function, eth_hs_function,
793 eth_ss_function);
794 if (status)
795 goto fail;
796
797 rndis->port.open = rndis_open;
798 rndis->port.close = rndis_close;
799
800 rndis_set_param_medium(rndis->config, RNDIS_MEDIUM_802_3, 0);
801 rndis_set_host_mac(rndis->config, rndis->ethaddr);
802
803 if (rndis->manufacturer && rndis->vendorID &&
804 rndis_set_param_vendor(rndis->config, rndis->vendorID,
805 rndis->manufacturer))
806 goto fail;
807
808 /* NOTE: all that is done without knowing or caring about
809 * the network link ... which is unavailable to this code
810 * until we're activated via set_alt().
811 */
812
813 DBG(cdev, "RNDIS: %s speed IN/%s OUT/%s NOTIFY/%s\n",
814 gadget_is_superspeed(c->cdev->gadget) ? "super" :
815 gadget_is_dualspeed(c->cdev->gadget) ? "dual" : "full",
816 rndis->port.in_ep->name, rndis->port.out_ep->name,
817 rndis->notify->name);
818 return 0;
819
820fail:
821 kfree(f->os_desc_table);
822 f->os_desc_n = 0;
823 usb_free_all_descriptors(f);
824
825 if (rndis->notify_req) {
826 kfree(rndis->notify_req->buf);
827 usb_ep_free_request(rndis->notify, rndis->notify_req);
828 }
829
830 /* we might as well release our claims on endpoints */
831 if (rndis->notify)
832 rndis->notify->driver_data = NULL;
833 if (rndis->port.out_ep)
834 rndis->port.out_ep->driver_data = NULL;
835 if (rndis->port.in_ep)
836 rndis->port.in_ep->driver_data = NULL;
837
838 ERROR(cdev, "%s: can't bind, err %d\n", f->name, status);
839
840 return status;
841}
842
843void rndis_borrow_net(struct usb_function_instance *f, struct net_device *net)
844{
845 struct f_rndis_opts *opts;
846
847 opts = container_of(f, struct f_rndis_opts, func_inst);
848 if (opts->bound)
849 gether_cleanup(netdev_priv(opts->net));
850 else
851 free_netdev(opts->net);
852 opts->borrowed_net = opts->bound = true;
853 opts->net = net;
854}
855EXPORT_SYMBOL_GPL(rndis_borrow_net);
856
857static inline struct f_rndis_opts *to_f_rndis_opts(struct config_item *item)
858{
859 return container_of(to_config_group(item), struct f_rndis_opts,
860 func_inst.group);
861}
862
863/* f_rndis_item_ops */
864USB_ETHERNET_CONFIGFS_ITEM(rndis);
865
866/* f_rndis_opts_dev_addr */
867USB_ETHERNET_CONFIGFS_ITEM_ATTR_DEV_ADDR(rndis);
868
869/* f_rndis_opts_host_addr */
870USB_ETHERNET_CONFIGFS_ITEM_ATTR_HOST_ADDR(rndis);
871
872/* f_rndis_opts_qmult */
873USB_ETHERNET_CONFIGFS_ITEM_ATTR_QMULT(rndis);
874
875/* f_rndis_opts_ifname */
876USB_ETHERNET_CONFIGFS_ITEM_ATTR_IFNAME(rndis);
877
878static struct configfs_attribute *rndis_attrs[] = {
879 &f_rndis_opts_dev_addr.attr,
880 &f_rndis_opts_host_addr.attr,
881 &f_rndis_opts_qmult.attr,
882 &f_rndis_opts_ifname.attr,
883 NULL,
884};
885
886static struct config_item_type rndis_func_type = {
887 .ct_item_ops = &rndis_item_ops,
888 .ct_attrs = rndis_attrs,
889 .ct_owner = THIS_MODULE,
890};
891
892static void rndis_free_inst(struct usb_function_instance *f)
893{
894 struct f_rndis_opts *opts;
895
896 opts = container_of(f, struct f_rndis_opts, func_inst);
897 if (!opts->borrowed_net) {
898 if (opts->bound)
899 gether_cleanup(netdev_priv(opts->net));
900 else
901 free_netdev(opts->net);
902 }
903
904 kfree(opts->rndis_os_desc.group.default_groups); /* single VLA chunk */
905 kfree(opts);
906}
907
908static struct usb_function_instance *rndis_alloc_inst(void)
909{
910 struct f_rndis_opts *opts;
911 struct usb_os_desc *descs[1];
912 char *names[1];
913
914 opts = kzalloc(sizeof(*opts), GFP_KERNEL);
915 if (!opts)
916 return ERR_PTR(-ENOMEM);
917 opts->rndis_os_desc.ext_compat_id = opts->rndis_ext_compat_id;
918
919 mutex_init(&opts->lock);
920 opts->func_inst.free_func_inst = rndis_free_inst;
921 opts->net = gether_setup_default();
922 if (IS_ERR(opts->net)) {
923 struct net_device *net = opts->net;
924 kfree(opts);
925 return ERR_CAST(net);
926 }
927 INIT_LIST_HEAD(&opts->rndis_os_desc.ext_prop);
928
929 descs[0] = &opts->rndis_os_desc;
930 names[0] = "rndis";
931 usb_os_desc_prepare_interf_dir(&opts->func_inst.group, 1, descs,
932 names, THIS_MODULE);
933 config_group_init_type_name(&opts->func_inst.group, "",
934 &rndis_func_type);
935
936 return &opts->func_inst;
937}
938
939static void rndis_free(struct usb_function *f)
940{
941 struct f_rndis *rndis;
942 struct f_rndis_opts *opts;
943
944 rndis = func_to_rndis(f);
945 rndis_deregister(rndis->config);
946 opts = container_of(f->fi, struct f_rndis_opts, func_inst);
947 kfree(rndis);
948 mutex_lock(&opts->lock);
949 opts->refcnt--;
950 mutex_unlock(&opts->lock);
951}
952
953static void rndis_unbind(struct usb_configuration *c, struct usb_function *f)
954{
955 struct f_rndis *rndis = func_to_rndis(f);
956
957 kfree(f->os_desc_table);
958 f->os_desc_n = 0;
959 usb_free_all_descriptors(f);
960
961 kfree(rndis->notify_req->buf);
962 usb_ep_free_request(rndis->notify, rndis->notify_req);
963}
964
965static struct usb_function *rndis_alloc(struct usb_function_instance *fi)
966{
967 struct f_rndis *rndis;
968 struct f_rndis_opts *opts;
969 int status;
970
971 /* allocate and initialize one new instance */
972 rndis = kzalloc(sizeof(*rndis), GFP_KERNEL);
973 if (!rndis)
974 return ERR_PTR(-ENOMEM);
975
976 opts = container_of(fi, struct f_rndis_opts, func_inst);
977 mutex_lock(&opts->lock);
978 opts->refcnt++;
979
980 gether_get_host_addr_u8(opts->net, rndis->ethaddr);
981 rndis->vendorID = opts->vendor_id;
982 rndis->manufacturer = opts->manufacturer;
983
984 rndis->port.ioport = netdev_priv(opts->net);
985 mutex_unlock(&opts->lock);
986 /* RNDIS activates when the host changes this filter */
987 rndis->port.cdc_filter = 0;
988
989 /* RNDIS has special (and complex) framing */
990 rndis->port.header_len = sizeof(struct rndis_packet_msg_type);
991 rndis->port.wrap = rndis_add_header;
992 rndis->port.unwrap = rndis_rm_hdr;
993
994 rndis->port.func.name = "rndis";
995 /* descriptors are per-instance copies */
996 rndis->port.func.bind = rndis_bind;
997 rndis->port.func.unbind = rndis_unbind;
998 rndis->port.func.set_alt = rndis_set_alt;
999 rndis->port.func.setup = rndis_setup;
1000 rndis->port.func.disable = rndis_disable;
1001 rndis->port.func.free_func = rndis_free;
1002
1003 status = rndis_register(rndis_response_available, rndis);
1004 if (status < 0) {
1005 kfree(rndis);
1006 return ERR_PTR(status);
1007 }
1008 rndis->config = status;
1009
1010 return &rndis->port.func;
1011}
1012
1013DECLARE_USB_FUNCTION(rndis, rndis_alloc_inst, rndis_alloc);
1014
1015static int __init rndis_mod_init(void)
1016{
1017 int ret;
1018
1019 ret = rndis_init();
1020 if (ret)
1021 return ret;
1022
1023 return usb_function_register(&rndisusb_func);
1024}
1025module_init(rndis_mod_init);
1026
1027static void __exit rndis_mod_exit(void)
1028{
1029 usb_function_unregister(&rndisusb_func);
1030 rndis_exit();
1031}
1032module_exit(rndis_mod_exit);
1033
1034MODULE_LICENSE("GPL");
1035MODULE_AUTHOR("David Brownell");
diff --git a/drivers/usb/gadget/function/f_serial.c b/drivers/usb/gadget/function/f_serial.c
new file mode 100644
index 000000000000..9ecbcbf36a45
--- /dev/null
+++ b/drivers/usb/gadget/function/f_serial.c
@@ -0,0 +1,385 @@
1/*
2 * f_serial.c - generic USB serial function driver
3 *
4 * Copyright (C) 2003 Al Borchers (alborchers@steinerpoint.com)
5 * Copyright (C) 2008 by David Brownell
6 * Copyright (C) 2008 by Nokia Corporation
7 *
8 * This software is distributed under the terms of the GNU General
9 * Public License ("GPL") as published by the Free Software Foundation,
10 * either version 2 of that License or (at your option) any later version.
11 */
12
13#include <linux/slab.h>
14#include <linux/kernel.h>
15#include <linux/module.h>
16#include <linux/device.h>
17
18#include "u_serial.h"
19#include "gadget_chips.h"
20
21
22/*
23 * This function packages a simple "generic serial" port with no real
24 * control mechanisms, just raw data transfer over two bulk endpoints.
25 *
26 * Because it's not standardized, this isn't as interoperable as the
27 * CDC ACM driver. However, for many purposes it's just as functional
28 * if you can arrange appropriate host side drivers.
29 */
30
31struct f_gser {
32 struct gserial port;
33 u8 data_id;
34 u8 port_num;
35};
36
37static inline struct f_gser *func_to_gser(struct usb_function *f)
38{
39 return container_of(f, struct f_gser, port.func);
40}
41
42/*-------------------------------------------------------------------------*/
43
44/* interface descriptor: */
45
46static struct usb_interface_descriptor gser_interface_desc = {
47 .bLength = USB_DT_INTERFACE_SIZE,
48 .bDescriptorType = USB_DT_INTERFACE,
49 /* .bInterfaceNumber = DYNAMIC */
50 .bNumEndpoints = 2,
51 .bInterfaceClass = USB_CLASS_VENDOR_SPEC,
52 .bInterfaceSubClass = 0,
53 .bInterfaceProtocol = 0,
54 /* .iInterface = DYNAMIC */
55};
56
57/* full speed support: */
58
59static struct usb_endpoint_descriptor gser_fs_in_desc = {
60 .bLength = USB_DT_ENDPOINT_SIZE,
61 .bDescriptorType = USB_DT_ENDPOINT,
62 .bEndpointAddress = USB_DIR_IN,
63 .bmAttributes = USB_ENDPOINT_XFER_BULK,
64};
65
66static struct usb_endpoint_descriptor gser_fs_out_desc = {
67 .bLength = USB_DT_ENDPOINT_SIZE,
68 .bDescriptorType = USB_DT_ENDPOINT,
69 .bEndpointAddress = USB_DIR_OUT,
70 .bmAttributes = USB_ENDPOINT_XFER_BULK,
71};
72
73static struct usb_descriptor_header *gser_fs_function[] = {
74 (struct usb_descriptor_header *) &gser_interface_desc,
75 (struct usb_descriptor_header *) &gser_fs_in_desc,
76 (struct usb_descriptor_header *) &gser_fs_out_desc,
77 NULL,
78};
79
80/* high speed support: */
81
82static struct usb_endpoint_descriptor gser_hs_in_desc = {
83 .bLength = USB_DT_ENDPOINT_SIZE,
84 .bDescriptorType = USB_DT_ENDPOINT,
85 .bmAttributes = USB_ENDPOINT_XFER_BULK,
86 .wMaxPacketSize = cpu_to_le16(512),
87};
88
89static struct usb_endpoint_descriptor gser_hs_out_desc = {
90 .bLength = USB_DT_ENDPOINT_SIZE,
91 .bDescriptorType = USB_DT_ENDPOINT,
92 .bmAttributes = USB_ENDPOINT_XFER_BULK,
93 .wMaxPacketSize = cpu_to_le16(512),
94};
95
96static struct usb_descriptor_header *gser_hs_function[] = {
97 (struct usb_descriptor_header *) &gser_interface_desc,
98 (struct usb_descriptor_header *) &gser_hs_in_desc,
99 (struct usb_descriptor_header *) &gser_hs_out_desc,
100 NULL,
101};
102
103static struct usb_endpoint_descriptor gser_ss_in_desc = {
104 .bLength = USB_DT_ENDPOINT_SIZE,
105 .bDescriptorType = USB_DT_ENDPOINT,
106 .bmAttributes = USB_ENDPOINT_XFER_BULK,
107 .wMaxPacketSize = cpu_to_le16(1024),
108};
109
110static struct usb_endpoint_descriptor gser_ss_out_desc = {
111 .bLength = USB_DT_ENDPOINT_SIZE,
112 .bDescriptorType = USB_DT_ENDPOINT,
113 .bmAttributes = USB_ENDPOINT_XFER_BULK,
114 .wMaxPacketSize = cpu_to_le16(1024),
115};
116
117static struct usb_ss_ep_comp_descriptor gser_ss_bulk_comp_desc = {
118 .bLength = sizeof gser_ss_bulk_comp_desc,
119 .bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
120};
121
122static struct usb_descriptor_header *gser_ss_function[] = {
123 (struct usb_descriptor_header *) &gser_interface_desc,
124 (struct usb_descriptor_header *) &gser_ss_in_desc,
125 (struct usb_descriptor_header *) &gser_ss_bulk_comp_desc,
126 (struct usb_descriptor_header *) &gser_ss_out_desc,
127 (struct usb_descriptor_header *) &gser_ss_bulk_comp_desc,
128 NULL,
129};
130
131/* string descriptors: */
132
133static struct usb_string gser_string_defs[] = {
134 [0].s = "Generic Serial",
135 { } /* end of list */
136};
137
138static struct usb_gadget_strings gser_string_table = {
139 .language = 0x0409, /* en-us */
140 .strings = gser_string_defs,
141};
142
143static struct usb_gadget_strings *gser_strings[] = {
144 &gser_string_table,
145 NULL,
146};
147
148/*-------------------------------------------------------------------------*/
149
150static int gser_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
151{
152 struct f_gser *gser = func_to_gser(f);
153 struct usb_composite_dev *cdev = f->config->cdev;
154
155 /* we know alt == 0, so this is an activation or a reset */
156
157 if (gser->port.in->driver_data) {
158 DBG(cdev, "reset generic ttyGS%d\n", gser->port_num);
159 gserial_disconnect(&gser->port);
160 }
161 if (!gser->port.in->desc || !gser->port.out->desc) {
162 DBG(cdev, "activate generic ttyGS%d\n", gser->port_num);
163 if (config_ep_by_speed(cdev->gadget, f, gser->port.in) ||
164 config_ep_by_speed(cdev->gadget, f, gser->port.out)) {
165 gser->port.in->desc = NULL;
166 gser->port.out->desc = NULL;
167 return -EINVAL;
168 }
169 }
170 gserial_connect(&gser->port, gser->port_num);
171 return 0;
172}
173
174static void gser_disable(struct usb_function *f)
175{
176 struct f_gser *gser = func_to_gser(f);
177 struct usb_composite_dev *cdev = f->config->cdev;
178
179 DBG(cdev, "generic ttyGS%d deactivated\n", gser->port_num);
180 gserial_disconnect(&gser->port);
181}
182
183/*-------------------------------------------------------------------------*/
184
185/* serial function driver setup/binding */
186
187static int gser_bind(struct usb_configuration *c, struct usb_function *f)
188{
189 struct usb_composite_dev *cdev = c->cdev;
190 struct f_gser *gser = func_to_gser(f);
191 int status;
192 struct usb_ep *ep;
193
194 /* REVISIT might want instance-specific strings to help
195 * distinguish instances ...
196 */
197
198 /* maybe allocate device-global string ID */
199 if (gser_string_defs[0].id == 0) {
200 status = usb_string_id(c->cdev);
201 if (status < 0)
202 return status;
203 gser_string_defs[0].id = status;
204 }
205
206 /* allocate instance-specific interface IDs */
207 status = usb_interface_id(c, f);
208 if (status < 0)
209 goto fail;
210 gser->data_id = status;
211 gser_interface_desc.bInterfaceNumber = status;
212
213 status = -ENODEV;
214
215 /* allocate instance-specific endpoints */
216 ep = usb_ep_autoconfig(cdev->gadget, &gser_fs_in_desc);
217 if (!ep)
218 goto fail;
219 gser->port.in = ep;
220 ep->driver_data = cdev; /* claim */
221
222 ep = usb_ep_autoconfig(cdev->gadget, &gser_fs_out_desc);
223 if (!ep)
224 goto fail;
225 gser->port.out = ep;
226 ep->driver_data = cdev; /* claim */
227
228 /* support all relevant hardware speeds... we expect that when
229 * hardware is dual speed, all bulk-capable endpoints work at
230 * both speeds
231 */
232 gser_hs_in_desc.bEndpointAddress = gser_fs_in_desc.bEndpointAddress;
233 gser_hs_out_desc.bEndpointAddress = gser_fs_out_desc.bEndpointAddress;
234
235 gser_ss_in_desc.bEndpointAddress = gser_fs_in_desc.bEndpointAddress;
236 gser_ss_out_desc.bEndpointAddress = gser_fs_out_desc.bEndpointAddress;
237
238 status = usb_assign_descriptors(f, gser_fs_function, gser_hs_function,
239 gser_ss_function);
240 if (status)
241 goto fail;
242 DBG(cdev, "generic ttyGS%d: %s speed IN/%s OUT/%s\n",
243 gser->port_num,
244 gadget_is_superspeed(c->cdev->gadget) ? "super" :
245 gadget_is_dualspeed(c->cdev->gadget) ? "dual" : "full",
246 gser->port.in->name, gser->port.out->name);
247 return 0;
248
249fail:
250 /* we might as well release our claims on endpoints */
251 if (gser->port.out)
252 gser->port.out->driver_data = NULL;
253 if (gser->port.in)
254 gser->port.in->driver_data = NULL;
255
256 ERROR(cdev, "%s: can't bind, err %d\n", f->name, status);
257
258 return status;
259}
260
261static inline struct f_serial_opts *to_f_serial_opts(struct config_item *item)
262{
263 return container_of(to_config_group(item), struct f_serial_opts,
264 func_inst.group);
265}
266
267CONFIGFS_ATTR_STRUCT(f_serial_opts);
268static ssize_t f_serial_attr_show(struct config_item *item,
269 struct configfs_attribute *attr,
270 char *page)
271{
272 struct f_serial_opts *opts = to_f_serial_opts(item);
273 struct f_serial_opts_attribute *f_serial_opts_attr =
274 container_of(attr, struct f_serial_opts_attribute, attr);
275 ssize_t ret = 0;
276
277 if (f_serial_opts_attr->show)
278 ret = f_serial_opts_attr->show(opts, page);
279
280 return ret;
281}
282
283static void serial_attr_release(struct config_item *item)
284{
285 struct f_serial_opts *opts = to_f_serial_opts(item);
286
287 usb_put_function_instance(&opts->func_inst);
288}
289
290static struct configfs_item_operations serial_item_ops = {
291 .release = serial_attr_release,
292 .show_attribute = f_serial_attr_show,
293};
294
295static ssize_t f_serial_port_num_show(struct f_serial_opts *opts, char *page)
296{
297 return sprintf(page, "%u\n", opts->port_num);
298}
299
300static struct f_serial_opts_attribute f_serial_port_num =
301 __CONFIGFS_ATTR_RO(port_num, f_serial_port_num_show);
302
303static struct configfs_attribute *acm_attrs[] = {
304 &f_serial_port_num.attr,
305 NULL,
306};
307
308static struct config_item_type serial_func_type = {
309 .ct_item_ops = &serial_item_ops,
310 .ct_attrs = acm_attrs,
311 .ct_owner = THIS_MODULE,
312};
313
314static void gser_free_inst(struct usb_function_instance *f)
315{
316 struct f_serial_opts *opts;
317
318 opts = container_of(f, struct f_serial_opts, func_inst);
319 gserial_free_line(opts->port_num);
320 kfree(opts);
321}
322
323static struct usb_function_instance *gser_alloc_inst(void)
324{
325 struct f_serial_opts *opts;
326 int ret;
327
328 opts = kzalloc(sizeof(*opts), GFP_KERNEL);
329 if (!opts)
330 return ERR_PTR(-ENOMEM);
331
332 opts->func_inst.free_func_inst = gser_free_inst;
333 ret = gserial_alloc_line(&opts->port_num);
334 if (ret) {
335 kfree(opts);
336 return ERR_PTR(ret);
337 }
338 config_group_init_type_name(&opts->func_inst.group, "",
339 &serial_func_type);
340
341 return &opts->func_inst;
342}
343
344static void gser_free(struct usb_function *f)
345{
346 struct f_gser *serial;
347
348 serial = func_to_gser(f);
349 kfree(serial);
350}
351
352static void gser_unbind(struct usb_configuration *c, struct usb_function *f)
353{
354 usb_free_all_descriptors(f);
355}
356
357static struct usb_function *gser_alloc(struct usb_function_instance *fi)
358{
359 struct f_gser *gser;
360 struct f_serial_opts *opts;
361
362 /* allocate and initialize one new instance */
363 gser = kzalloc(sizeof(*gser), GFP_KERNEL);
364 if (!gser)
365 return ERR_PTR(-ENOMEM);
366
367 opts = container_of(fi, struct f_serial_opts, func_inst);
368
369 gser->port_num = opts->port_num;
370
371 gser->port.func.name = "gser";
372 gser->port.func.strings = gser_strings;
373 gser->port.func.bind = gser_bind;
374 gser->port.func.unbind = gser_unbind;
375 gser->port.func.set_alt = gser_set_alt;
376 gser->port.func.disable = gser_disable;
377 gser->port.func.free_func = gser_free;
378
379 return &gser->port.func;
380}
381
382DECLARE_USB_FUNCTION_INIT(gser, gser_alloc_inst, gser_alloc);
383MODULE_LICENSE("GPL");
384MODULE_AUTHOR("Al Borchers");
385MODULE_AUTHOR("David Brownell");
diff --git a/drivers/usb/gadget/function/f_sourcesink.c b/drivers/usb/gadget/function/f_sourcesink.c
new file mode 100644
index 000000000000..d3cd52db78fe
--- /dev/null
+++ b/drivers/usb/gadget/function/f_sourcesink.c
@@ -0,0 +1,1247 @@
1/*
2 * f_sourcesink.c - USB peripheral source/sink configuration driver
3 *
4 * Copyright (C) 2003-2008 David Brownell
5 * Copyright (C) 2008 by Nokia Corporation
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 */
12
13/* #define VERBOSE_DEBUG */
14
15#include <linux/slab.h>
16#include <linux/kernel.h>
17#include <linux/device.h>
18#include <linux/module.h>
19#include <linux/usb/composite.h>
20#include <linux/err.h>
21
22#include "g_zero.h"
23#include "gadget_chips.h"
24#include "u_f.h"
25
26/*
27 * SOURCE/SINK FUNCTION ... a primary testing vehicle for USB peripheral
28 * controller drivers.
29 *
30 * This just sinks bulk packets OUT to the peripheral and sources them IN
31 * to the host, optionally with specific data patterns for integrity tests.
32 * As such it supports basic functionality and load tests.
33 *
34 * In terms of control messaging, this supports all the standard requests
35 * plus two that support control-OUT tests. If the optional "autoresume"
36 * mode is enabled, it provides good functional coverage for the "USBCV"
37 * test harness from USB-IF.
38 *
39 * Note that because this doesn't queue more than one request at a time,
40 * some other function must be used to test queueing logic. The network
41 * link (g_ether) is the best overall option for that, since its TX and RX
42 * queues are relatively independent, will receive a range of packet sizes,
43 * and can often be made to run out completely. Those issues are important
44 * when stress testing peripheral controller drivers.
45 *
46 *
47 * This is currently packaged as a configuration driver, which can't be
48 * combined with other functions to make composite devices. However, it
49 * can be combined with other independent configurations.
50 */
51struct f_sourcesink {
52 struct usb_function function;
53
54 struct usb_ep *in_ep;
55 struct usb_ep *out_ep;
56 struct usb_ep *iso_in_ep;
57 struct usb_ep *iso_out_ep;
58 int cur_alt;
59};
60
61static inline struct f_sourcesink *func_to_ss(struct usb_function *f)
62{
63 return container_of(f, struct f_sourcesink, function);
64}
65
66static unsigned pattern;
67static unsigned isoc_interval;
68static unsigned isoc_maxpacket;
69static unsigned isoc_mult;
70static unsigned isoc_maxburst;
71static unsigned buflen;
72
73/*-------------------------------------------------------------------------*/
74
75static struct usb_interface_descriptor source_sink_intf_alt0 = {
76 .bLength = USB_DT_INTERFACE_SIZE,
77 .bDescriptorType = USB_DT_INTERFACE,
78
79 .bAlternateSetting = 0,
80 .bNumEndpoints = 2,
81 .bInterfaceClass = USB_CLASS_VENDOR_SPEC,
82 /* .iInterface = DYNAMIC */
83};
84
85static struct usb_interface_descriptor source_sink_intf_alt1 = {
86 .bLength = USB_DT_INTERFACE_SIZE,
87 .bDescriptorType = USB_DT_INTERFACE,
88
89 .bAlternateSetting = 1,
90 .bNumEndpoints = 4,
91 .bInterfaceClass = USB_CLASS_VENDOR_SPEC,
92 /* .iInterface = DYNAMIC */
93};
94
95/* full speed support: */
96
97static struct usb_endpoint_descriptor fs_source_desc = {
98 .bLength = USB_DT_ENDPOINT_SIZE,
99 .bDescriptorType = USB_DT_ENDPOINT,
100
101 .bEndpointAddress = USB_DIR_IN,
102 .bmAttributes = USB_ENDPOINT_XFER_BULK,
103};
104
105static struct usb_endpoint_descriptor fs_sink_desc = {
106 .bLength = USB_DT_ENDPOINT_SIZE,
107 .bDescriptorType = USB_DT_ENDPOINT,
108
109 .bEndpointAddress = USB_DIR_OUT,
110 .bmAttributes = USB_ENDPOINT_XFER_BULK,
111};
112
113static struct usb_endpoint_descriptor fs_iso_source_desc = {
114 .bLength = USB_DT_ENDPOINT_SIZE,
115 .bDescriptorType = USB_DT_ENDPOINT,
116
117 .bEndpointAddress = USB_DIR_IN,
118 .bmAttributes = USB_ENDPOINT_XFER_ISOC,
119 .wMaxPacketSize = cpu_to_le16(1023),
120 .bInterval = 4,
121};
122
123static struct usb_endpoint_descriptor fs_iso_sink_desc = {
124 .bLength = USB_DT_ENDPOINT_SIZE,
125 .bDescriptorType = USB_DT_ENDPOINT,
126
127 .bEndpointAddress = USB_DIR_OUT,
128 .bmAttributes = USB_ENDPOINT_XFER_ISOC,
129 .wMaxPacketSize = cpu_to_le16(1023),
130 .bInterval = 4,
131};
132
133static struct usb_descriptor_header *fs_source_sink_descs[] = {
134 (struct usb_descriptor_header *) &source_sink_intf_alt0,
135 (struct usb_descriptor_header *) &fs_sink_desc,
136 (struct usb_descriptor_header *) &fs_source_desc,
137 (struct usb_descriptor_header *) &source_sink_intf_alt1,
138#define FS_ALT_IFC_1_OFFSET 3
139 (struct usb_descriptor_header *) &fs_sink_desc,
140 (struct usb_descriptor_header *) &fs_source_desc,
141 (struct usb_descriptor_header *) &fs_iso_sink_desc,
142 (struct usb_descriptor_header *) &fs_iso_source_desc,
143 NULL,
144};
145
146/* high speed support: */
147
148static struct usb_endpoint_descriptor hs_source_desc = {
149 .bLength = USB_DT_ENDPOINT_SIZE,
150 .bDescriptorType = USB_DT_ENDPOINT,
151
152 .bmAttributes = USB_ENDPOINT_XFER_BULK,
153 .wMaxPacketSize = cpu_to_le16(512),
154};
155
156static struct usb_endpoint_descriptor hs_sink_desc = {
157 .bLength = USB_DT_ENDPOINT_SIZE,
158 .bDescriptorType = USB_DT_ENDPOINT,
159
160 .bmAttributes = USB_ENDPOINT_XFER_BULK,
161 .wMaxPacketSize = cpu_to_le16(512),
162};
163
164static struct usb_endpoint_descriptor hs_iso_source_desc = {
165 .bLength = USB_DT_ENDPOINT_SIZE,
166 .bDescriptorType = USB_DT_ENDPOINT,
167
168 .bmAttributes = USB_ENDPOINT_XFER_ISOC,
169 .wMaxPacketSize = cpu_to_le16(1024),
170 .bInterval = 4,
171};
172
173static struct usb_endpoint_descriptor hs_iso_sink_desc = {
174 .bLength = USB_DT_ENDPOINT_SIZE,
175 .bDescriptorType = USB_DT_ENDPOINT,
176
177 .bmAttributes = USB_ENDPOINT_XFER_ISOC,
178 .wMaxPacketSize = cpu_to_le16(1024),
179 .bInterval = 4,
180};
181
182static struct usb_descriptor_header *hs_source_sink_descs[] = {
183 (struct usb_descriptor_header *) &source_sink_intf_alt0,
184 (struct usb_descriptor_header *) &hs_source_desc,
185 (struct usb_descriptor_header *) &hs_sink_desc,
186 (struct usb_descriptor_header *) &source_sink_intf_alt1,
187#define HS_ALT_IFC_1_OFFSET 3
188 (struct usb_descriptor_header *) &hs_source_desc,
189 (struct usb_descriptor_header *) &hs_sink_desc,
190 (struct usb_descriptor_header *) &hs_iso_source_desc,
191 (struct usb_descriptor_header *) &hs_iso_sink_desc,
192 NULL,
193};
194
195/* super speed support: */
196
197static struct usb_endpoint_descriptor ss_source_desc = {
198 .bLength = USB_DT_ENDPOINT_SIZE,
199 .bDescriptorType = USB_DT_ENDPOINT,
200
201 .bmAttributes = USB_ENDPOINT_XFER_BULK,
202 .wMaxPacketSize = cpu_to_le16(1024),
203};
204
205static struct usb_ss_ep_comp_descriptor ss_source_comp_desc = {
206 .bLength = USB_DT_SS_EP_COMP_SIZE,
207 .bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
208
209 .bMaxBurst = 0,
210 .bmAttributes = 0,
211 .wBytesPerInterval = 0,
212};
213
214static struct usb_endpoint_descriptor ss_sink_desc = {
215 .bLength = USB_DT_ENDPOINT_SIZE,
216 .bDescriptorType = USB_DT_ENDPOINT,
217
218 .bmAttributes = USB_ENDPOINT_XFER_BULK,
219 .wMaxPacketSize = cpu_to_le16(1024),
220};
221
222static struct usb_ss_ep_comp_descriptor ss_sink_comp_desc = {
223 .bLength = USB_DT_SS_EP_COMP_SIZE,
224 .bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
225
226 .bMaxBurst = 0,
227 .bmAttributes = 0,
228 .wBytesPerInterval = 0,
229};
230
231static struct usb_endpoint_descriptor ss_iso_source_desc = {
232 .bLength = USB_DT_ENDPOINT_SIZE,
233 .bDescriptorType = USB_DT_ENDPOINT,
234
235 .bmAttributes = USB_ENDPOINT_XFER_ISOC,
236 .wMaxPacketSize = cpu_to_le16(1024),
237 .bInterval = 4,
238};
239
240static struct usb_ss_ep_comp_descriptor ss_iso_source_comp_desc = {
241 .bLength = USB_DT_SS_EP_COMP_SIZE,
242 .bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
243
244 .bMaxBurst = 0,
245 .bmAttributes = 0,
246 .wBytesPerInterval = cpu_to_le16(1024),
247};
248
249static struct usb_endpoint_descriptor ss_iso_sink_desc = {
250 .bLength = USB_DT_ENDPOINT_SIZE,
251 .bDescriptorType = USB_DT_ENDPOINT,
252
253 .bmAttributes = USB_ENDPOINT_XFER_ISOC,
254 .wMaxPacketSize = cpu_to_le16(1024),
255 .bInterval = 4,
256};
257
258static struct usb_ss_ep_comp_descriptor ss_iso_sink_comp_desc = {
259 .bLength = USB_DT_SS_EP_COMP_SIZE,
260 .bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
261
262 .bMaxBurst = 0,
263 .bmAttributes = 0,
264 .wBytesPerInterval = cpu_to_le16(1024),
265};
266
267static struct usb_descriptor_header *ss_source_sink_descs[] = {
268 (struct usb_descriptor_header *) &source_sink_intf_alt0,
269 (struct usb_descriptor_header *) &ss_source_desc,
270 (struct usb_descriptor_header *) &ss_source_comp_desc,
271 (struct usb_descriptor_header *) &ss_sink_desc,
272 (struct usb_descriptor_header *) &ss_sink_comp_desc,
273 (struct usb_descriptor_header *) &source_sink_intf_alt1,
274#define SS_ALT_IFC_1_OFFSET 5
275 (struct usb_descriptor_header *) &ss_source_desc,
276 (struct usb_descriptor_header *) &ss_source_comp_desc,
277 (struct usb_descriptor_header *) &ss_sink_desc,
278 (struct usb_descriptor_header *) &ss_sink_comp_desc,
279 (struct usb_descriptor_header *) &ss_iso_source_desc,
280 (struct usb_descriptor_header *) &ss_iso_source_comp_desc,
281 (struct usb_descriptor_header *) &ss_iso_sink_desc,
282 (struct usb_descriptor_header *) &ss_iso_sink_comp_desc,
283 NULL,
284};
285
286/* function-specific strings: */
287
288static struct usb_string strings_sourcesink[] = {
289 [0].s = "source and sink data",
290 { } /* end of list */
291};
292
293static struct usb_gadget_strings stringtab_sourcesink = {
294 .language = 0x0409, /* en-us */
295 .strings = strings_sourcesink,
296};
297
298static struct usb_gadget_strings *sourcesink_strings[] = {
299 &stringtab_sourcesink,
300 NULL,
301};
302
303/*-------------------------------------------------------------------------*/
304
305static inline struct usb_request *ss_alloc_ep_req(struct usb_ep *ep, int len)
306{
307 return alloc_ep_req(ep, len, buflen);
308}
309
310void free_ep_req(struct usb_ep *ep, struct usb_request *req)
311{
312 kfree(req->buf);
313 usb_ep_free_request(ep, req);
314}
315
316static void disable_ep(struct usb_composite_dev *cdev, struct usb_ep *ep)
317{
318 int value;
319
320 if (ep->driver_data) {
321 value = usb_ep_disable(ep);
322 if (value < 0)
323 DBG(cdev, "disable %s --> %d\n",
324 ep->name, value);
325 ep->driver_data = NULL;
326 }
327}
328
329void disable_endpoints(struct usb_composite_dev *cdev,
330 struct usb_ep *in, struct usb_ep *out,
331 struct usb_ep *iso_in, struct usb_ep *iso_out)
332{
333 disable_ep(cdev, in);
334 disable_ep(cdev, out);
335 if (iso_in)
336 disable_ep(cdev, iso_in);
337 if (iso_out)
338 disable_ep(cdev, iso_out);
339}
340
341static int
342sourcesink_bind(struct usb_configuration *c, struct usb_function *f)
343{
344 struct usb_composite_dev *cdev = c->cdev;
345 struct f_sourcesink *ss = func_to_ss(f);
346 int id;
347 int ret;
348
349 /* allocate interface ID(s) */
350 id = usb_interface_id(c, f);
351 if (id < 0)
352 return id;
353 source_sink_intf_alt0.bInterfaceNumber = id;
354 source_sink_intf_alt1.bInterfaceNumber = id;
355
356 /* allocate bulk endpoints */
357 ss->in_ep = usb_ep_autoconfig(cdev->gadget, &fs_source_desc);
358 if (!ss->in_ep) {
359autoconf_fail:
360 ERROR(cdev, "%s: can't autoconfigure on %s\n",
361 f->name, cdev->gadget->name);
362 return -ENODEV;
363 }
364 ss->in_ep->driver_data = cdev; /* claim */
365
366 ss->out_ep = usb_ep_autoconfig(cdev->gadget, &fs_sink_desc);
367 if (!ss->out_ep)
368 goto autoconf_fail;
369 ss->out_ep->driver_data = cdev; /* claim */
370
371 /* sanity check the isoc module parameters */
372 if (isoc_interval < 1)
373 isoc_interval = 1;
374 if (isoc_interval > 16)
375 isoc_interval = 16;
376 if (isoc_mult > 2)
377 isoc_mult = 2;
378 if (isoc_maxburst > 15)
379 isoc_maxburst = 15;
380
381 /* fill in the FS isoc descriptors from the module parameters */
382 fs_iso_source_desc.wMaxPacketSize = isoc_maxpacket > 1023 ?
383 1023 : isoc_maxpacket;
384 fs_iso_source_desc.bInterval = isoc_interval;
385 fs_iso_sink_desc.wMaxPacketSize = isoc_maxpacket > 1023 ?
386 1023 : isoc_maxpacket;
387 fs_iso_sink_desc.bInterval = isoc_interval;
388
389 /* allocate iso endpoints */
390 ss->iso_in_ep = usb_ep_autoconfig(cdev->gadget, &fs_iso_source_desc);
391 if (!ss->iso_in_ep)
392 goto no_iso;
393 ss->iso_in_ep->driver_data = cdev; /* claim */
394
395 ss->iso_out_ep = usb_ep_autoconfig(cdev->gadget, &fs_iso_sink_desc);
396 if (ss->iso_out_ep) {
397 ss->iso_out_ep->driver_data = cdev; /* claim */
398 } else {
399 ss->iso_in_ep->driver_data = NULL;
400 ss->iso_in_ep = NULL;
401no_iso:
402 /*
403 * We still want to work even if the UDC doesn't have isoc
404 * endpoints, so null out the alt interface that contains
405 * them and continue.
406 */
407 fs_source_sink_descs[FS_ALT_IFC_1_OFFSET] = NULL;
408 hs_source_sink_descs[HS_ALT_IFC_1_OFFSET] = NULL;
409 ss_source_sink_descs[SS_ALT_IFC_1_OFFSET] = NULL;
410 }
411
412 if (isoc_maxpacket > 1024)
413 isoc_maxpacket = 1024;
414
415 /* support high speed hardware */
416 hs_source_desc.bEndpointAddress = fs_source_desc.bEndpointAddress;
417 hs_sink_desc.bEndpointAddress = fs_sink_desc.bEndpointAddress;
418
419 /*
420 * Fill in the HS isoc descriptors from the module parameters.
421 * We assume that the user knows what they are doing and won't
422 * give parameters that their UDC doesn't support.
423 */
424 hs_iso_source_desc.wMaxPacketSize = isoc_maxpacket;
425 hs_iso_source_desc.wMaxPacketSize |= isoc_mult << 11;
426 hs_iso_source_desc.bInterval = isoc_interval;
427 hs_iso_source_desc.bEndpointAddress =
428 fs_iso_source_desc.bEndpointAddress;
429
430 hs_iso_sink_desc.wMaxPacketSize = isoc_maxpacket;
431 hs_iso_sink_desc.wMaxPacketSize |= isoc_mult << 11;
432 hs_iso_sink_desc.bInterval = isoc_interval;
433 hs_iso_sink_desc.bEndpointAddress = fs_iso_sink_desc.bEndpointAddress;
434
435 /* support super speed hardware */
436 ss_source_desc.bEndpointAddress =
437 fs_source_desc.bEndpointAddress;
438 ss_sink_desc.bEndpointAddress =
439 fs_sink_desc.bEndpointAddress;
440
441 /*
442 * Fill in the SS isoc descriptors from the module parameters.
443 * We assume that the user knows what they are doing and won't
444 * give parameters that their UDC doesn't support.
445 */
446 ss_iso_source_desc.wMaxPacketSize = isoc_maxpacket;
447 ss_iso_source_desc.bInterval = isoc_interval;
448 ss_iso_source_comp_desc.bmAttributes = isoc_mult;
449 ss_iso_source_comp_desc.bMaxBurst = isoc_maxburst;
450 ss_iso_source_comp_desc.wBytesPerInterval =
451 isoc_maxpacket * (isoc_mult + 1) * (isoc_maxburst + 1);
452 ss_iso_source_desc.bEndpointAddress =
453 fs_iso_source_desc.bEndpointAddress;
454
455 ss_iso_sink_desc.wMaxPacketSize = isoc_maxpacket;
456 ss_iso_sink_desc.bInterval = isoc_interval;
457 ss_iso_sink_comp_desc.bmAttributes = isoc_mult;
458 ss_iso_sink_comp_desc.bMaxBurst = isoc_maxburst;
459 ss_iso_sink_comp_desc.wBytesPerInterval =
460 isoc_maxpacket * (isoc_mult + 1) * (isoc_maxburst + 1);
461 ss_iso_sink_desc.bEndpointAddress = fs_iso_sink_desc.bEndpointAddress;
462
463 ret = usb_assign_descriptors(f, fs_source_sink_descs,
464 hs_source_sink_descs, ss_source_sink_descs);
465 if (ret)
466 return ret;
467
468 DBG(cdev, "%s speed %s: IN/%s, OUT/%s, ISO-IN/%s, ISO-OUT/%s\n",
469 (gadget_is_superspeed(c->cdev->gadget) ? "super" :
470 (gadget_is_dualspeed(c->cdev->gadget) ? "dual" : "full")),
471 f->name, ss->in_ep->name, ss->out_ep->name,
472 ss->iso_in_ep ? ss->iso_in_ep->name : "<none>",
473 ss->iso_out_ep ? ss->iso_out_ep->name : "<none>");
474 return 0;
475}
476
477static void
478sourcesink_free_func(struct usb_function *f)
479{
480 struct f_ss_opts *opts;
481
482 opts = container_of(f->fi, struct f_ss_opts, func_inst);
483
484 mutex_lock(&opts->lock);
485 opts->refcnt--;
486 mutex_unlock(&opts->lock);
487
488 usb_free_all_descriptors(f);
489 kfree(func_to_ss(f));
490}
491
492/* optionally require specific source/sink data patterns */
493static int check_read_data(struct f_sourcesink *ss, struct usb_request *req)
494{
495 unsigned i;
496 u8 *buf = req->buf;
497 struct usb_composite_dev *cdev = ss->function.config->cdev;
498
499 if (pattern == 2)
500 return 0;
501
502 for (i = 0; i < req->actual; i++, buf++) {
503 switch (pattern) {
504
505 /* all-zeroes has no synchronization issues */
506 case 0:
507 if (*buf == 0)
508 continue;
509 break;
510
511 /* "mod63" stays in sync with short-terminated transfers,
512 * OR otherwise when host and gadget agree on how large
513 * each usb transfer request should be. Resync is done
514 * with set_interface or set_config. (We *WANT* it to
515 * get quickly out of sync if controllers or their drivers
516 * stutter for any reason, including buffer duplication...)
517 */
518 case 1:
519 if (*buf == (u8)(i % 63))
520 continue;
521 break;
522 }
523 ERROR(cdev, "bad OUT byte, buf[%d] = %d\n", i, *buf);
524 usb_ep_set_halt(ss->out_ep);
525 return -EINVAL;
526 }
527 return 0;
528}
529
530static void reinit_write_data(struct usb_ep *ep, struct usb_request *req)
531{
532 unsigned i;
533 u8 *buf = req->buf;
534
535 switch (pattern) {
536 case 0:
537 memset(req->buf, 0, req->length);
538 break;
539 case 1:
540 for (i = 0; i < req->length; i++)
541 *buf++ = (u8) (i % 63);
542 break;
543 case 2:
544 break;
545 }
546}
547
548static void source_sink_complete(struct usb_ep *ep, struct usb_request *req)
549{
550 struct usb_composite_dev *cdev;
551 struct f_sourcesink *ss = ep->driver_data;
552 int status = req->status;
553
554 /* driver_data will be null if ep has been disabled */
555 if (!ss)
556 return;
557
558 cdev = ss->function.config->cdev;
559
560 switch (status) {
561
562 case 0: /* normal completion? */
563 if (ep == ss->out_ep) {
564 check_read_data(ss, req);
565 if (pattern != 2)
566 memset(req->buf, 0x55, req->length);
567 }
568 break;
569
570 /* this endpoint is normally active while we're configured */
571 case -ECONNABORTED: /* hardware forced ep reset */
572 case -ECONNRESET: /* request dequeued */
573 case -ESHUTDOWN: /* disconnect from host */
574 VDBG(cdev, "%s gone (%d), %d/%d\n", ep->name, status,
575 req->actual, req->length);
576 if (ep == ss->out_ep)
577 check_read_data(ss, req);
578 free_ep_req(ep, req);
579 return;
580
581 case -EOVERFLOW: /* buffer overrun on read means that
582 * we didn't provide a big enough
583 * buffer.
584 */
585 default:
586#if 1
587 DBG(cdev, "%s complete --> %d, %d/%d\n", ep->name,
588 status, req->actual, req->length);
589#endif
590 case -EREMOTEIO: /* short read */
591 break;
592 }
593
594 status = usb_ep_queue(ep, req, GFP_ATOMIC);
595 if (status) {
596 ERROR(cdev, "kill %s: resubmit %d bytes --> %d\n",
597 ep->name, req->length, status);
598 usb_ep_set_halt(ep);
599 /* FIXME recover later ... somehow */
600 }
601}
602
603static int source_sink_start_ep(struct f_sourcesink *ss, bool is_in,
604 bool is_iso, int speed)
605{
606 struct usb_ep *ep;
607 struct usb_request *req;
608 int i, size, status;
609
610 for (i = 0; i < 8; i++) {
611 if (is_iso) {
612 switch (speed) {
613 case USB_SPEED_SUPER:
614 size = isoc_maxpacket * (isoc_mult + 1) *
615 (isoc_maxburst + 1);
616 break;
617 case USB_SPEED_HIGH:
618 size = isoc_maxpacket * (isoc_mult + 1);
619 break;
620 default:
621 size = isoc_maxpacket > 1023 ?
622 1023 : isoc_maxpacket;
623 break;
624 }
625 ep = is_in ? ss->iso_in_ep : ss->iso_out_ep;
626 req = ss_alloc_ep_req(ep, size);
627 } else {
628 ep = is_in ? ss->in_ep : ss->out_ep;
629 req = ss_alloc_ep_req(ep, 0);
630 }
631
632 if (!req)
633 return -ENOMEM;
634
635 req->complete = source_sink_complete;
636 if (is_in)
637 reinit_write_data(ep, req);
638 else if (pattern != 2)
639 memset(req->buf, 0x55, req->length);
640
641 status = usb_ep_queue(ep, req, GFP_ATOMIC);
642 if (status) {
643 struct usb_composite_dev *cdev;
644
645 cdev = ss->function.config->cdev;
646 ERROR(cdev, "start %s%s %s --> %d\n",
647 is_iso ? "ISO-" : "", is_in ? "IN" : "OUT",
648 ep->name, status);
649 free_ep_req(ep, req);
650 }
651
652 if (!is_iso)
653 break;
654 }
655
656 return status;
657}
658
659static void disable_source_sink(struct f_sourcesink *ss)
660{
661 struct usb_composite_dev *cdev;
662
663 cdev = ss->function.config->cdev;
664 disable_endpoints(cdev, ss->in_ep, ss->out_ep, ss->iso_in_ep,
665 ss->iso_out_ep);
666 VDBG(cdev, "%s disabled\n", ss->function.name);
667}
668
669static int
670enable_source_sink(struct usb_composite_dev *cdev, struct f_sourcesink *ss,
671 int alt)
672{
673 int result = 0;
674 int speed = cdev->gadget->speed;
675 struct usb_ep *ep;
676
677 /* one bulk endpoint writes (sources) zeroes IN (to the host) */
678 ep = ss->in_ep;
679 result = config_ep_by_speed(cdev->gadget, &(ss->function), ep);
680 if (result)
681 return result;
682 result = usb_ep_enable(ep);
683 if (result < 0)
684 return result;
685 ep->driver_data = ss;
686
687 result = source_sink_start_ep(ss, true, false, speed);
688 if (result < 0) {
689fail:
690 ep = ss->in_ep;
691 usb_ep_disable(ep);
692 ep->driver_data = NULL;
693 return result;
694 }
695
696 /* one bulk endpoint reads (sinks) anything OUT (from the host) */
697 ep = ss->out_ep;
698 result = config_ep_by_speed(cdev->gadget, &(ss->function), ep);
699 if (result)
700 goto fail;
701 result = usb_ep_enable(ep);
702 if (result < 0)
703 goto fail;
704 ep->driver_data = ss;
705
706 result = source_sink_start_ep(ss, false, false, speed);
707 if (result < 0) {
708fail2:
709 ep = ss->out_ep;
710 usb_ep_disable(ep);
711 ep->driver_data = NULL;
712 goto fail;
713 }
714
715 if (alt == 0)
716 goto out;
717
718 /* one iso endpoint writes (sources) zeroes IN (to the host) */
719 ep = ss->iso_in_ep;
720 if (ep) {
721 result = config_ep_by_speed(cdev->gadget, &(ss->function), ep);
722 if (result)
723 goto fail2;
724 result = usb_ep_enable(ep);
725 if (result < 0)
726 goto fail2;
727 ep->driver_data = ss;
728
729 result = source_sink_start_ep(ss, true, true, speed);
730 if (result < 0) {
731fail3:
732 ep = ss->iso_in_ep;
733 if (ep) {
734 usb_ep_disable(ep);
735 ep->driver_data = NULL;
736 }
737 goto fail2;
738 }
739 }
740
741 /* one iso endpoint reads (sinks) anything OUT (from the host) */
742 ep = ss->iso_out_ep;
743 if (ep) {
744 result = config_ep_by_speed(cdev->gadget, &(ss->function), ep);
745 if (result)
746 goto fail3;
747 result = usb_ep_enable(ep);
748 if (result < 0)
749 goto fail3;
750 ep->driver_data = ss;
751
752 result = source_sink_start_ep(ss, false, true, speed);
753 if (result < 0) {
754 usb_ep_disable(ep);
755 ep->driver_data = NULL;
756 goto fail3;
757 }
758 }
759out:
760 ss->cur_alt = alt;
761
762 DBG(cdev, "%s enabled, alt intf %d\n", ss->function.name, alt);
763 return result;
764}
765
766static int sourcesink_set_alt(struct usb_function *f,
767 unsigned intf, unsigned alt)
768{
769 struct f_sourcesink *ss = func_to_ss(f);
770 struct usb_composite_dev *cdev = f->config->cdev;
771
772 if (ss->in_ep->driver_data)
773 disable_source_sink(ss);
774 return enable_source_sink(cdev, ss, alt);
775}
776
777static int sourcesink_get_alt(struct usb_function *f, unsigned intf)
778{
779 struct f_sourcesink *ss = func_to_ss(f);
780
781 return ss->cur_alt;
782}
783
784static void sourcesink_disable(struct usb_function *f)
785{
786 struct f_sourcesink *ss = func_to_ss(f);
787
788 disable_source_sink(ss);
789}
790
791/*-------------------------------------------------------------------------*/
792
793static int sourcesink_setup(struct usb_function *f,
794 const struct usb_ctrlrequest *ctrl)
795{
796 struct usb_configuration *c = f->config;
797 struct usb_request *req = c->cdev->req;
798 int value = -EOPNOTSUPP;
799 u16 w_index = le16_to_cpu(ctrl->wIndex);
800 u16 w_value = le16_to_cpu(ctrl->wValue);
801 u16 w_length = le16_to_cpu(ctrl->wLength);
802
803 req->length = USB_COMP_EP0_BUFSIZ;
804
805 /* composite driver infrastructure handles everything except
806 * the two control test requests.
807 */
808 switch (ctrl->bRequest) {
809
810 /*
811 * These are the same vendor-specific requests supported by
812 * Intel's USB 2.0 compliance test devices. We exceed that
813 * device spec by allowing multiple-packet requests.
814 *
815 * NOTE: the Control-OUT data stays in req->buf ... better
816 * would be copying it into a scratch buffer, so that other
817 * requests may safely intervene.
818 */
819 case 0x5b: /* control WRITE test -- fill the buffer */
820 if (ctrl->bRequestType != (USB_DIR_OUT|USB_TYPE_VENDOR))
821 goto unknown;
822 if (w_value || w_index)
823 break;
824 /* just read that many bytes into the buffer */
825 if (w_length > req->length)
826 break;
827 value = w_length;
828 break;
829 case 0x5c: /* control READ test -- return the buffer */
830 if (ctrl->bRequestType != (USB_DIR_IN|USB_TYPE_VENDOR))
831 goto unknown;
832 if (w_value || w_index)
833 break;
834 /* expect those bytes are still in the buffer; send back */
835 if (w_length > req->length)
836 break;
837 value = w_length;
838 break;
839
840 default:
841unknown:
842 VDBG(c->cdev,
843 "unknown control req%02x.%02x v%04x i%04x l%d\n",
844 ctrl->bRequestType, ctrl->bRequest,
845 w_value, w_index, w_length);
846 }
847
848 /* respond with data transfer or status phase? */
849 if (value >= 0) {
850 VDBG(c->cdev, "source/sink req%02x.%02x v%04x i%04x l%d\n",
851 ctrl->bRequestType, ctrl->bRequest,
852 w_value, w_index, w_length);
853 req->zero = 0;
854 req->length = value;
855 value = usb_ep_queue(c->cdev->gadget->ep0, req, GFP_ATOMIC);
856 if (value < 0)
857 ERROR(c->cdev, "source/sink response, err %d\n",
858 value);
859 }
860
861 /* device either stalls (value < 0) or reports success */
862 return value;
863}
864
865static struct usb_function *source_sink_alloc_func(
866 struct usb_function_instance *fi)
867{
868 struct f_sourcesink *ss;
869 struct f_ss_opts *ss_opts;
870
871 ss = kzalloc(sizeof(*ss), GFP_KERNEL);
872 if (!ss)
873 return NULL;
874
875 ss_opts = container_of(fi, struct f_ss_opts, func_inst);
876
877 mutex_lock(&ss_opts->lock);
878 ss_opts->refcnt++;
879 mutex_unlock(&ss_opts->lock);
880
881 pattern = ss_opts->pattern;
882 isoc_interval = ss_opts->isoc_interval;
883 isoc_maxpacket = ss_opts->isoc_maxpacket;
884 isoc_mult = ss_opts->isoc_mult;
885 isoc_maxburst = ss_opts->isoc_maxburst;
886 buflen = ss_opts->bulk_buflen;
887
888 ss->function.name = "source/sink";
889 ss->function.bind = sourcesink_bind;
890 ss->function.set_alt = sourcesink_set_alt;
891 ss->function.get_alt = sourcesink_get_alt;
892 ss->function.disable = sourcesink_disable;
893 ss->function.setup = sourcesink_setup;
894 ss->function.strings = sourcesink_strings;
895
896 ss->function.free_func = sourcesink_free_func;
897
898 return &ss->function;
899}
900
901static inline struct f_ss_opts *to_f_ss_opts(struct config_item *item)
902{
903 return container_of(to_config_group(item), struct f_ss_opts,
904 func_inst.group);
905}
906
907CONFIGFS_ATTR_STRUCT(f_ss_opts);
908CONFIGFS_ATTR_OPS(f_ss_opts);
909
910static void ss_attr_release(struct config_item *item)
911{
912 struct f_ss_opts *ss_opts = to_f_ss_opts(item);
913
914 usb_put_function_instance(&ss_opts->func_inst);
915}
916
917static struct configfs_item_operations ss_item_ops = {
918 .release = ss_attr_release,
919 .show_attribute = f_ss_opts_attr_show,
920 .store_attribute = f_ss_opts_attr_store,
921};
922
923static ssize_t f_ss_opts_pattern_show(struct f_ss_opts *opts, char *page)
924{
925 int result;
926
927 mutex_lock(&opts->lock);
928 result = sprintf(page, "%d", opts->pattern);
929 mutex_unlock(&opts->lock);
930
931 return result;
932}
933
934static ssize_t f_ss_opts_pattern_store(struct f_ss_opts *opts,
935 const char *page, size_t len)
936{
937 int ret;
938 u8 num;
939
940 mutex_lock(&opts->lock);
941 if (opts->refcnt) {
942 ret = -EBUSY;
943 goto end;
944 }
945
946 ret = kstrtou8(page, 0, &num);
947 if (ret)
948 goto end;
949
950 if (num != 0 && num != 1 && num != 2) {
951 ret = -EINVAL;
952 goto end;
953 }
954
955 opts->pattern = num;
956 ret = len;
957end:
958 mutex_unlock(&opts->lock);
959 return ret;
960}
961
962static struct f_ss_opts_attribute f_ss_opts_pattern =
963 __CONFIGFS_ATTR(pattern, S_IRUGO | S_IWUSR,
964 f_ss_opts_pattern_show,
965 f_ss_opts_pattern_store);
966
967static ssize_t f_ss_opts_isoc_interval_show(struct f_ss_opts *opts, char *page)
968{
969 int result;
970
971 mutex_lock(&opts->lock);
972 result = sprintf(page, "%d", opts->isoc_interval);
973 mutex_unlock(&opts->lock);
974
975 return result;
976}
977
978static ssize_t f_ss_opts_isoc_interval_store(struct f_ss_opts *opts,
979 const char *page, size_t len)
980{
981 int ret;
982 u8 num;
983
984 mutex_lock(&opts->lock);
985 if (opts->refcnt) {
986 ret = -EBUSY;
987 goto end;
988 }
989
990 ret = kstrtou8(page, 0, &num);
991 if (ret)
992 goto end;
993
994 if (num > 16) {
995 ret = -EINVAL;
996 goto end;
997 }
998
999 opts->isoc_interval = num;
1000 ret = len;
1001end:
1002 mutex_unlock(&opts->lock);
1003 return ret;
1004}
1005
1006static struct f_ss_opts_attribute f_ss_opts_isoc_interval =
1007 __CONFIGFS_ATTR(isoc_interval, S_IRUGO | S_IWUSR,
1008 f_ss_opts_isoc_interval_show,
1009 f_ss_opts_isoc_interval_store);
1010
1011static ssize_t f_ss_opts_isoc_maxpacket_show(struct f_ss_opts *opts, char *page)
1012{
1013 int result;
1014
1015 mutex_lock(&opts->lock);
1016 result = sprintf(page, "%d", opts->isoc_maxpacket);
1017 mutex_unlock(&opts->lock);
1018
1019 return result;
1020}
1021
1022static ssize_t f_ss_opts_isoc_maxpacket_store(struct f_ss_opts *opts,
1023 const char *page, size_t len)
1024{
1025 int ret;
1026 u16 num;
1027
1028 mutex_lock(&opts->lock);
1029 if (opts->refcnt) {
1030 ret = -EBUSY;
1031 goto end;
1032 }
1033
1034 ret = kstrtou16(page, 0, &num);
1035 if (ret)
1036 goto end;
1037
1038 if (num > 1024) {
1039 ret = -EINVAL;
1040 goto end;
1041 }
1042
1043 opts->isoc_maxpacket = num;
1044 ret = len;
1045end:
1046 mutex_unlock(&opts->lock);
1047 return ret;
1048}
1049
1050static struct f_ss_opts_attribute f_ss_opts_isoc_maxpacket =
1051 __CONFIGFS_ATTR(isoc_maxpacket, S_IRUGO | S_IWUSR,
1052 f_ss_opts_isoc_maxpacket_show,
1053 f_ss_opts_isoc_maxpacket_store);
1054
1055static ssize_t f_ss_opts_isoc_mult_show(struct f_ss_opts *opts, char *page)
1056{
1057 int result;
1058
1059 mutex_lock(&opts->lock);
1060 result = sprintf(page, "%d", opts->isoc_mult);
1061 mutex_unlock(&opts->lock);
1062
1063 return result;
1064}
1065
1066static ssize_t f_ss_opts_isoc_mult_store(struct f_ss_opts *opts,
1067 const char *page, size_t len)
1068{
1069 int ret;
1070 u8 num;
1071
1072 mutex_lock(&opts->lock);
1073 if (opts->refcnt) {
1074 ret = -EBUSY;
1075 goto end;
1076 }
1077
1078 ret = kstrtou8(page, 0, &num);
1079 if (ret)
1080 goto end;
1081
1082 if (num > 2) {
1083 ret = -EINVAL;
1084 goto end;
1085 }
1086
1087 opts->isoc_mult = num;
1088 ret = len;
1089end:
1090 mutex_unlock(&opts->lock);
1091 return ret;
1092}
1093
1094static struct f_ss_opts_attribute f_ss_opts_isoc_mult =
1095 __CONFIGFS_ATTR(isoc_mult, S_IRUGO | S_IWUSR,
1096 f_ss_opts_isoc_mult_show,
1097 f_ss_opts_isoc_mult_store);
1098
1099static ssize_t f_ss_opts_isoc_maxburst_show(struct f_ss_opts *opts, char *page)
1100{
1101 int result;
1102
1103 mutex_lock(&opts->lock);
1104 result = sprintf(page, "%d", opts->isoc_maxburst);
1105 mutex_unlock(&opts->lock);
1106
1107 return result;
1108}
1109
1110static ssize_t f_ss_opts_isoc_maxburst_store(struct f_ss_opts *opts,
1111 const char *page, size_t len)
1112{
1113 int ret;
1114 u8 num;
1115
1116 mutex_lock(&opts->lock);
1117 if (opts->refcnt) {
1118 ret = -EBUSY;
1119 goto end;
1120 }
1121
1122 ret = kstrtou8(page, 0, &num);
1123 if (ret)
1124 goto end;
1125
1126 if (num > 15) {
1127 ret = -EINVAL;
1128 goto end;
1129 }
1130
1131 opts->isoc_maxburst = num;
1132 ret = len;
1133end:
1134 mutex_unlock(&opts->lock);
1135 return ret;
1136}
1137
1138static struct f_ss_opts_attribute f_ss_opts_isoc_maxburst =
1139 __CONFIGFS_ATTR(isoc_maxburst, S_IRUGO | S_IWUSR,
1140 f_ss_opts_isoc_maxburst_show,
1141 f_ss_opts_isoc_maxburst_store);
1142
1143static ssize_t f_ss_opts_bulk_buflen_show(struct f_ss_opts *opts, char *page)
1144{
1145 int result;
1146
1147 mutex_lock(&opts->lock);
1148 result = sprintf(page, "%d", opts->bulk_buflen);
1149 mutex_unlock(&opts->lock);
1150
1151 return result;
1152}
1153
1154static ssize_t f_ss_opts_bulk_buflen_store(struct f_ss_opts *opts,
1155 const char *page, size_t len)
1156{
1157 int ret;
1158 u32 num;
1159
1160 mutex_lock(&opts->lock);
1161 if (opts->refcnt) {
1162 ret = -EBUSY;
1163 goto end;
1164 }
1165
1166 ret = kstrtou32(page, 0, &num);
1167 if (ret)
1168 goto end;
1169
1170 opts->bulk_buflen = num;
1171 ret = len;
1172end:
1173 mutex_unlock(&opts->lock);
1174 return ret;
1175}
1176
1177static struct f_ss_opts_attribute f_ss_opts_bulk_buflen =
1178 __CONFIGFS_ATTR(buflen, S_IRUGO | S_IWUSR,
1179 f_ss_opts_bulk_buflen_show,
1180 f_ss_opts_bulk_buflen_store);
1181
1182static struct configfs_attribute *ss_attrs[] = {
1183 &f_ss_opts_pattern.attr,
1184 &f_ss_opts_isoc_interval.attr,
1185 &f_ss_opts_isoc_maxpacket.attr,
1186 &f_ss_opts_isoc_mult.attr,
1187 &f_ss_opts_isoc_maxburst.attr,
1188 &f_ss_opts_bulk_buflen.attr,
1189 NULL,
1190};
1191
1192static struct config_item_type ss_func_type = {
1193 .ct_item_ops = &ss_item_ops,
1194 .ct_attrs = ss_attrs,
1195 .ct_owner = THIS_MODULE,
1196};
1197
1198static void source_sink_free_instance(struct usb_function_instance *fi)
1199{
1200 struct f_ss_opts *ss_opts;
1201
1202 ss_opts = container_of(fi, struct f_ss_opts, func_inst);
1203 kfree(ss_opts);
1204}
1205
1206static struct usb_function_instance *source_sink_alloc_inst(void)
1207{
1208 struct f_ss_opts *ss_opts;
1209
1210 ss_opts = kzalloc(sizeof(*ss_opts), GFP_KERNEL);
1211 if (!ss_opts)
1212 return ERR_PTR(-ENOMEM);
1213 mutex_init(&ss_opts->lock);
1214 ss_opts->func_inst.free_func_inst = source_sink_free_instance;
1215 ss_opts->isoc_interval = GZERO_ISOC_INTERVAL;
1216 ss_opts->isoc_maxpacket = GZERO_ISOC_MAXPACKET;
1217 ss_opts->bulk_buflen = GZERO_BULK_BUFLEN;
1218
1219 config_group_init_type_name(&ss_opts->func_inst.group, "",
1220 &ss_func_type);
1221
1222 return &ss_opts->func_inst;
1223}
1224DECLARE_USB_FUNCTION(SourceSink, source_sink_alloc_inst,
1225 source_sink_alloc_func);
1226
1227static int __init sslb_modinit(void)
1228{
1229 int ret;
1230
1231 ret = usb_function_register(&SourceSinkusb_func);
1232 if (ret)
1233 return ret;
1234 ret = lb_modinit();
1235 if (ret)
1236 usb_function_unregister(&SourceSinkusb_func);
1237 return ret;
1238}
1239static void __exit sslb_modexit(void)
1240{
1241 usb_function_unregister(&SourceSinkusb_func);
1242 lb_modexit();
1243}
1244module_init(sslb_modinit);
1245module_exit(sslb_modexit);
1246
1247MODULE_LICENSE("GPL");
diff --git a/drivers/usb/gadget/function/f_subset.c b/drivers/usb/gadget/function/f_subset.c
new file mode 100644
index 000000000000..1ea8baf33333
--- /dev/null
+++ b/drivers/usb/gadget/function/f_subset.c
@@ -0,0 +1,519 @@
1/*
2 * f_subset.c -- "CDC Subset" Ethernet link function driver
3 *
4 * Copyright (C) 2003-2005,2008 David Brownell
5 * Copyright (C) 2008 Nokia Corporation
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 */
12
13#include <linux/slab.h>
14#include <linux/kernel.h>
15#include <linux/module.h>
16#include <linux/device.h>
17#include <linux/etherdevice.h>
18
19#include "u_ether.h"
20#include "u_ether_configfs.h"
21#include "u_gether.h"
22
23/*
24 * This function packages a simple "CDC Subset" Ethernet port with no real
25 * control mechanisms; just raw data transfer over two bulk endpoints.
26 * The data transfer model is exactly that of CDC Ethernet, which is
27 * why we call it the "CDC Subset".
28 *
29 * Because it's not standardized, this has some interoperability issues.
30 * They mostly relate to driver binding, since the data transfer model is
31 * so simple (CDC Ethernet). The original versions of this protocol used
32 * specific product/vendor IDs: byteswapped IDs for Digital Equipment's
33 * SA-1100 "Itsy" board, which could run Linux 2.4 kernels and supported
34 * daughtercards with USB peripheral connectors. (It was used more often
35 * with other boards, using the Itsy identifiers.) Linux hosts recognized
36 * this with CONFIG_USB_ARMLINUX; these devices have only one configuration
37 * and one interface.
38 *
39 * At some point, MCCI defined a (nonconformant) CDC MDLM variant called
40 * "SAFE", which happens to have a mode which is identical to the "CDC
41 * Subset" in terms of data transfer and lack of control model. This was
42 * adopted by later Sharp Zaurus models, and by some other software which
43 * Linux hosts recognize with CONFIG_USB_NET_ZAURUS.
44 *
45 * Because Microsoft's RNDIS drivers are far from robust, we added a few
46 * descriptors to the CDC Subset code, making this code look like a SAFE
47 * implementation. This lets you use MCCI's host side MS-Windows drivers
48 * if you get fed up with RNDIS. It also makes it easier for composite
49 * drivers to work, since they can use class based binding instead of
50 * caring about specific product and vendor IDs.
51 */
52
53struct f_gether {
54 struct gether port;
55
56 char ethaddr[14];
57};
58
59static inline struct f_gether *func_to_geth(struct usb_function *f)
60{
61 return container_of(f, struct f_gether, port.func);
62}
63
64/*-------------------------------------------------------------------------*/
65
66/*
67 * "Simple" CDC-subset option is a simple vendor-neutral model that most
68 * full speed controllers can handle: one interface, two bulk endpoints.
69 * To assist host side drivers, we fancy it up a bit, and add descriptors so
70 * some host side drivers will understand it as a "SAFE" variant.
71 *
72 * "SAFE" loosely follows CDC WMC MDLM, violating the spec in various ways.
73 * Data endpoints live in the control interface, there's no data interface.
74 * And it's not used to talk to a cell phone radio.
75 */
76
77/* interface descriptor: */
78
79static struct usb_interface_descriptor subset_data_intf = {
80 .bLength = sizeof subset_data_intf,
81 .bDescriptorType = USB_DT_INTERFACE,
82
83 /* .bInterfaceNumber = DYNAMIC */
84 .bAlternateSetting = 0,
85 .bNumEndpoints = 2,
86 .bInterfaceClass = USB_CLASS_COMM,
87 .bInterfaceSubClass = USB_CDC_SUBCLASS_MDLM,
88 .bInterfaceProtocol = 0,
89 /* .iInterface = DYNAMIC */
90};
91
92static struct usb_cdc_header_desc mdlm_header_desc = {
93 .bLength = sizeof mdlm_header_desc,
94 .bDescriptorType = USB_DT_CS_INTERFACE,
95 .bDescriptorSubType = USB_CDC_HEADER_TYPE,
96
97 .bcdCDC = cpu_to_le16(0x0110),
98};
99
100static struct usb_cdc_mdlm_desc mdlm_desc = {
101 .bLength = sizeof mdlm_desc,
102 .bDescriptorType = USB_DT_CS_INTERFACE,
103 .bDescriptorSubType = USB_CDC_MDLM_TYPE,
104
105 .bcdVersion = cpu_to_le16(0x0100),
106 .bGUID = {
107 0x5d, 0x34, 0xcf, 0x66, 0x11, 0x18, 0x11, 0xd6,
108 0xa2, 0x1a, 0x00, 0x01, 0x02, 0xca, 0x9a, 0x7f,
109 },
110};
111
112/* since "usb_cdc_mdlm_detail_desc" is a variable length structure, we
113 * can't really use its struct. All we do here is say that we're using
114 * the submode of "SAFE" which directly matches the CDC Subset.
115 */
116static u8 mdlm_detail_desc[] = {
117 6,
118 USB_DT_CS_INTERFACE,
119 USB_CDC_MDLM_DETAIL_TYPE,
120
121 0, /* "SAFE" */
122 0, /* network control capabilities (none) */
123 0, /* network data capabilities ("raw" encapsulation) */
124};
125
126static struct usb_cdc_ether_desc ether_desc = {
127 .bLength = sizeof ether_desc,
128 .bDescriptorType = USB_DT_CS_INTERFACE,
129 .bDescriptorSubType = USB_CDC_ETHERNET_TYPE,
130
131 /* this descriptor actually adds value, surprise! */
132 /* .iMACAddress = DYNAMIC */
133 .bmEthernetStatistics = cpu_to_le32(0), /* no statistics */
134 .wMaxSegmentSize = cpu_to_le16(ETH_FRAME_LEN),
135 .wNumberMCFilters = cpu_to_le16(0),
136 .bNumberPowerFilters = 0,
137};
138
139/* full speed support: */
140
141static struct usb_endpoint_descriptor fs_subset_in_desc = {
142 .bLength = USB_DT_ENDPOINT_SIZE,
143 .bDescriptorType = USB_DT_ENDPOINT,
144
145 .bEndpointAddress = USB_DIR_IN,
146 .bmAttributes = USB_ENDPOINT_XFER_BULK,
147};
148
149static struct usb_endpoint_descriptor fs_subset_out_desc = {
150 .bLength = USB_DT_ENDPOINT_SIZE,
151 .bDescriptorType = USB_DT_ENDPOINT,
152
153 .bEndpointAddress = USB_DIR_OUT,
154 .bmAttributes = USB_ENDPOINT_XFER_BULK,
155};
156
157static struct usb_descriptor_header *fs_eth_function[] = {
158 (struct usb_descriptor_header *) &subset_data_intf,
159 (struct usb_descriptor_header *) &mdlm_header_desc,
160 (struct usb_descriptor_header *) &mdlm_desc,
161 (struct usb_descriptor_header *) &mdlm_detail_desc,
162 (struct usb_descriptor_header *) &ether_desc,
163 (struct usb_descriptor_header *) &fs_subset_in_desc,
164 (struct usb_descriptor_header *) &fs_subset_out_desc,
165 NULL,
166};
167
168/* high speed support: */
169
170static struct usb_endpoint_descriptor hs_subset_in_desc = {
171 .bLength = USB_DT_ENDPOINT_SIZE,
172 .bDescriptorType = USB_DT_ENDPOINT,
173
174 .bmAttributes = USB_ENDPOINT_XFER_BULK,
175 .wMaxPacketSize = cpu_to_le16(512),
176};
177
178static struct usb_endpoint_descriptor hs_subset_out_desc = {
179 .bLength = USB_DT_ENDPOINT_SIZE,
180 .bDescriptorType = USB_DT_ENDPOINT,
181
182 .bmAttributes = USB_ENDPOINT_XFER_BULK,
183 .wMaxPacketSize = cpu_to_le16(512),
184};
185
186static struct usb_descriptor_header *hs_eth_function[] = {
187 (struct usb_descriptor_header *) &subset_data_intf,
188 (struct usb_descriptor_header *) &mdlm_header_desc,
189 (struct usb_descriptor_header *) &mdlm_desc,
190 (struct usb_descriptor_header *) &mdlm_detail_desc,
191 (struct usb_descriptor_header *) &ether_desc,
192 (struct usb_descriptor_header *) &hs_subset_in_desc,
193 (struct usb_descriptor_header *) &hs_subset_out_desc,
194 NULL,
195};
196
197/* super speed support: */
198
199static struct usb_endpoint_descriptor ss_subset_in_desc = {
200 .bLength = USB_DT_ENDPOINT_SIZE,
201 .bDescriptorType = USB_DT_ENDPOINT,
202
203 .bmAttributes = USB_ENDPOINT_XFER_BULK,
204 .wMaxPacketSize = cpu_to_le16(1024),
205};
206
207static struct usb_endpoint_descriptor ss_subset_out_desc = {
208 .bLength = USB_DT_ENDPOINT_SIZE,
209 .bDescriptorType = USB_DT_ENDPOINT,
210
211 .bmAttributes = USB_ENDPOINT_XFER_BULK,
212 .wMaxPacketSize = cpu_to_le16(1024),
213};
214
215static struct usb_ss_ep_comp_descriptor ss_subset_bulk_comp_desc = {
216 .bLength = sizeof ss_subset_bulk_comp_desc,
217 .bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
218
219 /* the following 2 values can be tweaked if necessary */
220 /* .bMaxBurst = 0, */
221 /* .bmAttributes = 0, */
222};
223
224static struct usb_descriptor_header *ss_eth_function[] = {
225 (struct usb_descriptor_header *) &subset_data_intf,
226 (struct usb_descriptor_header *) &mdlm_header_desc,
227 (struct usb_descriptor_header *) &mdlm_desc,
228 (struct usb_descriptor_header *) &mdlm_detail_desc,
229 (struct usb_descriptor_header *) &ether_desc,
230 (struct usb_descriptor_header *) &ss_subset_in_desc,
231 (struct usb_descriptor_header *) &ss_subset_bulk_comp_desc,
232 (struct usb_descriptor_header *) &ss_subset_out_desc,
233 (struct usb_descriptor_header *) &ss_subset_bulk_comp_desc,
234 NULL,
235};
236
237/* string descriptors: */
238
239static struct usb_string geth_string_defs[] = {
240 [0].s = "CDC Ethernet Subset/SAFE",
241 [1].s = "",
242 { } /* end of list */
243};
244
245static struct usb_gadget_strings geth_string_table = {
246 .language = 0x0409, /* en-us */
247 .strings = geth_string_defs,
248};
249
250static struct usb_gadget_strings *geth_strings[] = {
251 &geth_string_table,
252 NULL,
253};
254
255/*-------------------------------------------------------------------------*/
256
257static int geth_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
258{
259 struct f_gether *geth = func_to_geth(f);
260 struct usb_composite_dev *cdev = f->config->cdev;
261 struct net_device *net;
262
263 /* we know alt == 0, so this is an activation or a reset */
264
265 if (geth->port.in_ep->driver_data) {
266 DBG(cdev, "reset cdc subset\n");
267 gether_disconnect(&geth->port);
268 }
269
270 DBG(cdev, "init + activate cdc subset\n");
271 if (config_ep_by_speed(cdev->gadget, f, geth->port.in_ep) ||
272 config_ep_by_speed(cdev->gadget, f, geth->port.out_ep)) {
273 geth->port.in_ep->desc = NULL;
274 geth->port.out_ep->desc = NULL;
275 return -EINVAL;
276 }
277
278 net = gether_connect(&geth->port);
279 return PTR_ERR_OR_ZERO(net);
280}
281
282static void geth_disable(struct usb_function *f)
283{
284 struct f_gether *geth = func_to_geth(f);
285 struct usb_composite_dev *cdev = f->config->cdev;
286
287 DBG(cdev, "net deactivated\n");
288 gether_disconnect(&geth->port);
289}
290
291/*-------------------------------------------------------------------------*/
292
293/* serial function driver setup/binding */
294
295static int
296geth_bind(struct usb_configuration *c, struct usb_function *f)
297{
298 struct usb_composite_dev *cdev = c->cdev;
299 struct f_gether *geth = func_to_geth(f);
300 struct usb_string *us;
301 int status;
302 struct usb_ep *ep;
303
304 struct f_gether_opts *gether_opts;
305
306 gether_opts = container_of(f->fi, struct f_gether_opts, func_inst);
307
308 /*
309 * in drivers/usb/gadget/configfs.c:configfs_composite_bind()
310 * configurations are bound in sequence with list_for_each_entry,
311 * in each configuration its functions are bound in sequence
312 * with list_for_each_entry, so we assume no race condition
313 * with regard to gether_opts->bound access
314 */
315 if (!gether_opts->bound) {
316 mutex_lock(&gether_opts->lock);
317 gether_set_gadget(gether_opts->net, cdev->gadget);
318 status = gether_register_netdev(gether_opts->net);
319 mutex_unlock(&gether_opts->lock);
320 if (status)
321 return status;
322 gether_opts->bound = true;
323 }
324
325 us = usb_gstrings_attach(cdev, geth_strings,
326 ARRAY_SIZE(geth_string_defs));
327 if (IS_ERR(us))
328 return PTR_ERR(us);
329
330 subset_data_intf.iInterface = us[0].id;
331 ether_desc.iMACAddress = us[1].id;
332
333 /* allocate instance-specific interface IDs */
334 status = usb_interface_id(c, f);
335 if (status < 0)
336 goto fail;
337 subset_data_intf.bInterfaceNumber = status;
338
339 status = -ENODEV;
340
341 /* allocate instance-specific endpoints */
342 ep = usb_ep_autoconfig(cdev->gadget, &fs_subset_in_desc);
343 if (!ep)
344 goto fail;
345 geth->port.in_ep = ep;
346 ep->driver_data = cdev; /* claim */
347
348 ep = usb_ep_autoconfig(cdev->gadget, &fs_subset_out_desc);
349 if (!ep)
350 goto fail;
351 geth->port.out_ep = ep;
352 ep->driver_data = cdev; /* claim */
353
354 /* support all relevant hardware speeds... we expect that when
355 * hardware is dual speed, all bulk-capable endpoints work at
356 * both speeds
357 */
358 hs_subset_in_desc.bEndpointAddress = fs_subset_in_desc.bEndpointAddress;
359 hs_subset_out_desc.bEndpointAddress =
360 fs_subset_out_desc.bEndpointAddress;
361
362 ss_subset_in_desc.bEndpointAddress = fs_subset_in_desc.bEndpointAddress;
363 ss_subset_out_desc.bEndpointAddress =
364 fs_subset_out_desc.bEndpointAddress;
365
366 status = usb_assign_descriptors(f, fs_eth_function, hs_eth_function,
367 ss_eth_function);
368 if (status)
369 goto fail;
370
371 /* NOTE: all that is done without knowing or caring about
372 * the network link ... which is unavailable to this code
373 * until we're activated via set_alt().
374 */
375
376 DBG(cdev, "CDC Subset: %s speed IN/%s OUT/%s\n",
377 gadget_is_superspeed(c->cdev->gadget) ? "super" :
378 gadget_is_dualspeed(c->cdev->gadget) ? "dual" : "full",
379 geth->port.in_ep->name, geth->port.out_ep->name);
380 return 0;
381
382fail:
383 usb_free_all_descriptors(f);
384 /* we might as well release our claims on endpoints */
385 if (geth->port.out_ep)
386 geth->port.out_ep->driver_data = NULL;
387 if (geth->port.in_ep)
388 geth->port.in_ep->driver_data = NULL;
389
390 ERROR(cdev, "%s: can't bind, err %d\n", f->name, status);
391
392 return status;
393}
394
395static inline struct f_gether_opts *to_f_gether_opts(struct config_item *item)
396{
397 return container_of(to_config_group(item), struct f_gether_opts,
398 func_inst.group);
399}
400
401/* f_gether_item_ops */
402USB_ETHERNET_CONFIGFS_ITEM(gether);
403
404/* f_gether_opts_dev_addr */
405USB_ETHERNET_CONFIGFS_ITEM_ATTR_DEV_ADDR(gether);
406
407/* f_gether_opts_host_addr */
408USB_ETHERNET_CONFIGFS_ITEM_ATTR_HOST_ADDR(gether);
409
410/* f_gether_opts_qmult */
411USB_ETHERNET_CONFIGFS_ITEM_ATTR_QMULT(gether);
412
413/* f_gether_opts_ifname */
414USB_ETHERNET_CONFIGFS_ITEM_ATTR_IFNAME(gether);
415
416static struct configfs_attribute *gether_attrs[] = {
417 &f_gether_opts_dev_addr.attr,
418 &f_gether_opts_host_addr.attr,
419 &f_gether_opts_qmult.attr,
420 &f_gether_opts_ifname.attr,
421 NULL,
422};
423
424static struct config_item_type gether_func_type = {
425 .ct_item_ops = &gether_item_ops,
426 .ct_attrs = gether_attrs,
427 .ct_owner = THIS_MODULE,
428};
429
430static void geth_free_inst(struct usb_function_instance *f)
431{
432 struct f_gether_opts *opts;
433
434 opts = container_of(f, struct f_gether_opts, func_inst);
435 if (opts->bound)
436 gether_cleanup(netdev_priv(opts->net));
437 else
438 free_netdev(opts->net);
439 kfree(opts);
440}
441
442static struct usb_function_instance *geth_alloc_inst(void)
443{
444 struct f_gether_opts *opts;
445
446 opts = kzalloc(sizeof(*opts), GFP_KERNEL);
447 if (!opts)
448 return ERR_PTR(-ENOMEM);
449 mutex_init(&opts->lock);
450 opts->func_inst.free_func_inst = geth_free_inst;
451 opts->net = gether_setup_default();
452 if (IS_ERR(opts->net)) {
453 struct net_device *net = opts->net;
454 kfree(opts);
455 return ERR_CAST(net);
456 }
457
458 config_group_init_type_name(&opts->func_inst.group, "",
459 &gether_func_type);
460
461 return &opts->func_inst;
462}
463
464static void geth_free(struct usb_function *f)
465{
466 struct f_gether *eth;
467
468 eth = func_to_geth(f);
469 kfree(eth);
470}
471
472static void geth_unbind(struct usb_configuration *c, struct usb_function *f)
473{
474 geth_string_defs[0].id = 0;
475 usb_free_all_descriptors(f);
476}
477
478static struct usb_function *geth_alloc(struct usb_function_instance *fi)
479{
480 struct f_gether *geth;
481 struct f_gether_opts *opts;
482 int status;
483
484 /* allocate and initialize one new instance */
485 geth = kzalloc(sizeof(*geth), GFP_KERNEL);
486 if (!geth)
487 return ERR_PTR(-ENOMEM);
488
489 opts = container_of(fi, struct f_gether_opts, func_inst);
490
491 mutex_lock(&opts->lock);
492 opts->refcnt++;
493 /* export host's Ethernet address in CDC format */
494 status = gether_get_host_addr_cdc(opts->net, geth->ethaddr,
495 sizeof(geth->ethaddr));
496 if (status < 12) {
497 kfree(geth);
498 mutex_unlock(&opts->lock);
499 return ERR_PTR(-EINVAL);
500 }
501 geth_string_defs[1].s = geth->ethaddr;
502
503 geth->port.ioport = netdev_priv(opts->net);
504 mutex_unlock(&opts->lock);
505 geth->port.cdc_filter = DEFAULT_FILTER;
506
507 geth->port.func.name = "cdc_subset";
508 geth->port.func.bind = geth_bind;
509 geth->port.func.unbind = geth_unbind;
510 geth->port.func.set_alt = geth_set_alt;
511 geth->port.func.disable = geth_disable;
512 geth->port.func.free_func = geth_free;
513
514 return &geth->port.func;
515}
516
517DECLARE_USB_FUNCTION_INIT(geth, geth_alloc_inst, geth_alloc);
518MODULE_LICENSE("GPL");
519MODULE_AUTHOR("David Brownell");
diff --git a/drivers/usb/gadget/function/f_uac1.c b/drivers/usb/gadget/function/f_uac1.c
new file mode 100644
index 000000000000..2b4c82d84bfc
--- /dev/null
+++ b/drivers/usb/gadget/function/f_uac1.c
@@ -0,0 +1,768 @@
1/*
2 * f_audio.c -- USB Audio class function driver
3 *
4 * Copyright (C) 2008 Bryan Wu <cooloney@kernel.org>
5 * Copyright (C) 2008 Analog Devices, Inc
6 *
7 * Enter bugs at http://blackfin.uclinux.org/
8 *
9 * Licensed under the GPL-2 or later.
10 */
11
12#include <linux/slab.h>
13#include <linux/kernel.h>
14#include <linux/device.h>
15#include <linux/atomic.h>
16
17#include "u_uac1.h"
18
19#define OUT_EP_MAX_PACKET_SIZE 200
20static int req_buf_size = OUT_EP_MAX_PACKET_SIZE;
21module_param(req_buf_size, int, S_IRUGO);
22MODULE_PARM_DESC(req_buf_size, "ISO OUT endpoint request buffer size");
23
24static int req_count = 256;
25module_param(req_count, int, S_IRUGO);
26MODULE_PARM_DESC(req_count, "ISO OUT endpoint request count");
27
28static int audio_buf_size = 48000;
29module_param(audio_buf_size, int, S_IRUGO);
30MODULE_PARM_DESC(audio_buf_size, "Audio buffer size");
31
32static int generic_set_cmd(struct usb_audio_control *con, u8 cmd, int value);
33static int generic_get_cmd(struct usb_audio_control *con, u8 cmd);
34
35/*
36 * DESCRIPTORS ... most are static, but strings and full
37 * configuration descriptors are built on demand.
38 */
39
40/*
41 * We have two interfaces- AudioControl and AudioStreaming
42 * TODO: only supcard playback currently
43 */
44#define F_AUDIO_AC_INTERFACE 0
45#define F_AUDIO_AS_INTERFACE 1
46#define F_AUDIO_NUM_INTERFACES 2
47
48/* B.3.1 Standard AC Interface Descriptor */
49static struct usb_interface_descriptor ac_interface_desc __initdata = {
50 .bLength = USB_DT_INTERFACE_SIZE,
51 .bDescriptorType = USB_DT_INTERFACE,
52 .bNumEndpoints = 0,
53 .bInterfaceClass = USB_CLASS_AUDIO,
54 .bInterfaceSubClass = USB_SUBCLASS_AUDIOCONTROL,
55};
56
57DECLARE_UAC_AC_HEADER_DESCRIPTOR(2);
58
59#define UAC_DT_AC_HEADER_LENGTH UAC_DT_AC_HEADER_SIZE(F_AUDIO_NUM_INTERFACES)
60/* 1 input terminal, 1 output terminal and 1 feature unit */
61#define UAC_DT_TOTAL_LENGTH (UAC_DT_AC_HEADER_LENGTH + UAC_DT_INPUT_TERMINAL_SIZE \
62 + UAC_DT_OUTPUT_TERMINAL_SIZE + UAC_DT_FEATURE_UNIT_SIZE(0))
63/* B.3.2 Class-Specific AC Interface Descriptor */
64static struct uac1_ac_header_descriptor_2 ac_header_desc = {
65 .bLength = UAC_DT_AC_HEADER_LENGTH,
66 .bDescriptorType = USB_DT_CS_INTERFACE,
67 .bDescriptorSubtype = UAC_HEADER,
68 .bcdADC = __constant_cpu_to_le16(0x0100),
69 .wTotalLength = __constant_cpu_to_le16(UAC_DT_TOTAL_LENGTH),
70 .bInCollection = F_AUDIO_NUM_INTERFACES,
71 .baInterfaceNr = {
72 [0] = F_AUDIO_AC_INTERFACE,
73 [1] = F_AUDIO_AS_INTERFACE,
74 }
75};
76
77#define INPUT_TERMINAL_ID 1
78static struct uac_input_terminal_descriptor input_terminal_desc = {
79 .bLength = UAC_DT_INPUT_TERMINAL_SIZE,
80 .bDescriptorType = USB_DT_CS_INTERFACE,
81 .bDescriptorSubtype = UAC_INPUT_TERMINAL,
82 .bTerminalID = INPUT_TERMINAL_ID,
83 .wTerminalType = UAC_TERMINAL_STREAMING,
84 .bAssocTerminal = 0,
85 .wChannelConfig = 0x3,
86};
87
88DECLARE_UAC_FEATURE_UNIT_DESCRIPTOR(0);
89
90#define FEATURE_UNIT_ID 2
91static struct uac_feature_unit_descriptor_0 feature_unit_desc = {
92 .bLength = UAC_DT_FEATURE_UNIT_SIZE(0),
93 .bDescriptorType = USB_DT_CS_INTERFACE,
94 .bDescriptorSubtype = UAC_FEATURE_UNIT,
95 .bUnitID = FEATURE_UNIT_ID,
96 .bSourceID = INPUT_TERMINAL_ID,
97 .bControlSize = 2,
98 .bmaControls[0] = (UAC_FU_MUTE | UAC_FU_VOLUME),
99};
100
101static struct usb_audio_control mute_control = {
102 .list = LIST_HEAD_INIT(mute_control.list),
103 .name = "Mute Control",
104 .type = UAC_FU_MUTE,
105 /* Todo: add real Mute control code */
106 .set = generic_set_cmd,
107 .get = generic_get_cmd,
108};
109
110static struct usb_audio_control volume_control = {
111 .list = LIST_HEAD_INIT(volume_control.list),
112 .name = "Volume Control",
113 .type = UAC_FU_VOLUME,
114 /* Todo: add real Volume control code */
115 .set = generic_set_cmd,
116 .get = generic_get_cmd,
117};
118
119static struct usb_audio_control_selector feature_unit = {
120 .list = LIST_HEAD_INIT(feature_unit.list),
121 .id = FEATURE_UNIT_ID,
122 .name = "Mute & Volume Control",
123 .type = UAC_FEATURE_UNIT,
124 .desc = (struct usb_descriptor_header *)&feature_unit_desc,
125};
126
127#define OUTPUT_TERMINAL_ID 3
128static struct uac1_output_terminal_descriptor output_terminal_desc = {
129 .bLength = UAC_DT_OUTPUT_TERMINAL_SIZE,
130 .bDescriptorType = USB_DT_CS_INTERFACE,
131 .bDescriptorSubtype = UAC_OUTPUT_TERMINAL,
132 .bTerminalID = OUTPUT_TERMINAL_ID,
133 .wTerminalType = UAC_OUTPUT_TERMINAL_SPEAKER,
134 .bAssocTerminal = FEATURE_UNIT_ID,
135 .bSourceID = FEATURE_UNIT_ID,
136};
137
138/* B.4.1 Standard AS Interface Descriptor */
139static struct usb_interface_descriptor as_interface_alt_0_desc = {
140 .bLength = USB_DT_INTERFACE_SIZE,
141 .bDescriptorType = USB_DT_INTERFACE,
142 .bAlternateSetting = 0,
143 .bNumEndpoints = 0,
144 .bInterfaceClass = USB_CLASS_AUDIO,
145 .bInterfaceSubClass = USB_SUBCLASS_AUDIOSTREAMING,
146};
147
148static struct usb_interface_descriptor as_interface_alt_1_desc = {
149 .bLength = USB_DT_INTERFACE_SIZE,
150 .bDescriptorType = USB_DT_INTERFACE,
151 .bAlternateSetting = 1,
152 .bNumEndpoints = 1,
153 .bInterfaceClass = USB_CLASS_AUDIO,
154 .bInterfaceSubClass = USB_SUBCLASS_AUDIOSTREAMING,
155};
156
157/* B.4.2 Class-Specific AS Interface Descriptor */
158static struct uac1_as_header_descriptor as_header_desc = {
159 .bLength = UAC_DT_AS_HEADER_SIZE,
160 .bDescriptorType = USB_DT_CS_INTERFACE,
161 .bDescriptorSubtype = UAC_AS_GENERAL,
162 .bTerminalLink = INPUT_TERMINAL_ID,
163 .bDelay = 1,
164 .wFormatTag = UAC_FORMAT_TYPE_I_PCM,
165};
166
167DECLARE_UAC_FORMAT_TYPE_I_DISCRETE_DESC(1);
168
169static struct uac_format_type_i_discrete_descriptor_1 as_type_i_desc = {
170 .bLength = UAC_FORMAT_TYPE_I_DISCRETE_DESC_SIZE(1),
171 .bDescriptorType = USB_DT_CS_INTERFACE,
172 .bDescriptorSubtype = UAC_FORMAT_TYPE,
173 .bFormatType = UAC_FORMAT_TYPE_I,
174 .bSubframeSize = 2,
175 .bBitResolution = 16,
176 .bSamFreqType = 1,
177};
178
179/* Standard ISO OUT Endpoint Descriptor */
180static struct usb_endpoint_descriptor as_out_ep_desc = {
181 .bLength = USB_DT_ENDPOINT_AUDIO_SIZE,
182 .bDescriptorType = USB_DT_ENDPOINT,
183 .bEndpointAddress = USB_DIR_OUT,
184 .bmAttributes = USB_ENDPOINT_SYNC_ADAPTIVE
185 | USB_ENDPOINT_XFER_ISOC,
186 .wMaxPacketSize = __constant_cpu_to_le16(OUT_EP_MAX_PACKET_SIZE),
187 .bInterval = 4,
188};
189
190/* Class-specific AS ISO OUT Endpoint Descriptor */
191static struct uac_iso_endpoint_descriptor as_iso_out_desc __initdata = {
192 .bLength = UAC_ISO_ENDPOINT_DESC_SIZE,
193 .bDescriptorType = USB_DT_CS_ENDPOINT,
194 .bDescriptorSubtype = UAC_EP_GENERAL,
195 .bmAttributes = 1,
196 .bLockDelayUnits = 1,
197 .wLockDelay = __constant_cpu_to_le16(1),
198};
199
200static struct usb_descriptor_header *f_audio_desc[] __initdata = {
201 (struct usb_descriptor_header *)&ac_interface_desc,
202 (struct usb_descriptor_header *)&ac_header_desc,
203
204 (struct usb_descriptor_header *)&input_terminal_desc,
205 (struct usb_descriptor_header *)&output_terminal_desc,
206 (struct usb_descriptor_header *)&feature_unit_desc,
207
208 (struct usb_descriptor_header *)&as_interface_alt_0_desc,
209 (struct usb_descriptor_header *)&as_interface_alt_1_desc,
210 (struct usb_descriptor_header *)&as_header_desc,
211
212 (struct usb_descriptor_header *)&as_type_i_desc,
213
214 (struct usb_descriptor_header *)&as_out_ep_desc,
215 (struct usb_descriptor_header *)&as_iso_out_desc,
216 NULL,
217};
218
219/*
220 * This function is an ALSA sound card following USB Audio Class Spec 1.0.
221 */
222
223/*-------------------------------------------------------------------------*/
224struct f_audio_buf {
225 u8 *buf;
226 int actual;
227 struct list_head list;
228};
229
230static struct f_audio_buf *f_audio_buffer_alloc(int buf_size)
231{
232 struct f_audio_buf *copy_buf;
233
234 copy_buf = kzalloc(sizeof *copy_buf, GFP_ATOMIC);
235 if (!copy_buf)
236 return ERR_PTR(-ENOMEM);
237
238 copy_buf->buf = kzalloc(buf_size, GFP_ATOMIC);
239 if (!copy_buf->buf) {
240 kfree(copy_buf);
241 return ERR_PTR(-ENOMEM);
242 }
243
244 return copy_buf;
245}
246
247static void f_audio_buffer_free(struct f_audio_buf *audio_buf)
248{
249 kfree(audio_buf->buf);
250 kfree(audio_buf);
251}
252/*-------------------------------------------------------------------------*/
253
254struct f_audio {
255 struct gaudio card;
256
257 /* endpoints handle full and/or high speeds */
258 struct usb_ep *out_ep;
259
260 spinlock_t lock;
261 struct f_audio_buf *copy_buf;
262 struct work_struct playback_work;
263 struct list_head play_queue;
264
265 /* Control Set command */
266 struct list_head cs;
267 u8 set_cmd;
268 struct usb_audio_control *set_con;
269};
270
271static inline struct f_audio *func_to_audio(struct usb_function *f)
272{
273 return container_of(f, struct f_audio, card.func);
274}
275
276/*-------------------------------------------------------------------------*/
277
278static void f_audio_playback_work(struct work_struct *data)
279{
280 struct f_audio *audio = container_of(data, struct f_audio,
281 playback_work);
282 struct f_audio_buf *play_buf;
283
284 spin_lock_irq(&audio->lock);
285 if (list_empty(&audio->play_queue)) {
286 spin_unlock_irq(&audio->lock);
287 return;
288 }
289 play_buf = list_first_entry(&audio->play_queue,
290 struct f_audio_buf, list);
291 list_del(&play_buf->list);
292 spin_unlock_irq(&audio->lock);
293
294 u_audio_playback(&audio->card, play_buf->buf, play_buf->actual);
295 f_audio_buffer_free(play_buf);
296}
297
298static int f_audio_out_ep_complete(struct usb_ep *ep, struct usb_request *req)
299{
300 struct f_audio *audio = req->context;
301 struct usb_composite_dev *cdev = audio->card.func.config->cdev;
302 struct f_audio_buf *copy_buf = audio->copy_buf;
303 int err;
304
305 if (!copy_buf)
306 return -EINVAL;
307
308 /* Copy buffer is full, add it to the play_queue */
309 if (audio_buf_size - copy_buf->actual < req->actual) {
310 list_add_tail(&copy_buf->list, &audio->play_queue);
311 schedule_work(&audio->playback_work);
312 copy_buf = f_audio_buffer_alloc(audio_buf_size);
313 if (IS_ERR(copy_buf))
314 return -ENOMEM;
315 }
316
317 memcpy(copy_buf->buf + copy_buf->actual, req->buf, req->actual);
318 copy_buf->actual += req->actual;
319 audio->copy_buf = copy_buf;
320
321 err = usb_ep_queue(ep, req, GFP_ATOMIC);
322 if (err)
323 ERROR(cdev, "%s queue req: %d\n", ep->name, err);
324
325 return 0;
326
327}
328
329static void f_audio_complete(struct usb_ep *ep, struct usb_request *req)
330{
331 struct f_audio *audio = req->context;
332 int status = req->status;
333 u32 data = 0;
334 struct usb_ep *out_ep = audio->out_ep;
335
336 switch (status) {
337
338 case 0: /* normal completion? */
339 if (ep == out_ep)
340 f_audio_out_ep_complete(ep, req);
341 else if (audio->set_con) {
342 memcpy(&data, req->buf, req->length);
343 audio->set_con->set(audio->set_con, audio->set_cmd,
344 le16_to_cpu(data));
345 audio->set_con = NULL;
346 }
347 break;
348 default:
349 break;
350 }
351}
352
353static int audio_set_intf_req(struct usb_function *f,
354 const struct usb_ctrlrequest *ctrl)
355{
356 struct f_audio *audio = func_to_audio(f);
357 struct usb_composite_dev *cdev = f->config->cdev;
358 struct usb_request *req = cdev->req;
359 u8 id = ((le16_to_cpu(ctrl->wIndex) >> 8) & 0xFF);
360 u16 len = le16_to_cpu(ctrl->wLength);
361 u16 w_value = le16_to_cpu(ctrl->wValue);
362 u8 con_sel = (w_value >> 8) & 0xFF;
363 u8 cmd = (ctrl->bRequest & 0x0F);
364 struct usb_audio_control_selector *cs;
365 struct usb_audio_control *con;
366
367 DBG(cdev, "bRequest 0x%x, w_value 0x%04x, len %d, entity %d\n",
368 ctrl->bRequest, w_value, len, id);
369
370 list_for_each_entry(cs, &audio->cs, list) {
371 if (cs->id == id) {
372 list_for_each_entry(con, &cs->control, list) {
373 if (con->type == con_sel) {
374 audio->set_con = con;
375 break;
376 }
377 }
378 break;
379 }
380 }
381
382 audio->set_cmd = cmd;
383 req->context = audio;
384 req->complete = f_audio_complete;
385
386 return len;
387}
388
389static int audio_get_intf_req(struct usb_function *f,
390 const struct usb_ctrlrequest *ctrl)
391{
392 struct f_audio *audio = func_to_audio(f);
393 struct usb_composite_dev *cdev = f->config->cdev;
394 struct usb_request *req = cdev->req;
395 int value = -EOPNOTSUPP;
396 u8 id = ((le16_to_cpu(ctrl->wIndex) >> 8) & 0xFF);
397 u16 len = le16_to_cpu(ctrl->wLength);
398 u16 w_value = le16_to_cpu(ctrl->wValue);
399 u8 con_sel = (w_value >> 8) & 0xFF;
400 u8 cmd = (ctrl->bRequest & 0x0F);
401 struct usb_audio_control_selector *cs;
402 struct usb_audio_control *con;
403
404 DBG(cdev, "bRequest 0x%x, w_value 0x%04x, len %d, entity %d\n",
405 ctrl->bRequest, w_value, len, id);
406
407 list_for_each_entry(cs, &audio->cs, list) {
408 if (cs->id == id) {
409 list_for_each_entry(con, &cs->control, list) {
410 if (con->type == con_sel && con->get) {
411 value = con->get(con, cmd);
412 break;
413 }
414 }
415 break;
416 }
417 }
418
419 req->context = audio;
420 req->complete = f_audio_complete;
421 len = min_t(size_t, sizeof(value), len);
422 memcpy(req->buf, &value, len);
423
424 return len;
425}
426
427static int audio_set_endpoint_req(struct usb_function *f,
428 const struct usb_ctrlrequest *ctrl)
429{
430 struct usb_composite_dev *cdev = f->config->cdev;
431 int value = -EOPNOTSUPP;
432 u16 ep = le16_to_cpu(ctrl->wIndex);
433 u16 len = le16_to_cpu(ctrl->wLength);
434 u16 w_value = le16_to_cpu(ctrl->wValue);
435
436 DBG(cdev, "bRequest 0x%x, w_value 0x%04x, len %d, endpoint %d\n",
437 ctrl->bRequest, w_value, len, ep);
438
439 switch (ctrl->bRequest) {
440 case UAC_SET_CUR:
441 value = len;
442 break;
443
444 case UAC_SET_MIN:
445 break;
446
447 case UAC_SET_MAX:
448 break;
449
450 case UAC_SET_RES:
451 break;
452
453 case UAC_SET_MEM:
454 break;
455
456 default:
457 break;
458 }
459
460 return value;
461}
462
463static int audio_get_endpoint_req(struct usb_function *f,
464 const struct usb_ctrlrequest *ctrl)
465{
466 struct usb_composite_dev *cdev = f->config->cdev;
467 int value = -EOPNOTSUPP;
468 u8 ep = ((le16_to_cpu(ctrl->wIndex) >> 8) & 0xFF);
469 u16 len = le16_to_cpu(ctrl->wLength);
470 u16 w_value = le16_to_cpu(ctrl->wValue);
471
472 DBG(cdev, "bRequest 0x%x, w_value 0x%04x, len %d, endpoint %d\n",
473 ctrl->bRequest, w_value, len, ep);
474
475 switch (ctrl->bRequest) {
476 case UAC_GET_CUR:
477 case UAC_GET_MIN:
478 case UAC_GET_MAX:
479 case UAC_GET_RES:
480 value = len;
481 break;
482 case UAC_GET_MEM:
483 break;
484 default:
485 break;
486 }
487
488 return value;
489}
490
491static int
492f_audio_setup(struct usb_function *f, const struct usb_ctrlrequest *ctrl)
493{
494 struct usb_composite_dev *cdev = f->config->cdev;
495 struct usb_request *req = cdev->req;
496 int value = -EOPNOTSUPP;
497 u16 w_index = le16_to_cpu(ctrl->wIndex);
498 u16 w_value = le16_to_cpu(ctrl->wValue);
499 u16 w_length = le16_to_cpu(ctrl->wLength);
500
501 /* composite driver infrastructure handles everything; interface
502 * activation uses set_alt().
503 */
504 switch (ctrl->bRequestType) {
505 case USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE:
506 value = audio_set_intf_req(f, ctrl);
507 break;
508
509 case USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE:
510 value = audio_get_intf_req(f, ctrl);
511 break;
512
513 case USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_ENDPOINT:
514 value = audio_set_endpoint_req(f, ctrl);
515 break;
516
517 case USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_ENDPOINT:
518 value = audio_get_endpoint_req(f, ctrl);
519 break;
520
521 default:
522 ERROR(cdev, "invalid control req%02x.%02x v%04x i%04x l%d\n",
523 ctrl->bRequestType, ctrl->bRequest,
524 w_value, w_index, w_length);
525 }
526
527 /* respond with data transfer or status phase? */
528 if (value >= 0) {
529 DBG(cdev, "audio req%02x.%02x v%04x i%04x l%d\n",
530 ctrl->bRequestType, ctrl->bRequest,
531 w_value, w_index, w_length);
532 req->zero = 0;
533 req->length = value;
534 value = usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC);
535 if (value < 0)
536 ERROR(cdev, "audio response on err %d\n", value);
537 }
538
539 /* device either stalls (value < 0) or reports success */
540 return value;
541}
542
543static int f_audio_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
544{
545 struct f_audio *audio = func_to_audio(f);
546 struct usb_composite_dev *cdev = f->config->cdev;
547 struct usb_ep *out_ep = audio->out_ep;
548 struct usb_request *req;
549 int i = 0, err = 0;
550
551 DBG(cdev, "intf %d, alt %d\n", intf, alt);
552
553 if (intf == 1) {
554 if (alt == 1) {
555 usb_ep_enable(out_ep);
556 out_ep->driver_data = audio;
557 audio->copy_buf = f_audio_buffer_alloc(audio_buf_size);
558 if (IS_ERR(audio->copy_buf))
559 return -ENOMEM;
560
561 /*
562 * allocate a bunch of read buffers
563 * and queue them all at once.
564 */
565 for (i = 0; i < req_count && err == 0; i++) {
566 req = usb_ep_alloc_request(out_ep, GFP_ATOMIC);
567 if (req) {
568 req->buf = kzalloc(req_buf_size,
569 GFP_ATOMIC);
570 if (req->buf) {
571 req->length = req_buf_size;
572 req->context = audio;
573 req->complete =
574 f_audio_complete;
575 err = usb_ep_queue(out_ep,
576 req, GFP_ATOMIC);
577 if (err)
578 ERROR(cdev,
579 "%s queue req: %d\n",
580 out_ep->name, err);
581 } else
582 err = -ENOMEM;
583 } else
584 err = -ENOMEM;
585 }
586
587 } else {
588 struct f_audio_buf *copy_buf = audio->copy_buf;
589 if (copy_buf) {
590 list_add_tail(&copy_buf->list,
591 &audio->play_queue);
592 schedule_work(&audio->playback_work);
593 }
594 }
595 }
596
597 return err;
598}
599
600static void f_audio_disable(struct usb_function *f)
601{
602 return;
603}
604
605/*-------------------------------------------------------------------------*/
606
607static void f_audio_build_desc(struct f_audio *audio)
608{
609 struct gaudio *card = &audio->card;
610 u8 *sam_freq;
611 int rate;
612
613 /* Set channel numbers */
614 input_terminal_desc.bNrChannels = u_audio_get_playback_channels(card);
615 as_type_i_desc.bNrChannels = u_audio_get_playback_channels(card);
616
617 /* Set sample rates */
618 rate = u_audio_get_playback_rate(card);
619 sam_freq = as_type_i_desc.tSamFreq[0];
620 memcpy(sam_freq, &rate, 3);
621
622 /* Todo: Set Sample bits and other parameters */
623
624 return;
625}
626
627/* audio function driver setup/binding */
628static int __init
629f_audio_bind(struct usb_configuration *c, struct usb_function *f)
630{
631 struct usb_composite_dev *cdev = c->cdev;
632 struct f_audio *audio = func_to_audio(f);
633 int status;
634 struct usb_ep *ep = NULL;
635
636 f_audio_build_desc(audio);
637
638 /* allocate instance-specific interface IDs, and patch descriptors */
639 status = usb_interface_id(c, f);
640 if (status < 0)
641 goto fail;
642 ac_interface_desc.bInterfaceNumber = status;
643
644 status = usb_interface_id(c, f);
645 if (status < 0)
646 goto fail;
647 as_interface_alt_0_desc.bInterfaceNumber = status;
648 as_interface_alt_1_desc.bInterfaceNumber = status;
649
650 status = -ENODEV;
651
652 /* allocate instance-specific endpoints */
653 ep = usb_ep_autoconfig(cdev->gadget, &as_out_ep_desc);
654 if (!ep)
655 goto fail;
656 audio->out_ep = ep;
657 audio->out_ep->desc = &as_out_ep_desc;
658 ep->driver_data = cdev; /* claim */
659
660 status = -ENOMEM;
661
662 /* copy descriptors, and track endpoint copies */
663 status = usb_assign_descriptors(f, f_audio_desc, f_audio_desc, NULL);
664 if (status)
665 goto fail;
666 return 0;
667
668fail:
669 if (ep)
670 ep->driver_data = NULL;
671 return status;
672}
673
674static void
675f_audio_unbind(struct usb_configuration *c, struct usb_function *f)
676{
677 struct f_audio *audio = func_to_audio(f);
678
679 usb_free_all_descriptors(f);
680 kfree(audio);
681}
682
683/*-------------------------------------------------------------------------*/
684
685static int generic_set_cmd(struct usb_audio_control *con, u8 cmd, int value)
686{
687 con->data[cmd] = value;
688
689 return 0;
690}
691
692static int generic_get_cmd(struct usb_audio_control *con, u8 cmd)
693{
694 return con->data[cmd];
695}
696
697/* Todo: add more control selecotor dynamically */
698static int __init control_selector_init(struct f_audio *audio)
699{
700 INIT_LIST_HEAD(&audio->cs);
701 list_add(&feature_unit.list, &audio->cs);
702
703 INIT_LIST_HEAD(&feature_unit.control);
704 list_add(&mute_control.list, &feature_unit.control);
705 list_add(&volume_control.list, &feature_unit.control);
706
707 volume_control.data[UAC__CUR] = 0xffc0;
708 volume_control.data[UAC__MIN] = 0xe3a0;
709 volume_control.data[UAC__MAX] = 0xfff0;
710 volume_control.data[UAC__RES] = 0x0030;
711
712 return 0;
713}
714
715/**
716 * audio_bind_config - add USB audio function to a configuration
717 * @c: the configuration to supcard the USB audio function
718 * Context: single threaded during gadget setup
719 *
720 * Returns zero on success, else negative errno.
721 */
722static int __init audio_bind_config(struct usb_configuration *c)
723{
724 struct f_audio *audio;
725 int status;
726
727 /* allocate and initialize one new instance */
728 audio = kzalloc(sizeof *audio, GFP_KERNEL);
729 if (!audio)
730 return -ENOMEM;
731
732 audio->card.func.name = "g_audio";
733 audio->card.gadget = c->cdev->gadget;
734
735 INIT_LIST_HEAD(&audio->play_queue);
736 spin_lock_init(&audio->lock);
737
738 /* set up ASLA audio devices */
739 status = gaudio_setup(&audio->card);
740 if (status < 0)
741 goto setup_fail;
742
743 audio->card.func.strings = audio_strings;
744 audio->card.func.bind = f_audio_bind;
745 audio->card.func.unbind = f_audio_unbind;
746 audio->card.func.set_alt = f_audio_set_alt;
747 audio->card.func.setup = f_audio_setup;
748 audio->card.func.disable = f_audio_disable;
749
750 control_selector_init(audio);
751
752 INIT_WORK(&audio->playback_work, f_audio_playback_work);
753
754 status = usb_add_function(c, &audio->card.func);
755 if (status)
756 goto add_fail;
757
758 INFO(c->cdev, "audio_buf_size %d, req_buf_size %d, req_count %d\n",
759 audio_buf_size, req_buf_size, req_count);
760
761 return status;
762
763add_fail:
764 gaudio_cleanup();
765setup_fail:
766 kfree(audio);
767 return status;
768}
diff --git a/drivers/usb/gadget/function/f_uac2.c b/drivers/usb/gadget/function/f_uac2.c
new file mode 100644
index 000000000000..3ed89ecc8d6d
--- /dev/null
+++ b/drivers/usb/gadget/function/f_uac2.c
@@ -0,0 +1,1374 @@
1/*
2 * f_uac2.c -- USB Audio Class 2.0 Function
3 *
4 * Copyright (C) 2011
5 * Yadwinder Singh (yadi.brar01@gmail.com)
6 * Jaswinder Singh (jaswinder.singh@linaro.org)
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 */
13
14#include <linux/usb/audio.h>
15#include <linux/usb/audio-v2.h>
16#include <linux/platform_device.h>
17#include <linux/module.h>
18
19#include <sound/core.h>
20#include <sound/pcm.h>
21#include <sound/pcm_params.h>
22
23/* Playback(USB-IN) Default Stereo - Fl/Fr */
24static int p_chmask = 0x3;
25module_param(p_chmask, uint, S_IRUGO);
26MODULE_PARM_DESC(p_chmask, "Playback Channel Mask");
27
28/* Playback Default 48 KHz */
29static int p_srate = 48000;
30module_param(p_srate, uint, S_IRUGO);
31MODULE_PARM_DESC(p_srate, "Playback Sampling Rate");
32
33/* Playback Default 16bits/sample */
34static int p_ssize = 2;
35module_param(p_ssize, uint, S_IRUGO);
36MODULE_PARM_DESC(p_ssize, "Playback Sample Size(bytes)");
37
38/* Capture(USB-OUT) Default Stereo - Fl/Fr */
39static int c_chmask = 0x3;
40module_param(c_chmask, uint, S_IRUGO);
41MODULE_PARM_DESC(c_chmask, "Capture Channel Mask");
42
43/* Capture Default 64 KHz */
44static int c_srate = 64000;
45module_param(c_srate, uint, S_IRUGO);
46MODULE_PARM_DESC(c_srate, "Capture Sampling Rate");
47
48/* Capture Default 16bits/sample */
49static int c_ssize = 2;
50module_param(c_ssize, uint, S_IRUGO);
51MODULE_PARM_DESC(c_ssize, "Capture Sample Size(bytes)");
52
53/* Keep everyone on toes */
54#define USB_XFERS 2
55
56/*
57 * The driver implements a simple UAC_2 topology.
58 * USB-OUT -> IT_1 -> OT_3 -> ALSA_Capture
59 * ALSA_Playback -> IT_2 -> OT_4 -> USB-IN
60 * Capture and Playback sampling rates are independently
61 * controlled by two clock sources :
62 * CLK_5 := c_srate, and CLK_6 := p_srate
63 */
64#define USB_OUT_IT_ID 1
65#define IO_IN_IT_ID 2
66#define IO_OUT_OT_ID 3
67#define USB_IN_OT_ID 4
68#define USB_OUT_CLK_ID 5
69#define USB_IN_CLK_ID 6
70
71#define CONTROL_ABSENT 0
72#define CONTROL_RDONLY 1
73#define CONTROL_RDWR 3
74
75#define CLK_FREQ_CTRL 0
76#define CLK_VLD_CTRL 2
77
78#define COPY_CTRL 0
79#define CONN_CTRL 2
80#define OVRLD_CTRL 4
81#define CLSTR_CTRL 6
82#define UNFLW_CTRL 8
83#define OVFLW_CTRL 10
84
85const char *uac2_name = "snd_uac2";
86
87struct uac2_req {
88 struct uac2_rtd_params *pp; /* parent param */
89 struct usb_request *req;
90};
91
92struct uac2_rtd_params {
93 struct snd_uac2_chip *uac2; /* parent chip */
94 bool ep_enabled; /* if the ep is enabled */
95 /* Size of the ring buffer */
96 size_t dma_bytes;
97 unsigned char *dma_area;
98
99 struct snd_pcm_substream *ss;
100
101 /* Ring buffer */
102 ssize_t hw_ptr;
103
104 void *rbuf;
105
106 size_t period_size;
107
108 unsigned max_psize;
109 struct uac2_req ureq[USB_XFERS];
110
111 spinlock_t lock;
112};
113
114struct snd_uac2_chip {
115 struct platform_device pdev;
116 struct platform_driver pdrv;
117
118 struct uac2_rtd_params p_prm;
119 struct uac2_rtd_params c_prm;
120
121 struct snd_card *card;
122 struct snd_pcm *pcm;
123};
124
125#define BUFF_SIZE_MAX (PAGE_SIZE * 16)
126#define PRD_SIZE_MAX PAGE_SIZE
127#define MIN_PERIODS 4
128
129static struct snd_pcm_hardware uac2_pcm_hardware = {
130 .info = SNDRV_PCM_INFO_INTERLEAVED | SNDRV_PCM_INFO_BLOCK_TRANSFER
131 | SNDRV_PCM_INFO_MMAP | SNDRV_PCM_INFO_MMAP_VALID
132 | SNDRV_PCM_INFO_PAUSE | SNDRV_PCM_INFO_RESUME,
133 .rates = SNDRV_PCM_RATE_CONTINUOUS,
134 .periods_max = BUFF_SIZE_MAX / PRD_SIZE_MAX,
135 .buffer_bytes_max = BUFF_SIZE_MAX,
136 .period_bytes_max = PRD_SIZE_MAX,
137 .periods_min = MIN_PERIODS,
138};
139
140struct audio_dev {
141 u8 ac_intf, ac_alt;
142 u8 as_out_intf, as_out_alt;
143 u8 as_in_intf, as_in_alt;
144
145 struct usb_ep *in_ep, *out_ep;
146 struct usb_function func;
147
148 /* The ALSA Sound Card it represents on the USB-Client side */
149 struct snd_uac2_chip uac2;
150};
151
152static struct audio_dev *agdev_g;
153
154static inline
155struct audio_dev *func_to_agdev(struct usb_function *f)
156{
157 return container_of(f, struct audio_dev, func);
158}
159
160static inline
161struct audio_dev *uac2_to_agdev(struct snd_uac2_chip *u)
162{
163 return container_of(u, struct audio_dev, uac2);
164}
165
166static inline
167struct snd_uac2_chip *pdev_to_uac2(struct platform_device *p)
168{
169 return container_of(p, struct snd_uac2_chip, pdev);
170}
171
172static inline
173uint num_channels(uint chanmask)
174{
175 uint num = 0;
176
177 while (chanmask) {
178 num += (chanmask & 1);
179 chanmask >>= 1;
180 }
181
182 return num;
183}
184
185static void
186agdev_iso_complete(struct usb_ep *ep, struct usb_request *req)
187{
188 unsigned pending;
189 unsigned long flags;
190 bool update_alsa = false;
191 unsigned char *src, *dst;
192 int status = req->status;
193 struct uac2_req *ur = req->context;
194 struct snd_pcm_substream *substream;
195 struct uac2_rtd_params *prm = ur->pp;
196 struct snd_uac2_chip *uac2 = prm->uac2;
197
198 /* i/f shutting down */
199 if (!prm->ep_enabled || req->status == -ESHUTDOWN)
200 return;
201
202 /*
203 * We can't really do much about bad xfers.
204 * Afterall, the ISOCH xfers could fail legitimately.
205 */
206 if (status)
207 pr_debug("%s: iso_complete status(%d) %d/%d\n",
208 __func__, status, req->actual, req->length);
209
210 substream = prm->ss;
211
212 /* Do nothing if ALSA isn't active */
213 if (!substream)
214 goto exit;
215
216 spin_lock_irqsave(&prm->lock, flags);
217
218 if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
219 src = prm->dma_area + prm->hw_ptr;
220 req->actual = req->length;
221 dst = req->buf;
222 } else {
223 dst = prm->dma_area + prm->hw_ptr;
224 src = req->buf;
225 }
226
227 pending = prm->hw_ptr % prm->period_size;
228 pending += req->actual;
229 if (pending >= prm->period_size)
230 update_alsa = true;
231
232 prm->hw_ptr = (prm->hw_ptr + req->actual) % prm->dma_bytes;
233
234 spin_unlock_irqrestore(&prm->lock, flags);
235
236 /* Pack USB load in ALSA ring buffer */
237 memcpy(dst, src, req->actual);
238exit:
239 if (usb_ep_queue(ep, req, GFP_ATOMIC))
240 dev_err(&uac2->pdev.dev, "%d Error!\n", __LINE__);
241
242 if (update_alsa)
243 snd_pcm_period_elapsed(substream);
244
245 return;
246}
247
248static int
249uac2_pcm_trigger(struct snd_pcm_substream *substream, int cmd)
250{
251 struct snd_uac2_chip *uac2 = snd_pcm_substream_chip(substream);
252 struct uac2_rtd_params *prm;
253 unsigned long flags;
254 int err = 0;
255
256 if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
257 prm = &uac2->p_prm;
258 else
259 prm = &uac2->c_prm;
260
261 spin_lock_irqsave(&prm->lock, flags);
262
263 /* Reset */
264 prm->hw_ptr = 0;
265
266 switch (cmd) {
267 case SNDRV_PCM_TRIGGER_START:
268 case SNDRV_PCM_TRIGGER_RESUME:
269 prm->ss = substream;
270 break;
271 case SNDRV_PCM_TRIGGER_STOP:
272 case SNDRV_PCM_TRIGGER_SUSPEND:
273 prm->ss = NULL;
274 break;
275 default:
276 err = -EINVAL;
277 }
278
279 spin_unlock_irqrestore(&prm->lock, flags);
280
281 /* Clear buffer after Play stops */
282 if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK && !prm->ss)
283 memset(prm->rbuf, 0, prm->max_psize * USB_XFERS);
284
285 return err;
286}
287
288static snd_pcm_uframes_t uac2_pcm_pointer(struct snd_pcm_substream *substream)
289{
290 struct snd_uac2_chip *uac2 = snd_pcm_substream_chip(substream);
291 struct uac2_rtd_params *prm;
292
293 if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
294 prm = &uac2->p_prm;
295 else
296 prm = &uac2->c_prm;
297
298 return bytes_to_frames(substream->runtime, prm->hw_ptr);
299}
300
301static int uac2_pcm_hw_params(struct snd_pcm_substream *substream,
302 struct snd_pcm_hw_params *hw_params)
303{
304 struct snd_uac2_chip *uac2 = snd_pcm_substream_chip(substream);
305 struct uac2_rtd_params *prm;
306 int err;
307
308 if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
309 prm = &uac2->p_prm;
310 else
311 prm = &uac2->c_prm;
312
313 err = snd_pcm_lib_malloc_pages(substream,
314 params_buffer_bytes(hw_params));
315 if (err >= 0) {
316 prm->dma_bytes = substream->runtime->dma_bytes;
317 prm->dma_area = substream->runtime->dma_area;
318 prm->period_size = params_period_bytes(hw_params);
319 }
320
321 return err;
322}
323
324static int uac2_pcm_hw_free(struct snd_pcm_substream *substream)
325{
326 struct snd_uac2_chip *uac2 = snd_pcm_substream_chip(substream);
327 struct uac2_rtd_params *prm;
328
329 if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
330 prm = &uac2->p_prm;
331 else
332 prm = &uac2->c_prm;
333
334 prm->dma_area = NULL;
335 prm->dma_bytes = 0;
336 prm->period_size = 0;
337
338 return snd_pcm_lib_free_pages(substream);
339}
340
341static int uac2_pcm_open(struct snd_pcm_substream *substream)
342{
343 struct snd_uac2_chip *uac2 = snd_pcm_substream_chip(substream);
344 struct snd_pcm_runtime *runtime = substream->runtime;
345
346 runtime->hw = uac2_pcm_hardware;
347
348 if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) {
349 spin_lock_init(&uac2->p_prm.lock);
350 runtime->hw.rate_min = p_srate;
351 switch (p_ssize) {
352 case 3:
353 runtime->hw.formats = SNDRV_PCM_FMTBIT_S24_3LE;
354 break;
355 case 4:
356 runtime->hw.formats = SNDRV_PCM_FMTBIT_S32_LE;
357 break;
358 default:
359 runtime->hw.formats = SNDRV_PCM_FMTBIT_S16_LE;
360 break;
361 }
362 runtime->hw.channels_min = num_channels(p_chmask);
363 runtime->hw.period_bytes_min = 2 * uac2->p_prm.max_psize
364 / runtime->hw.periods_min;
365 } else {
366 spin_lock_init(&uac2->c_prm.lock);
367 runtime->hw.rate_min = c_srate;
368 switch (c_ssize) {
369 case 3:
370 runtime->hw.formats = SNDRV_PCM_FMTBIT_S24_3LE;
371 break;
372 case 4:
373 runtime->hw.formats = SNDRV_PCM_FMTBIT_S32_LE;
374 break;
375 default:
376 runtime->hw.formats = SNDRV_PCM_FMTBIT_S16_LE;
377 break;
378 }
379 runtime->hw.channels_min = num_channels(c_chmask);
380 runtime->hw.period_bytes_min = 2 * uac2->c_prm.max_psize
381 / runtime->hw.periods_min;
382 }
383
384 runtime->hw.rate_max = runtime->hw.rate_min;
385 runtime->hw.channels_max = runtime->hw.channels_min;
386
387 snd_pcm_hw_constraint_integer(runtime, SNDRV_PCM_HW_PARAM_PERIODS);
388
389 return 0;
390}
391
392/* ALSA cries without these function pointers */
393static int uac2_pcm_null(struct snd_pcm_substream *substream)
394{
395 return 0;
396}
397
398static struct snd_pcm_ops uac2_pcm_ops = {
399 .open = uac2_pcm_open,
400 .close = uac2_pcm_null,
401 .ioctl = snd_pcm_lib_ioctl,
402 .hw_params = uac2_pcm_hw_params,
403 .hw_free = uac2_pcm_hw_free,
404 .trigger = uac2_pcm_trigger,
405 .pointer = uac2_pcm_pointer,
406 .prepare = uac2_pcm_null,
407};
408
409static int snd_uac2_probe(struct platform_device *pdev)
410{
411 struct snd_uac2_chip *uac2 = pdev_to_uac2(pdev);
412 struct snd_card *card;
413 struct snd_pcm *pcm;
414 int err;
415
416 /* Choose any slot, with no id */
417 err = snd_card_new(&pdev->dev, -1, NULL, THIS_MODULE, 0, &card);
418 if (err < 0)
419 return err;
420
421 uac2->card = card;
422
423 /*
424 * Create first PCM device
425 * Create a substream only for non-zero channel streams
426 */
427 err = snd_pcm_new(uac2->card, "UAC2 PCM", 0,
428 p_chmask ? 1 : 0, c_chmask ? 1 : 0, &pcm);
429 if (err < 0)
430 goto snd_fail;
431
432 strcpy(pcm->name, "UAC2 PCM");
433 pcm->private_data = uac2;
434
435 uac2->pcm = pcm;
436
437 snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &uac2_pcm_ops);
438 snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &uac2_pcm_ops);
439
440 strcpy(card->driver, "UAC2_Gadget");
441 strcpy(card->shortname, "UAC2_Gadget");
442 sprintf(card->longname, "UAC2_Gadget %i", pdev->id);
443
444 snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_CONTINUOUS,
445 snd_dma_continuous_data(GFP_KERNEL), 0, BUFF_SIZE_MAX);
446
447 err = snd_card_register(card);
448 if (!err) {
449 platform_set_drvdata(pdev, card);
450 return 0;
451 }
452
453snd_fail:
454 snd_card_free(card);
455
456 uac2->pcm = NULL;
457 uac2->card = NULL;
458
459 return err;
460}
461
462static int snd_uac2_remove(struct platform_device *pdev)
463{
464 struct snd_card *card = platform_get_drvdata(pdev);
465
466 if (card)
467 return snd_card_free(card);
468
469 return 0;
470}
471
472static int alsa_uac2_init(struct audio_dev *agdev)
473{
474 struct snd_uac2_chip *uac2 = &agdev->uac2;
475 int err;
476
477 uac2->pdrv.probe = snd_uac2_probe;
478 uac2->pdrv.remove = snd_uac2_remove;
479 uac2->pdrv.driver.name = uac2_name;
480
481 uac2->pdev.id = 0;
482 uac2->pdev.name = uac2_name;
483
484 /* Register snd_uac2 driver */
485 err = platform_driver_register(&uac2->pdrv);
486 if (err)
487 return err;
488
489 /* Register snd_uac2 device */
490 err = platform_device_register(&uac2->pdev);
491 if (err)
492 platform_driver_unregister(&uac2->pdrv);
493
494 return err;
495}
496
497static void alsa_uac2_exit(struct audio_dev *agdev)
498{
499 struct snd_uac2_chip *uac2 = &agdev->uac2;
500
501 platform_driver_unregister(&uac2->pdrv);
502 platform_device_unregister(&uac2->pdev);
503}
504
505
506/* --------- USB Function Interface ------------- */
507
508enum {
509 STR_ASSOC,
510 STR_IF_CTRL,
511 STR_CLKSRC_IN,
512 STR_CLKSRC_OUT,
513 STR_USB_IT,
514 STR_IO_IT,
515 STR_USB_OT,
516 STR_IO_OT,
517 STR_AS_OUT_ALT0,
518 STR_AS_OUT_ALT1,
519 STR_AS_IN_ALT0,
520 STR_AS_IN_ALT1,
521};
522
523static char clksrc_in[8];
524static char clksrc_out[8];
525
526static struct usb_string strings_fn[] = {
527 [STR_ASSOC].s = "Source/Sink",
528 [STR_IF_CTRL].s = "Topology Control",
529 [STR_CLKSRC_IN].s = clksrc_in,
530 [STR_CLKSRC_OUT].s = clksrc_out,
531 [STR_USB_IT].s = "USBH Out",
532 [STR_IO_IT].s = "USBD Out",
533 [STR_USB_OT].s = "USBH In",
534 [STR_IO_OT].s = "USBD In",
535 [STR_AS_OUT_ALT0].s = "Playback Inactive",
536 [STR_AS_OUT_ALT1].s = "Playback Active",
537 [STR_AS_IN_ALT0].s = "Capture Inactive",
538 [STR_AS_IN_ALT1].s = "Capture Active",
539 { },
540};
541
542static struct usb_gadget_strings str_fn = {
543 .language = 0x0409, /* en-us */
544 .strings = strings_fn,
545};
546
547static struct usb_gadget_strings *fn_strings[] = {
548 &str_fn,
549 NULL,
550};
551
552static struct usb_qualifier_descriptor devqual_desc = {
553 .bLength = sizeof devqual_desc,
554 .bDescriptorType = USB_DT_DEVICE_QUALIFIER,
555
556 .bcdUSB = cpu_to_le16(0x200),
557 .bDeviceClass = USB_CLASS_MISC,
558 .bDeviceSubClass = 0x02,
559 .bDeviceProtocol = 0x01,
560 .bNumConfigurations = 1,
561 .bRESERVED = 0,
562};
563
564static struct usb_interface_assoc_descriptor iad_desc = {
565 .bLength = sizeof iad_desc,
566 .bDescriptorType = USB_DT_INTERFACE_ASSOCIATION,
567
568 .bFirstInterface = 0,
569 .bInterfaceCount = 3,
570 .bFunctionClass = USB_CLASS_AUDIO,
571 .bFunctionSubClass = UAC2_FUNCTION_SUBCLASS_UNDEFINED,
572 .bFunctionProtocol = UAC_VERSION_2,
573};
574
575/* Audio Control Interface */
576static struct usb_interface_descriptor std_ac_if_desc = {
577 .bLength = sizeof std_ac_if_desc,
578 .bDescriptorType = USB_DT_INTERFACE,
579
580 .bAlternateSetting = 0,
581 .bNumEndpoints = 0,
582 .bInterfaceClass = USB_CLASS_AUDIO,
583 .bInterfaceSubClass = USB_SUBCLASS_AUDIOCONTROL,
584 .bInterfaceProtocol = UAC_VERSION_2,
585};
586
587/* Clock source for IN traffic */
588struct uac_clock_source_descriptor in_clk_src_desc = {
589 .bLength = sizeof in_clk_src_desc,
590 .bDescriptorType = USB_DT_CS_INTERFACE,
591
592 .bDescriptorSubtype = UAC2_CLOCK_SOURCE,
593 .bClockID = USB_IN_CLK_ID,
594 .bmAttributes = UAC_CLOCK_SOURCE_TYPE_INT_FIXED,
595 .bmControls = (CONTROL_RDONLY << CLK_FREQ_CTRL),
596 .bAssocTerminal = 0,
597};
598
599/* Clock source for OUT traffic */
600struct uac_clock_source_descriptor out_clk_src_desc = {
601 .bLength = sizeof out_clk_src_desc,
602 .bDescriptorType = USB_DT_CS_INTERFACE,
603
604 .bDescriptorSubtype = UAC2_CLOCK_SOURCE,
605 .bClockID = USB_OUT_CLK_ID,
606 .bmAttributes = UAC_CLOCK_SOURCE_TYPE_INT_FIXED,
607 .bmControls = (CONTROL_RDONLY << CLK_FREQ_CTRL),
608 .bAssocTerminal = 0,
609};
610
611/* Input Terminal for USB_OUT */
612struct uac2_input_terminal_descriptor usb_out_it_desc = {
613 .bLength = sizeof usb_out_it_desc,
614 .bDescriptorType = USB_DT_CS_INTERFACE,
615
616 .bDescriptorSubtype = UAC_INPUT_TERMINAL,
617 .bTerminalID = USB_OUT_IT_ID,
618 .wTerminalType = cpu_to_le16(UAC_TERMINAL_STREAMING),
619 .bAssocTerminal = 0,
620 .bCSourceID = USB_OUT_CLK_ID,
621 .iChannelNames = 0,
622 .bmControls = (CONTROL_RDWR << COPY_CTRL),
623};
624
625/* Input Terminal for I/O-In */
626struct uac2_input_terminal_descriptor io_in_it_desc = {
627 .bLength = sizeof io_in_it_desc,
628 .bDescriptorType = USB_DT_CS_INTERFACE,
629
630 .bDescriptorSubtype = UAC_INPUT_TERMINAL,
631 .bTerminalID = IO_IN_IT_ID,
632 .wTerminalType = cpu_to_le16(UAC_INPUT_TERMINAL_UNDEFINED),
633 .bAssocTerminal = 0,
634 .bCSourceID = USB_IN_CLK_ID,
635 .iChannelNames = 0,
636 .bmControls = (CONTROL_RDWR << COPY_CTRL),
637};
638
639/* Ouput Terminal for USB_IN */
640struct uac2_output_terminal_descriptor usb_in_ot_desc = {
641 .bLength = sizeof usb_in_ot_desc,
642 .bDescriptorType = USB_DT_CS_INTERFACE,
643
644 .bDescriptorSubtype = UAC_OUTPUT_TERMINAL,
645 .bTerminalID = USB_IN_OT_ID,
646 .wTerminalType = cpu_to_le16(UAC_TERMINAL_STREAMING),
647 .bAssocTerminal = 0,
648 .bSourceID = IO_IN_IT_ID,
649 .bCSourceID = USB_IN_CLK_ID,
650 .bmControls = (CONTROL_RDWR << COPY_CTRL),
651};
652
653/* Ouput Terminal for I/O-Out */
654struct uac2_output_terminal_descriptor io_out_ot_desc = {
655 .bLength = sizeof io_out_ot_desc,
656 .bDescriptorType = USB_DT_CS_INTERFACE,
657
658 .bDescriptorSubtype = UAC_OUTPUT_TERMINAL,
659 .bTerminalID = IO_OUT_OT_ID,
660 .wTerminalType = cpu_to_le16(UAC_OUTPUT_TERMINAL_UNDEFINED),
661 .bAssocTerminal = 0,
662 .bSourceID = USB_OUT_IT_ID,
663 .bCSourceID = USB_OUT_CLK_ID,
664 .bmControls = (CONTROL_RDWR << COPY_CTRL),
665};
666
667struct uac2_ac_header_descriptor ac_hdr_desc = {
668 .bLength = sizeof ac_hdr_desc,
669 .bDescriptorType = USB_DT_CS_INTERFACE,
670
671 .bDescriptorSubtype = UAC_MS_HEADER,
672 .bcdADC = cpu_to_le16(0x200),
673 .bCategory = UAC2_FUNCTION_IO_BOX,
674 .wTotalLength = sizeof in_clk_src_desc + sizeof out_clk_src_desc
675 + sizeof usb_out_it_desc + sizeof io_in_it_desc
676 + sizeof usb_in_ot_desc + sizeof io_out_ot_desc,
677 .bmControls = 0,
678};
679
680/* Audio Streaming OUT Interface - Alt0 */
681static struct usb_interface_descriptor std_as_out_if0_desc = {
682 .bLength = sizeof std_as_out_if0_desc,
683 .bDescriptorType = USB_DT_INTERFACE,
684
685 .bAlternateSetting = 0,
686 .bNumEndpoints = 0,
687 .bInterfaceClass = USB_CLASS_AUDIO,
688 .bInterfaceSubClass = USB_SUBCLASS_AUDIOSTREAMING,
689 .bInterfaceProtocol = UAC_VERSION_2,
690};
691
692/* Audio Streaming OUT Interface - Alt1 */
693static struct usb_interface_descriptor std_as_out_if1_desc = {
694 .bLength = sizeof std_as_out_if1_desc,
695 .bDescriptorType = USB_DT_INTERFACE,
696
697 .bAlternateSetting = 1,
698 .bNumEndpoints = 1,
699 .bInterfaceClass = USB_CLASS_AUDIO,
700 .bInterfaceSubClass = USB_SUBCLASS_AUDIOSTREAMING,
701 .bInterfaceProtocol = UAC_VERSION_2,
702};
703
704/* Audio Stream OUT Intface Desc */
705struct uac2_as_header_descriptor as_out_hdr_desc = {
706 .bLength = sizeof as_out_hdr_desc,
707 .bDescriptorType = USB_DT_CS_INTERFACE,
708
709 .bDescriptorSubtype = UAC_AS_GENERAL,
710 .bTerminalLink = USB_OUT_IT_ID,
711 .bmControls = 0,
712 .bFormatType = UAC_FORMAT_TYPE_I,
713 .bmFormats = cpu_to_le32(UAC_FORMAT_TYPE_I_PCM),
714 .iChannelNames = 0,
715};
716
717/* Audio USB_OUT Format */
718struct uac2_format_type_i_descriptor as_out_fmt1_desc = {
719 .bLength = sizeof as_out_fmt1_desc,
720 .bDescriptorType = USB_DT_CS_INTERFACE,
721 .bDescriptorSubtype = UAC_FORMAT_TYPE,
722 .bFormatType = UAC_FORMAT_TYPE_I,
723};
724
725/* STD AS ISO OUT Endpoint */
726struct usb_endpoint_descriptor fs_epout_desc = {
727 .bLength = USB_DT_ENDPOINT_SIZE,
728 .bDescriptorType = USB_DT_ENDPOINT,
729
730 .bEndpointAddress = USB_DIR_OUT,
731 .bmAttributes = USB_ENDPOINT_XFER_ISOC | USB_ENDPOINT_SYNC_ASYNC,
732 .bInterval = 1,
733};
734
735struct usb_endpoint_descriptor hs_epout_desc = {
736 .bLength = USB_DT_ENDPOINT_SIZE,
737 .bDescriptorType = USB_DT_ENDPOINT,
738
739 .bmAttributes = USB_ENDPOINT_XFER_ISOC | USB_ENDPOINT_SYNC_ASYNC,
740 .bInterval = 4,
741};
742
743/* CS AS ISO OUT Endpoint */
744static struct uac2_iso_endpoint_descriptor as_iso_out_desc = {
745 .bLength = sizeof as_iso_out_desc,
746 .bDescriptorType = USB_DT_CS_ENDPOINT,
747
748 .bDescriptorSubtype = UAC_EP_GENERAL,
749 .bmAttributes = 0,
750 .bmControls = 0,
751 .bLockDelayUnits = 0,
752 .wLockDelay = 0,
753};
754
755/* Audio Streaming IN Interface - Alt0 */
756static struct usb_interface_descriptor std_as_in_if0_desc = {
757 .bLength = sizeof std_as_in_if0_desc,
758 .bDescriptorType = USB_DT_INTERFACE,
759
760 .bAlternateSetting = 0,
761 .bNumEndpoints = 0,
762 .bInterfaceClass = USB_CLASS_AUDIO,
763 .bInterfaceSubClass = USB_SUBCLASS_AUDIOSTREAMING,
764 .bInterfaceProtocol = UAC_VERSION_2,
765};
766
767/* Audio Streaming IN Interface - Alt1 */
768static struct usb_interface_descriptor std_as_in_if1_desc = {
769 .bLength = sizeof std_as_in_if1_desc,
770 .bDescriptorType = USB_DT_INTERFACE,
771
772 .bAlternateSetting = 1,
773 .bNumEndpoints = 1,
774 .bInterfaceClass = USB_CLASS_AUDIO,
775 .bInterfaceSubClass = USB_SUBCLASS_AUDIOSTREAMING,
776 .bInterfaceProtocol = UAC_VERSION_2,
777};
778
779/* Audio Stream IN Intface Desc */
780struct uac2_as_header_descriptor as_in_hdr_desc = {
781 .bLength = sizeof as_in_hdr_desc,
782 .bDescriptorType = USB_DT_CS_INTERFACE,
783
784 .bDescriptorSubtype = UAC_AS_GENERAL,
785 .bTerminalLink = USB_IN_OT_ID,
786 .bmControls = 0,
787 .bFormatType = UAC_FORMAT_TYPE_I,
788 .bmFormats = cpu_to_le32(UAC_FORMAT_TYPE_I_PCM),
789 .iChannelNames = 0,
790};
791
792/* Audio USB_IN Format */
793struct uac2_format_type_i_descriptor as_in_fmt1_desc = {
794 .bLength = sizeof as_in_fmt1_desc,
795 .bDescriptorType = USB_DT_CS_INTERFACE,
796 .bDescriptorSubtype = UAC_FORMAT_TYPE,
797 .bFormatType = UAC_FORMAT_TYPE_I,
798};
799
800/* STD AS ISO IN Endpoint */
801struct usb_endpoint_descriptor fs_epin_desc = {
802 .bLength = USB_DT_ENDPOINT_SIZE,
803 .bDescriptorType = USB_DT_ENDPOINT,
804
805 .bEndpointAddress = USB_DIR_IN,
806 .bmAttributes = USB_ENDPOINT_XFER_ISOC | USB_ENDPOINT_SYNC_ASYNC,
807 .bInterval = 1,
808};
809
810struct usb_endpoint_descriptor hs_epin_desc = {
811 .bLength = USB_DT_ENDPOINT_SIZE,
812 .bDescriptorType = USB_DT_ENDPOINT,
813
814 .bmAttributes = USB_ENDPOINT_XFER_ISOC | USB_ENDPOINT_SYNC_ASYNC,
815 .bInterval = 4,
816};
817
818/* CS AS ISO IN Endpoint */
819static struct uac2_iso_endpoint_descriptor as_iso_in_desc = {
820 .bLength = sizeof as_iso_in_desc,
821 .bDescriptorType = USB_DT_CS_ENDPOINT,
822
823 .bDescriptorSubtype = UAC_EP_GENERAL,
824 .bmAttributes = 0,
825 .bmControls = 0,
826 .bLockDelayUnits = 0,
827 .wLockDelay = 0,
828};
829
830static struct usb_descriptor_header *fs_audio_desc[] = {
831 (struct usb_descriptor_header *)&iad_desc,
832 (struct usb_descriptor_header *)&std_ac_if_desc,
833
834 (struct usb_descriptor_header *)&ac_hdr_desc,
835 (struct usb_descriptor_header *)&in_clk_src_desc,
836 (struct usb_descriptor_header *)&out_clk_src_desc,
837 (struct usb_descriptor_header *)&usb_out_it_desc,
838 (struct usb_descriptor_header *)&io_in_it_desc,
839 (struct usb_descriptor_header *)&usb_in_ot_desc,
840 (struct usb_descriptor_header *)&io_out_ot_desc,
841
842 (struct usb_descriptor_header *)&std_as_out_if0_desc,
843 (struct usb_descriptor_header *)&std_as_out_if1_desc,
844
845 (struct usb_descriptor_header *)&as_out_hdr_desc,
846 (struct usb_descriptor_header *)&as_out_fmt1_desc,
847 (struct usb_descriptor_header *)&fs_epout_desc,
848 (struct usb_descriptor_header *)&as_iso_out_desc,
849
850 (struct usb_descriptor_header *)&std_as_in_if0_desc,
851 (struct usb_descriptor_header *)&std_as_in_if1_desc,
852
853 (struct usb_descriptor_header *)&as_in_hdr_desc,
854 (struct usb_descriptor_header *)&as_in_fmt1_desc,
855 (struct usb_descriptor_header *)&fs_epin_desc,
856 (struct usb_descriptor_header *)&as_iso_in_desc,
857 NULL,
858};
859
860static struct usb_descriptor_header *hs_audio_desc[] = {
861 (struct usb_descriptor_header *)&iad_desc,
862 (struct usb_descriptor_header *)&std_ac_if_desc,
863
864 (struct usb_descriptor_header *)&ac_hdr_desc,
865 (struct usb_descriptor_header *)&in_clk_src_desc,
866 (struct usb_descriptor_header *)&out_clk_src_desc,
867 (struct usb_descriptor_header *)&usb_out_it_desc,
868 (struct usb_descriptor_header *)&io_in_it_desc,
869 (struct usb_descriptor_header *)&usb_in_ot_desc,
870 (struct usb_descriptor_header *)&io_out_ot_desc,
871
872 (struct usb_descriptor_header *)&std_as_out_if0_desc,
873 (struct usb_descriptor_header *)&std_as_out_if1_desc,
874
875 (struct usb_descriptor_header *)&as_out_hdr_desc,
876 (struct usb_descriptor_header *)&as_out_fmt1_desc,
877 (struct usb_descriptor_header *)&hs_epout_desc,
878 (struct usb_descriptor_header *)&as_iso_out_desc,
879
880 (struct usb_descriptor_header *)&std_as_in_if0_desc,
881 (struct usb_descriptor_header *)&std_as_in_if1_desc,
882
883 (struct usb_descriptor_header *)&as_in_hdr_desc,
884 (struct usb_descriptor_header *)&as_in_fmt1_desc,
885 (struct usb_descriptor_header *)&hs_epin_desc,
886 (struct usb_descriptor_header *)&as_iso_in_desc,
887 NULL,
888};
889
890struct cntrl_cur_lay3 {
891 __u32 dCUR;
892};
893
894struct cntrl_range_lay3 {
895 __u16 wNumSubRanges;
896 __u32 dMIN;
897 __u32 dMAX;
898 __u32 dRES;
899} __packed;
900
901static inline void
902free_ep(struct uac2_rtd_params *prm, struct usb_ep *ep)
903{
904 struct snd_uac2_chip *uac2 = prm->uac2;
905 int i;
906
907 prm->ep_enabled = false;
908
909 for (i = 0; i < USB_XFERS; i++) {
910 if (prm->ureq[i].req) {
911 usb_ep_dequeue(ep, prm->ureq[i].req);
912 usb_ep_free_request(ep, prm->ureq[i].req);
913 prm->ureq[i].req = NULL;
914 }
915 }
916
917 if (usb_ep_disable(ep))
918 dev_err(&uac2->pdev.dev,
919 "%s:%d Error!\n", __func__, __LINE__);
920}
921
922static int __init
923afunc_bind(struct usb_configuration *cfg, struct usb_function *fn)
924{
925 struct audio_dev *agdev = func_to_agdev(fn);
926 struct snd_uac2_chip *uac2 = &agdev->uac2;
927 struct usb_composite_dev *cdev = cfg->cdev;
928 struct usb_gadget *gadget = cdev->gadget;
929 struct uac2_rtd_params *prm;
930 int ret;
931
932 ret = usb_interface_id(cfg, fn);
933 if (ret < 0) {
934 dev_err(&uac2->pdev.dev,
935 "%s:%d Error!\n", __func__, __LINE__);
936 return ret;
937 }
938 std_ac_if_desc.bInterfaceNumber = ret;
939 agdev->ac_intf = ret;
940 agdev->ac_alt = 0;
941
942 ret = usb_interface_id(cfg, fn);
943 if (ret < 0) {
944 dev_err(&uac2->pdev.dev,
945 "%s:%d Error!\n", __func__, __LINE__);
946 return ret;
947 }
948 std_as_out_if0_desc.bInterfaceNumber = ret;
949 std_as_out_if1_desc.bInterfaceNumber = ret;
950 agdev->as_out_intf = ret;
951 agdev->as_out_alt = 0;
952
953 ret = usb_interface_id(cfg, fn);
954 if (ret < 0) {
955 dev_err(&uac2->pdev.dev,
956 "%s:%d Error!\n", __func__, __LINE__);
957 return ret;
958 }
959 std_as_in_if0_desc.bInterfaceNumber = ret;
960 std_as_in_if1_desc.bInterfaceNumber = ret;
961 agdev->as_in_intf = ret;
962 agdev->as_in_alt = 0;
963
964 agdev->out_ep = usb_ep_autoconfig(gadget, &fs_epout_desc);
965 if (!agdev->out_ep) {
966 dev_err(&uac2->pdev.dev,
967 "%s:%d Error!\n", __func__, __LINE__);
968 goto err;
969 }
970 agdev->out_ep->driver_data = agdev;
971
972 agdev->in_ep = usb_ep_autoconfig(gadget, &fs_epin_desc);
973 if (!agdev->in_ep) {
974 dev_err(&uac2->pdev.dev,
975 "%s:%d Error!\n", __func__, __LINE__);
976 goto err;
977 }
978 agdev->in_ep->driver_data = agdev;
979
980 uac2->p_prm.uac2 = uac2;
981 uac2->c_prm.uac2 = uac2;
982
983 hs_epout_desc.bEndpointAddress = fs_epout_desc.bEndpointAddress;
984 hs_epout_desc.wMaxPacketSize = fs_epout_desc.wMaxPacketSize;
985 hs_epin_desc.bEndpointAddress = fs_epin_desc.bEndpointAddress;
986 hs_epin_desc.wMaxPacketSize = fs_epin_desc.wMaxPacketSize;
987
988 ret = usb_assign_descriptors(fn, fs_audio_desc, hs_audio_desc, NULL);
989 if (ret)
990 goto err;
991
992 prm = &agdev->uac2.c_prm;
993 prm->max_psize = hs_epout_desc.wMaxPacketSize;
994 prm->rbuf = kzalloc(prm->max_psize * USB_XFERS, GFP_KERNEL);
995 if (!prm->rbuf) {
996 prm->max_psize = 0;
997 goto err;
998 }
999
1000 prm = &agdev->uac2.p_prm;
1001 prm->max_psize = hs_epin_desc.wMaxPacketSize;
1002 prm->rbuf = kzalloc(prm->max_psize * USB_XFERS, GFP_KERNEL);
1003 if (!prm->rbuf) {
1004 prm->max_psize = 0;
1005 goto err;
1006 }
1007
1008 ret = alsa_uac2_init(agdev);
1009 if (ret)
1010 goto err;
1011 return 0;
1012err:
1013 kfree(agdev->uac2.p_prm.rbuf);
1014 kfree(agdev->uac2.c_prm.rbuf);
1015 usb_free_all_descriptors(fn);
1016 if (agdev->in_ep)
1017 agdev->in_ep->driver_data = NULL;
1018 if (agdev->out_ep)
1019 agdev->out_ep->driver_data = NULL;
1020 return -EINVAL;
1021}
1022
1023static void
1024afunc_unbind(struct usb_configuration *cfg, struct usb_function *fn)
1025{
1026 struct audio_dev *agdev = func_to_agdev(fn);
1027 struct uac2_rtd_params *prm;
1028
1029 alsa_uac2_exit(agdev);
1030
1031 prm = &agdev->uac2.p_prm;
1032 kfree(prm->rbuf);
1033
1034 prm = &agdev->uac2.c_prm;
1035 kfree(prm->rbuf);
1036 usb_free_all_descriptors(fn);
1037
1038 if (agdev->in_ep)
1039 agdev->in_ep->driver_data = NULL;
1040 if (agdev->out_ep)
1041 agdev->out_ep->driver_data = NULL;
1042}
1043
1044static int
1045afunc_set_alt(struct usb_function *fn, unsigned intf, unsigned alt)
1046{
1047 struct usb_composite_dev *cdev = fn->config->cdev;
1048 struct audio_dev *agdev = func_to_agdev(fn);
1049 struct snd_uac2_chip *uac2 = &agdev->uac2;
1050 struct usb_gadget *gadget = cdev->gadget;
1051 struct usb_request *req;
1052 struct usb_ep *ep;
1053 struct uac2_rtd_params *prm;
1054 int i;
1055
1056 /* No i/f has more than 2 alt settings */
1057 if (alt > 1) {
1058 dev_err(&uac2->pdev.dev,
1059 "%s:%d Error!\n", __func__, __LINE__);
1060 return -EINVAL;
1061 }
1062
1063 if (intf == agdev->ac_intf) {
1064 /* Control I/f has only 1 AltSetting - 0 */
1065 if (alt) {
1066 dev_err(&uac2->pdev.dev,
1067 "%s:%d Error!\n", __func__, __LINE__);
1068 return -EINVAL;
1069 }
1070 return 0;
1071 }
1072
1073 if (intf == agdev->as_out_intf) {
1074 ep = agdev->out_ep;
1075 prm = &uac2->c_prm;
1076 config_ep_by_speed(gadget, fn, ep);
1077 agdev->as_out_alt = alt;
1078 } else if (intf == agdev->as_in_intf) {
1079 ep = agdev->in_ep;
1080 prm = &uac2->p_prm;
1081 config_ep_by_speed(gadget, fn, ep);
1082 agdev->as_in_alt = alt;
1083 } else {
1084 dev_err(&uac2->pdev.dev,
1085 "%s:%d Error!\n", __func__, __LINE__);
1086 return -EINVAL;
1087 }
1088
1089 if (alt == 0) {
1090 free_ep(prm, ep);
1091 return 0;
1092 }
1093
1094 prm->ep_enabled = true;
1095 usb_ep_enable(ep);
1096
1097 for (i = 0; i < USB_XFERS; i++) {
1098 if (prm->ureq[i].req) {
1099 if (usb_ep_queue(ep, prm->ureq[i].req, GFP_ATOMIC))
1100 dev_err(&uac2->pdev.dev, "%d Error!\n",
1101 __LINE__);
1102 continue;
1103 }
1104
1105 req = usb_ep_alloc_request(ep, GFP_ATOMIC);
1106 if (req == NULL) {
1107 dev_err(&uac2->pdev.dev,
1108 "%s:%d Error!\n", __func__, __LINE__);
1109 return -EINVAL;
1110 }
1111
1112 prm->ureq[i].req = req;
1113 prm->ureq[i].pp = prm;
1114
1115 req->zero = 0;
1116 req->context = &prm->ureq[i];
1117 req->length = prm->max_psize;
1118 req->complete = agdev_iso_complete;
1119 req->buf = prm->rbuf + i * req->length;
1120
1121 if (usb_ep_queue(ep, req, GFP_ATOMIC))
1122 dev_err(&uac2->pdev.dev, "%d Error!\n", __LINE__);
1123 }
1124
1125 return 0;
1126}
1127
1128static int
1129afunc_get_alt(struct usb_function *fn, unsigned intf)
1130{
1131 struct audio_dev *agdev = func_to_agdev(fn);
1132 struct snd_uac2_chip *uac2 = &agdev->uac2;
1133
1134 if (intf == agdev->ac_intf)
1135 return agdev->ac_alt;
1136 else if (intf == agdev->as_out_intf)
1137 return agdev->as_out_alt;
1138 else if (intf == agdev->as_in_intf)
1139 return agdev->as_in_alt;
1140 else
1141 dev_err(&uac2->pdev.dev,
1142 "%s:%d Invalid Interface %d!\n",
1143 __func__, __LINE__, intf);
1144
1145 return -EINVAL;
1146}
1147
1148static void
1149afunc_disable(struct usb_function *fn)
1150{
1151 struct audio_dev *agdev = func_to_agdev(fn);
1152 struct snd_uac2_chip *uac2 = &agdev->uac2;
1153
1154 free_ep(&uac2->p_prm, agdev->in_ep);
1155 agdev->as_in_alt = 0;
1156
1157 free_ep(&uac2->c_prm, agdev->out_ep);
1158 agdev->as_out_alt = 0;
1159}
1160
1161static int
1162in_rq_cur(struct usb_function *fn, const struct usb_ctrlrequest *cr)
1163{
1164 struct usb_request *req = fn->config->cdev->req;
1165 struct audio_dev *agdev = func_to_agdev(fn);
1166 struct snd_uac2_chip *uac2 = &agdev->uac2;
1167 u16 w_length = le16_to_cpu(cr->wLength);
1168 u16 w_index = le16_to_cpu(cr->wIndex);
1169 u16 w_value = le16_to_cpu(cr->wValue);
1170 u8 entity_id = (w_index >> 8) & 0xff;
1171 u8 control_selector = w_value >> 8;
1172 int value = -EOPNOTSUPP;
1173
1174 if (control_selector == UAC2_CS_CONTROL_SAM_FREQ) {
1175 struct cntrl_cur_lay3 c;
1176
1177 if (entity_id == USB_IN_CLK_ID)
1178 c.dCUR = p_srate;
1179 else if (entity_id == USB_OUT_CLK_ID)
1180 c.dCUR = c_srate;
1181
1182 value = min_t(unsigned, w_length, sizeof c);
1183 memcpy(req->buf, &c, value);
1184 } else if (control_selector == UAC2_CS_CONTROL_CLOCK_VALID) {
1185 *(u8 *)req->buf = 1;
1186 value = min_t(unsigned, w_length, 1);
1187 } else {
1188 dev_err(&uac2->pdev.dev,
1189 "%s:%d control_selector=%d TODO!\n",
1190 __func__, __LINE__, control_selector);
1191 }
1192
1193 return value;
1194}
1195
1196static int
1197in_rq_range(struct usb_function *fn, const struct usb_ctrlrequest *cr)
1198{
1199 struct usb_request *req = fn->config->cdev->req;
1200 struct audio_dev *agdev = func_to_agdev(fn);
1201 struct snd_uac2_chip *uac2 = &agdev->uac2;
1202 u16 w_length = le16_to_cpu(cr->wLength);
1203 u16 w_index = le16_to_cpu(cr->wIndex);
1204 u16 w_value = le16_to_cpu(cr->wValue);
1205 u8 entity_id = (w_index >> 8) & 0xff;
1206 u8 control_selector = w_value >> 8;
1207 struct cntrl_range_lay3 r;
1208 int value = -EOPNOTSUPP;
1209
1210 if (control_selector == UAC2_CS_CONTROL_SAM_FREQ) {
1211 if (entity_id == USB_IN_CLK_ID)
1212 r.dMIN = p_srate;
1213 else if (entity_id == USB_OUT_CLK_ID)
1214 r.dMIN = c_srate;
1215 else
1216 return -EOPNOTSUPP;
1217
1218 r.dMAX = r.dMIN;
1219 r.dRES = 0;
1220 r.wNumSubRanges = 1;
1221
1222 value = min_t(unsigned, w_length, sizeof r);
1223 memcpy(req->buf, &r, value);
1224 } else {
1225 dev_err(&uac2->pdev.dev,
1226 "%s:%d control_selector=%d TODO!\n",
1227 __func__, __LINE__, control_selector);
1228 }
1229
1230 return value;
1231}
1232
1233static int
1234ac_rq_in(struct usb_function *fn, const struct usb_ctrlrequest *cr)
1235{
1236 if (cr->bRequest == UAC2_CS_CUR)
1237 return in_rq_cur(fn, cr);
1238 else if (cr->bRequest == UAC2_CS_RANGE)
1239 return in_rq_range(fn, cr);
1240 else
1241 return -EOPNOTSUPP;
1242}
1243
1244static int
1245out_rq_cur(struct usb_function *fn, const struct usb_ctrlrequest *cr)
1246{
1247 u16 w_length = le16_to_cpu(cr->wLength);
1248 u16 w_value = le16_to_cpu(cr->wValue);
1249 u8 control_selector = w_value >> 8;
1250
1251 if (control_selector == UAC2_CS_CONTROL_SAM_FREQ)
1252 return w_length;
1253
1254 return -EOPNOTSUPP;
1255}
1256
1257static int
1258setup_rq_inf(struct usb_function *fn, const struct usb_ctrlrequest *cr)
1259{
1260 struct audio_dev *agdev = func_to_agdev(fn);
1261 struct snd_uac2_chip *uac2 = &agdev->uac2;
1262 u16 w_index = le16_to_cpu(cr->wIndex);
1263 u8 intf = w_index & 0xff;
1264
1265 if (intf != agdev->ac_intf) {
1266 dev_err(&uac2->pdev.dev,
1267 "%s:%d Error!\n", __func__, __LINE__);
1268 return -EOPNOTSUPP;
1269 }
1270
1271 if (cr->bRequestType & USB_DIR_IN)
1272 return ac_rq_in(fn, cr);
1273 else if (cr->bRequest == UAC2_CS_CUR)
1274 return out_rq_cur(fn, cr);
1275
1276 return -EOPNOTSUPP;
1277}
1278
1279static int
1280afunc_setup(struct usb_function *fn, const struct usb_ctrlrequest *cr)
1281{
1282 struct usb_composite_dev *cdev = fn->config->cdev;
1283 struct audio_dev *agdev = func_to_agdev(fn);
1284 struct snd_uac2_chip *uac2 = &agdev->uac2;
1285 struct usb_request *req = cdev->req;
1286 u16 w_length = le16_to_cpu(cr->wLength);
1287 int value = -EOPNOTSUPP;
1288
1289 /* Only Class specific requests are supposed to reach here */
1290 if ((cr->bRequestType & USB_TYPE_MASK) != USB_TYPE_CLASS)
1291 return -EOPNOTSUPP;
1292
1293 if ((cr->bRequestType & USB_RECIP_MASK) == USB_RECIP_INTERFACE)
1294 value = setup_rq_inf(fn, cr);
1295 else
1296 dev_err(&uac2->pdev.dev, "%s:%d Error!\n", __func__, __LINE__);
1297
1298 if (value >= 0) {
1299 req->length = value;
1300 req->zero = value < w_length;
1301 value = usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC);
1302 if (value < 0) {
1303 dev_err(&uac2->pdev.dev,
1304 "%s:%d Error!\n", __func__, __LINE__);
1305 req->status = 0;
1306 }
1307 }
1308
1309 return value;
1310}
1311
1312static int audio_bind_config(struct usb_configuration *cfg)
1313{
1314 int res;
1315
1316 agdev_g = kzalloc(sizeof *agdev_g, GFP_KERNEL);
1317 if (agdev_g == NULL)
1318 return -ENOMEM;
1319
1320 res = usb_string_ids_tab(cfg->cdev, strings_fn);
1321 if (res)
1322 return res;
1323 iad_desc.iFunction = strings_fn[STR_ASSOC].id;
1324 std_ac_if_desc.iInterface = strings_fn[STR_IF_CTRL].id;
1325 in_clk_src_desc.iClockSource = strings_fn[STR_CLKSRC_IN].id;
1326 out_clk_src_desc.iClockSource = strings_fn[STR_CLKSRC_OUT].id;
1327 usb_out_it_desc.iTerminal = strings_fn[STR_USB_IT].id;
1328 io_in_it_desc.iTerminal = strings_fn[STR_IO_IT].id;
1329 usb_in_ot_desc.iTerminal = strings_fn[STR_USB_OT].id;
1330 io_out_ot_desc.iTerminal = strings_fn[STR_IO_OT].id;
1331 std_as_out_if0_desc.iInterface = strings_fn[STR_AS_OUT_ALT0].id;
1332 std_as_out_if1_desc.iInterface = strings_fn[STR_AS_OUT_ALT1].id;
1333 std_as_in_if0_desc.iInterface = strings_fn[STR_AS_IN_ALT0].id;
1334 std_as_in_if1_desc.iInterface = strings_fn[STR_AS_IN_ALT1].id;
1335
1336 agdev_g->func.name = "uac2_func";
1337 agdev_g->func.strings = fn_strings;
1338 agdev_g->func.bind = afunc_bind;
1339 agdev_g->func.unbind = afunc_unbind;
1340 agdev_g->func.set_alt = afunc_set_alt;
1341 agdev_g->func.get_alt = afunc_get_alt;
1342 agdev_g->func.disable = afunc_disable;
1343 agdev_g->func.setup = afunc_setup;
1344
1345 /* Initialize the configurable parameters */
1346 usb_out_it_desc.bNrChannels = num_channels(c_chmask);
1347 usb_out_it_desc.bmChannelConfig = cpu_to_le32(c_chmask);
1348 io_in_it_desc.bNrChannels = num_channels(p_chmask);
1349 io_in_it_desc.bmChannelConfig = cpu_to_le32(p_chmask);
1350 as_out_hdr_desc.bNrChannels = num_channels(c_chmask);
1351 as_out_hdr_desc.bmChannelConfig = cpu_to_le32(c_chmask);
1352 as_in_hdr_desc.bNrChannels = num_channels(p_chmask);
1353 as_in_hdr_desc.bmChannelConfig = cpu_to_le32(p_chmask);
1354 as_out_fmt1_desc.bSubslotSize = c_ssize;
1355 as_out_fmt1_desc.bBitResolution = c_ssize * 8;
1356 as_in_fmt1_desc.bSubslotSize = p_ssize;
1357 as_in_fmt1_desc.bBitResolution = p_ssize * 8;
1358
1359 snprintf(clksrc_in, sizeof(clksrc_in), "%uHz", p_srate);
1360 snprintf(clksrc_out, sizeof(clksrc_out), "%uHz", c_srate);
1361
1362 res = usb_add_function(cfg, &agdev_g->func);
1363 if (res < 0)
1364 kfree(agdev_g);
1365
1366 return res;
1367}
1368
1369static void
1370uac2_unbind_config(struct usb_configuration *cfg)
1371{
1372 kfree(agdev_g);
1373 agdev_g = NULL;
1374}
diff --git a/drivers/usb/gadget/function/f_uvc.c b/drivers/usb/gadget/function/f_uvc.c
new file mode 100644
index 000000000000..e2a1f50bd93c
--- /dev/null
+++ b/drivers/usb/gadget/function/f_uvc.c
@@ -0,0 +1,836 @@
1/*
2 * uvc_gadget.c -- USB Video Class Gadget driver
3 *
4 * Copyright (C) 2009-2010
5 * Laurent Pinchart (laurent.pinchart@ideasonboard.com)
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 */
12
13#include <linux/kernel.h>
14#include <linux/device.h>
15#include <linux/errno.h>
16#include <linux/fs.h>
17#include <linux/list.h>
18#include <linux/mutex.h>
19#include <linux/string.h>
20#include <linux/usb/ch9.h>
21#include <linux/usb/gadget.h>
22#include <linux/usb/video.h>
23#include <linux/vmalloc.h>
24#include <linux/wait.h>
25
26#include <media/v4l2-dev.h>
27#include <media/v4l2-event.h>
28
29#include "uvc.h"
30
31unsigned int uvc_gadget_trace_param;
32
33/*-------------------------------------------------------------------------*/
34
35/* module parameters specific to the Video streaming endpoint */
36static unsigned int streaming_interval = 1;
37module_param(streaming_interval, uint, S_IRUGO|S_IWUSR);
38MODULE_PARM_DESC(streaming_interval, "1 - 16");
39
40static unsigned int streaming_maxpacket = 1024;
41module_param(streaming_maxpacket, uint, S_IRUGO|S_IWUSR);
42MODULE_PARM_DESC(streaming_maxpacket, "1 - 1023 (FS), 1 - 3072 (hs/ss)");
43
44static unsigned int streaming_maxburst;
45module_param(streaming_maxburst, uint, S_IRUGO|S_IWUSR);
46MODULE_PARM_DESC(streaming_maxburst, "0 - 15 (ss only)");
47
48/* --------------------------------------------------------------------------
49 * Function descriptors
50 */
51
52/* string IDs are assigned dynamically */
53
54#define UVC_STRING_CONTROL_IDX 0
55#define UVC_STRING_STREAMING_IDX 1
56
57static struct usb_string uvc_en_us_strings[] = {
58 [UVC_STRING_CONTROL_IDX].s = "UVC Camera",
59 [UVC_STRING_STREAMING_IDX].s = "Video Streaming",
60 { }
61};
62
63static struct usb_gadget_strings uvc_stringtab = {
64 .language = 0x0409, /* en-us */
65 .strings = uvc_en_us_strings,
66};
67
68static struct usb_gadget_strings *uvc_function_strings[] = {
69 &uvc_stringtab,
70 NULL,
71};
72
73#define UVC_INTF_VIDEO_CONTROL 0
74#define UVC_INTF_VIDEO_STREAMING 1
75
76#define UVC_STATUS_MAX_PACKET_SIZE 16 /* 16 bytes status */
77
78static struct usb_interface_assoc_descriptor uvc_iad __initdata = {
79 .bLength = sizeof(uvc_iad),
80 .bDescriptorType = USB_DT_INTERFACE_ASSOCIATION,
81 .bFirstInterface = 0,
82 .bInterfaceCount = 2,
83 .bFunctionClass = USB_CLASS_VIDEO,
84 .bFunctionSubClass = UVC_SC_VIDEO_INTERFACE_COLLECTION,
85 .bFunctionProtocol = 0x00,
86 .iFunction = 0,
87};
88
89static struct usb_interface_descriptor uvc_control_intf __initdata = {
90 .bLength = USB_DT_INTERFACE_SIZE,
91 .bDescriptorType = USB_DT_INTERFACE,
92 .bInterfaceNumber = UVC_INTF_VIDEO_CONTROL,
93 .bAlternateSetting = 0,
94 .bNumEndpoints = 1,
95 .bInterfaceClass = USB_CLASS_VIDEO,
96 .bInterfaceSubClass = UVC_SC_VIDEOCONTROL,
97 .bInterfaceProtocol = 0x00,
98 .iInterface = 0,
99};
100
101static struct usb_endpoint_descriptor uvc_control_ep __initdata = {
102 .bLength = USB_DT_ENDPOINT_SIZE,
103 .bDescriptorType = USB_DT_ENDPOINT,
104 .bEndpointAddress = USB_DIR_IN,
105 .bmAttributes = USB_ENDPOINT_XFER_INT,
106 .wMaxPacketSize = cpu_to_le16(UVC_STATUS_MAX_PACKET_SIZE),
107 .bInterval = 8,
108};
109
110static struct usb_ss_ep_comp_descriptor uvc_ss_control_comp __initdata = {
111 .bLength = sizeof(uvc_ss_control_comp),
112 .bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
113 /* The following 3 values can be tweaked if necessary. */
114 .bMaxBurst = 0,
115 .bmAttributes = 0,
116 .wBytesPerInterval = cpu_to_le16(UVC_STATUS_MAX_PACKET_SIZE),
117};
118
119static struct uvc_control_endpoint_descriptor uvc_control_cs_ep __initdata = {
120 .bLength = UVC_DT_CONTROL_ENDPOINT_SIZE,
121 .bDescriptorType = USB_DT_CS_ENDPOINT,
122 .bDescriptorSubType = UVC_EP_INTERRUPT,
123 .wMaxTransferSize = cpu_to_le16(UVC_STATUS_MAX_PACKET_SIZE),
124};
125
126static struct usb_interface_descriptor uvc_streaming_intf_alt0 __initdata = {
127 .bLength = USB_DT_INTERFACE_SIZE,
128 .bDescriptorType = USB_DT_INTERFACE,
129 .bInterfaceNumber = UVC_INTF_VIDEO_STREAMING,
130 .bAlternateSetting = 0,
131 .bNumEndpoints = 0,
132 .bInterfaceClass = USB_CLASS_VIDEO,
133 .bInterfaceSubClass = UVC_SC_VIDEOSTREAMING,
134 .bInterfaceProtocol = 0x00,
135 .iInterface = 0,
136};
137
138static struct usb_interface_descriptor uvc_streaming_intf_alt1 __initdata = {
139 .bLength = USB_DT_INTERFACE_SIZE,
140 .bDescriptorType = USB_DT_INTERFACE,
141 .bInterfaceNumber = UVC_INTF_VIDEO_STREAMING,
142 .bAlternateSetting = 1,
143 .bNumEndpoints = 1,
144 .bInterfaceClass = USB_CLASS_VIDEO,
145 .bInterfaceSubClass = UVC_SC_VIDEOSTREAMING,
146 .bInterfaceProtocol = 0x00,
147 .iInterface = 0,
148};
149
150static struct usb_endpoint_descriptor uvc_fs_streaming_ep __initdata = {
151 .bLength = USB_DT_ENDPOINT_SIZE,
152 .bDescriptorType = USB_DT_ENDPOINT,
153 .bEndpointAddress = USB_DIR_IN,
154 .bmAttributes = USB_ENDPOINT_SYNC_ASYNC
155 | USB_ENDPOINT_XFER_ISOC,
156 /* The wMaxPacketSize and bInterval values will be initialized from
157 * module parameters.
158 */
159};
160
161static struct usb_endpoint_descriptor uvc_hs_streaming_ep __initdata = {
162 .bLength = USB_DT_ENDPOINT_SIZE,
163 .bDescriptorType = USB_DT_ENDPOINT,
164 .bEndpointAddress = USB_DIR_IN,
165 .bmAttributes = USB_ENDPOINT_SYNC_ASYNC
166 | USB_ENDPOINT_XFER_ISOC,
167 /* The wMaxPacketSize and bInterval values will be initialized from
168 * module parameters.
169 */
170};
171
172static struct usb_endpoint_descriptor uvc_ss_streaming_ep __initdata = {
173 .bLength = USB_DT_ENDPOINT_SIZE,
174 .bDescriptorType = USB_DT_ENDPOINT,
175
176 .bEndpointAddress = USB_DIR_IN,
177 .bmAttributes = USB_ENDPOINT_SYNC_ASYNC
178 | USB_ENDPOINT_XFER_ISOC,
179 /* The wMaxPacketSize and bInterval values will be initialized from
180 * module parameters.
181 */
182};
183
184static struct usb_ss_ep_comp_descriptor uvc_ss_streaming_comp __initdata = {
185 .bLength = sizeof(uvc_ss_streaming_comp),
186 .bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
187 /* The bMaxBurst, bmAttributes and wBytesPerInterval values will be
188 * initialized from module parameters.
189 */
190};
191
192static const struct usb_descriptor_header * const uvc_fs_streaming[] = {
193 (struct usb_descriptor_header *) &uvc_streaming_intf_alt1,
194 (struct usb_descriptor_header *) &uvc_fs_streaming_ep,
195 NULL,
196};
197
198static const struct usb_descriptor_header * const uvc_hs_streaming[] = {
199 (struct usb_descriptor_header *) &uvc_streaming_intf_alt1,
200 (struct usb_descriptor_header *) &uvc_hs_streaming_ep,
201 NULL,
202};
203
204static const struct usb_descriptor_header * const uvc_ss_streaming[] = {
205 (struct usb_descriptor_header *) &uvc_streaming_intf_alt1,
206 (struct usb_descriptor_header *) &uvc_ss_streaming_ep,
207 (struct usb_descriptor_header *) &uvc_ss_streaming_comp,
208 NULL,
209};
210
211/* --------------------------------------------------------------------------
212 * Control requests
213 */
214
215static void
216uvc_function_ep0_complete(struct usb_ep *ep, struct usb_request *req)
217{
218 struct uvc_device *uvc = req->context;
219 struct v4l2_event v4l2_event;
220 struct uvc_event *uvc_event = (void *)&v4l2_event.u.data;
221
222 if (uvc->event_setup_out) {
223 uvc->event_setup_out = 0;
224
225 memset(&v4l2_event, 0, sizeof(v4l2_event));
226 v4l2_event.type = UVC_EVENT_DATA;
227 uvc_event->data.length = req->actual;
228 memcpy(&uvc_event->data.data, req->buf, req->actual);
229 v4l2_event_queue(uvc->vdev, &v4l2_event);
230 }
231}
232
233static int
234uvc_function_setup(struct usb_function *f, const struct usb_ctrlrequest *ctrl)
235{
236 struct uvc_device *uvc = to_uvc(f);
237 struct v4l2_event v4l2_event;
238 struct uvc_event *uvc_event = (void *)&v4l2_event.u.data;
239
240 /* printk(KERN_INFO "setup request %02x %02x value %04x index %04x %04x\n",
241 * ctrl->bRequestType, ctrl->bRequest, le16_to_cpu(ctrl->wValue),
242 * le16_to_cpu(ctrl->wIndex), le16_to_cpu(ctrl->wLength));
243 */
244
245 if ((ctrl->bRequestType & USB_TYPE_MASK) != USB_TYPE_CLASS) {
246 INFO(f->config->cdev, "invalid request type\n");
247 return -EINVAL;
248 }
249
250 /* Stall too big requests. */
251 if (le16_to_cpu(ctrl->wLength) > UVC_MAX_REQUEST_SIZE)
252 return -EINVAL;
253
254 memset(&v4l2_event, 0, sizeof(v4l2_event));
255 v4l2_event.type = UVC_EVENT_SETUP;
256 memcpy(&uvc_event->req, ctrl, sizeof(uvc_event->req));
257 v4l2_event_queue(uvc->vdev, &v4l2_event);
258
259 return 0;
260}
261
262void uvc_function_setup_continue(struct uvc_device *uvc)
263{
264 struct usb_composite_dev *cdev = uvc->func.config->cdev;
265
266 usb_composite_setup_continue(cdev);
267}
268
269static int
270uvc_function_get_alt(struct usb_function *f, unsigned interface)
271{
272 struct uvc_device *uvc = to_uvc(f);
273
274 INFO(f->config->cdev, "uvc_function_get_alt(%u)\n", interface);
275
276 if (interface == uvc->control_intf)
277 return 0;
278 else if (interface != uvc->streaming_intf)
279 return -EINVAL;
280 else
281 return uvc->state == UVC_STATE_STREAMING ? 1 : 0;
282}
283
284static int
285uvc_function_set_alt(struct usb_function *f, unsigned interface, unsigned alt)
286{
287 struct uvc_device *uvc = to_uvc(f);
288 struct v4l2_event v4l2_event;
289 struct uvc_event *uvc_event = (void *)&v4l2_event.u.data;
290 int ret;
291
292 INFO(f->config->cdev, "uvc_function_set_alt(%u, %u)\n", interface, alt);
293
294 if (interface == uvc->control_intf) {
295 if (alt)
296 return -EINVAL;
297
298 if (uvc->state == UVC_STATE_DISCONNECTED) {
299 memset(&v4l2_event, 0, sizeof(v4l2_event));
300 v4l2_event.type = UVC_EVENT_CONNECT;
301 uvc_event->speed = f->config->cdev->gadget->speed;
302 v4l2_event_queue(uvc->vdev, &v4l2_event);
303
304 uvc->state = UVC_STATE_CONNECTED;
305 }
306
307 return 0;
308 }
309
310 if (interface != uvc->streaming_intf)
311 return -EINVAL;
312
313 /* TODO
314 if (usb_endpoint_xfer_bulk(&uvc->desc.vs_ep))
315 return alt ? -EINVAL : 0;
316 */
317
318 switch (alt) {
319 case 0:
320 if (uvc->state != UVC_STATE_STREAMING)
321 return 0;
322
323 if (uvc->video.ep)
324 usb_ep_disable(uvc->video.ep);
325
326 memset(&v4l2_event, 0, sizeof(v4l2_event));
327 v4l2_event.type = UVC_EVENT_STREAMOFF;
328 v4l2_event_queue(uvc->vdev, &v4l2_event);
329
330 uvc->state = UVC_STATE_CONNECTED;
331 return 0;
332
333 case 1:
334 if (uvc->state != UVC_STATE_CONNECTED)
335 return 0;
336
337 if (uvc->video.ep) {
338 ret = config_ep_by_speed(f->config->cdev->gadget,
339 &(uvc->func), uvc->video.ep);
340 if (ret)
341 return ret;
342 usb_ep_enable(uvc->video.ep);
343 }
344
345 memset(&v4l2_event, 0, sizeof(v4l2_event));
346 v4l2_event.type = UVC_EVENT_STREAMON;
347 v4l2_event_queue(uvc->vdev, &v4l2_event);
348 return USB_GADGET_DELAYED_STATUS;
349
350 default:
351 return -EINVAL;
352 }
353}
354
355static void
356uvc_function_disable(struct usb_function *f)
357{
358 struct uvc_device *uvc = to_uvc(f);
359 struct v4l2_event v4l2_event;
360
361 INFO(f->config->cdev, "uvc_function_disable\n");
362
363 memset(&v4l2_event, 0, sizeof(v4l2_event));
364 v4l2_event.type = UVC_EVENT_DISCONNECT;
365 v4l2_event_queue(uvc->vdev, &v4l2_event);
366
367 uvc->state = UVC_STATE_DISCONNECTED;
368}
369
370/* --------------------------------------------------------------------------
371 * Connection / disconnection
372 */
373
374void
375uvc_function_connect(struct uvc_device *uvc)
376{
377 struct usb_composite_dev *cdev = uvc->func.config->cdev;
378 int ret;
379
380 if ((ret = usb_function_activate(&uvc->func)) < 0)
381 INFO(cdev, "UVC connect failed with %d\n", ret);
382}
383
384void
385uvc_function_disconnect(struct uvc_device *uvc)
386{
387 struct usb_composite_dev *cdev = uvc->func.config->cdev;
388 int ret;
389
390 if ((ret = usb_function_deactivate(&uvc->func)) < 0)
391 INFO(cdev, "UVC disconnect failed with %d\n", ret);
392}
393
394/* --------------------------------------------------------------------------
395 * USB probe and disconnect
396 */
397
398static int
399uvc_register_video(struct uvc_device *uvc)
400{
401 struct usb_composite_dev *cdev = uvc->func.config->cdev;
402 struct video_device *video;
403
404 /* TODO reference counting. */
405 video = video_device_alloc();
406 if (video == NULL)
407 return -ENOMEM;
408
409 video->v4l2_dev = &uvc->v4l2_dev;
410 video->fops = &uvc_v4l2_fops;
411 video->release = video_device_release;
412 strlcpy(video->name, cdev->gadget->name, sizeof(video->name));
413
414 uvc->vdev = video;
415 video_set_drvdata(video, uvc);
416
417 return video_register_device(video, VFL_TYPE_GRABBER, -1);
418}
419
420#define UVC_COPY_DESCRIPTOR(mem, dst, desc) \
421 do { \
422 memcpy(mem, desc, (desc)->bLength); \
423 *(dst)++ = mem; \
424 mem += (desc)->bLength; \
425 } while (0);
426
427#define UVC_COPY_DESCRIPTORS(mem, dst, src) \
428 do { \
429 const struct usb_descriptor_header * const *__src; \
430 for (__src = src; *__src; ++__src) { \
431 memcpy(mem, *__src, (*__src)->bLength); \
432 *dst++ = mem; \
433 mem += (*__src)->bLength; \
434 } \
435 } while (0)
436
437static struct usb_descriptor_header ** __init
438uvc_copy_descriptors(struct uvc_device *uvc, enum usb_device_speed speed)
439{
440 struct uvc_input_header_descriptor *uvc_streaming_header;
441 struct uvc_header_descriptor *uvc_control_header;
442 const struct uvc_descriptor_header * const *uvc_control_desc;
443 const struct uvc_descriptor_header * const *uvc_streaming_cls;
444 const struct usb_descriptor_header * const *uvc_streaming_std;
445 const struct usb_descriptor_header * const *src;
446 struct usb_descriptor_header **dst;
447 struct usb_descriptor_header **hdr;
448 unsigned int control_size;
449 unsigned int streaming_size;
450 unsigned int n_desc;
451 unsigned int bytes;
452 void *mem;
453
454 switch (speed) {
455 case USB_SPEED_SUPER:
456 uvc_control_desc = uvc->desc.ss_control;
457 uvc_streaming_cls = uvc->desc.ss_streaming;
458 uvc_streaming_std = uvc_ss_streaming;
459 break;
460
461 case USB_SPEED_HIGH:
462 uvc_control_desc = uvc->desc.fs_control;
463 uvc_streaming_cls = uvc->desc.hs_streaming;
464 uvc_streaming_std = uvc_hs_streaming;
465 break;
466
467 case USB_SPEED_FULL:
468 default:
469 uvc_control_desc = uvc->desc.fs_control;
470 uvc_streaming_cls = uvc->desc.fs_streaming;
471 uvc_streaming_std = uvc_fs_streaming;
472 break;
473 }
474
475 /* Descriptors layout
476 *
477 * uvc_iad
478 * uvc_control_intf
479 * Class-specific UVC control descriptors
480 * uvc_control_ep
481 * uvc_control_cs_ep
482 * uvc_ss_control_comp (for SS only)
483 * uvc_streaming_intf_alt0
484 * Class-specific UVC streaming descriptors
485 * uvc_{fs|hs}_streaming
486 */
487
488 /* Count descriptors and compute their size. */
489 control_size = 0;
490 streaming_size = 0;
491 bytes = uvc_iad.bLength + uvc_control_intf.bLength
492 + uvc_control_ep.bLength + uvc_control_cs_ep.bLength
493 + uvc_streaming_intf_alt0.bLength;
494
495 if (speed == USB_SPEED_SUPER) {
496 bytes += uvc_ss_control_comp.bLength;
497 n_desc = 6;
498 } else {
499 n_desc = 5;
500 }
501
502 for (src = (const struct usb_descriptor_header **)uvc_control_desc;
503 *src; ++src) {
504 control_size += (*src)->bLength;
505 bytes += (*src)->bLength;
506 n_desc++;
507 }
508 for (src = (const struct usb_descriptor_header **)uvc_streaming_cls;
509 *src; ++src) {
510 streaming_size += (*src)->bLength;
511 bytes += (*src)->bLength;
512 n_desc++;
513 }
514 for (src = uvc_streaming_std; *src; ++src) {
515 bytes += (*src)->bLength;
516 n_desc++;
517 }
518
519 mem = kmalloc((n_desc + 1) * sizeof(*src) + bytes, GFP_KERNEL);
520 if (mem == NULL)
521 return NULL;
522
523 hdr = mem;
524 dst = mem;
525 mem += (n_desc + 1) * sizeof(*src);
526
527 /* Copy the descriptors. */
528 UVC_COPY_DESCRIPTOR(mem, dst, &uvc_iad);
529 UVC_COPY_DESCRIPTOR(mem, dst, &uvc_control_intf);
530
531 uvc_control_header = mem;
532 UVC_COPY_DESCRIPTORS(mem, dst,
533 (const struct usb_descriptor_header **)uvc_control_desc);
534 uvc_control_header->wTotalLength = cpu_to_le16(control_size);
535 uvc_control_header->bInCollection = 1;
536 uvc_control_header->baInterfaceNr[0] = uvc->streaming_intf;
537
538 UVC_COPY_DESCRIPTOR(mem, dst, &uvc_control_ep);
539 if (speed == USB_SPEED_SUPER)
540 UVC_COPY_DESCRIPTOR(mem, dst, &uvc_ss_control_comp);
541
542 UVC_COPY_DESCRIPTOR(mem, dst, &uvc_control_cs_ep);
543 UVC_COPY_DESCRIPTOR(mem, dst, &uvc_streaming_intf_alt0);
544
545 uvc_streaming_header = mem;
546 UVC_COPY_DESCRIPTORS(mem, dst,
547 (const struct usb_descriptor_header**)uvc_streaming_cls);
548 uvc_streaming_header->wTotalLength = cpu_to_le16(streaming_size);
549 uvc_streaming_header->bEndpointAddress = uvc->video.ep->address;
550
551 UVC_COPY_DESCRIPTORS(mem, dst, uvc_streaming_std);
552
553 *dst = NULL;
554 return hdr;
555}
556
557static void
558uvc_function_unbind(struct usb_configuration *c, struct usb_function *f)
559{
560 struct usb_composite_dev *cdev = c->cdev;
561 struct uvc_device *uvc = to_uvc(f);
562
563 INFO(cdev, "uvc_function_unbind\n");
564
565 video_unregister_device(uvc->vdev);
566 v4l2_device_unregister(&uvc->v4l2_dev);
567 uvc->control_ep->driver_data = NULL;
568 uvc->video.ep->driver_data = NULL;
569
570 uvc_en_us_strings[UVC_STRING_CONTROL_IDX].id = 0;
571 usb_ep_free_request(cdev->gadget->ep0, uvc->control_req);
572 kfree(uvc->control_buf);
573
574 usb_free_all_descriptors(f);
575
576 kfree(uvc);
577}
578
579static int __init
580uvc_function_bind(struct usb_configuration *c, struct usb_function *f)
581{
582 struct usb_composite_dev *cdev = c->cdev;
583 struct uvc_device *uvc = to_uvc(f);
584 unsigned int max_packet_mult;
585 unsigned int max_packet_size;
586 struct usb_ep *ep;
587 int ret = -EINVAL;
588
589 INFO(cdev, "uvc_function_bind\n");
590
591 /* Sanity check the streaming endpoint module parameters.
592 */
593 streaming_interval = clamp(streaming_interval, 1U, 16U);
594 streaming_maxpacket = clamp(streaming_maxpacket, 1U, 3072U);
595 streaming_maxburst = min(streaming_maxburst, 15U);
596
597 /* Fill in the FS/HS/SS Video Streaming specific descriptors from the
598 * module parameters.
599 *
600 * NOTE: We assume that the user knows what they are doing and won't
601 * give parameters that their UDC doesn't support.
602 */
603 if (streaming_maxpacket <= 1024) {
604 max_packet_mult = 1;
605 max_packet_size = streaming_maxpacket;
606 } else if (streaming_maxpacket <= 2048) {
607 max_packet_mult = 2;
608 max_packet_size = streaming_maxpacket / 2;
609 } else {
610 max_packet_mult = 3;
611 max_packet_size = streaming_maxpacket / 3;
612 }
613
614 uvc_fs_streaming_ep.wMaxPacketSize = min(streaming_maxpacket, 1023U);
615 uvc_fs_streaming_ep.bInterval = streaming_interval;
616
617 uvc_hs_streaming_ep.wMaxPacketSize = max_packet_size;
618 uvc_hs_streaming_ep.wMaxPacketSize |= ((max_packet_mult - 1) << 11);
619 uvc_hs_streaming_ep.bInterval = streaming_interval;
620
621 uvc_ss_streaming_ep.wMaxPacketSize = max_packet_size;
622 uvc_ss_streaming_ep.bInterval = streaming_interval;
623 uvc_ss_streaming_comp.bmAttributes = max_packet_mult - 1;
624 uvc_ss_streaming_comp.bMaxBurst = streaming_maxburst;
625 uvc_ss_streaming_comp.wBytesPerInterval =
626 max_packet_size * max_packet_mult * streaming_maxburst;
627
628 /* Allocate endpoints. */
629 ep = usb_ep_autoconfig(cdev->gadget, &uvc_control_ep);
630 if (!ep) {
631 INFO(cdev, "Unable to allocate control EP\n");
632 goto error;
633 }
634 uvc->control_ep = ep;
635 ep->driver_data = uvc;
636
637 if (gadget_is_superspeed(c->cdev->gadget))
638 ep = usb_ep_autoconfig_ss(cdev->gadget, &uvc_ss_streaming_ep,
639 &uvc_ss_streaming_comp);
640 else if (gadget_is_dualspeed(cdev->gadget))
641 ep = usb_ep_autoconfig(cdev->gadget, &uvc_hs_streaming_ep);
642 else
643 ep = usb_ep_autoconfig(cdev->gadget, &uvc_fs_streaming_ep);
644
645 if (!ep) {
646 INFO(cdev, "Unable to allocate streaming EP\n");
647 goto error;
648 }
649 uvc->video.ep = ep;
650 ep->driver_data = uvc;
651
652 uvc_fs_streaming_ep.bEndpointAddress = uvc->video.ep->address;
653 uvc_hs_streaming_ep.bEndpointAddress = uvc->video.ep->address;
654 uvc_ss_streaming_ep.bEndpointAddress = uvc->video.ep->address;
655
656 /* Allocate interface IDs. */
657 if ((ret = usb_interface_id(c, f)) < 0)
658 goto error;
659 uvc_iad.bFirstInterface = ret;
660 uvc_control_intf.bInterfaceNumber = ret;
661 uvc->control_intf = ret;
662
663 if ((ret = usb_interface_id(c, f)) < 0)
664 goto error;
665 uvc_streaming_intf_alt0.bInterfaceNumber = ret;
666 uvc_streaming_intf_alt1.bInterfaceNumber = ret;
667 uvc->streaming_intf = ret;
668
669 /* Copy descriptors */
670 f->fs_descriptors = uvc_copy_descriptors(uvc, USB_SPEED_FULL);
671 if (gadget_is_dualspeed(cdev->gadget))
672 f->hs_descriptors = uvc_copy_descriptors(uvc, USB_SPEED_HIGH);
673 if (gadget_is_superspeed(c->cdev->gadget))
674 f->ss_descriptors = uvc_copy_descriptors(uvc, USB_SPEED_SUPER);
675
676 /* Preallocate control endpoint request. */
677 uvc->control_req = usb_ep_alloc_request(cdev->gadget->ep0, GFP_KERNEL);
678 uvc->control_buf = kmalloc(UVC_MAX_REQUEST_SIZE, GFP_KERNEL);
679 if (uvc->control_req == NULL || uvc->control_buf == NULL) {
680 ret = -ENOMEM;
681 goto error;
682 }
683
684 uvc->control_req->buf = uvc->control_buf;
685 uvc->control_req->complete = uvc_function_ep0_complete;
686 uvc->control_req->context = uvc;
687
688 /* Avoid letting this gadget enumerate until the userspace server is
689 * active.
690 */
691 if ((ret = usb_function_deactivate(f)) < 0)
692 goto error;
693
694 if (v4l2_device_register(&cdev->gadget->dev, &uvc->v4l2_dev)) {
695 printk(KERN_INFO "v4l2_device_register failed\n");
696 goto error;
697 }
698
699 /* Initialise video. */
700 ret = uvc_video_init(&uvc->video);
701 if (ret < 0)
702 goto error;
703
704 /* Register a V4L2 device. */
705 ret = uvc_register_video(uvc);
706 if (ret < 0) {
707 printk(KERN_INFO "Unable to register video device\n");
708 goto error;
709 }
710
711 return 0;
712
713error:
714 v4l2_device_unregister(&uvc->v4l2_dev);
715 if (uvc->vdev)
716 video_device_release(uvc->vdev);
717
718 if (uvc->control_ep)
719 uvc->control_ep->driver_data = NULL;
720 if (uvc->video.ep)
721 uvc->video.ep->driver_data = NULL;
722
723 if (uvc->control_req) {
724 usb_ep_free_request(cdev->gadget->ep0, uvc->control_req);
725 kfree(uvc->control_buf);
726 }
727
728 usb_free_all_descriptors(f);
729 return ret;
730}
731
732/* --------------------------------------------------------------------------
733 * USB gadget function
734 */
735
736/**
737 * uvc_bind_config - add a UVC function to a configuration
738 * @c: the configuration to support the UVC instance
739 * Context: single threaded during gadget setup
740 *
741 * Returns zero on success, else negative errno.
742 *
743 * Caller must have called @uvc_setup(). Caller is also responsible for
744 * calling @uvc_cleanup() before module unload.
745 */
746int __init
747uvc_bind_config(struct usb_configuration *c,
748 const struct uvc_descriptor_header * const *fs_control,
749 const struct uvc_descriptor_header * const *ss_control,
750 const struct uvc_descriptor_header * const *fs_streaming,
751 const struct uvc_descriptor_header * const *hs_streaming,
752 const struct uvc_descriptor_header * const *ss_streaming)
753{
754 struct uvc_device *uvc;
755 int ret = 0;
756
757 /* TODO Check if the USB device controller supports the required
758 * features.
759 */
760 if (!gadget_is_dualspeed(c->cdev->gadget))
761 return -EINVAL;
762
763 uvc = kzalloc(sizeof(*uvc), GFP_KERNEL);
764 if (uvc == NULL)
765 return -ENOMEM;
766
767 uvc->state = UVC_STATE_DISCONNECTED;
768
769 /* Validate the descriptors. */
770 if (fs_control == NULL || fs_control[0] == NULL ||
771 fs_control[0]->bDescriptorSubType != UVC_VC_HEADER)
772 goto error;
773
774 if (ss_control == NULL || ss_control[0] == NULL ||
775 ss_control[0]->bDescriptorSubType != UVC_VC_HEADER)
776 goto error;
777
778 if (fs_streaming == NULL || fs_streaming[0] == NULL ||
779 fs_streaming[0]->bDescriptorSubType != UVC_VS_INPUT_HEADER)
780 goto error;
781
782 if (hs_streaming == NULL || hs_streaming[0] == NULL ||
783 hs_streaming[0]->bDescriptorSubType != UVC_VS_INPUT_HEADER)
784 goto error;
785
786 if (ss_streaming == NULL || ss_streaming[0] == NULL ||
787 ss_streaming[0]->bDescriptorSubType != UVC_VS_INPUT_HEADER)
788 goto error;
789
790 uvc->desc.fs_control = fs_control;
791 uvc->desc.ss_control = ss_control;
792 uvc->desc.fs_streaming = fs_streaming;
793 uvc->desc.hs_streaming = hs_streaming;
794 uvc->desc.ss_streaming = ss_streaming;
795
796 /* String descriptors are global, we only need to allocate string IDs
797 * for the first UVC function. UVC functions beyond the first (if any)
798 * will reuse the same IDs.
799 */
800 if (uvc_en_us_strings[UVC_STRING_CONTROL_IDX].id == 0) {
801 ret = usb_string_ids_tab(c->cdev, uvc_en_us_strings);
802 if (ret)
803 goto error;
804 uvc_iad.iFunction =
805 uvc_en_us_strings[UVC_STRING_CONTROL_IDX].id;
806 uvc_control_intf.iInterface =
807 uvc_en_us_strings[UVC_STRING_CONTROL_IDX].id;
808 ret = uvc_en_us_strings[UVC_STRING_STREAMING_IDX].id;
809 uvc_streaming_intf_alt0.iInterface = ret;
810 uvc_streaming_intf_alt1.iInterface = ret;
811 }
812
813 /* Register the function. */
814 uvc->func.name = "uvc";
815 uvc->func.strings = uvc_function_strings;
816 uvc->func.bind = uvc_function_bind;
817 uvc->func.unbind = uvc_function_unbind;
818 uvc->func.get_alt = uvc_function_get_alt;
819 uvc->func.set_alt = uvc_function_set_alt;
820 uvc->func.disable = uvc_function_disable;
821 uvc->func.setup = uvc_function_setup;
822
823 ret = usb_add_function(c, &uvc->func);
824 if (ret)
825 kfree(uvc);
826
827 return ret;
828
829error:
830 kfree(uvc);
831 return ret;
832}
833
834module_param_named(trace, uvc_gadget_trace_param, uint, S_IRUGO|S_IWUSR);
835MODULE_PARM_DESC(trace, "Trace level bitmask");
836
diff --git a/drivers/usb/gadget/function/f_uvc.h b/drivers/usb/gadget/function/f_uvc.h
new file mode 100644
index 000000000000..ec52752f7326
--- /dev/null
+++ b/drivers/usb/gadget/function/f_uvc.h
@@ -0,0 +1,27 @@
1/*
2 * f_uvc.h -- USB Video Class Gadget driver
3 *
4 * Copyright (C) 2009-2010
5 * Laurent Pinchart (laurent.pinchart@ideasonboard.com)
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 */
12
13#ifndef _F_UVC_H_
14#define _F_UVC_H_
15
16#include <linux/usb/composite.h>
17#include <linux/usb/video.h>
18
19int uvc_bind_config(struct usb_configuration *c,
20 const struct uvc_descriptor_header * const *fs_control,
21 const struct uvc_descriptor_header * const *hs_control,
22 const struct uvc_descriptor_header * const *fs_streaming,
23 const struct uvc_descriptor_header * const *hs_streaming,
24 const struct uvc_descriptor_header * const *ss_streaming);
25
26#endif /* _F_UVC_H_ */
27
diff --git a/drivers/usb/gadget/function/g_zero.h b/drivers/usb/gadget/function/g_zero.h
new file mode 100644
index 000000000000..15f180904f8a
--- /dev/null
+++ b/drivers/usb/gadget/function/g_zero.h
@@ -0,0 +1,67 @@
1/*
2 * This header declares the utility functions used by "Gadget Zero", plus
3 * interfaces to its two single-configuration function drivers.
4 */
5
6#ifndef __G_ZERO_H
7#define __G_ZERO_H
8
9#define GZERO_BULK_BUFLEN 4096
10#define GZERO_QLEN 32
11#define GZERO_ISOC_INTERVAL 4
12#define GZERO_ISOC_MAXPACKET 1024
13
14struct usb_zero_options {
15 unsigned pattern;
16 unsigned isoc_interval;
17 unsigned isoc_maxpacket;
18 unsigned isoc_mult;
19 unsigned isoc_maxburst;
20 unsigned bulk_buflen;
21 unsigned qlen;
22};
23
24struct f_ss_opts {
25 struct usb_function_instance func_inst;
26 unsigned pattern;
27 unsigned isoc_interval;
28 unsigned isoc_maxpacket;
29 unsigned isoc_mult;
30 unsigned isoc_maxburst;
31 unsigned bulk_buflen;
32
33 /*
34 * Read/write access to configfs attributes is handled by configfs.
35 *
36 * This is to protect the data from concurrent access by read/write
37 * and create symlink/remove symlink.
38 */
39 struct mutex lock;
40 int refcnt;
41};
42
43struct f_lb_opts {
44 struct usb_function_instance func_inst;
45 unsigned bulk_buflen;
46 unsigned qlen;
47
48 /*
49 * Read/write access to configfs attributes is handled by configfs.
50 *
51 * This is to protect the data from concurrent access by read/write
52 * and create symlink/remove symlink.
53 */
54 struct mutex lock;
55 int refcnt;
56};
57
58void lb_modexit(void);
59int lb_modinit(void);
60
61/* common utilities */
62void free_ep_req(struct usb_ep *ep, struct usb_request *req);
63void disable_endpoints(struct usb_composite_dev *cdev,
64 struct usb_ep *in, struct usb_ep *out,
65 struct usb_ep *iso_in, struct usb_ep *iso_out);
66
67#endif /* __G_ZERO_H */
diff --git a/drivers/usb/gadget/function/ndis.h b/drivers/usb/gadget/function/ndis.h
new file mode 100644
index 000000000000..a19f72dec0cd
--- /dev/null
+++ b/drivers/usb/gadget/function/ndis.h
@@ -0,0 +1,47 @@
1/*
2 * ndis.h
3 *
4 * ntddndis.h modified by Benedikt Spranger <b.spranger@pengutronix.de>
5 *
6 * Thanks to the cygwin development team,
7 * espacially to Casper S. Hornstrup <chorns@users.sourceforge.net>
8 *
9 * THIS SOFTWARE IS NOT COPYRIGHTED
10 *
11 * This source code is offered for use in the public domain. You may
12 * use, modify or distribute it freely.
13 */
14
15#ifndef _LINUX_NDIS_H
16#define _LINUX_NDIS_H
17
18enum NDIS_DEVICE_POWER_STATE {
19 NdisDeviceStateUnspecified = 0,
20 NdisDeviceStateD0,
21 NdisDeviceStateD1,
22 NdisDeviceStateD2,
23 NdisDeviceStateD3,
24 NdisDeviceStateMaximum
25};
26
27struct NDIS_PM_WAKE_UP_CAPABILITIES {
28 enum NDIS_DEVICE_POWER_STATE MinMagicPacketWakeUp;
29 enum NDIS_DEVICE_POWER_STATE MinPatternWakeUp;
30 enum NDIS_DEVICE_POWER_STATE MinLinkChangeWakeUp;
31};
32
33struct NDIS_PNP_CAPABILITIES {
34 __le32 Flags;
35 struct NDIS_PM_WAKE_UP_CAPABILITIES WakeUpCapabilities;
36};
37
38struct NDIS_PM_PACKET_PATTERN {
39 __le32 Priority;
40 __le32 Reserved;
41 __le32 MaskSize;
42 __le32 PatternOffset;
43 __le32 PatternSize;
44 __le32 PatternFlags;
45};
46
47#endif /* _LINUX_NDIS_H */
diff --git a/drivers/usb/gadget/function/rndis.c b/drivers/usb/gadget/function/rndis.c
new file mode 100644
index 000000000000..95d2324f6977
--- /dev/null
+++ b/drivers/usb/gadget/function/rndis.c
@@ -0,0 +1,1190 @@
1/*
2 * RNDIS MSG parser
3 *
4 * Authors: Benedikt Spranger, Pengutronix
5 * Robert Schwebel, Pengutronix
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * version 2, as published by the Free Software Foundation.
10 *
11 * This software was originally developed in conformance with
12 * Microsoft's Remote NDIS Specification License Agreement.
13 *
14 * 03/12/2004 Kai-Uwe Bloem <linux-development@auerswald.de>
15 * Fixed message length bug in init_response
16 *
17 * 03/25/2004 Kai-Uwe Bloem <linux-development@auerswald.de>
18 * Fixed rndis_rm_hdr length bug.
19 *
20 * Copyright (C) 2004 by David Brownell
21 * updates to merge with Linux 2.6, better match RNDIS spec
22 */
23
24#include <linux/module.h>
25#include <linux/moduleparam.h>
26#include <linux/kernel.h>
27#include <linux/errno.h>
28#include <linux/list.h>
29#include <linux/proc_fs.h>
30#include <linux/slab.h>
31#include <linux/seq_file.h>
32#include <linux/netdevice.h>
33
34#include <asm/io.h>
35#include <asm/byteorder.h>
36#include <asm/unaligned.h>
37
38#include "u_rndis.h"
39
40#undef VERBOSE_DEBUG
41
42#include "rndis.h"
43
44
45/* The driver for your USB chip needs to support ep0 OUT to work with
46 * RNDIS, plus all three CDC Ethernet endpoints (interrupt not optional).
47 *
48 * Windows hosts need an INF file like Documentation/usb/linux.inf
49 * and will be happier if you provide the host_addr module parameter.
50 */
51
52#if 0
53static int rndis_debug = 0;
54module_param (rndis_debug, int, 0);
55MODULE_PARM_DESC (rndis_debug, "enable debugging");
56#else
57#define rndis_debug 0
58#endif
59
60#define RNDIS_MAX_CONFIGS 1
61
62
63static rndis_params rndis_per_dev_params[RNDIS_MAX_CONFIGS];
64
65/* Driver Version */
66static const __le32 rndis_driver_version = cpu_to_le32(1);
67
68/* Function Prototypes */
69static rndis_resp_t *rndis_add_response(int configNr, u32 length);
70
71
72/* supported OIDs */
73static const u32 oid_supported_list[] =
74{
75 /* the general stuff */
76 RNDIS_OID_GEN_SUPPORTED_LIST,
77 RNDIS_OID_GEN_HARDWARE_STATUS,
78 RNDIS_OID_GEN_MEDIA_SUPPORTED,
79 RNDIS_OID_GEN_MEDIA_IN_USE,
80 RNDIS_OID_GEN_MAXIMUM_FRAME_SIZE,
81 RNDIS_OID_GEN_LINK_SPEED,
82 RNDIS_OID_GEN_TRANSMIT_BLOCK_SIZE,
83 RNDIS_OID_GEN_RECEIVE_BLOCK_SIZE,
84 RNDIS_OID_GEN_VENDOR_ID,
85 RNDIS_OID_GEN_VENDOR_DESCRIPTION,
86 RNDIS_OID_GEN_VENDOR_DRIVER_VERSION,
87 RNDIS_OID_GEN_CURRENT_PACKET_FILTER,
88 RNDIS_OID_GEN_MAXIMUM_TOTAL_SIZE,
89 RNDIS_OID_GEN_MEDIA_CONNECT_STATUS,
90 RNDIS_OID_GEN_PHYSICAL_MEDIUM,
91
92 /* the statistical stuff */
93 RNDIS_OID_GEN_XMIT_OK,
94 RNDIS_OID_GEN_RCV_OK,
95 RNDIS_OID_GEN_XMIT_ERROR,
96 RNDIS_OID_GEN_RCV_ERROR,
97 RNDIS_OID_GEN_RCV_NO_BUFFER,
98#ifdef RNDIS_OPTIONAL_STATS
99 RNDIS_OID_GEN_DIRECTED_BYTES_XMIT,
100 RNDIS_OID_GEN_DIRECTED_FRAMES_XMIT,
101 RNDIS_OID_GEN_MULTICAST_BYTES_XMIT,
102 RNDIS_OID_GEN_MULTICAST_FRAMES_XMIT,
103 RNDIS_OID_GEN_BROADCAST_BYTES_XMIT,
104 RNDIS_OID_GEN_BROADCAST_FRAMES_XMIT,
105 RNDIS_OID_GEN_DIRECTED_BYTES_RCV,
106 RNDIS_OID_GEN_DIRECTED_FRAMES_RCV,
107 RNDIS_OID_GEN_MULTICAST_BYTES_RCV,
108 RNDIS_OID_GEN_MULTICAST_FRAMES_RCV,
109 RNDIS_OID_GEN_BROADCAST_BYTES_RCV,
110 RNDIS_OID_GEN_BROADCAST_FRAMES_RCV,
111 RNDIS_OID_GEN_RCV_CRC_ERROR,
112 RNDIS_OID_GEN_TRANSMIT_QUEUE_LENGTH,
113#endif /* RNDIS_OPTIONAL_STATS */
114
115 /* mandatory 802.3 */
116 /* the general stuff */
117 RNDIS_OID_802_3_PERMANENT_ADDRESS,
118 RNDIS_OID_802_3_CURRENT_ADDRESS,
119 RNDIS_OID_802_3_MULTICAST_LIST,
120 RNDIS_OID_802_3_MAC_OPTIONS,
121 RNDIS_OID_802_3_MAXIMUM_LIST_SIZE,
122
123 /* the statistical stuff */
124 RNDIS_OID_802_3_RCV_ERROR_ALIGNMENT,
125 RNDIS_OID_802_3_XMIT_ONE_COLLISION,
126 RNDIS_OID_802_3_XMIT_MORE_COLLISIONS,
127#ifdef RNDIS_OPTIONAL_STATS
128 RNDIS_OID_802_3_XMIT_DEFERRED,
129 RNDIS_OID_802_3_XMIT_MAX_COLLISIONS,
130 RNDIS_OID_802_3_RCV_OVERRUN,
131 RNDIS_OID_802_3_XMIT_UNDERRUN,
132 RNDIS_OID_802_3_XMIT_HEARTBEAT_FAILURE,
133 RNDIS_OID_802_3_XMIT_TIMES_CRS_LOST,
134 RNDIS_OID_802_3_XMIT_LATE_COLLISIONS,
135#endif /* RNDIS_OPTIONAL_STATS */
136
137#ifdef RNDIS_PM
138 /* PM and wakeup are "mandatory" for USB, but the RNDIS specs
139 * don't say what they mean ... and the NDIS specs are often
140 * confusing and/or ambiguous in this context. (That is, more
141 * so than their specs for the other OIDs.)
142 *
143 * FIXME someone who knows what these should do, please
144 * implement them!
145 */
146
147 /* power management */
148 OID_PNP_CAPABILITIES,
149 OID_PNP_QUERY_POWER,
150 OID_PNP_SET_POWER,
151
152#ifdef RNDIS_WAKEUP
153 /* wake up host */
154 OID_PNP_ENABLE_WAKE_UP,
155 OID_PNP_ADD_WAKE_UP_PATTERN,
156 OID_PNP_REMOVE_WAKE_UP_PATTERN,
157#endif /* RNDIS_WAKEUP */
158#endif /* RNDIS_PM */
159};
160
161
162/* NDIS Functions */
163static int gen_ndis_query_resp(int configNr, u32 OID, u8 *buf,
164 unsigned buf_len, rndis_resp_t *r)
165{
166 int retval = -ENOTSUPP;
167 u32 length = 4; /* usually */
168 __le32 *outbuf;
169 int i, count;
170 rndis_query_cmplt_type *resp;
171 struct net_device *net;
172 struct rtnl_link_stats64 temp;
173 const struct rtnl_link_stats64 *stats;
174
175 if (!r) return -ENOMEM;
176 resp = (rndis_query_cmplt_type *)r->buf;
177
178 if (!resp) return -ENOMEM;
179
180 if (buf_len && rndis_debug > 1) {
181 pr_debug("query OID %08x value, len %d:\n", OID, buf_len);
182 for (i = 0; i < buf_len; i += 16) {
183 pr_debug("%03d: %08x %08x %08x %08x\n", i,
184 get_unaligned_le32(&buf[i]),
185 get_unaligned_le32(&buf[i + 4]),
186 get_unaligned_le32(&buf[i + 8]),
187 get_unaligned_le32(&buf[i + 12]));
188 }
189 }
190
191 /* response goes here, right after the header */
192 outbuf = (__le32 *)&resp[1];
193 resp->InformationBufferOffset = cpu_to_le32(16);
194
195 net = rndis_per_dev_params[configNr].dev;
196 stats = dev_get_stats(net, &temp);
197
198 switch (OID) {
199
200 /* general oids (table 4-1) */
201
202 /* mandatory */
203 case RNDIS_OID_GEN_SUPPORTED_LIST:
204 pr_debug("%s: RNDIS_OID_GEN_SUPPORTED_LIST\n", __func__);
205 length = sizeof(oid_supported_list);
206 count = length / sizeof(u32);
207 for (i = 0; i < count; i++)
208 outbuf[i] = cpu_to_le32(oid_supported_list[i]);
209 retval = 0;
210 break;
211
212 /* mandatory */
213 case RNDIS_OID_GEN_HARDWARE_STATUS:
214 pr_debug("%s: RNDIS_OID_GEN_HARDWARE_STATUS\n", __func__);
215 /* Bogus question!
216 * Hardware must be ready to receive high level protocols.
217 * BTW:
218 * reddite ergo quae sunt Caesaris Caesari
219 * et quae sunt Dei Deo!
220 */
221 *outbuf = cpu_to_le32(0);
222 retval = 0;
223 break;
224
225 /* mandatory */
226 case RNDIS_OID_GEN_MEDIA_SUPPORTED:
227 pr_debug("%s: RNDIS_OID_GEN_MEDIA_SUPPORTED\n", __func__);
228 *outbuf = cpu_to_le32(rndis_per_dev_params[configNr].medium);
229 retval = 0;
230 break;
231
232 /* mandatory */
233 case RNDIS_OID_GEN_MEDIA_IN_USE:
234 pr_debug("%s: RNDIS_OID_GEN_MEDIA_IN_USE\n", __func__);
235 /* one medium, one transport... (maybe you do it better) */
236 *outbuf = cpu_to_le32(rndis_per_dev_params[configNr].medium);
237 retval = 0;
238 break;
239
240 /* mandatory */
241 case RNDIS_OID_GEN_MAXIMUM_FRAME_SIZE:
242 pr_debug("%s: RNDIS_OID_GEN_MAXIMUM_FRAME_SIZE\n", __func__);
243 if (rndis_per_dev_params[configNr].dev) {
244 *outbuf = cpu_to_le32(
245 rndis_per_dev_params[configNr].dev->mtu);
246 retval = 0;
247 }
248 break;
249
250 /* mandatory */
251 case RNDIS_OID_GEN_LINK_SPEED:
252 if (rndis_debug > 1)
253 pr_debug("%s: RNDIS_OID_GEN_LINK_SPEED\n", __func__);
254 if (rndis_per_dev_params[configNr].media_state
255 == RNDIS_MEDIA_STATE_DISCONNECTED)
256 *outbuf = cpu_to_le32(0);
257 else
258 *outbuf = cpu_to_le32(
259 rndis_per_dev_params[configNr].speed);
260 retval = 0;
261 break;
262
263 /* mandatory */
264 case RNDIS_OID_GEN_TRANSMIT_BLOCK_SIZE:
265 pr_debug("%s: RNDIS_OID_GEN_TRANSMIT_BLOCK_SIZE\n", __func__);
266 if (rndis_per_dev_params[configNr].dev) {
267 *outbuf = cpu_to_le32(
268 rndis_per_dev_params[configNr].dev->mtu);
269 retval = 0;
270 }
271 break;
272
273 /* mandatory */
274 case RNDIS_OID_GEN_RECEIVE_BLOCK_SIZE:
275 pr_debug("%s: RNDIS_OID_GEN_RECEIVE_BLOCK_SIZE\n", __func__);
276 if (rndis_per_dev_params[configNr].dev) {
277 *outbuf = cpu_to_le32(
278 rndis_per_dev_params[configNr].dev->mtu);
279 retval = 0;
280 }
281 break;
282
283 /* mandatory */
284 case RNDIS_OID_GEN_VENDOR_ID:
285 pr_debug("%s: RNDIS_OID_GEN_VENDOR_ID\n", __func__);
286 *outbuf = cpu_to_le32(
287 rndis_per_dev_params[configNr].vendorID);
288 retval = 0;
289 break;
290
291 /* mandatory */
292 case RNDIS_OID_GEN_VENDOR_DESCRIPTION:
293 pr_debug("%s: RNDIS_OID_GEN_VENDOR_DESCRIPTION\n", __func__);
294 if (rndis_per_dev_params[configNr].vendorDescr) {
295 length = strlen(rndis_per_dev_params[configNr].
296 vendorDescr);
297 memcpy(outbuf,
298 rndis_per_dev_params[configNr].vendorDescr,
299 length);
300 } else {
301 outbuf[0] = 0;
302 }
303 retval = 0;
304 break;
305
306 case RNDIS_OID_GEN_VENDOR_DRIVER_VERSION:
307 pr_debug("%s: RNDIS_OID_GEN_VENDOR_DRIVER_VERSION\n", __func__);
308 /* Created as LE */
309 *outbuf = rndis_driver_version;
310 retval = 0;
311 break;
312
313 /* mandatory */
314 case RNDIS_OID_GEN_CURRENT_PACKET_FILTER:
315 pr_debug("%s: RNDIS_OID_GEN_CURRENT_PACKET_FILTER\n", __func__);
316 *outbuf = cpu_to_le32(*rndis_per_dev_params[configNr].filter);
317 retval = 0;
318 break;
319
320 /* mandatory */
321 case RNDIS_OID_GEN_MAXIMUM_TOTAL_SIZE:
322 pr_debug("%s: RNDIS_OID_GEN_MAXIMUM_TOTAL_SIZE\n", __func__);
323 *outbuf = cpu_to_le32(RNDIS_MAX_TOTAL_SIZE);
324 retval = 0;
325 break;
326
327 /* mandatory */
328 case RNDIS_OID_GEN_MEDIA_CONNECT_STATUS:
329 if (rndis_debug > 1)
330 pr_debug("%s: RNDIS_OID_GEN_MEDIA_CONNECT_STATUS\n", __func__);
331 *outbuf = cpu_to_le32(rndis_per_dev_params[configNr]
332 .media_state);
333 retval = 0;
334 break;
335
336 case RNDIS_OID_GEN_PHYSICAL_MEDIUM:
337 pr_debug("%s: RNDIS_OID_GEN_PHYSICAL_MEDIUM\n", __func__);
338 *outbuf = cpu_to_le32(0);
339 retval = 0;
340 break;
341
342 /* The RNDIS specification is incomplete/wrong. Some versions
343 * of MS-Windows expect OIDs that aren't specified there. Other
344 * versions emit undefined RNDIS messages. DOCUMENT ALL THESE!
345 */
346 case RNDIS_OID_GEN_MAC_OPTIONS: /* from WinME */
347 pr_debug("%s: RNDIS_OID_GEN_MAC_OPTIONS\n", __func__);
348 *outbuf = cpu_to_le32(
349 RNDIS_MAC_OPTION_RECEIVE_SERIALIZED
350 | RNDIS_MAC_OPTION_FULL_DUPLEX);
351 retval = 0;
352 break;
353
354 /* statistics OIDs (table 4-2) */
355
356 /* mandatory */
357 case RNDIS_OID_GEN_XMIT_OK:
358 if (rndis_debug > 1)
359 pr_debug("%s: RNDIS_OID_GEN_XMIT_OK\n", __func__);
360 if (stats) {
361 *outbuf = cpu_to_le32(stats->tx_packets
362 - stats->tx_errors - stats->tx_dropped);
363 retval = 0;
364 }
365 break;
366
367 /* mandatory */
368 case RNDIS_OID_GEN_RCV_OK:
369 if (rndis_debug > 1)
370 pr_debug("%s: RNDIS_OID_GEN_RCV_OK\n", __func__);
371 if (stats) {
372 *outbuf = cpu_to_le32(stats->rx_packets
373 - stats->rx_errors - stats->rx_dropped);
374 retval = 0;
375 }
376 break;
377
378 /* mandatory */
379 case RNDIS_OID_GEN_XMIT_ERROR:
380 if (rndis_debug > 1)
381 pr_debug("%s: RNDIS_OID_GEN_XMIT_ERROR\n", __func__);
382 if (stats) {
383 *outbuf = cpu_to_le32(stats->tx_errors);
384 retval = 0;
385 }
386 break;
387
388 /* mandatory */
389 case RNDIS_OID_GEN_RCV_ERROR:
390 if (rndis_debug > 1)
391 pr_debug("%s: RNDIS_OID_GEN_RCV_ERROR\n", __func__);
392 if (stats) {
393 *outbuf = cpu_to_le32(stats->rx_errors);
394 retval = 0;
395 }
396 break;
397
398 /* mandatory */
399 case RNDIS_OID_GEN_RCV_NO_BUFFER:
400 pr_debug("%s: RNDIS_OID_GEN_RCV_NO_BUFFER\n", __func__);
401 if (stats) {
402 *outbuf = cpu_to_le32(stats->rx_dropped);
403 retval = 0;
404 }
405 break;
406
407 /* ieee802.3 OIDs (table 4-3) */
408
409 /* mandatory */
410 case RNDIS_OID_802_3_PERMANENT_ADDRESS:
411 pr_debug("%s: RNDIS_OID_802_3_PERMANENT_ADDRESS\n", __func__);
412 if (rndis_per_dev_params[configNr].dev) {
413 length = ETH_ALEN;
414 memcpy(outbuf,
415 rndis_per_dev_params[configNr].host_mac,
416 length);
417 retval = 0;
418 }
419 break;
420
421 /* mandatory */
422 case RNDIS_OID_802_3_CURRENT_ADDRESS:
423 pr_debug("%s: RNDIS_OID_802_3_CURRENT_ADDRESS\n", __func__);
424 if (rndis_per_dev_params[configNr].dev) {
425 length = ETH_ALEN;
426 memcpy(outbuf,
427 rndis_per_dev_params [configNr].host_mac,
428 length);
429 retval = 0;
430 }
431 break;
432
433 /* mandatory */
434 case RNDIS_OID_802_3_MULTICAST_LIST:
435 pr_debug("%s: RNDIS_OID_802_3_MULTICAST_LIST\n", __func__);
436 /* Multicast base address only */
437 *outbuf = cpu_to_le32(0xE0000000);
438 retval = 0;
439 break;
440
441 /* mandatory */
442 case RNDIS_OID_802_3_MAXIMUM_LIST_SIZE:
443 pr_debug("%s: RNDIS_OID_802_3_MAXIMUM_LIST_SIZE\n", __func__);
444 /* Multicast base address only */
445 *outbuf = cpu_to_le32(1);
446 retval = 0;
447 break;
448
449 case RNDIS_OID_802_3_MAC_OPTIONS:
450 pr_debug("%s: RNDIS_OID_802_3_MAC_OPTIONS\n", __func__);
451 *outbuf = cpu_to_le32(0);
452 retval = 0;
453 break;
454
455 /* ieee802.3 statistics OIDs (table 4-4) */
456
457 /* mandatory */
458 case RNDIS_OID_802_3_RCV_ERROR_ALIGNMENT:
459 pr_debug("%s: RNDIS_OID_802_3_RCV_ERROR_ALIGNMENT\n", __func__);
460 if (stats) {
461 *outbuf = cpu_to_le32(stats->rx_frame_errors);
462 retval = 0;
463 }
464 break;
465
466 /* mandatory */
467 case RNDIS_OID_802_3_XMIT_ONE_COLLISION:
468 pr_debug("%s: RNDIS_OID_802_3_XMIT_ONE_COLLISION\n", __func__);
469 *outbuf = cpu_to_le32(0);
470 retval = 0;
471 break;
472
473 /* mandatory */
474 case RNDIS_OID_802_3_XMIT_MORE_COLLISIONS:
475 pr_debug("%s: RNDIS_OID_802_3_XMIT_MORE_COLLISIONS\n", __func__);
476 *outbuf = cpu_to_le32(0);
477 retval = 0;
478 break;
479
480 default:
481 pr_warning("%s: query unknown OID 0x%08X\n",
482 __func__, OID);
483 }
484 if (retval < 0)
485 length = 0;
486
487 resp->InformationBufferLength = cpu_to_le32(length);
488 r->length = length + sizeof(*resp);
489 resp->MessageLength = cpu_to_le32(r->length);
490 return retval;
491}
492
493static int gen_ndis_set_resp(u8 configNr, u32 OID, u8 *buf, u32 buf_len,
494 rndis_resp_t *r)
495{
496 rndis_set_cmplt_type *resp;
497 int i, retval = -ENOTSUPP;
498 struct rndis_params *params;
499
500 if (!r)
501 return -ENOMEM;
502 resp = (rndis_set_cmplt_type *)r->buf;
503 if (!resp)
504 return -ENOMEM;
505
506 if (buf_len && rndis_debug > 1) {
507 pr_debug("set OID %08x value, len %d:\n", OID, buf_len);
508 for (i = 0; i < buf_len; i += 16) {
509 pr_debug("%03d: %08x %08x %08x %08x\n", i,
510 get_unaligned_le32(&buf[i]),
511 get_unaligned_le32(&buf[i + 4]),
512 get_unaligned_le32(&buf[i + 8]),
513 get_unaligned_le32(&buf[i + 12]));
514 }
515 }
516
517 params = &rndis_per_dev_params[configNr];
518 switch (OID) {
519 case RNDIS_OID_GEN_CURRENT_PACKET_FILTER:
520
521 /* these NDIS_PACKET_TYPE_* bitflags are shared with
522 * cdc_filter; it's not RNDIS-specific
523 * NDIS_PACKET_TYPE_x == USB_CDC_PACKET_TYPE_x for x in:
524 * PROMISCUOUS, DIRECTED,
525 * MULTICAST, ALL_MULTICAST, BROADCAST
526 */
527 *params->filter = (u16)get_unaligned_le32(buf);
528 pr_debug("%s: RNDIS_OID_GEN_CURRENT_PACKET_FILTER %08x\n",
529 __func__, *params->filter);
530
531 /* this call has a significant side effect: it's
532 * what makes the packet flow start and stop, like
533 * activating the CDC Ethernet altsetting.
534 */
535 retval = 0;
536 if (*params->filter) {
537 params->state = RNDIS_DATA_INITIALIZED;
538 netif_carrier_on(params->dev);
539 if (netif_running(params->dev))
540 netif_wake_queue(params->dev);
541 } else {
542 params->state = RNDIS_INITIALIZED;
543 netif_carrier_off(params->dev);
544 netif_stop_queue(params->dev);
545 }
546 break;
547
548 case RNDIS_OID_802_3_MULTICAST_LIST:
549 /* I think we can ignore this */
550 pr_debug("%s: RNDIS_OID_802_3_MULTICAST_LIST\n", __func__);
551 retval = 0;
552 break;
553
554 default:
555 pr_warning("%s: set unknown OID 0x%08X, size %d\n",
556 __func__, OID, buf_len);
557 }
558
559 return retval;
560}
561
562/*
563 * Response Functions
564 */
565
566static int rndis_init_response(int configNr, rndis_init_msg_type *buf)
567{
568 rndis_init_cmplt_type *resp;
569 rndis_resp_t *r;
570 struct rndis_params *params = rndis_per_dev_params + configNr;
571
572 if (!params->dev)
573 return -ENOTSUPP;
574
575 r = rndis_add_response(configNr, sizeof(rndis_init_cmplt_type));
576 if (!r)
577 return -ENOMEM;
578 resp = (rndis_init_cmplt_type *)r->buf;
579
580 resp->MessageType = cpu_to_le32(RNDIS_MSG_INIT_C);
581 resp->MessageLength = cpu_to_le32(52);
582 resp->RequestID = buf->RequestID; /* Still LE in msg buffer */
583 resp->Status = cpu_to_le32(RNDIS_STATUS_SUCCESS);
584 resp->MajorVersion = cpu_to_le32(RNDIS_MAJOR_VERSION);
585 resp->MinorVersion = cpu_to_le32(RNDIS_MINOR_VERSION);
586 resp->DeviceFlags = cpu_to_le32(RNDIS_DF_CONNECTIONLESS);
587 resp->Medium = cpu_to_le32(RNDIS_MEDIUM_802_3);
588 resp->MaxPacketsPerTransfer = cpu_to_le32(1);
589 resp->MaxTransferSize = cpu_to_le32(
590 params->dev->mtu
591 + sizeof(struct ethhdr)
592 + sizeof(struct rndis_packet_msg_type)
593 + 22);
594 resp->PacketAlignmentFactor = cpu_to_le32(0);
595 resp->AFListOffset = cpu_to_le32(0);
596 resp->AFListSize = cpu_to_le32(0);
597
598 params->resp_avail(params->v);
599 return 0;
600}
601
602static int rndis_query_response(int configNr, rndis_query_msg_type *buf)
603{
604 rndis_query_cmplt_type *resp;
605 rndis_resp_t *r;
606 struct rndis_params *params = rndis_per_dev_params + configNr;
607
608 /* pr_debug("%s: OID = %08X\n", __func__, cpu_to_le32(buf->OID)); */
609 if (!params->dev)
610 return -ENOTSUPP;
611
612 /*
613 * we need more memory:
614 * gen_ndis_query_resp expects enough space for
615 * rndis_query_cmplt_type followed by data.
616 * oid_supported_list is the largest data reply
617 */
618 r = rndis_add_response(configNr,
619 sizeof(oid_supported_list) + sizeof(rndis_query_cmplt_type));
620 if (!r)
621 return -ENOMEM;
622 resp = (rndis_query_cmplt_type *)r->buf;
623
624 resp->MessageType = cpu_to_le32(RNDIS_MSG_QUERY_C);
625 resp->RequestID = buf->RequestID; /* Still LE in msg buffer */
626
627 if (gen_ndis_query_resp(configNr, le32_to_cpu(buf->OID),
628 le32_to_cpu(buf->InformationBufferOffset)
629 + 8 + (u8 *)buf,
630 le32_to_cpu(buf->InformationBufferLength),
631 r)) {
632 /* OID not supported */
633 resp->Status = cpu_to_le32(RNDIS_STATUS_NOT_SUPPORTED);
634 resp->MessageLength = cpu_to_le32(sizeof *resp);
635 resp->InformationBufferLength = cpu_to_le32(0);
636 resp->InformationBufferOffset = cpu_to_le32(0);
637 } else
638 resp->Status = cpu_to_le32(RNDIS_STATUS_SUCCESS);
639
640 params->resp_avail(params->v);
641 return 0;
642}
643
644static int rndis_set_response(int configNr, rndis_set_msg_type *buf)
645{
646 u32 BufLength, BufOffset;
647 rndis_set_cmplt_type *resp;
648 rndis_resp_t *r;
649 struct rndis_params *params = rndis_per_dev_params + configNr;
650
651 r = rndis_add_response(configNr, sizeof(rndis_set_cmplt_type));
652 if (!r)
653 return -ENOMEM;
654 resp = (rndis_set_cmplt_type *)r->buf;
655
656 BufLength = le32_to_cpu(buf->InformationBufferLength);
657 BufOffset = le32_to_cpu(buf->InformationBufferOffset);
658
659#ifdef VERBOSE_DEBUG
660 pr_debug("%s: Length: %d\n", __func__, BufLength);
661 pr_debug("%s: Offset: %d\n", __func__, BufOffset);
662 pr_debug("%s: InfoBuffer: ", __func__);
663
664 for (i = 0; i < BufLength; i++) {
665 pr_debug("%02x ", *(((u8 *) buf) + i + 8 + BufOffset));
666 }
667
668 pr_debug("\n");
669#endif
670
671 resp->MessageType = cpu_to_le32(RNDIS_MSG_SET_C);
672 resp->MessageLength = cpu_to_le32(16);
673 resp->RequestID = buf->RequestID; /* Still LE in msg buffer */
674 if (gen_ndis_set_resp(configNr, le32_to_cpu(buf->OID),
675 ((u8 *)buf) + 8 + BufOffset, BufLength, r))
676 resp->Status = cpu_to_le32(RNDIS_STATUS_NOT_SUPPORTED);
677 else
678 resp->Status = cpu_to_le32(RNDIS_STATUS_SUCCESS);
679
680 params->resp_avail(params->v);
681 return 0;
682}
683
684static int rndis_reset_response(int configNr, rndis_reset_msg_type *buf)
685{
686 rndis_reset_cmplt_type *resp;
687 rndis_resp_t *r;
688 struct rndis_params *params = rndis_per_dev_params + configNr;
689
690 r = rndis_add_response(configNr, sizeof(rndis_reset_cmplt_type));
691 if (!r)
692 return -ENOMEM;
693 resp = (rndis_reset_cmplt_type *)r->buf;
694
695 resp->MessageType = cpu_to_le32(RNDIS_MSG_RESET_C);
696 resp->MessageLength = cpu_to_le32(16);
697 resp->Status = cpu_to_le32(RNDIS_STATUS_SUCCESS);
698 /* resent information */
699 resp->AddressingReset = cpu_to_le32(1);
700
701 params->resp_avail(params->v);
702 return 0;
703}
704
705static int rndis_keepalive_response(int configNr,
706 rndis_keepalive_msg_type *buf)
707{
708 rndis_keepalive_cmplt_type *resp;
709 rndis_resp_t *r;
710 struct rndis_params *params = rndis_per_dev_params + configNr;
711
712 /* host "should" check only in RNDIS_DATA_INITIALIZED state */
713
714 r = rndis_add_response(configNr, sizeof(rndis_keepalive_cmplt_type));
715 if (!r)
716 return -ENOMEM;
717 resp = (rndis_keepalive_cmplt_type *)r->buf;
718
719 resp->MessageType = cpu_to_le32(RNDIS_MSG_KEEPALIVE_C);
720 resp->MessageLength = cpu_to_le32(16);
721 resp->RequestID = buf->RequestID; /* Still LE in msg buffer */
722 resp->Status = cpu_to_le32(RNDIS_STATUS_SUCCESS);
723
724 params->resp_avail(params->v);
725 return 0;
726}
727
728
729/*
730 * Device to Host Comunication
731 */
732static int rndis_indicate_status_msg(int configNr, u32 status)
733{
734 rndis_indicate_status_msg_type *resp;
735 rndis_resp_t *r;
736 struct rndis_params *params = rndis_per_dev_params + configNr;
737
738 if (params->state == RNDIS_UNINITIALIZED)
739 return -ENOTSUPP;
740
741 r = rndis_add_response(configNr,
742 sizeof(rndis_indicate_status_msg_type));
743 if (!r)
744 return -ENOMEM;
745 resp = (rndis_indicate_status_msg_type *)r->buf;
746
747 resp->MessageType = cpu_to_le32(RNDIS_MSG_INDICATE);
748 resp->MessageLength = cpu_to_le32(20);
749 resp->Status = cpu_to_le32(status);
750 resp->StatusBufferLength = cpu_to_le32(0);
751 resp->StatusBufferOffset = cpu_to_le32(0);
752
753 params->resp_avail(params->v);
754 return 0;
755}
756
757int rndis_signal_connect(int configNr)
758{
759 rndis_per_dev_params[configNr].media_state
760 = RNDIS_MEDIA_STATE_CONNECTED;
761 return rndis_indicate_status_msg(configNr,
762 RNDIS_STATUS_MEDIA_CONNECT);
763}
764EXPORT_SYMBOL_GPL(rndis_signal_connect);
765
766int rndis_signal_disconnect(int configNr)
767{
768 rndis_per_dev_params[configNr].media_state
769 = RNDIS_MEDIA_STATE_DISCONNECTED;
770 return rndis_indicate_status_msg(configNr,
771 RNDIS_STATUS_MEDIA_DISCONNECT);
772}
773EXPORT_SYMBOL_GPL(rndis_signal_disconnect);
774
775void rndis_uninit(int configNr)
776{
777 u8 *buf;
778 u32 length;
779
780 if (configNr >= RNDIS_MAX_CONFIGS)
781 return;
782 rndis_per_dev_params[configNr].state = RNDIS_UNINITIALIZED;
783
784 /* drain the response queue */
785 while ((buf = rndis_get_next_response(configNr, &length)))
786 rndis_free_response(configNr, buf);
787}
788EXPORT_SYMBOL_GPL(rndis_uninit);
789
790void rndis_set_host_mac(int configNr, const u8 *addr)
791{
792 rndis_per_dev_params[configNr].host_mac = addr;
793}
794EXPORT_SYMBOL_GPL(rndis_set_host_mac);
795
796/*
797 * Message Parser
798 */
799int rndis_msg_parser(u8 configNr, u8 *buf)
800{
801 u32 MsgType, MsgLength;
802 __le32 *tmp;
803 struct rndis_params *params;
804
805 if (!buf)
806 return -ENOMEM;
807
808 tmp = (__le32 *)buf;
809 MsgType = get_unaligned_le32(tmp++);
810 MsgLength = get_unaligned_le32(tmp++);
811
812 if (configNr >= RNDIS_MAX_CONFIGS)
813 return -ENOTSUPP;
814 params = &rndis_per_dev_params[configNr];
815
816 /* NOTE: RNDIS is *EXTREMELY* chatty ... Windows constantly polls for
817 * rx/tx statistics and link status, in addition to KEEPALIVE traffic
818 * and normal HC level polling to see if there's any IN traffic.
819 */
820
821 /* For USB: responses may take up to 10 seconds */
822 switch (MsgType) {
823 case RNDIS_MSG_INIT:
824 pr_debug("%s: RNDIS_MSG_INIT\n",
825 __func__);
826 params->state = RNDIS_INITIALIZED;
827 return rndis_init_response(configNr,
828 (rndis_init_msg_type *)buf);
829
830 case RNDIS_MSG_HALT:
831 pr_debug("%s: RNDIS_MSG_HALT\n",
832 __func__);
833 params->state = RNDIS_UNINITIALIZED;
834 if (params->dev) {
835 netif_carrier_off(params->dev);
836 netif_stop_queue(params->dev);
837 }
838 return 0;
839
840 case RNDIS_MSG_QUERY:
841 return rndis_query_response(configNr,
842 (rndis_query_msg_type *)buf);
843
844 case RNDIS_MSG_SET:
845 return rndis_set_response(configNr,
846 (rndis_set_msg_type *)buf);
847
848 case RNDIS_MSG_RESET:
849 pr_debug("%s: RNDIS_MSG_RESET\n",
850 __func__);
851 return rndis_reset_response(configNr,
852 (rndis_reset_msg_type *)buf);
853
854 case RNDIS_MSG_KEEPALIVE:
855 /* For USB: host does this every 5 seconds */
856 if (rndis_debug > 1)
857 pr_debug("%s: RNDIS_MSG_KEEPALIVE\n",
858 __func__);
859 return rndis_keepalive_response(configNr,
860 (rndis_keepalive_msg_type *)
861 buf);
862
863 default:
864 /* At least Windows XP emits some undefined RNDIS messages.
865 * In one case those messages seemed to relate to the host
866 * suspending itself.
867 */
868 pr_warning("%s: unknown RNDIS message 0x%08X len %d\n",
869 __func__, MsgType, MsgLength);
870 print_hex_dump_bytes(__func__, DUMP_PREFIX_OFFSET,
871 buf, MsgLength);
872 break;
873 }
874
875 return -ENOTSUPP;
876}
877EXPORT_SYMBOL_GPL(rndis_msg_parser);
878
879int rndis_register(void (*resp_avail)(void *v), void *v)
880{
881 u8 i;
882
883 if (!resp_avail)
884 return -EINVAL;
885
886 for (i = 0; i < RNDIS_MAX_CONFIGS; i++) {
887 if (!rndis_per_dev_params[i].used) {
888 rndis_per_dev_params[i].used = 1;
889 rndis_per_dev_params[i].resp_avail = resp_avail;
890 rndis_per_dev_params[i].v = v;
891 pr_debug("%s: configNr = %d\n", __func__, i);
892 return i;
893 }
894 }
895 pr_debug("failed\n");
896
897 return -ENODEV;
898}
899EXPORT_SYMBOL_GPL(rndis_register);
900
901void rndis_deregister(int configNr)
902{
903 pr_debug("%s:\n", __func__);
904
905 if (configNr >= RNDIS_MAX_CONFIGS) return;
906 rndis_per_dev_params[configNr].used = 0;
907}
908EXPORT_SYMBOL_GPL(rndis_deregister);
909
910int rndis_set_param_dev(u8 configNr, struct net_device *dev, u16 *cdc_filter)
911{
912 pr_debug("%s:\n", __func__);
913 if (!dev)
914 return -EINVAL;
915 if (configNr >= RNDIS_MAX_CONFIGS) return -1;
916
917 rndis_per_dev_params[configNr].dev = dev;
918 rndis_per_dev_params[configNr].filter = cdc_filter;
919
920 return 0;
921}
922EXPORT_SYMBOL_GPL(rndis_set_param_dev);
923
924int rndis_set_param_vendor(u8 configNr, u32 vendorID, const char *vendorDescr)
925{
926 pr_debug("%s:\n", __func__);
927 if (!vendorDescr) return -1;
928 if (configNr >= RNDIS_MAX_CONFIGS) return -1;
929
930 rndis_per_dev_params[configNr].vendorID = vendorID;
931 rndis_per_dev_params[configNr].vendorDescr = vendorDescr;
932
933 return 0;
934}
935EXPORT_SYMBOL_GPL(rndis_set_param_vendor);
936
937int rndis_set_param_medium(u8 configNr, u32 medium, u32 speed)
938{
939 pr_debug("%s: %u %u\n", __func__, medium, speed);
940 if (configNr >= RNDIS_MAX_CONFIGS) return -1;
941
942 rndis_per_dev_params[configNr].medium = medium;
943 rndis_per_dev_params[configNr].speed = speed;
944
945 return 0;
946}
947EXPORT_SYMBOL_GPL(rndis_set_param_medium);
948
949void rndis_add_hdr(struct sk_buff *skb)
950{
951 struct rndis_packet_msg_type *header;
952
953 if (!skb)
954 return;
955 header = (void *)skb_push(skb, sizeof(*header));
956 memset(header, 0, sizeof *header);
957 header->MessageType = cpu_to_le32(RNDIS_MSG_PACKET);
958 header->MessageLength = cpu_to_le32(skb->len);
959 header->DataOffset = cpu_to_le32(36);
960 header->DataLength = cpu_to_le32(skb->len - sizeof(*header));
961}
962EXPORT_SYMBOL_GPL(rndis_add_hdr);
963
964void rndis_free_response(int configNr, u8 *buf)
965{
966 rndis_resp_t *r;
967 struct list_head *act, *tmp;
968
969 list_for_each_safe(act, tmp,
970 &(rndis_per_dev_params[configNr].resp_queue))
971 {
972 r = list_entry(act, rndis_resp_t, list);
973 if (r && r->buf == buf) {
974 list_del(&r->list);
975 kfree(r);
976 }
977 }
978}
979EXPORT_SYMBOL_GPL(rndis_free_response);
980
981u8 *rndis_get_next_response(int configNr, u32 *length)
982{
983 rndis_resp_t *r;
984 struct list_head *act, *tmp;
985
986 if (!length) return NULL;
987
988 list_for_each_safe(act, tmp,
989 &(rndis_per_dev_params[configNr].resp_queue))
990 {
991 r = list_entry(act, rndis_resp_t, list);
992 if (!r->send) {
993 r->send = 1;
994 *length = r->length;
995 return r->buf;
996 }
997 }
998
999 return NULL;
1000}
1001EXPORT_SYMBOL_GPL(rndis_get_next_response);
1002
1003static rndis_resp_t *rndis_add_response(int configNr, u32 length)
1004{
1005 rndis_resp_t *r;
1006
1007 /* NOTE: this gets copied into ether.c USB_BUFSIZ bytes ... */
1008 r = kmalloc(sizeof(rndis_resp_t) + length, GFP_ATOMIC);
1009 if (!r) return NULL;
1010
1011 r->buf = (u8 *)(r + 1);
1012 r->length = length;
1013 r->send = 0;
1014
1015 list_add_tail(&r->list,
1016 &(rndis_per_dev_params[configNr].resp_queue));
1017 return r;
1018}
1019
1020int rndis_rm_hdr(struct gether *port,
1021 struct sk_buff *skb,
1022 struct sk_buff_head *list)
1023{
1024 /* tmp points to a struct rndis_packet_msg_type */
1025 __le32 *tmp = (void *)skb->data;
1026
1027 /* MessageType, MessageLength */
1028 if (cpu_to_le32(RNDIS_MSG_PACKET)
1029 != get_unaligned(tmp++)) {
1030 dev_kfree_skb_any(skb);
1031 return -EINVAL;
1032 }
1033 tmp++;
1034
1035 /* DataOffset, DataLength */
1036 if (!skb_pull(skb, get_unaligned_le32(tmp++) + 8)) {
1037 dev_kfree_skb_any(skb);
1038 return -EOVERFLOW;
1039 }
1040 skb_trim(skb, get_unaligned_le32(tmp++));
1041
1042 skb_queue_tail(list, skb);
1043 return 0;
1044}
1045EXPORT_SYMBOL_GPL(rndis_rm_hdr);
1046
1047#ifdef CONFIG_USB_GADGET_DEBUG_FILES
1048
1049static int rndis_proc_show(struct seq_file *m, void *v)
1050{
1051 rndis_params *param = m->private;
1052
1053 seq_printf(m,
1054 "Config Nr. %d\n"
1055 "used : %s\n"
1056 "state : %s\n"
1057 "medium : 0x%08X\n"
1058 "speed : %d\n"
1059 "cable : %s\n"
1060 "vendor ID : 0x%08X\n"
1061 "vendor : %s\n",
1062 param->confignr, (param->used) ? "y" : "n",
1063 ({ char *s = "?";
1064 switch (param->state) {
1065 case RNDIS_UNINITIALIZED:
1066 s = "RNDIS_UNINITIALIZED"; break;
1067 case RNDIS_INITIALIZED:
1068 s = "RNDIS_INITIALIZED"; break;
1069 case RNDIS_DATA_INITIALIZED:
1070 s = "RNDIS_DATA_INITIALIZED"; break;
1071 } s; }),
1072 param->medium,
1073 (param->media_state) ? 0 : param->speed*100,
1074 (param->media_state) ? "disconnected" : "connected",
1075 param->vendorID, param->vendorDescr);
1076 return 0;
1077}
1078
1079static ssize_t rndis_proc_write(struct file *file, const char __user *buffer,
1080 size_t count, loff_t *ppos)
1081{
1082 rndis_params *p = PDE_DATA(file_inode(file));
1083 u32 speed = 0;
1084 int i, fl_speed = 0;
1085
1086 for (i = 0; i < count; i++) {
1087 char c;
1088 if (get_user(c, buffer))
1089 return -EFAULT;
1090 switch (c) {
1091 case '0':
1092 case '1':
1093 case '2':
1094 case '3':
1095 case '4':
1096 case '5':
1097 case '6':
1098 case '7':
1099 case '8':
1100 case '9':
1101 fl_speed = 1;
1102 speed = speed * 10 + c - '0';
1103 break;
1104 case 'C':
1105 case 'c':
1106 rndis_signal_connect(p->confignr);
1107 break;
1108 case 'D':
1109 case 'd':
1110 rndis_signal_disconnect(p->confignr);
1111 break;
1112 default:
1113 if (fl_speed) p->speed = speed;
1114 else pr_debug("%c is not valid\n", c);
1115 break;
1116 }
1117
1118 buffer++;
1119 }
1120
1121 return count;
1122}
1123
1124static int rndis_proc_open(struct inode *inode, struct file *file)
1125{
1126 return single_open(file, rndis_proc_show, PDE_DATA(inode));
1127}
1128
1129static const struct file_operations rndis_proc_fops = {
1130 .owner = THIS_MODULE,
1131 .open = rndis_proc_open,
1132 .read = seq_read,
1133 .llseek = seq_lseek,
1134 .release = single_release,
1135 .write = rndis_proc_write,
1136};
1137
1138#define NAME_TEMPLATE "driver/rndis-%03d"
1139
1140static struct proc_dir_entry *rndis_connect_state [RNDIS_MAX_CONFIGS];
1141
1142#endif /* CONFIG_USB_GADGET_DEBUG_FILES */
1143
1144
1145int rndis_init(void)
1146{
1147 u8 i;
1148
1149 for (i = 0; i < RNDIS_MAX_CONFIGS; i++) {
1150#ifdef CONFIG_USB_GADGET_DEBUG_FILES
1151 char name [20];
1152
1153 sprintf(name, NAME_TEMPLATE, i);
1154 rndis_connect_state[i] = proc_create_data(name, 0660, NULL,
1155 &rndis_proc_fops,
1156 (void *)(rndis_per_dev_params + i));
1157 if (!rndis_connect_state[i]) {
1158 pr_debug("%s: remove entries", __func__);
1159 while (i) {
1160 sprintf(name, NAME_TEMPLATE, --i);
1161 remove_proc_entry(name, NULL);
1162 }
1163 pr_debug("\n");
1164 return -EIO;
1165 }
1166#endif
1167 rndis_per_dev_params[i].confignr = i;
1168 rndis_per_dev_params[i].used = 0;
1169 rndis_per_dev_params[i].state = RNDIS_UNINITIALIZED;
1170 rndis_per_dev_params[i].media_state
1171 = RNDIS_MEDIA_STATE_DISCONNECTED;
1172 INIT_LIST_HEAD(&(rndis_per_dev_params[i].resp_queue));
1173 }
1174
1175 return 0;
1176}
1177
1178void rndis_exit(void)
1179{
1180#ifdef CONFIG_USB_GADGET_DEBUG_FILES
1181 u8 i;
1182 char name[20];
1183
1184 for (i = 0; i < RNDIS_MAX_CONFIGS; i++) {
1185 sprintf(name, NAME_TEMPLATE, i);
1186 remove_proc_entry(name, NULL);
1187 }
1188#endif
1189}
1190
diff --git a/drivers/usb/gadget/function/rndis.h b/drivers/usb/gadget/function/rndis.h
new file mode 100644
index 000000000000..0f4abb4c3775
--- /dev/null
+++ b/drivers/usb/gadget/function/rndis.h
@@ -0,0 +1,220 @@
1/*
2 * RNDIS Definitions for Remote NDIS
3 *
4 * Authors: Benedikt Spranger, Pengutronix
5 * Robert Schwebel, Pengutronix
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * version 2, as published by the Free Software Foundation.
10 *
11 * This software was originally developed in conformance with
12 * Microsoft's Remote NDIS Specification License Agreement.
13 */
14
15#ifndef _LINUX_RNDIS_H
16#define _LINUX_RNDIS_H
17
18#include <linux/rndis.h>
19#include "u_ether.h"
20#include "ndis.h"
21
22#define RNDIS_MAXIMUM_FRAME_SIZE 1518
23#define RNDIS_MAX_TOTAL_SIZE 1558
24
25typedef struct rndis_init_msg_type
26{
27 __le32 MessageType;
28 __le32 MessageLength;
29 __le32 RequestID;
30 __le32 MajorVersion;
31 __le32 MinorVersion;
32 __le32 MaxTransferSize;
33} rndis_init_msg_type;
34
35typedef struct rndis_init_cmplt_type
36{
37 __le32 MessageType;
38 __le32 MessageLength;
39 __le32 RequestID;
40 __le32 Status;
41 __le32 MajorVersion;
42 __le32 MinorVersion;
43 __le32 DeviceFlags;
44 __le32 Medium;
45 __le32 MaxPacketsPerTransfer;
46 __le32 MaxTransferSize;
47 __le32 PacketAlignmentFactor;
48 __le32 AFListOffset;
49 __le32 AFListSize;
50} rndis_init_cmplt_type;
51
52typedef struct rndis_halt_msg_type
53{
54 __le32 MessageType;
55 __le32 MessageLength;
56 __le32 RequestID;
57} rndis_halt_msg_type;
58
59typedef struct rndis_query_msg_type
60{
61 __le32 MessageType;
62 __le32 MessageLength;
63 __le32 RequestID;
64 __le32 OID;
65 __le32 InformationBufferLength;
66 __le32 InformationBufferOffset;
67 __le32 DeviceVcHandle;
68} rndis_query_msg_type;
69
70typedef struct rndis_query_cmplt_type
71{
72 __le32 MessageType;
73 __le32 MessageLength;
74 __le32 RequestID;
75 __le32 Status;
76 __le32 InformationBufferLength;
77 __le32 InformationBufferOffset;
78} rndis_query_cmplt_type;
79
80typedef struct rndis_set_msg_type
81{
82 __le32 MessageType;
83 __le32 MessageLength;
84 __le32 RequestID;
85 __le32 OID;
86 __le32 InformationBufferLength;
87 __le32 InformationBufferOffset;
88 __le32 DeviceVcHandle;
89} rndis_set_msg_type;
90
91typedef struct rndis_set_cmplt_type
92{
93 __le32 MessageType;
94 __le32 MessageLength;
95 __le32 RequestID;
96 __le32 Status;
97} rndis_set_cmplt_type;
98
99typedef struct rndis_reset_msg_type
100{
101 __le32 MessageType;
102 __le32 MessageLength;
103 __le32 Reserved;
104} rndis_reset_msg_type;
105
106typedef struct rndis_reset_cmplt_type
107{
108 __le32 MessageType;
109 __le32 MessageLength;
110 __le32 Status;
111 __le32 AddressingReset;
112} rndis_reset_cmplt_type;
113
114typedef struct rndis_indicate_status_msg_type
115{
116 __le32 MessageType;
117 __le32 MessageLength;
118 __le32 Status;
119 __le32 StatusBufferLength;
120 __le32 StatusBufferOffset;
121} rndis_indicate_status_msg_type;
122
123typedef struct rndis_keepalive_msg_type
124{
125 __le32 MessageType;
126 __le32 MessageLength;
127 __le32 RequestID;
128} rndis_keepalive_msg_type;
129
130typedef struct rndis_keepalive_cmplt_type
131{
132 __le32 MessageType;
133 __le32 MessageLength;
134 __le32 RequestID;
135 __le32 Status;
136} rndis_keepalive_cmplt_type;
137
138struct rndis_packet_msg_type
139{
140 __le32 MessageType;
141 __le32 MessageLength;
142 __le32 DataOffset;
143 __le32 DataLength;
144 __le32 OOBDataOffset;
145 __le32 OOBDataLength;
146 __le32 NumOOBDataElements;
147 __le32 PerPacketInfoOffset;
148 __le32 PerPacketInfoLength;
149 __le32 VcHandle;
150 __le32 Reserved;
151} __attribute__ ((packed));
152
153struct rndis_config_parameter
154{
155 __le32 ParameterNameOffset;
156 __le32 ParameterNameLength;
157 __le32 ParameterType;
158 __le32 ParameterValueOffset;
159 __le32 ParameterValueLength;
160};
161
162/* implementation specific */
163enum rndis_state
164{
165 RNDIS_UNINITIALIZED,
166 RNDIS_INITIALIZED,
167 RNDIS_DATA_INITIALIZED,
168};
169
170typedef struct rndis_resp_t
171{
172 struct list_head list;
173 u8 *buf;
174 u32 length;
175 int send;
176} rndis_resp_t;
177
178typedef struct rndis_params
179{
180 u8 confignr;
181 u8 used;
182 u16 saved_filter;
183 enum rndis_state state;
184 u32 medium;
185 u32 speed;
186 u32 media_state;
187
188 const u8 *host_mac;
189 u16 *filter;
190 struct net_device *dev;
191
192 u32 vendorID;
193 const char *vendorDescr;
194 void (*resp_avail)(void *v);
195 void *v;
196 struct list_head resp_queue;
197} rndis_params;
198
199/* RNDIS Message parser and other useless functions */
200int rndis_msg_parser (u8 configNr, u8 *buf);
201int rndis_register(void (*resp_avail)(void *v), void *v);
202void rndis_deregister (int configNr);
203int rndis_set_param_dev (u8 configNr, struct net_device *dev,
204 u16 *cdc_filter);
205int rndis_set_param_vendor (u8 configNr, u32 vendorID,
206 const char *vendorDescr);
207int rndis_set_param_medium (u8 configNr, u32 medium, u32 speed);
208void rndis_add_hdr (struct sk_buff *skb);
209int rndis_rm_hdr(struct gether *port, struct sk_buff *skb,
210 struct sk_buff_head *list);
211u8 *rndis_get_next_response (int configNr, u32 *length);
212void rndis_free_response (int configNr, u8 *buf);
213
214void rndis_uninit (int configNr);
215int rndis_signal_connect (int configNr);
216int rndis_signal_disconnect (int configNr);
217int rndis_state (int configNr);
218extern void rndis_set_host_mac (int configNr, const u8 *addr);
219
220#endif /* _LINUX_RNDIS_H */
diff --git a/drivers/usb/gadget/function/storage_common.c b/drivers/usb/gadget/function/storage_common.c
new file mode 100644
index 000000000000..648f9e489b39
--- /dev/null
+++ b/drivers/usb/gadget/function/storage_common.c
@@ -0,0 +1,504 @@
1/*
2 * storage_common.c -- Common definitions for mass storage functionality
3 *
4 * Copyright (C) 2003-2008 Alan Stern
5 * Copyeight (C) 2009 Samsung Electronics
6 * Author: Michal Nazarewicz (mina86@mina86.com)
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 */
13
14/*
15 * This file requires the following identifiers used in USB strings to
16 * be defined (each of type pointer to char):
17 * - fsg_string_interface -- name of the interface
18 */
19
20/*
21 * When USB_GADGET_DEBUG_FILES is defined the module param num_buffers
22 * sets the number of pipeline buffers (length of the fsg_buffhd array).
23 * The valid range of num_buffers is: num >= 2 && num <= 4.
24 */
25
26#include <linux/module.h>
27#include <linux/blkdev.h>
28#include <linux/file.h>
29#include <linux/fs.h>
30#include <linux/usb/composite.h>
31
32#include "storage_common.h"
33
34/* There is only one interface. */
35
36struct usb_interface_descriptor fsg_intf_desc = {
37 .bLength = sizeof fsg_intf_desc,
38 .bDescriptorType = USB_DT_INTERFACE,
39
40 .bNumEndpoints = 2, /* Adjusted during fsg_bind() */
41 .bInterfaceClass = USB_CLASS_MASS_STORAGE,
42 .bInterfaceSubClass = USB_SC_SCSI, /* Adjusted during fsg_bind() */
43 .bInterfaceProtocol = USB_PR_BULK, /* Adjusted during fsg_bind() */
44 .iInterface = FSG_STRING_INTERFACE,
45};
46EXPORT_SYMBOL_GPL(fsg_intf_desc);
47
48/*
49 * Three full-speed endpoint descriptors: bulk-in, bulk-out, and
50 * interrupt-in.
51 */
52
53struct usb_endpoint_descriptor fsg_fs_bulk_in_desc = {
54 .bLength = USB_DT_ENDPOINT_SIZE,
55 .bDescriptorType = USB_DT_ENDPOINT,
56
57 .bEndpointAddress = USB_DIR_IN,
58 .bmAttributes = USB_ENDPOINT_XFER_BULK,
59 /* wMaxPacketSize set by autoconfiguration */
60};
61EXPORT_SYMBOL_GPL(fsg_fs_bulk_in_desc);
62
63struct usb_endpoint_descriptor fsg_fs_bulk_out_desc = {
64 .bLength = USB_DT_ENDPOINT_SIZE,
65 .bDescriptorType = USB_DT_ENDPOINT,
66
67 .bEndpointAddress = USB_DIR_OUT,
68 .bmAttributes = USB_ENDPOINT_XFER_BULK,
69 /* wMaxPacketSize set by autoconfiguration */
70};
71EXPORT_SYMBOL_GPL(fsg_fs_bulk_out_desc);
72
73struct usb_descriptor_header *fsg_fs_function[] = {
74 (struct usb_descriptor_header *) &fsg_intf_desc,
75 (struct usb_descriptor_header *) &fsg_fs_bulk_in_desc,
76 (struct usb_descriptor_header *) &fsg_fs_bulk_out_desc,
77 NULL,
78};
79EXPORT_SYMBOL_GPL(fsg_fs_function);
80
81
82/*
83 * USB 2.0 devices need to expose both high speed and full speed
84 * descriptors, unless they only run at full speed.
85 *
86 * That means alternate endpoint descriptors (bigger packets)
87 * and a "device qualifier" ... plus more construction options
88 * for the configuration descriptor.
89 */
90struct usb_endpoint_descriptor fsg_hs_bulk_in_desc = {
91 .bLength = USB_DT_ENDPOINT_SIZE,
92 .bDescriptorType = USB_DT_ENDPOINT,
93
94 /* bEndpointAddress copied from fs_bulk_in_desc during fsg_bind() */
95 .bmAttributes = USB_ENDPOINT_XFER_BULK,
96 .wMaxPacketSize = cpu_to_le16(512),
97};
98EXPORT_SYMBOL_GPL(fsg_hs_bulk_in_desc);
99
100struct usb_endpoint_descriptor fsg_hs_bulk_out_desc = {
101 .bLength = USB_DT_ENDPOINT_SIZE,
102 .bDescriptorType = USB_DT_ENDPOINT,
103
104 /* bEndpointAddress copied from fs_bulk_out_desc during fsg_bind() */
105 .bmAttributes = USB_ENDPOINT_XFER_BULK,
106 .wMaxPacketSize = cpu_to_le16(512),
107 .bInterval = 1, /* NAK every 1 uframe */
108};
109EXPORT_SYMBOL_GPL(fsg_hs_bulk_out_desc);
110
111
112struct usb_descriptor_header *fsg_hs_function[] = {
113 (struct usb_descriptor_header *) &fsg_intf_desc,
114 (struct usb_descriptor_header *) &fsg_hs_bulk_in_desc,
115 (struct usb_descriptor_header *) &fsg_hs_bulk_out_desc,
116 NULL,
117};
118EXPORT_SYMBOL_GPL(fsg_hs_function);
119
120struct usb_endpoint_descriptor fsg_ss_bulk_in_desc = {
121 .bLength = USB_DT_ENDPOINT_SIZE,
122 .bDescriptorType = USB_DT_ENDPOINT,
123
124 /* bEndpointAddress copied from fs_bulk_in_desc during fsg_bind() */
125 .bmAttributes = USB_ENDPOINT_XFER_BULK,
126 .wMaxPacketSize = cpu_to_le16(1024),
127};
128EXPORT_SYMBOL_GPL(fsg_ss_bulk_in_desc);
129
130struct usb_ss_ep_comp_descriptor fsg_ss_bulk_in_comp_desc = {
131 .bLength = sizeof(fsg_ss_bulk_in_comp_desc),
132 .bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
133
134 /*.bMaxBurst = DYNAMIC, */
135};
136EXPORT_SYMBOL_GPL(fsg_ss_bulk_in_comp_desc);
137
138struct usb_endpoint_descriptor fsg_ss_bulk_out_desc = {
139 .bLength = USB_DT_ENDPOINT_SIZE,
140 .bDescriptorType = USB_DT_ENDPOINT,
141
142 /* bEndpointAddress copied from fs_bulk_out_desc during fsg_bind() */
143 .bmAttributes = USB_ENDPOINT_XFER_BULK,
144 .wMaxPacketSize = cpu_to_le16(1024),
145};
146EXPORT_SYMBOL_GPL(fsg_ss_bulk_out_desc);
147
148struct usb_ss_ep_comp_descriptor fsg_ss_bulk_out_comp_desc = {
149 .bLength = sizeof(fsg_ss_bulk_in_comp_desc),
150 .bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
151
152 /*.bMaxBurst = DYNAMIC, */
153};
154EXPORT_SYMBOL_GPL(fsg_ss_bulk_out_comp_desc);
155
156struct usb_descriptor_header *fsg_ss_function[] = {
157 (struct usb_descriptor_header *) &fsg_intf_desc,
158 (struct usb_descriptor_header *) &fsg_ss_bulk_in_desc,
159 (struct usb_descriptor_header *) &fsg_ss_bulk_in_comp_desc,
160 (struct usb_descriptor_header *) &fsg_ss_bulk_out_desc,
161 (struct usb_descriptor_header *) &fsg_ss_bulk_out_comp_desc,
162 NULL,
163};
164EXPORT_SYMBOL_GPL(fsg_ss_function);
165
166
167 /*-------------------------------------------------------------------------*/
168
169/*
170 * If the next two routines are called while the gadget is registered,
171 * the caller must own fsg->filesem for writing.
172 */
173
174void fsg_lun_close(struct fsg_lun *curlun)
175{
176 if (curlun->filp) {
177 LDBG(curlun, "close backing file\n");
178 fput(curlun->filp);
179 curlun->filp = NULL;
180 }
181}
182EXPORT_SYMBOL_GPL(fsg_lun_close);
183
184int fsg_lun_open(struct fsg_lun *curlun, const char *filename)
185{
186 int ro;
187 struct file *filp = NULL;
188 int rc = -EINVAL;
189 struct inode *inode = NULL;
190 loff_t size;
191 loff_t num_sectors;
192 loff_t min_sectors;
193 unsigned int blkbits;
194 unsigned int blksize;
195
196 /* R/W if we can, R/O if we must */
197 ro = curlun->initially_ro;
198 if (!ro) {
199 filp = filp_open(filename, O_RDWR | O_LARGEFILE, 0);
200 if (PTR_ERR(filp) == -EROFS || PTR_ERR(filp) == -EACCES)
201 ro = 1;
202 }
203 if (ro)
204 filp = filp_open(filename, O_RDONLY | O_LARGEFILE, 0);
205 if (IS_ERR(filp)) {
206 LINFO(curlun, "unable to open backing file: %s\n", filename);
207 return PTR_ERR(filp);
208 }
209
210 if (!(filp->f_mode & FMODE_WRITE))
211 ro = 1;
212
213 inode = file_inode(filp);
214 if ((!S_ISREG(inode->i_mode) && !S_ISBLK(inode->i_mode))) {
215 LINFO(curlun, "invalid file type: %s\n", filename);
216 goto out;
217 }
218
219 /*
220 * If we can't read the file, it's no good.
221 * If we can't write the file, use it read-only.
222 */
223 if (!(filp->f_mode & FMODE_CAN_READ)) {
224 LINFO(curlun, "file not readable: %s\n", filename);
225 goto out;
226 }
227 if (!(filp->f_mode & FMODE_CAN_WRITE))
228 ro = 1;
229
230 size = i_size_read(inode->i_mapping->host);
231 if (size < 0) {
232 LINFO(curlun, "unable to find file size: %s\n", filename);
233 rc = (int) size;
234 goto out;
235 }
236
237 if (curlun->cdrom) {
238 blksize = 2048;
239 blkbits = 11;
240 } else if (inode->i_bdev) {
241 blksize = bdev_logical_block_size(inode->i_bdev);
242 blkbits = blksize_bits(blksize);
243 } else {
244 blksize = 512;
245 blkbits = 9;
246 }
247
248 num_sectors = size >> blkbits; /* File size in logic-block-size blocks */
249 min_sectors = 1;
250 if (curlun->cdrom) {
251 min_sectors = 300; /* Smallest track is 300 frames */
252 if (num_sectors >= 256*60*75) {
253 num_sectors = 256*60*75 - 1;
254 LINFO(curlun, "file too big: %s\n", filename);
255 LINFO(curlun, "using only first %d blocks\n",
256 (int) num_sectors);
257 }
258 }
259 if (num_sectors < min_sectors) {
260 LINFO(curlun, "file too small: %s\n", filename);
261 rc = -ETOOSMALL;
262 goto out;
263 }
264
265 if (fsg_lun_is_open(curlun))
266 fsg_lun_close(curlun);
267
268 curlun->blksize = blksize;
269 curlun->blkbits = blkbits;
270 curlun->ro = ro;
271 curlun->filp = filp;
272 curlun->file_length = size;
273 curlun->num_sectors = num_sectors;
274 LDBG(curlun, "open backing file: %s\n", filename);
275 return 0;
276
277out:
278 fput(filp);
279 return rc;
280}
281EXPORT_SYMBOL_GPL(fsg_lun_open);
282
283
284/*-------------------------------------------------------------------------*/
285
286/*
287 * Sync the file data, don't bother with the metadata.
288 * This code was copied from fs/buffer.c:sys_fdatasync().
289 */
290int fsg_lun_fsync_sub(struct fsg_lun *curlun)
291{
292 struct file *filp = curlun->filp;
293
294 if (curlun->ro || !filp)
295 return 0;
296 return vfs_fsync(filp, 1);
297}
298EXPORT_SYMBOL_GPL(fsg_lun_fsync_sub);
299
300void store_cdrom_address(u8 *dest, int msf, u32 addr)
301{
302 if (msf) {
303 /* Convert to Minutes-Seconds-Frames */
304 addr >>= 2; /* Convert to 2048-byte frames */
305 addr += 2*75; /* Lead-in occupies 2 seconds */
306 dest[3] = addr % 75; /* Frames */
307 addr /= 75;
308 dest[2] = addr % 60; /* Seconds */
309 addr /= 60;
310 dest[1] = addr; /* Minutes */
311 dest[0] = 0; /* Reserved */
312 } else {
313 /* Absolute sector */
314 put_unaligned_be32(addr, dest);
315 }
316}
317EXPORT_SYMBOL_GPL(store_cdrom_address);
318
319/*-------------------------------------------------------------------------*/
320
321
322ssize_t fsg_show_ro(struct fsg_lun *curlun, char *buf)
323{
324 return sprintf(buf, "%d\n", fsg_lun_is_open(curlun)
325 ? curlun->ro
326 : curlun->initially_ro);
327}
328EXPORT_SYMBOL_GPL(fsg_show_ro);
329
330ssize_t fsg_show_nofua(struct fsg_lun *curlun, char *buf)
331{
332 return sprintf(buf, "%u\n", curlun->nofua);
333}
334EXPORT_SYMBOL_GPL(fsg_show_nofua);
335
336ssize_t fsg_show_file(struct fsg_lun *curlun, struct rw_semaphore *filesem,
337 char *buf)
338{
339 char *p;
340 ssize_t rc;
341
342 down_read(filesem);
343 if (fsg_lun_is_open(curlun)) { /* Get the complete pathname */
344 p = d_path(&curlun->filp->f_path, buf, PAGE_SIZE - 1);
345 if (IS_ERR(p))
346 rc = PTR_ERR(p);
347 else {
348 rc = strlen(p);
349 memmove(buf, p, rc);
350 buf[rc] = '\n'; /* Add a newline */
351 buf[++rc] = 0;
352 }
353 } else { /* No file, return 0 bytes */
354 *buf = 0;
355 rc = 0;
356 }
357 up_read(filesem);
358 return rc;
359}
360EXPORT_SYMBOL_GPL(fsg_show_file);
361
362ssize_t fsg_show_cdrom(struct fsg_lun *curlun, char *buf)
363{
364 return sprintf(buf, "%u\n", curlun->cdrom);
365}
366EXPORT_SYMBOL_GPL(fsg_show_cdrom);
367
368ssize_t fsg_show_removable(struct fsg_lun *curlun, char *buf)
369{
370 return sprintf(buf, "%u\n", curlun->removable);
371}
372EXPORT_SYMBOL_GPL(fsg_show_removable);
373
374/*
375 * The caller must hold fsg->filesem for reading when calling this function.
376 */
377static ssize_t _fsg_store_ro(struct fsg_lun *curlun, bool ro)
378{
379 if (fsg_lun_is_open(curlun)) {
380 LDBG(curlun, "read-only status change prevented\n");
381 return -EBUSY;
382 }
383
384 curlun->ro = ro;
385 curlun->initially_ro = ro;
386 LDBG(curlun, "read-only status set to %d\n", curlun->ro);
387
388 return 0;
389}
390
391ssize_t fsg_store_ro(struct fsg_lun *curlun, struct rw_semaphore *filesem,
392 const char *buf, size_t count)
393{
394 ssize_t rc;
395 bool ro;
396
397 rc = strtobool(buf, &ro);
398 if (rc)
399 return rc;
400
401 /*
402 * Allow the write-enable status to change only while the
403 * backing file is closed.
404 */
405 down_read(filesem);
406 rc = _fsg_store_ro(curlun, ro);
407 if (!rc)
408 rc = count;
409 up_read(filesem);
410
411 return rc;
412}
413EXPORT_SYMBOL_GPL(fsg_store_ro);
414
415ssize_t fsg_store_nofua(struct fsg_lun *curlun, const char *buf, size_t count)
416{
417 bool nofua;
418 int ret;
419
420 ret = strtobool(buf, &nofua);
421 if (ret)
422 return ret;
423
424 /* Sync data when switching from async mode to sync */
425 if (!nofua && curlun->nofua)
426 fsg_lun_fsync_sub(curlun);
427
428 curlun->nofua = nofua;
429
430 return count;
431}
432EXPORT_SYMBOL_GPL(fsg_store_nofua);
433
434ssize_t fsg_store_file(struct fsg_lun *curlun, struct rw_semaphore *filesem,
435 const char *buf, size_t count)
436{
437 int rc = 0;
438
439 if (curlun->prevent_medium_removal && fsg_lun_is_open(curlun)) {
440 LDBG(curlun, "eject attempt prevented\n");
441 return -EBUSY; /* "Door is locked" */
442 }
443
444 /* Remove a trailing newline */
445 if (count > 0 && buf[count-1] == '\n')
446 ((char *) buf)[count-1] = 0; /* Ugh! */
447
448 /* Load new medium */
449 down_write(filesem);
450 if (count > 0 && buf[0]) {
451 /* fsg_lun_open() will close existing file if any. */
452 rc = fsg_lun_open(curlun, buf);
453 if (rc == 0)
454 curlun->unit_attention_data =
455 SS_NOT_READY_TO_READY_TRANSITION;
456 } else if (fsg_lun_is_open(curlun)) {
457 fsg_lun_close(curlun);
458 curlun->unit_attention_data = SS_MEDIUM_NOT_PRESENT;
459 }
460 up_write(filesem);
461 return (rc < 0 ? rc : count);
462}
463EXPORT_SYMBOL_GPL(fsg_store_file);
464
465ssize_t fsg_store_cdrom(struct fsg_lun *curlun, struct rw_semaphore *filesem,
466 const char *buf, size_t count)
467{
468 bool cdrom;
469 int ret;
470
471 ret = strtobool(buf, &cdrom);
472 if (ret)
473 return ret;
474
475 down_read(filesem);
476 ret = cdrom ? _fsg_store_ro(curlun, true) : 0;
477
478 if (!ret) {
479 curlun->cdrom = cdrom;
480 ret = count;
481 }
482 up_read(filesem);
483
484 return ret;
485}
486EXPORT_SYMBOL_GPL(fsg_store_cdrom);
487
488ssize_t fsg_store_removable(struct fsg_lun *curlun, const char *buf,
489 size_t count)
490{
491 bool removable;
492 int ret;
493
494 ret = strtobool(buf, &removable);
495 if (ret)
496 return ret;
497
498 curlun->removable = removable;
499
500 return count;
501}
502EXPORT_SYMBOL_GPL(fsg_store_removable);
503
504MODULE_LICENSE("GPL");
diff --git a/drivers/usb/gadget/function/storage_common.h b/drivers/usb/gadget/function/storage_common.h
new file mode 100644
index 000000000000..70c891469f57
--- /dev/null
+++ b/drivers/usb/gadget/function/storage_common.h
@@ -0,0 +1,225 @@
1#ifndef USB_STORAGE_COMMON_H
2#define USB_STORAGE_COMMON_H
3
4#include <linux/device.h>
5#include <linux/usb/storage.h>
6#include <scsi/scsi.h>
7#include <asm/unaligned.h>
8
9#ifndef DEBUG
10#undef VERBOSE_DEBUG
11#undef DUMP_MSGS
12#endif /* !DEBUG */
13
14#ifdef VERBOSE_DEBUG
15#define VLDBG LDBG
16#else
17#define VLDBG(lun, fmt, args...) do { } while (0)
18#endif /* VERBOSE_DEBUG */
19
20#define _LMSG(func, lun, fmt, args...) \
21 do { \
22 if ((lun)->name_pfx && *(lun)->name_pfx) \
23 func("%s/%s: " fmt, *(lun)->name_pfx, \
24 (lun)->name, ## args); \
25 else \
26 func("%s: " fmt, (lun)->name, ## args); \
27 } while (0)
28
29#define LDBG(lun, fmt, args...) _LMSG(pr_debug, lun, fmt, ## args)
30#define LERROR(lun, fmt, args...) _LMSG(pr_err, lun, fmt, ## args)
31#define LWARN(lun, fmt, args...) _LMSG(pr_warn, lun, fmt, ## args)
32#define LINFO(lun, fmt, args...) _LMSG(pr_info, lun, fmt, ## args)
33
34
35#ifdef DUMP_MSGS
36
37# define dump_msg(fsg, /* const char * */ label, \
38 /* const u8 * */ buf, /* unsigned */ length) \
39do { \
40 if (length < 512) { \
41 DBG(fsg, "%s, length %u:\n", label, length); \
42 print_hex_dump(KERN_DEBUG, "", DUMP_PREFIX_OFFSET, \
43 16, 1, buf, length, 0); \
44 } \
45} while (0)
46
47# define dump_cdb(fsg) do { } while (0)
48
49#else
50
51# define dump_msg(fsg, /* const char * */ label, \
52 /* const u8 * */ buf, /* unsigned */ length) do { } while (0)
53
54# ifdef VERBOSE_DEBUG
55
56# define dump_cdb(fsg) \
57 print_hex_dump(KERN_DEBUG, "SCSI CDB: ", DUMP_PREFIX_NONE, \
58 16, 1, (fsg)->cmnd, (fsg)->cmnd_size, 0) \
59
60# else
61
62# define dump_cdb(fsg) do { } while (0)
63
64# endif /* VERBOSE_DEBUG */
65
66#endif /* DUMP_MSGS */
67
68/* Length of a SCSI Command Data Block */
69#define MAX_COMMAND_SIZE 16
70
71/* SCSI Sense Key/Additional Sense Code/ASC Qualifier values */
72#define SS_NO_SENSE 0
73#define SS_COMMUNICATION_FAILURE 0x040800
74#define SS_INVALID_COMMAND 0x052000
75#define SS_INVALID_FIELD_IN_CDB 0x052400
76#define SS_LOGICAL_BLOCK_ADDRESS_OUT_OF_RANGE 0x052100
77#define SS_LOGICAL_UNIT_NOT_SUPPORTED 0x052500
78#define SS_MEDIUM_NOT_PRESENT 0x023a00
79#define SS_MEDIUM_REMOVAL_PREVENTED 0x055302
80#define SS_NOT_READY_TO_READY_TRANSITION 0x062800
81#define SS_RESET_OCCURRED 0x062900
82#define SS_SAVING_PARAMETERS_NOT_SUPPORTED 0x053900
83#define SS_UNRECOVERED_READ_ERROR 0x031100
84#define SS_WRITE_ERROR 0x030c02
85#define SS_WRITE_PROTECTED 0x072700
86
87#define SK(x) ((u8) ((x) >> 16)) /* Sense Key byte, etc. */
88#define ASC(x) ((u8) ((x) >> 8))
89#define ASCQ(x) ((u8) (x))
90
91struct fsg_lun {
92 struct file *filp;
93 loff_t file_length;
94 loff_t num_sectors;
95
96 unsigned int initially_ro:1;
97 unsigned int ro:1;
98 unsigned int removable:1;
99 unsigned int cdrom:1;
100 unsigned int prevent_medium_removal:1;
101 unsigned int registered:1;
102 unsigned int info_valid:1;
103 unsigned int nofua:1;
104
105 u32 sense_data;
106 u32 sense_data_info;
107 u32 unit_attention_data;
108
109 unsigned int blkbits; /* Bits of logical block size
110 of bound block device */
111 unsigned int blksize; /* logical block size of bound block device */
112 struct device dev;
113 const char *name; /* "lun.name" */
114 const char **name_pfx; /* "function.name" */
115};
116
117static inline bool fsg_lun_is_open(struct fsg_lun *curlun)
118{
119 return curlun->filp != NULL;
120}
121
122/* Default size of buffer length. */
123#define FSG_BUFLEN ((u32)16384)
124
125/* Maximal number of LUNs supported in mass storage function */
126#define FSG_MAX_LUNS 8
127
128enum fsg_buffer_state {
129 BUF_STATE_EMPTY = 0,
130 BUF_STATE_FULL,
131 BUF_STATE_BUSY
132};
133
134struct fsg_buffhd {
135 void *buf;
136 enum fsg_buffer_state state;
137 struct fsg_buffhd *next;
138
139 /*
140 * The NetChip 2280 is faster, and handles some protocol faults
141 * better, if we don't submit any short bulk-out read requests.
142 * So we will record the intended request length here.
143 */
144 unsigned int bulk_out_intended_length;
145
146 struct usb_request *inreq;
147 int inreq_busy;
148 struct usb_request *outreq;
149 int outreq_busy;
150};
151
152enum fsg_state {
153 /* This one isn't used anywhere */
154 FSG_STATE_COMMAND_PHASE = -10,
155 FSG_STATE_DATA_PHASE,
156 FSG_STATE_STATUS_PHASE,
157
158 FSG_STATE_IDLE = 0,
159 FSG_STATE_ABORT_BULK_OUT,
160 FSG_STATE_RESET,
161 FSG_STATE_INTERFACE_CHANGE,
162 FSG_STATE_CONFIG_CHANGE,
163 FSG_STATE_DISCONNECT,
164 FSG_STATE_EXIT,
165 FSG_STATE_TERMINATED
166};
167
168enum data_direction {
169 DATA_DIR_UNKNOWN = 0,
170 DATA_DIR_FROM_HOST,
171 DATA_DIR_TO_HOST,
172 DATA_DIR_NONE
173};
174
175static inline u32 get_unaligned_be24(u8 *buf)
176{
177 return 0xffffff & (u32) get_unaligned_be32(buf - 1);
178}
179
180static inline struct fsg_lun *fsg_lun_from_dev(struct device *dev)
181{
182 return container_of(dev, struct fsg_lun, dev);
183}
184
185enum {
186 FSG_STRING_INTERFACE
187};
188
189extern struct usb_interface_descriptor fsg_intf_desc;
190
191extern struct usb_endpoint_descriptor fsg_fs_bulk_in_desc;
192extern struct usb_endpoint_descriptor fsg_fs_bulk_out_desc;
193extern struct usb_descriptor_header *fsg_fs_function[];
194
195extern struct usb_endpoint_descriptor fsg_hs_bulk_in_desc;
196extern struct usb_endpoint_descriptor fsg_hs_bulk_out_desc;
197extern struct usb_descriptor_header *fsg_hs_function[];
198
199extern struct usb_endpoint_descriptor fsg_ss_bulk_in_desc;
200extern struct usb_ss_ep_comp_descriptor fsg_ss_bulk_in_comp_desc;
201extern struct usb_endpoint_descriptor fsg_ss_bulk_out_desc;
202extern struct usb_ss_ep_comp_descriptor fsg_ss_bulk_out_comp_desc;
203extern struct usb_descriptor_header *fsg_ss_function[];
204
205void fsg_lun_close(struct fsg_lun *curlun);
206int fsg_lun_open(struct fsg_lun *curlun, const char *filename);
207int fsg_lun_fsync_sub(struct fsg_lun *curlun);
208void store_cdrom_address(u8 *dest, int msf, u32 addr);
209ssize_t fsg_show_ro(struct fsg_lun *curlun, char *buf);
210ssize_t fsg_show_nofua(struct fsg_lun *curlun, char *buf);
211ssize_t fsg_show_file(struct fsg_lun *curlun, struct rw_semaphore *filesem,
212 char *buf);
213ssize_t fsg_show_cdrom(struct fsg_lun *curlun, char *buf);
214ssize_t fsg_show_removable(struct fsg_lun *curlun, char *buf);
215ssize_t fsg_store_ro(struct fsg_lun *curlun, struct rw_semaphore *filesem,
216 const char *buf, size_t count);
217ssize_t fsg_store_nofua(struct fsg_lun *curlun, const char *buf, size_t count);
218ssize_t fsg_store_file(struct fsg_lun *curlun, struct rw_semaphore *filesem,
219 const char *buf, size_t count);
220ssize_t fsg_store_cdrom(struct fsg_lun *curlun, struct rw_semaphore *filesem,
221 const char *buf, size_t count);
222ssize_t fsg_store_removable(struct fsg_lun *curlun, const char *buf,
223 size_t count);
224
225#endif /* USB_STORAGE_COMMON_H */
diff --git a/drivers/usb/gadget/function/u_ecm.h b/drivers/usb/gadget/function/u_ecm.h
new file mode 100644
index 000000000000..262cc03cc2c0
--- /dev/null
+++ b/drivers/usb/gadget/function/u_ecm.h
@@ -0,0 +1,36 @@
1/*
2 * u_ecm.h
3 *
4 * Utility definitions for the ecm function
5 *
6 * Copyright (c) 2013 Samsung Electronics Co., Ltd.
7 * http://www.samsung.com
8 *
9 * Author: Andrzej Pietrasiewicz <andrzej.p@samsung.com>
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License version 2 as
13 * published by the Free Software Foundation.
14 */
15
16#ifndef U_ECM_H
17#define U_ECM_H
18
19#include <linux/usb/composite.h>
20
21struct f_ecm_opts {
22 struct usb_function_instance func_inst;
23 struct net_device *net;
24 bool bound;
25
26 /*
27 * Read/write access to configfs attributes is handled by configfs.
28 *
29 * This is to protect the data from concurrent access by read/write
30 * and create symlink/remove symlink.
31 */
32 struct mutex lock;
33 int refcnt;
34};
35
36#endif /* U_ECM_H */
diff --git a/drivers/usb/gadget/function/u_eem.h b/drivers/usb/gadget/function/u_eem.h
new file mode 100644
index 000000000000..e3ae97874c4f
--- /dev/null
+++ b/drivers/usb/gadget/function/u_eem.h
@@ -0,0 +1,36 @@
1/*
2 * u_eem.h
3 *
4 * Utility definitions for the eem function
5 *
6 * Copyright (c) 2013 Samsung Electronics Co., Ltd.
7 * http://www.samsung.com
8 *
9 * Author: Andrzej Pietrasiewicz <andrzej.p@samsung.com>
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License version 2 as
13 * published by the Free Software Foundation.
14 */
15
16#ifndef U_EEM_H
17#define U_EEM_H
18
19#include <linux/usb/composite.h>
20
21struct f_eem_opts {
22 struct usb_function_instance func_inst;
23 struct net_device *net;
24 bool bound;
25
26 /*
27 * Read/write access to configfs attributes is handled by configfs.
28 *
29 * This is to protect the data from concurrent access by read/write
30 * and create symlink/remove symlink.
31 */
32 struct mutex lock;
33 int refcnt;
34};
35
36#endif /* U_EEM_H */
diff --git a/drivers/usb/gadget/function/u_ether.c b/drivers/usb/gadget/function/u_ether.c
new file mode 100644
index 000000000000..d50adda913cf
--- /dev/null
+++ b/drivers/usb/gadget/function/u_ether.c
@@ -0,0 +1,1182 @@
1/*
2 * u_ether.c -- Ethernet-over-USB link layer utilities for Gadget stack
3 *
4 * Copyright (C) 2003-2005,2008 David Brownell
5 * Copyright (C) 2003-2004 Robert Schwebel, Benedikt Spranger
6 * Copyright (C) 2008 Nokia Corporation
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 */
13
14/* #define VERBOSE_DEBUG */
15
16#include <linux/kernel.h>
17#include <linux/module.h>
18#include <linux/gfp.h>
19#include <linux/device.h>
20#include <linux/ctype.h>
21#include <linux/etherdevice.h>
22#include <linux/ethtool.h>
23#include <linux/if_vlan.h>
24
25#include "u_ether.h"
26
27
28/*
29 * This component encapsulates the Ethernet link glue needed to provide
30 * one (!) network link through the USB gadget stack, normally "usb0".
31 *
32 * The control and data models are handled by the function driver which
33 * connects to this code; such as CDC Ethernet (ECM or EEM),
34 * "CDC Subset", or RNDIS. That includes all descriptor and endpoint
35 * management.
36 *
37 * Link level addressing is handled by this component using module
38 * parameters; if no such parameters are provided, random link level
39 * addresses are used. Each end of the link uses one address. The
40 * host end address is exported in various ways, and is often recorded
41 * in configuration databases.
42 *
43 * The driver which assembles each configuration using such a link is
44 * responsible for ensuring that each configuration includes at most one
45 * instance of is network link. (The network layer provides ways for
46 * this single "physical" link to be used by multiple virtual links.)
47 */
48
49#define UETH__VERSION "29-May-2008"
50
51struct eth_dev {
52 /* lock is held while accessing port_usb
53 */
54 spinlock_t lock;
55 struct gether *port_usb;
56
57 struct net_device *net;
58 struct usb_gadget *gadget;
59
60 spinlock_t req_lock; /* guard {rx,tx}_reqs */
61 struct list_head tx_reqs, rx_reqs;
62 atomic_t tx_qlen;
63
64 struct sk_buff_head rx_frames;
65
66 unsigned qmult;
67
68 unsigned header_len;
69 struct sk_buff *(*wrap)(struct gether *, struct sk_buff *skb);
70 int (*unwrap)(struct gether *,
71 struct sk_buff *skb,
72 struct sk_buff_head *list);
73
74 struct work_struct work;
75
76 unsigned long todo;
77#define WORK_RX_MEMORY 0
78
79 bool zlp;
80 u8 host_mac[ETH_ALEN];
81 u8 dev_mac[ETH_ALEN];
82};
83
84/*-------------------------------------------------------------------------*/
85
86#define RX_EXTRA 20 /* bytes guarding against rx overflows */
87
88#define DEFAULT_QLEN 2 /* double buffering by default */
89
90/* for dual-speed hardware, use deeper queues at high/super speed */
91static inline int qlen(struct usb_gadget *gadget, unsigned qmult)
92{
93 if (gadget_is_dualspeed(gadget) && (gadget->speed == USB_SPEED_HIGH ||
94 gadget->speed == USB_SPEED_SUPER))
95 return qmult * DEFAULT_QLEN;
96 else
97 return DEFAULT_QLEN;
98}
99
100/*-------------------------------------------------------------------------*/
101
102/* REVISIT there must be a better way than having two sets
103 * of debug calls ...
104 */
105
106#undef DBG
107#undef VDBG
108#undef ERROR
109#undef INFO
110
111#define xprintk(d, level, fmt, args...) \
112 printk(level "%s: " fmt , (d)->net->name , ## args)
113
114#ifdef DEBUG
115#undef DEBUG
116#define DBG(dev, fmt, args...) \
117 xprintk(dev , KERN_DEBUG , fmt , ## args)
118#else
119#define DBG(dev, fmt, args...) \
120 do { } while (0)
121#endif /* DEBUG */
122
123#ifdef VERBOSE_DEBUG
124#define VDBG DBG
125#else
126#define VDBG(dev, fmt, args...) \
127 do { } while (0)
128#endif /* DEBUG */
129
130#define ERROR(dev, fmt, args...) \
131 xprintk(dev , KERN_ERR , fmt , ## args)
132#define INFO(dev, fmt, args...) \
133 xprintk(dev , KERN_INFO , fmt , ## args)
134
135/*-------------------------------------------------------------------------*/
136
137/* NETWORK DRIVER HOOKUP (to the layer above this driver) */
138
139static int ueth_change_mtu(struct net_device *net, int new_mtu)
140{
141 struct eth_dev *dev = netdev_priv(net);
142 unsigned long flags;
143 int status = 0;
144
145 /* don't change MTU on "live" link (peer won't know) */
146 spin_lock_irqsave(&dev->lock, flags);
147 if (dev->port_usb)
148 status = -EBUSY;
149 else if (new_mtu <= ETH_HLEN || new_mtu > ETH_FRAME_LEN)
150 status = -ERANGE;
151 else
152 net->mtu = new_mtu;
153 spin_unlock_irqrestore(&dev->lock, flags);
154
155 return status;
156}
157
158static void eth_get_drvinfo(struct net_device *net, struct ethtool_drvinfo *p)
159{
160 struct eth_dev *dev = netdev_priv(net);
161
162 strlcpy(p->driver, "g_ether", sizeof(p->driver));
163 strlcpy(p->version, UETH__VERSION, sizeof(p->version));
164 strlcpy(p->fw_version, dev->gadget->name, sizeof(p->fw_version));
165 strlcpy(p->bus_info, dev_name(&dev->gadget->dev), sizeof(p->bus_info));
166}
167
168/* REVISIT can also support:
169 * - WOL (by tracking suspends and issuing remote wakeup)
170 * - msglevel (implies updated messaging)
171 * - ... probably more ethtool ops
172 */
173
174static const struct ethtool_ops ops = {
175 .get_drvinfo = eth_get_drvinfo,
176 .get_link = ethtool_op_get_link,
177};
178
179static void defer_kevent(struct eth_dev *dev, int flag)
180{
181 if (test_and_set_bit(flag, &dev->todo))
182 return;
183 if (!schedule_work(&dev->work))
184 ERROR(dev, "kevent %d may have been dropped\n", flag);
185 else
186 DBG(dev, "kevent %d scheduled\n", flag);
187}
188
189static void rx_complete(struct usb_ep *ep, struct usb_request *req);
190
191static int
192rx_submit(struct eth_dev *dev, struct usb_request *req, gfp_t gfp_flags)
193{
194 struct sk_buff *skb;
195 int retval = -ENOMEM;
196 size_t size = 0;
197 struct usb_ep *out;
198 unsigned long flags;
199
200 spin_lock_irqsave(&dev->lock, flags);
201 if (dev->port_usb)
202 out = dev->port_usb->out_ep;
203 else
204 out = NULL;
205 spin_unlock_irqrestore(&dev->lock, flags);
206
207 if (!out)
208 return -ENOTCONN;
209
210
211 /* Padding up to RX_EXTRA handles minor disagreements with host.
212 * Normally we use the USB "terminate on short read" convention;
213 * so allow up to (N*maxpacket), since that memory is normally
214 * already allocated. Some hardware doesn't deal well with short
215 * reads (e.g. DMA must be N*maxpacket), so for now don't trim a
216 * byte off the end (to force hardware errors on overflow).
217 *
218 * RNDIS uses internal framing, and explicitly allows senders to
219 * pad to end-of-packet. That's potentially nice for speed, but
220 * means receivers can't recover lost synch on their own (because
221 * new packets don't only start after a short RX).
222 */
223 size += sizeof(struct ethhdr) + dev->net->mtu + RX_EXTRA;
224 size += dev->port_usb->header_len;
225 size += out->maxpacket - 1;
226 size -= size % out->maxpacket;
227
228 if (dev->port_usb->is_fixed)
229 size = max_t(size_t, size, dev->port_usb->fixed_out_len);
230
231 skb = alloc_skb(size + NET_IP_ALIGN, gfp_flags);
232 if (skb == NULL) {
233 DBG(dev, "no rx skb\n");
234 goto enomem;
235 }
236
237 /* Some platforms perform better when IP packets are aligned,
238 * but on at least one, checksumming fails otherwise. Note:
239 * RNDIS headers involve variable numbers of LE32 values.
240 */
241 skb_reserve(skb, NET_IP_ALIGN);
242
243 req->buf = skb->data;
244 req->length = size;
245 req->complete = rx_complete;
246 req->context = skb;
247
248 retval = usb_ep_queue(out, req, gfp_flags);
249 if (retval == -ENOMEM)
250enomem:
251 defer_kevent(dev, WORK_RX_MEMORY);
252 if (retval) {
253 DBG(dev, "rx submit --> %d\n", retval);
254 if (skb)
255 dev_kfree_skb_any(skb);
256 spin_lock_irqsave(&dev->req_lock, flags);
257 list_add(&req->list, &dev->rx_reqs);
258 spin_unlock_irqrestore(&dev->req_lock, flags);
259 }
260 return retval;
261}
262
263static void rx_complete(struct usb_ep *ep, struct usb_request *req)
264{
265 struct sk_buff *skb = req->context, *skb2;
266 struct eth_dev *dev = ep->driver_data;
267 int status = req->status;
268
269 switch (status) {
270
271 /* normal completion */
272 case 0:
273 skb_put(skb, req->actual);
274
275 if (dev->unwrap) {
276 unsigned long flags;
277
278 spin_lock_irqsave(&dev->lock, flags);
279 if (dev->port_usb) {
280 status = dev->unwrap(dev->port_usb,
281 skb,
282 &dev->rx_frames);
283 } else {
284 dev_kfree_skb_any(skb);
285 status = -ENOTCONN;
286 }
287 spin_unlock_irqrestore(&dev->lock, flags);
288 } else {
289 skb_queue_tail(&dev->rx_frames, skb);
290 }
291 skb = NULL;
292
293 skb2 = skb_dequeue(&dev->rx_frames);
294 while (skb2) {
295 if (status < 0
296 || ETH_HLEN > skb2->len
297 || skb2->len > VLAN_ETH_FRAME_LEN) {
298 dev->net->stats.rx_errors++;
299 dev->net->stats.rx_length_errors++;
300 DBG(dev, "rx length %d\n", skb2->len);
301 dev_kfree_skb_any(skb2);
302 goto next_frame;
303 }
304 skb2->protocol = eth_type_trans(skb2, dev->net);
305 dev->net->stats.rx_packets++;
306 dev->net->stats.rx_bytes += skb2->len;
307
308 /* no buffer copies needed, unless hardware can't
309 * use skb buffers.
310 */
311 status = netif_rx(skb2);
312next_frame:
313 skb2 = skb_dequeue(&dev->rx_frames);
314 }
315 break;
316
317 /* software-driven interface shutdown */
318 case -ECONNRESET: /* unlink */
319 case -ESHUTDOWN: /* disconnect etc */
320 VDBG(dev, "rx shutdown, code %d\n", status);
321 goto quiesce;
322
323 /* for hardware automagic (such as pxa) */
324 case -ECONNABORTED: /* endpoint reset */
325 DBG(dev, "rx %s reset\n", ep->name);
326 defer_kevent(dev, WORK_RX_MEMORY);
327quiesce:
328 dev_kfree_skb_any(skb);
329 goto clean;
330
331 /* data overrun */
332 case -EOVERFLOW:
333 dev->net->stats.rx_over_errors++;
334 /* FALLTHROUGH */
335
336 default:
337 dev->net->stats.rx_errors++;
338 DBG(dev, "rx status %d\n", status);
339 break;
340 }
341
342 if (skb)
343 dev_kfree_skb_any(skb);
344 if (!netif_running(dev->net)) {
345clean:
346 spin_lock(&dev->req_lock);
347 list_add(&req->list, &dev->rx_reqs);
348 spin_unlock(&dev->req_lock);
349 req = NULL;
350 }
351 if (req)
352 rx_submit(dev, req, GFP_ATOMIC);
353}
354
355static int prealloc(struct list_head *list, struct usb_ep *ep, unsigned n)
356{
357 unsigned i;
358 struct usb_request *req;
359
360 if (!n)
361 return -ENOMEM;
362
363 /* queue/recycle up to N requests */
364 i = n;
365 list_for_each_entry(req, list, list) {
366 if (i-- == 0)
367 goto extra;
368 }
369 while (i--) {
370 req = usb_ep_alloc_request(ep, GFP_ATOMIC);
371 if (!req)
372 return list_empty(list) ? -ENOMEM : 0;
373 list_add(&req->list, list);
374 }
375 return 0;
376
377extra:
378 /* free extras */
379 for (;;) {
380 struct list_head *next;
381
382 next = req->list.next;
383 list_del(&req->list);
384 usb_ep_free_request(ep, req);
385
386 if (next == list)
387 break;
388
389 req = container_of(next, struct usb_request, list);
390 }
391 return 0;
392}
393
394static int alloc_requests(struct eth_dev *dev, struct gether *link, unsigned n)
395{
396 int status;
397
398 spin_lock(&dev->req_lock);
399 status = prealloc(&dev->tx_reqs, link->in_ep, n);
400 if (status < 0)
401 goto fail;
402 status = prealloc(&dev->rx_reqs, link->out_ep, n);
403 if (status < 0)
404 goto fail;
405 goto done;
406fail:
407 DBG(dev, "can't alloc requests\n");
408done:
409 spin_unlock(&dev->req_lock);
410 return status;
411}
412
413static void rx_fill(struct eth_dev *dev, gfp_t gfp_flags)
414{
415 struct usb_request *req;
416 unsigned long flags;
417
418 /* fill unused rxq slots with some skb */
419 spin_lock_irqsave(&dev->req_lock, flags);
420 while (!list_empty(&dev->rx_reqs)) {
421 req = container_of(dev->rx_reqs.next,
422 struct usb_request, list);
423 list_del_init(&req->list);
424 spin_unlock_irqrestore(&dev->req_lock, flags);
425
426 if (rx_submit(dev, req, gfp_flags) < 0) {
427 defer_kevent(dev, WORK_RX_MEMORY);
428 return;
429 }
430
431 spin_lock_irqsave(&dev->req_lock, flags);
432 }
433 spin_unlock_irqrestore(&dev->req_lock, flags);
434}
435
436static void eth_work(struct work_struct *work)
437{
438 struct eth_dev *dev = container_of(work, struct eth_dev, work);
439
440 if (test_and_clear_bit(WORK_RX_MEMORY, &dev->todo)) {
441 if (netif_running(dev->net))
442 rx_fill(dev, GFP_KERNEL);
443 }
444
445 if (dev->todo)
446 DBG(dev, "work done, flags = 0x%lx\n", dev->todo);
447}
448
449static void tx_complete(struct usb_ep *ep, struct usb_request *req)
450{
451 struct sk_buff *skb = req->context;
452 struct eth_dev *dev = ep->driver_data;
453
454 switch (req->status) {
455 default:
456 dev->net->stats.tx_errors++;
457 VDBG(dev, "tx err %d\n", req->status);
458 /* FALLTHROUGH */
459 case -ECONNRESET: /* unlink */
460 case -ESHUTDOWN: /* disconnect etc */
461 break;
462 case 0:
463 dev->net->stats.tx_bytes += skb->len;
464 }
465 dev->net->stats.tx_packets++;
466
467 spin_lock(&dev->req_lock);
468 list_add(&req->list, &dev->tx_reqs);
469 spin_unlock(&dev->req_lock);
470 dev_kfree_skb_any(skb);
471
472 atomic_dec(&dev->tx_qlen);
473 if (netif_carrier_ok(dev->net))
474 netif_wake_queue(dev->net);
475}
476
477static inline int is_promisc(u16 cdc_filter)
478{
479 return cdc_filter & USB_CDC_PACKET_TYPE_PROMISCUOUS;
480}
481
482static netdev_tx_t eth_start_xmit(struct sk_buff *skb,
483 struct net_device *net)
484{
485 struct eth_dev *dev = netdev_priv(net);
486 int length = 0;
487 int retval;
488 struct usb_request *req = NULL;
489 unsigned long flags;
490 struct usb_ep *in;
491 u16 cdc_filter;
492
493 spin_lock_irqsave(&dev->lock, flags);
494 if (dev->port_usb) {
495 in = dev->port_usb->in_ep;
496 cdc_filter = dev->port_usb->cdc_filter;
497 } else {
498 in = NULL;
499 cdc_filter = 0;
500 }
501 spin_unlock_irqrestore(&dev->lock, flags);
502
503 if (skb && !in) {
504 dev_kfree_skb_any(skb);
505 return NETDEV_TX_OK;
506 }
507
508 /* apply outgoing CDC or RNDIS filters */
509 if (skb && !is_promisc(cdc_filter)) {
510 u8 *dest = skb->data;
511
512 if (is_multicast_ether_addr(dest)) {
513 u16 type;
514
515 /* ignores USB_CDC_PACKET_TYPE_MULTICAST and host
516 * SET_ETHERNET_MULTICAST_FILTERS requests
517 */
518 if (is_broadcast_ether_addr(dest))
519 type = USB_CDC_PACKET_TYPE_BROADCAST;
520 else
521 type = USB_CDC_PACKET_TYPE_ALL_MULTICAST;
522 if (!(cdc_filter & type)) {
523 dev_kfree_skb_any(skb);
524 return NETDEV_TX_OK;
525 }
526 }
527 /* ignores USB_CDC_PACKET_TYPE_DIRECTED */
528 }
529
530 spin_lock_irqsave(&dev->req_lock, flags);
531 /*
532 * this freelist can be empty if an interrupt triggered disconnect()
533 * and reconfigured the gadget (shutting down this queue) after the
534 * network stack decided to xmit but before we got the spinlock.
535 */
536 if (list_empty(&dev->tx_reqs)) {
537 spin_unlock_irqrestore(&dev->req_lock, flags);
538 return NETDEV_TX_BUSY;
539 }
540
541 req = container_of(dev->tx_reqs.next, struct usb_request, list);
542 list_del(&req->list);
543
544 /* temporarily stop TX queue when the freelist empties */
545 if (list_empty(&dev->tx_reqs))
546 netif_stop_queue(net);
547 spin_unlock_irqrestore(&dev->req_lock, flags);
548
549 /* no buffer copies needed, unless the network stack did it
550 * or the hardware can't use skb buffers.
551 * or there's not enough space for extra headers we need
552 */
553 if (dev->wrap) {
554 unsigned long flags;
555
556 spin_lock_irqsave(&dev->lock, flags);
557 if (dev->port_usb)
558 skb = dev->wrap(dev->port_usb, skb);
559 spin_unlock_irqrestore(&dev->lock, flags);
560 if (!skb) {
561 /* Multi frame CDC protocols may store the frame for
562 * later which is not a dropped frame.
563 */
564 if (dev->port_usb->supports_multi_frame)
565 goto multiframe;
566 goto drop;
567 }
568 }
569
570 length = skb->len;
571 req->buf = skb->data;
572 req->context = skb;
573 req->complete = tx_complete;
574
575 /* NCM requires no zlp if transfer is dwNtbInMaxSize */
576 if (dev->port_usb->is_fixed &&
577 length == dev->port_usb->fixed_in_len &&
578 (length % in->maxpacket) == 0)
579 req->zero = 0;
580 else
581 req->zero = 1;
582
583 /* use zlp framing on tx for strict CDC-Ether conformance,
584 * though any robust network rx path ignores extra padding.
585 * and some hardware doesn't like to write zlps.
586 */
587 if (req->zero && !dev->zlp && (length % in->maxpacket) == 0)
588 length++;
589
590 req->length = length;
591
592 /* throttle high/super speed IRQ rate back slightly */
593 if (gadget_is_dualspeed(dev->gadget))
594 req->no_interrupt = (dev->gadget->speed == USB_SPEED_HIGH ||
595 dev->gadget->speed == USB_SPEED_SUPER)
596 ? ((atomic_read(&dev->tx_qlen) % dev->qmult) != 0)
597 : 0;
598
599 retval = usb_ep_queue(in, req, GFP_ATOMIC);
600 switch (retval) {
601 default:
602 DBG(dev, "tx queue err %d\n", retval);
603 break;
604 case 0:
605 net->trans_start = jiffies;
606 atomic_inc(&dev->tx_qlen);
607 }
608
609 if (retval) {
610 dev_kfree_skb_any(skb);
611drop:
612 dev->net->stats.tx_dropped++;
613multiframe:
614 spin_lock_irqsave(&dev->req_lock, flags);
615 if (list_empty(&dev->tx_reqs))
616 netif_start_queue(net);
617 list_add(&req->list, &dev->tx_reqs);
618 spin_unlock_irqrestore(&dev->req_lock, flags);
619 }
620 return NETDEV_TX_OK;
621}
622
623/*-------------------------------------------------------------------------*/
624
625static void eth_start(struct eth_dev *dev, gfp_t gfp_flags)
626{
627 DBG(dev, "%s\n", __func__);
628
629 /* fill the rx queue */
630 rx_fill(dev, gfp_flags);
631
632 /* and open the tx floodgates */
633 atomic_set(&dev->tx_qlen, 0);
634 netif_wake_queue(dev->net);
635}
636
637static int eth_open(struct net_device *net)
638{
639 struct eth_dev *dev = netdev_priv(net);
640 struct gether *link;
641
642 DBG(dev, "%s\n", __func__);
643 if (netif_carrier_ok(dev->net))
644 eth_start(dev, GFP_KERNEL);
645
646 spin_lock_irq(&dev->lock);
647 link = dev->port_usb;
648 if (link && link->open)
649 link->open(link);
650 spin_unlock_irq(&dev->lock);
651
652 return 0;
653}
654
655static int eth_stop(struct net_device *net)
656{
657 struct eth_dev *dev = netdev_priv(net);
658 unsigned long flags;
659
660 VDBG(dev, "%s\n", __func__);
661 netif_stop_queue(net);
662
663 DBG(dev, "stop stats: rx/tx %ld/%ld, errs %ld/%ld\n",
664 dev->net->stats.rx_packets, dev->net->stats.tx_packets,
665 dev->net->stats.rx_errors, dev->net->stats.tx_errors
666 );
667
668 /* ensure there are no more active requests */
669 spin_lock_irqsave(&dev->lock, flags);
670 if (dev->port_usb) {
671 struct gether *link = dev->port_usb;
672 const struct usb_endpoint_descriptor *in;
673 const struct usb_endpoint_descriptor *out;
674
675 if (link->close)
676 link->close(link);
677
678 /* NOTE: we have no abort-queue primitive we could use
679 * to cancel all pending I/O. Instead, we disable then
680 * reenable the endpoints ... this idiom may leave toggle
681 * wrong, but that's a self-correcting error.
682 *
683 * REVISIT: we *COULD* just let the transfers complete at
684 * their own pace; the network stack can handle old packets.
685 * For the moment we leave this here, since it works.
686 */
687 in = link->in_ep->desc;
688 out = link->out_ep->desc;
689 usb_ep_disable(link->in_ep);
690 usb_ep_disable(link->out_ep);
691 if (netif_carrier_ok(net)) {
692 DBG(dev, "host still using in/out endpoints\n");
693 link->in_ep->desc = in;
694 link->out_ep->desc = out;
695 usb_ep_enable(link->in_ep);
696 usb_ep_enable(link->out_ep);
697 }
698 }
699 spin_unlock_irqrestore(&dev->lock, flags);
700
701 return 0;
702}
703
704/*-------------------------------------------------------------------------*/
705
706static int get_ether_addr(const char *str, u8 *dev_addr)
707{
708 if (str) {
709 unsigned i;
710
711 for (i = 0; i < 6; i++) {
712 unsigned char num;
713
714 if ((*str == '.') || (*str == ':'))
715 str++;
716 num = hex_to_bin(*str++) << 4;
717 num |= hex_to_bin(*str++);
718 dev_addr [i] = num;
719 }
720 if (is_valid_ether_addr(dev_addr))
721 return 0;
722 }
723 eth_random_addr(dev_addr);
724 return 1;
725}
726
727static int get_ether_addr_str(u8 dev_addr[ETH_ALEN], char *str, int len)
728{
729 if (len < 18)
730 return -EINVAL;
731
732 snprintf(str, len, "%02x:%02x:%02x:%02x:%02x:%02x",
733 dev_addr[0], dev_addr[1], dev_addr[2],
734 dev_addr[3], dev_addr[4], dev_addr[5]);
735 return 18;
736}
737
738static const struct net_device_ops eth_netdev_ops = {
739 .ndo_open = eth_open,
740 .ndo_stop = eth_stop,
741 .ndo_start_xmit = eth_start_xmit,
742 .ndo_change_mtu = ueth_change_mtu,
743 .ndo_set_mac_address = eth_mac_addr,
744 .ndo_validate_addr = eth_validate_addr,
745};
746
747static struct device_type gadget_type = {
748 .name = "gadget",
749};
750
751/**
752 * gether_setup_name - initialize one ethernet-over-usb link
753 * @g: gadget to associated with these links
754 * @ethaddr: NULL, or a buffer in which the ethernet address of the
755 * host side of the link is recorded
756 * @netname: name for network device (for example, "usb")
757 * Context: may sleep
758 *
759 * This sets up the single network link that may be exported by a
760 * gadget driver using this framework. The link layer addresses are
761 * set up using module parameters.
762 *
763 * Returns an eth_dev pointer on success, or an ERR_PTR on failure.
764 */
765struct eth_dev *gether_setup_name(struct usb_gadget *g,
766 const char *dev_addr, const char *host_addr,
767 u8 ethaddr[ETH_ALEN], unsigned qmult, const char *netname)
768{
769 struct eth_dev *dev;
770 struct net_device *net;
771 int status;
772
773 net = alloc_etherdev(sizeof *dev);
774 if (!net)
775 return ERR_PTR(-ENOMEM);
776
777 dev = netdev_priv(net);
778 spin_lock_init(&dev->lock);
779 spin_lock_init(&dev->req_lock);
780 INIT_WORK(&dev->work, eth_work);
781 INIT_LIST_HEAD(&dev->tx_reqs);
782 INIT_LIST_HEAD(&dev->rx_reqs);
783
784 skb_queue_head_init(&dev->rx_frames);
785
786 /* network device setup */
787 dev->net = net;
788 dev->qmult = qmult;
789 snprintf(net->name, sizeof(net->name), "%s%%d", netname);
790
791 if (get_ether_addr(dev_addr, net->dev_addr))
792 dev_warn(&g->dev,
793 "using random %s ethernet address\n", "self");
794 if (get_ether_addr(host_addr, dev->host_mac))
795 dev_warn(&g->dev,
796 "using random %s ethernet address\n", "host");
797
798 if (ethaddr)
799 memcpy(ethaddr, dev->host_mac, ETH_ALEN);
800
801 net->netdev_ops = &eth_netdev_ops;
802
803 net->ethtool_ops = &ops;
804
805 dev->gadget = g;
806 SET_NETDEV_DEV(net, &g->dev);
807 SET_NETDEV_DEVTYPE(net, &gadget_type);
808
809 status = register_netdev(net);
810 if (status < 0) {
811 dev_dbg(&g->dev, "register_netdev failed, %d\n", status);
812 free_netdev(net);
813 dev = ERR_PTR(status);
814 } else {
815 INFO(dev, "MAC %pM\n", net->dev_addr);
816 INFO(dev, "HOST MAC %pM\n", dev->host_mac);
817
818 /*
819 * two kinds of host-initiated state changes:
820 * - iff DATA transfer is active, carrier is "on"
821 * - tx queueing enabled if open *and* carrier is "on"
822 */
823 netif_carrier_off(net);
824 }
825
826 return dev;
827}
828EXPORT_SYMBOL_GPL(gether_setup_name);
829
830struct net_device *gether_setup_name_default(const char *netname)
831{
832 struct net_device *net;
833 struct eth_dev *dev;
834
835 net = alloc_etherdev(sizeof(*dev));
836 if (!net)
837 return ERR_PTR(-ENOMEM);
838
839 dev = netdev_priv(net);
840 spin_lock_init(&dev->lock);
841 spin_lock_init(&dev->req_lock);
842 INIT_WORK(&dev->work, eth_work);
843 INIT_LIST_HEAD(&dev->tx_reqs);
844 INIT_LIST_HEAD(&dev->rx_reqs);
845
846 skb_queue_head_init(&dev->rx_frames);
847
848 /* network device setup */
849 dev->net = net;
850 dev->qmult = QMULT_DEFAULT;
851 snprintf(net->name, sizeof(net->name), "%s%%d", netname);
852
853 eth_random_addr(dev->dev_mac);
854 pr_warn("using random %s ethernet address\n", "self");
855 eth_random_addr(dev->host_mac);
856 pr_warn("using random %s ethernet address\n", "host");
857
858 net->netdev_ops = &eth_netdev_ops;
859
860 net->ethtool_ops = &ops;
861 SET_NETDEV_DEVTYPE(net, &gadget_type);
862
863 return net;
864}
865EXPORT_SYMBOL_GPL(gether_setup_name_default);
866
867int gether_register_netdev(struct net_device *net)
868{
869 struct eth_dev *dev;
870 struct usb_gadget *g;
871 struct sockaddr sa;
872 int status;
873
874 if (!net->dev.parent)
875 return -EINVAL;
876 dev = netdev_priv(net);
877 g = dev->gadget;
878 status = register_netdev(net);
879 if (status < 0) {
880 dev_dbg(&g->dev, "register_netdev failed, %d\n", status);
881 return status;
882 } else {
883 INFO(dev, "HOST MAC %pM\n", dev->host_mac);
884
885 /* two kinds of host-initiated state changes:
886 * - iff DATA transfer is active, carrier is "on"
887 * - tx queueing enabled if open *and* carrier is "on"
888 */
889 netif_carrier_off(net);
890 }
891 sa.sa_family = net->type;
892 memcpy(sa.sa_data, dev->dev_mac, ETH_ALEN);
893 rtnl_lock();
894 status = dev_set_mac_address(net, &sa);
895 rtnl_unlock();
896 if (status)
897 pr_warn("cannot set self ethernet address: %d\n", status);
898 else
899 INFO(dev, "MAC %pM\n", dev->dev_mac);
900
901 return status;
902}
903EXPORT_SYMBOL_GPL(gether_register_netdev);
904
905void gether_set_gadget(struct net_device *net, struct usb_gadget *g)
906{
907 struct eth_dev *dev;
908
909 dev = netdev_priv(net);
910 dev->gadget = g;
911 SET_NETDEV_DEV(net, &g->dev);
912}
913EXPORT_SYMBOL_GPL(gether_set_gadget);
914
915int gether_set_dev_addr(struct net_device *net, const char *dev_addr)
916{
917 struct eth_dev *dev;
918 u8 new_addr[ETH_ALEN];
919
920 dev = netdev_priv(net);
921 if (get_ether_addr(dev_addr, new_addr))
922 return -EINVAL;
923 memcpy(dev->dev_mac, new_addr, ETH_ALEN);
924 return 0;
925}
926EXPORT_SYMBOL_GPL(gether_set_dev_addr);
927
928int gether_get_dev_addr(struct net_device *net, char *dev_addr, int len)
929{
930 struct eth_dev *dev;
931
932 dev = netdev_priv(net);
933 return get_ether_addr_str(dev->dev_mac, dev_addr, len);
934}
935EXPORT_SYMBOL_GPL(gether_get_dev_addr);
936
937int gether_set_host_addr(struct net_device *net, const char *host_addr)
938{
939 struct eth_dev *dev;
940 u8 new_addr[ETH_ALEN];
941
942 dev = netdev_priv(net);
943 if (get_ether_addr(host_addr, new_addr))
944 return -EINVAL;
945 memcpy(dev->host_mac, new_addr, ETH_ALEN);
946 return 0;
947}
948EXPORT_SYMBOL_GPL(gether_set_host_addr);
949
950int gether_get_host_addr(struct net_device *net, char *host_addr, int len)
951{
952 struct eth_dev *dev;
953
954 dev = netdev_priv(net);
955 return get_ether_addr_str(dev->host_mac, host_addr, len);
956}
957EXPORT_SYMBOL_GPL(gether_get_host_addr);
958
959int gether_get_host_addr_cdc(struct net_device *net, char *host_addr, int len)
960{
961 struct eth_dev *dev;
962
963 if (len < 13)
964 return -EINVAL;
965
966 dev = netdev_priv(net);
967 snprintf(host_addr, len, "%pm", dev->host_mac);
968
969 return strlen(host_addr);
970}
971EXPORT_SYMBOL_GPL(gether_get_host_addr_cdc);
972
973void gether_get_host_addr_u8(struct net_device *net, u8 host_mac[ETH_ALEN])
974{
975 struct eth_dev *dev;
976
977 dev = netdev_priv(net);
978 memcpy(host_mac, dev->host_mac, ETH_ALEN);
979}
980EXPORT_SYMBOL_GPL(gether_get_host_addr_u8);
981
982void gether_set_qmult(struct net_device *net, unsigned qmult)
983{
984 struct eth_dev *dev;
985
986 dev = netdev_priv(net);
987 dev->qmult = qmult;
988}
989EXPORT_SYMBOL_GPL(gether_set_qmult);
990
991unsigned gether_get_qmult(struct net_device *net)
992{
993 struct eth_dev *dev;
994
995 dev = netdev_priv(net);
996 return dev->qmult;
997}
998EXPORT_SYMBOL_GPL(gether_get_qmult);
999
1000int gether_get_ifname(struct net_device *net, char *name, int len)
1001{
1002 rtnl_lock();
1003 strlcpy(name, netdev_name(net), len);
1004 rtnl_unlock();
1005 return strlen(name);
1006}
1007EXPORT_SYMBOL_GPL(gether_get_ifname);
1008
1009/**
1010 * gether_cleanup - remove Ethernet-over-USB device
1011 * Context: may sleep
1012 *
1013 * This is called to free all resources allocated by @gether_setup().
1014 */
1015void gether_cleanup(struct eth_dev *dev)
1016{
1017 if (!dev)
1018 return;
1019
1020 unregister_netdev(dev->net);
1021 flush_work(&dev->work);
1022 free_netdev(dev->net);
1023}
1024EXPORT_SYMBOL_GPL(gether_cleanup);
1025
1026/**
1027 * gether_connect - notify network layer that USB link is active
1028 * @link: the USB link, set up with endpoints, descriptors matching
1029 * current device speed, and any framing wrapper(s) set up.
1030 * Context: irqs blocked
1031 *
1032 * This is called to activate endpoints and let the network layer know
1033 * the connection is active ("carrier detect"). It may cause the I/O
1034 * queues to open and start letting network packets flow, but will in
1035 * any case activate the endpoints so that they respond properly to the
1036 * USB host.
1037 *
1038 * Verify net_device pointer returned using IS_ERR(). If it doesn't
1039 * indicate some error code (negative errno), ep->driver_data values
1040 * have been overwritten.
1041 */
1042struct net_device *gether_connect(struct gether *link)
1043{
1044 struct eth_dev *dev = link->ioport;
1045 int result = 0;
1046
1047 if (!dev)
1048 return ERR_PTR(-EINVAL);
1049
1050 link->in_ep->driver_data = dev;
1051 result = usb_ep_enable(link->in_ep);
1052 if (result != 0) {
1053 DBG(dev, "enable %s --> %d\n",
1054 link->in_ep->name, result);
1055 goto fail0;
1056 }
1057
1058 link->out_ep->driver_data = dev;
1059 result = usb_ep_enable(link->out_ep);
1060 if (result != 0) {
1061 DBG(dev, "enable %s --> %d\n",
1062 link->out_ep->name, result);
1063 goto fail1;
1064 }
1065
1066 if (result == 0)
1067 result = alloc_requests(dev, link, qlen(dev->gadget,
1068 dev->qmult));
1069
1070 if (result == 0) {
1071 dev->zlp = link->is_zlp_ok;
1072 DBG(dev, "qlen %d\n", qlen(dev->gadget, dev->qmult));
1073
1074 dev->header_len = link->header_len;
1075 dev->unwrap = link->unwrap;
1076 dev->wrap = link->wrap;
1077
1078 spin_lock(&dev->lock);
1079 dev->port_usb = link;
1080 if (netif_running(dev->net)) {
1081 if (link->open)
1082 link->open(link);
1083 } else {
1084 if (link->close)
1085 link->close(link);
1086 }
1087 spin_unlock(&dev->lock);
1088
1089 netif_carrier_on(dev->net);
1090 if (netif_running(dev->net))
1091 eth_start(dev, GFP_ATOMIC);
1092
1093 /* on error, disable any endpoints */
1094 } else {
1095 (void) usb_ep_disable(link->out_ep);
1096fail1:
1097 (void) usb_ep_disable(link->in_ep);
1098 }
1099fail0:
1100 /* caller is responsible for cleanup on error */
1101 if (result < 0)
1102 return ERR_PTR(result);
1103 return dev->net;
1104}
1105EXPORT_SYMBOL_GPL(gether_connect);
1106
1107/**
1108 * gether_disconnect - notify network layer that USB link is inactive
1109 * @link: the USB link, on which gether_connect() was called
1110 * Context: irqs blocked
1111 *
1112 * This is called to deactivate endpoints and let the network layer know
1113 * the connection went inactive ("no carrier").
1114 *
1115 * On return, the state is as if gether_connect() had never been called.
1116 * The endpoints are inactive, and accordingly without active USB I/O.
1117 * Pointers to endpoint descriptors and endpoint private data are nulled.
1118 */
1119void gether_disconnect(struct gether *link)
1120{
1121 struct eth_dev *dev = link->ioport;
1122 struct usb_request *req;
1123
1124 WARN_ON(!dev);
1125 if (!dev)
1126 return;
1127
1128 DBG(dev, "%s\n", __func__);
1129
1130 netif_tx_lock(dev->net);
1131 netif_stop_queue(dev->net);
1132 netif_tx_unlock(dev->net);
1133
1134 netif_carrier_off(dev->net);
1135
1136 /* disable endpoints, forcing (synchronous) completion
1137 * of all pending i/o. then free the request objects
1138 * and forget about the endpoints.
1139 */
1140 usb_ep_disable(link->in_ep);
1141 spin_lock(&dev->req_lock);
1142 while (!list_empty(&dev->tx_reqs)) {
1143 req = container_of(dev->tx_reqs.next,
1144 struct usb_request, list);
1145 list_del(&req->list);
1146
1147 spin_unlock(&dev->req_lock);
1148 usb_ep_free_request(link->in_ep, req);
1149 spin_lock(&dev->req_lock);
1150 }
1151 spin_unlock(&dev->req_lock);
1152 link->in_ep->driver_data = NULL;
1153 link->in_ep->desc = NULL;
1154
1155 usb_ep_disable(link->out_ep);
1156 spin_lock(&dev->req_lock);
1157 while (!list_empty(&dev->rx_reqs)) {
1158 req = container_of(dev->rx_reqs.next,
1159 struct usb_request, list);
1160 list_del(&req->list);
1161
1162 spin_unlock(&dev->req_lock);
1163 usb_ep_free_request(link->out_ep, req);
1164 spin_lock(&dev->req_lock);
1165 }
1166 spin_unlock(&dev->req_lock);
1167 link->out_ep->driver_data = NULL;
1168 link->out_ep->desc = NULL;
1169
1170 /* finish forgetting about this USB link episode */
1171 dev->header_len = 0;
1172 dev->unwrap = NULL;
1173 dev->wrap = NULL;
1174
1175 spin_lock(&dev->lock);
1176 dev->port_usb = NULL;
1177 spin_unlock(&dev->lock);
1178}
1179EXPORT_SYMBOL_GPL(gether_disconnect);
1180
1181MODULE_LICENSE("GPL");
1182MODULE_AUTHOR("David Brownell");
diff --git a/drivers/usb/gadget/function/u_ether.h b/drivers/usb/gadget/function/u_ether.h
new file mode 100644
index 000000000000..334b38947916
--- /dev/null
+++ b/drivers/usb/gadget/function/u_ether.h
@@ -0,0 +1,272 @@
1/*
2 * u_ether.h -- interface to USB gadget "ethernet link" utilities
3 *
4 * Copyright (C) 2003-2005,2008 David Brownell
5 * Copyright (C) 2003-2004 Robert Schwebel, Benedikt Spranger
6 * Copyright (C) 2008 Nokia Corporation
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 */
13
14#ifndef __U_ETHER_H
15#define __U_ETHER_H
16
17#include <linux/err.h>
18#include <linux/if_ether.h>
19#include <linux/usb/composite.h>
20#include <linux/usb/cdc.h>
21#include <linux/netdevice.h>
22
23#include "gadget_chips.h"
24
25#define QMULT_DEFAULT 5
26
27/*
28 * dev_addr: initial value
29 * changed by "ifconfig usb0 hw ether xx:xx:xx:xx:xx:xx"
30 * host_addr: this address is invisible to ifconfig
31 */
32#define USB_ETHERNET_MODULE_PARAMETERS() \
33 static unsigned qmult = QMULT_DEFAULT; \
34 module_param(qmult, uint, S_IRUGO|S_IWUSR); \
35 MODULE_PARM_DESC(qmult, "queue length multiplier at high/super speed");\
36 \
37 static char *dev_addr; \
38 module_param(dev_addr, charp, S_IRUGO); \
39 MODULE_PARM_DESC(dev_addr, "Device Ethernet Address"); \
40 \
41 static char *host_addr; \
42 module_param(host_addr, charp, S_IRUGO); \
43 MODULE_PARM_DESC(host_addr, "Host Ethernet Address")
44
45struct eth_dev;
46
47/*
48 * This represents the USB side of an "ethernet" link, managed by a USB
49 * function which provides control and (maybe) framing. Two functions
50 * in different configurations could share the same ethernet link/netdev,
51 * using different host interaction models.
52 *
53 * There is a current limitation that only one instance of this link may
54 * be present in any given configuration. When that's a problem, network
55 * layer facilities can be used to package multiple logical links on this
56 * single "physical" one.
57 */
58struct gether {
59 struct usb_function func;
60
61 /* updated by gether_{connect,disconnect} */
62 struct eth_dev *ioport;
63
64 /* endpoints handle full and/or high speeds */
65 struct usb_ep *in_ep;
66 struct usb_ep *out_ep;
67
68 bool is_zlp_ok;
69
70 u16 cdc_filter;
71
72 /* hooks for added framing, as needed for RNDIS and EEM. */
73 u32 header_len;
74 /* NCM requires fixed size bundles */
75 bool is_fixed;
76 u32 fixed_out_len;
77 u32 fixed_in_len;
78 bool supports_multi_frame;
79 struct sk_buff *(*wrap)(struct gether *port,
80 struct sk_buff *skb);
81 int (*unwrap)(struct gether *port,
82 struct sk_buff *skb,
83 struct sk_buff_head *list);
84
85 /* called on network open/close */
86 void (*open)(struct gether *);
87 void (*close)(struct gether *);
88};
89
90#define DEFAULT_FILTER (USB_CDC_PACKET_TYPE_BROADCAST \
91 |USB_CDC_PACKET_TYPE_ALL_MULTICAST \
92 |USB_CDC_PACKET_TYPE_PROMISCUOUS \
93 |USB_CDC_PACKET_TYPE_DIRECTED)
94
95/* variant of gether_setup that allows customizing network device name */
96struct eth_dev *gether_setup_name(struct usb_gadget *g,
97 const char *dev_addr, const char *host_addr,
98 u8 ethaddr[ETH_ALEN], unsigned qmult, const char *netname);
99
100/* netdev setup/teardown as directed by the gadget driver */
101/* gether_setup - initialize one ethernet-over-usb link
102 * @g: gadget to associated with these links
103 * @ethaddr: NULL, or a buffer in which the ethernet address of the
104 * host side of the link is recorded
105 * Context: may sleep
106 *
107 * This sets up the single network link that may be exported by a
108 * gadget driver using this framework. The link layer addresses are
109 * set up using module parameters.
110 *
111 * Returns a eth_dev pointer on success, or an ERR_PTR on failure
112 */
113static inline struct eth_dev *gether_setup(struct usb_gadget *g,
114 const char *dev_addr, const char *host_addr,
115 u8 ethaddr[ETH_ALEN], unsigned qmult)
116{
117 return gether_setup_name(g, dev_addr, host_addr, ethaddr, qmult, "usb");
118}
119
120/*
121 * variant of gether_setup_default that allows customizing
122 * network device name
123 */
124struct net_device *gether_setup_name_default(const char *netname);
125
126/*
127 * gether_register_netdev - register the net device
128 * @net: net device to register
129 *
130 * Registers the net device associated with this ethernet-over-usb link
131 *
132 */
133int gether_register_netdev(struct net_device *net);
134
135/* gether_setup_default - initialize one ethernet-over-usb link
136 * Context: may sleep
137 *
138 * This sets up the single network link that may be exported by a
139 * gadget driver using this framework. The link layer addresses
140 * are set to random values.
141 *
142 * Returns negative errno, or zero on success
143 */
144static inline struct net_device *gether_setup_default(void)
145{
146 return gether_setup_name_default("usb");
147}
148
149/**
150 * gether_set_gadget - initialize one ethernet-over-usb link with a gadget
151 * @net: device representing this link
152 * @g: the gadget to initialize with
153 *
154 * This associates one ethernet-over-usb link with a gadget.
155 */
156void gether_set_gadget(struct net_device *net, struct usb_gadget *g);
157
158/**
159 * gether_set_dev_addr - initialize an ethernet-over-usb link with eth address
160 * @net: device representing this link
161 * @dev_addr: eth address of this device
162 *
163 * This sets the device-side Ethernet address of this ethernet-over-usb link
164 * if dev_addr is correct.
165 * Returns negative errno if the new address is incorrect.
166 */
167int gether_set_dev_addr(struct net_device *net, const char *dev_addr);
168
169/**
170 * gether_get_dev_addr - get an ethernet-over-usb link eth address
171 * @net: device representing this link
172 * @dev_addr: place to store device's eth address
173 * @len: length of the @dev_addr buffer
174 *
175 * This gets the device-side Ethernet address of this ethernet-over-usb link.
176 * Returns zero on success, else negative errno.
177 */
178int gether_get_dev_addr(struct net_device *net, char *dev_addr, int len);
179
180/**
181 * gether_set_host_addr - initialize an ethernet-over-usb link with host address
182 * @net: device representing this link
183 * @host_addr: eth address of the host
184 *
185 * This sets the host-side Ethernet address of this ethernet-over-usb link
186 * if host_addr is correct.
187 * Returns negative errno if the new address is incorrect.
188 */
189int gether_set_host_addr(struct net_device *net, const char *host_addr);
190
191/**
192 * gether_get_host_addr - get an ethernet-over-usb link host address
193 * @net: device representing this link
194 * @host_addr: place to store eth address of the host
195 * @len: length of the @host_addr buffer
196 *
197 * This gets the host-side Ethernet address of this ethernet-over-usb link.
198 * Returns zero on success, else negative errno.
199 */
200int gether_get_host_addr(struct net_device *net, char *host_addr, int len);
201
202/**
203 * gether_get_host_addr_cdc - get an ethernet-over-usb link host address
204 * @net: device representing this link
205 * @host_addr: place to store eth address of the host
206 * @len: length of the @host_addr buffer
207 *
208 * This gets the CDC formatted host-side Ethernet address of this
209 * ethernet-over-usb link.
210 * Returns zero on success, else negative errno.
211 */
212int gether_get_host_addr_cdc(struct net_device *net, char *host_addr, int len);
213
214/**
215 * gether_get_host_addr_u8 - get an ethernet-over-usb link host address
216 * @net: device representing this link
217 * @host_mac: place to store the eth address of the host
218 *
219 * This gets the binary formatted host-side Ethernet address of this
220 * ethernet-over-usb link.
221 */
222void gether_get_host_addr_u8(struct net_device *net, u8 host_mac[ETH_ALEN]);
223
224/**
225 * gether_set_qmult - initialize an ethernet-over-usb link with a multiplier
226 * @net: device representing this link
227 * @qmult: queue multiplier
228 *
229 * This sets the queue length multiplier of this ethernet-over-usb link.
230 * For higher speeds use longer queues.
231 */
232void gether_set_qmult(struct net_device *net, unsigned qmult);
233
234/**
235 * gether_get_qmult - get an ethernet-over-usb link multiplier
236 * @net: device representing this link
237 *
238 * This gets the queue length multiplier of this ethernet-over-usb link.
239 */
240unsigned gether_get_qmult(struct net_device *net);
241
242/**
243 * gether_get_ifname - get an ethernet-over-usb link interface name
244 * @net: device representing this link
245 * @name: place to store the interface name
246 * @len: length of the @name buffer
247 *
248 * This gets the interface name of this ethernet-over-usb link.
249 * Returns zero on success, else negative errno.
250 */
251int gether_get_ifname(struct net_device *net, char *name, int len);
252
253void gether_cleanup(struct eth_dev *dev);
254
255/* connect/disconnect is handled by individual functions */
256struct net_device *gether_connect(struct gether *);
257void gether_disconnect(struct gether *);
258
259/* Some controllers can't support CDC Ethernet (ECM) ... */
260static inline bool can_support_ecm(struct usb_gadget *gadget)
261{
262 if (!gadget_supports_altsettings(gadget))
263 return false;
264
265 /* Everything else is *presumably* fine ... but this is a bit
266 * chancy, so be **CERTAIN** there are no hardware issues with
267 * your controller. Add it above if it can't handle CDC.
268 */
269 return true;
270}
271
272#endif /* __U_ETHER_H */
diff --git a/drivers/usb/gadget/function/u_ether_configfs.h b/drivers/usb/gadget/function/u_ether_configfs.h
new file mode 100644
index 000000000000..bcbd30146cfd
--- /dev/null
+++ b/drivers/usb/gadget/function/u_ether_configfs.h
@@ -0,0 +1,164 @@
1/*
2 * u_ether_configfs.h
3 *
4 * Utility definitions for configfs support in USB Ethernet functions
5 *
6 * Copyright (c) 2013 Samsung Electronics Co., Ltd.
7 * http://www.samsung.com
8 *
9 * Author: Andrzej Pietrasiewicz <andrzej.p@samsung.com>
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License version 2 as
13 * published by the Free Software Foundation.
14 */
15
16#ifndef __U_ETHER_CONFIGFS_H
17#define __U_ETHER_CONFIGFS_H
18
19#define USB_ETHERNET_CONFIGFS_ITEM(_f_) \
20 CONFIGFS_ATTR_STRUCT(f_##_f_##_opts); \
21 CONFIGFS_ATTR_OPS(f_##_f_##_opts); \
22 \
23 static void _f_##_attr_release(struct config_item *item) \
24 { \
25 struct f_##_f_##_opts *opts = to_f_##_f_##_opts(item); \
26 \
27 usb_put_function_instance(&opts->func_inst); \
28 } \
29 \
30 static struct configfs_item_operations _f_##_item_ops = { \
31 .release = _f_##_attr_release, \
32 .show_attribute = f_##_f_##_opts_attr_show, \
33 .store_attribute = f_##_f_##_opts_attr_store, \
34 }
35
36#define USB_ETHERNET_CONFIGFS_ITEM_ATTR_DEV_ADDR(_f_) \
37 static ssize_t _f_##_opts_dev_addr_show(struct f_##_f_##_opts *opts, \
38 char *page) \
39 { \
40 int result; \
41 \
42 mutex_lock(&opts->lock); \
43 result = gether_get_dev_addr(opts->net, page, PAGE_SIZE); \
44 mutex_unlock(&opts->lock); \
45 \
46 return result; \
47 } \
48 \
49 static ssize_t _f_##_opts_dev_addr_store(struct f_##_f_##_opts *opts, \
50 const char *page, size_t len)\
51 { \
52 int ret; \
53 \
54 mutex_lock(&opts->lock); \
55 if (opts->refcnt) { \
56 mutex_unlock(&opts->lock); \
57 return -EBUSY; \
58 } \
59 \
60 ret = gether_set_dev_addr(opts->net, page); \
61 mutex_unlock(&opts->lock); \
62 if (!ret) \
63 ret = len; \
64 return ret; \
65 } \
66 \
67 static struct f_##_f_##_opts_attribute f_##_f_##_opts_dev_addr = \
68 __CONFIGFS_ATTR(dev_addr, S_IRUGO | S_IWUSR, \
69 _f_##_opts_dev_addr_show, \
70 _f_##_opts_dev_addr_store)
71
72#define USB_ETHERNET_CONFIGFS_ITEM_ATTR_HOST_ADDR(_f_) \
73 static ssize_t _f_##_opts_host_addr_show(struct f_##_f_##_opts *opts, \
74 char *page) \
75 { \
76 int result; \
77 \
78 mutex_lock(&opts->lock); \
79 result = gether_get_host_addr(opts->net, page, PAGE_SIZE); \
80 mutex_unlock(&opts->lock); \
81 \
82 return result; \
83 } \
84 \
85 static ssize_t _f_##_opts_host_addr_store(struct f_##_f_##_opts *opts, \
86 const char *page, size_t len)\
87 { \
88 int ret; \
89 \
90 mutex_lock(&opts->lock); \
91 if (opts->refcnt) { \
92 mutex_unlock(&opts->lock); \
93 return -EBUSY; \
94 } \
95 \
96 ret = gether_set_host_addr(opts->net, page); \
97 mutex_unlock(&opts->lock); \
98 if (!ret) \
99 ret = len; \
100 return ret; \
101 } \
102 \
103 static struct f_##_f_##_opts_attribute f_##_f_##_opts_host_addr = \
104 __CONFIGFS_ATTR(host_addr, S_IRUGO | S_IWUSR, \
105 _f_##_opts_host_addr_show, \
106 _f_##_opts_host_addr_store)
107
108#define USB_ETHERNET_CONFIGFS_ITEM_ATTR_QMULT(_f_) \
109 static ssize_t _f_##_opts_qmult_show(struct f_##_f_##_opts *opts, \
110 char *page) \
111 { \
112 unsigned qmult; \
113 \
114 mutex_lock(&opts->lock); \
115 qmult = gether_get_qmult(opts->net); \
116 mutex_unlock(&opts->lock); \
117 return sprintf(page, "%d", qmult); \
118 } \
119 \
120 static ssize_t _f_##_opts_qmult_store(struct f_##_f_##_opts *opts, \
121 const char *page, size_t len)\
122 { \
123 u8 val; \
124 int ret; \
125 \
126 mutex_lock(&opts->lock); \
127 if (opts->refcnt) { \
128 ret = -EBUSY; \
129 goto out; \
130 } \
131 \
132 ret = kstrtou8(page, 0, &val); \
133 if (ret) \
134 goto out; \
135 \
136 gether_set_qmult(opts->net, val); \
137 ret = len; \
138out: \
139 mutex_unlock(&opts->lock); \
140 return ret; \
141 } \
142 \
143 static struct f_##_f_##_opts_attribute f_##_f_##_opts_qmult = \
144 __CONFIGFS_ATTR(qmult, S_IRUGO | S_IWUSR, \
145 _f_##_opts_qmult_show, \
146 _f_##_opts_qmult_store)
147
148#define USB_ETHERNET_CONFIGFS_ITEM_ATTR_IFNAME(_f_) \
149 static ssize_t _f_##_opts_ifname_show(struct f_##_f_##_opts *opts, \
150 char *page) \
151 { \
152 int ret; \
153 \
154 mutex_lock(&opts->lock); \
155 ret = gether_get_ifname(opts->net, page, PAGE_SIZE); \
156 mutex_unlock(&opts->lock); \
157 \
158 return ret; \
159 } \
160 \
161 static struct f_##_f_##_opts_attribute f_##_f_##_opts_ifname = \
162 __CONFIGFS_ATTR_RO(ifname, _f_##_opts_ifname_show)
163
164#endif /* __U_ETHER_CONFIGFS_H */
diff --git a/drivers/usb/gadget/function/u_fs.h b/drivers/usb/gadget/function/u_fs.h
new file mode 100644
index 000000000000..63d6e71569c1
--- /dev/null
+++ b/drivers/usb/gadget/function/u_fs.h
@@ -0,0 +1,270 @@
1/*
2 * u_fs.h
3 *
4 * Utility definitions for the FunctionFS
5 *
6 * Copyright (c) 2013 Samsung Electronics Co., Ltd.
7 * http://www.samsung.com
8 *
9 * Author: Andrzej Pietrasiewicz <andrzej.p@samsung.com>
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License version 2 as
13 * published by the Free Software Foundation.
14 */
15
16#ifndef U_FFS_H
17#define U_FFS_H
18
19#include <linux/usb/composite.h>
20#include <linux/list.h>
21#include <linux/mutex.h>
22
23#ifdef VERBOSE_DEBUG
24#ifndef pr_vdebug
25# define pr_vdebug pr_debug
26#endif /* pr_vdebug */
27# define ffs_dump_mem(prefix, ptr, len) \
28 print_hex_dump_bytes(pr_fmt(prefix ": "), DUMP_PREFIX_NONE, ptr, len)
29#else
30#ifndef pr_vdebug
31# define pr_vdebug(...) do { } while (0)
32#endif /* pr_vdebug */
33# define ffs_dump_mem(prefix, ptr, len) do { } while (0)
34#endif /* VERBOSE_DEBUG */
35
36#define ENTER() pr_vdebug("%s()\n", __func__)
37
38struct f_fs_opts;
39
40struct ffs_dev {
41 const char *name;
42 bool name_allocated;
43 bool mounted;
44 bool desc_ready;
45 bool single;
46 struct ffs_data *ffs_data;
47 struct f_fs_opts *opts;
48 struct list_head entry;
49
50 int (*ffs_ready_callback)(struct ffs_data *ffs);
51 void (*ffs_closed_callback)(struct ffs_data *ffs);
52 void *(*ffs_acquire_dev_callback)(struct ffs_dev *dev);
53 void (*ffs_release_dev_callback)(struct ffs_dev *dev);
54};
55
56extern struct mutex ffs_lock;
57
58static inline void ffs_dev_lock(void)
59{
60 mutex_lock(&ffs_lock);
61}
62
63static inline void ffs_dev_unlock(void)
64{
65 mutex_unlock(&ffs_lock);
66}
67
68int ffs_name_dev(struct ffs_dev *dev, const char *name);
69int ffs_single_dev(struct ffs_dev *dev);
70
71struct ffs_epfile;
72struct ffs_function;
73
74enum ffs_state {
75 /*
76 * Waiting for descriptors and strings.
77 *
78 * In this state no open(2), read(2) or write(2) on epfiles
79 * may succeed (which should not be the problem as there
80 * should be no such files opened in the first place).
81 */
82 FFS_READ_DESCRIPTORS,
83 FFS_READ_STRINGS,
84
85 /*
86 * We've got descriptors and strings. We are or have called
87 * functionfs_ready_callback(). functionfs_bind() may have
88 * been called but we don't know.
89 *
90 * This is the only state in which operations on epfiles may
91 * succeed.
92 */
93 FFS_ACTIVE,
94
95 /*
96 * All endpoints have been closed. This state is also set if
97 * we encounter an unrecoverable error. The only
98 * unrecoverable error is situation when after reading strings
99 * from user space we fail to initialise epfiles or
100 * functionfs_ready_callback() returns with error (<0).
101 *
102 * In this state no open(2), read(2) or write(2) (both on ep0
103 * as well as epfile) may succeed (at this point epfiles are
104 * unlinked and all closed so this is not a problem; ep0 is
105 * also closed but ep0 file exists and so open(2) on ep0 must
106 * fail).
107 */
108 FFS_CLOSING
109};
110
111enum ffs_setup_state {
112 /* There is no setup request pending. */
113 FFS_NO_SETUP,
114 /*
115 * User has read events and there was a setup request event
116 * there. The next read/write on ep0 will handle the
117 * request.
118 */
119 FFS_SETUP_PENDING,
120 /*
121 * There was event pending but before user space handled it
122 * some other event was introduced which canceled existing
123 * setup. If this state is set read/write on ep0 return
124 * -EIDRM. This state is only set when adding event.
125 */
126 FFS_SETUP_CANCELLED
127};
128
129struct ffs_data {
130 struct usb_gadget *gadget;
131
132 /*
133 * Protect access read/write operations, only one read/write
134 * at a time. As a consequence protects ep0req and company.
135 * While setup request is being processed (queued) this is
136 * held.
137 */
138 struct mutex mutex;
139
140 /*
141 * Protect access to endpoint related structures (basically
142 * usb_ep_queue(), usb_ep_dequeue(), etc. calls) except for
143 * endpoint zero.
144 */
145 spinlock_t eps_lock;
146
147 /*
148 * XXX REVISIT do we need our own request? Since we are not
149 * handling setup requests immediately user space may be so
150 * slow that another setup will be sent to the gadget but this
151 * time not to us but another function and then there could be
152 * a race. Is that the case? Or maybe we can use cdev->req
153 * after all, maybe we just need some spinlock for that?
154 */
155 struct usb_request *ep0req; /* P: mutex */
156 struct completion ep0req_completion; /* P: mutex */
157
158 /* reference counter */
159 atomic_t ref;
160 /* how many files are opened (EP0 and others) */
161 atomic_t opened;
162
163 /* EP0 state */
164 enum ffs_state state;
165
166 /*
167 * Possible transitions:
168 * + FFS_NO_SETUP -> FFS_SETUP_PENDING -- P: ev.waitq.lock
169 * happens only in ep0 read which is P: mutex
170 * + FFS_SETUP_PENDING -> FFS_NO_SETUP -- P: ev.waitq.lock
171 * happens only in ep0 i/o which is P: mutex
172 * + FFS_SETUP_PENDING -> FFS_SETUP_CANCELLED -- P: ev.waitq.lock
173 * + FFS_SETUP_CANCELLED -> FFS_NO_SETUP -- cmpxchg
174 *
175 * This field should never be accessed directly and instead
176 * ffs_setup_state_clear_cancelled function should be used.
177 */
178 enum ffs_setup_state setup_state;
179
180 /* Events & such. */
181 struct {
182 u8 types[4];
183 unsigned short count;
184 /* XXX REVISIT need to update it in some places, or do we? */
185 unsigned short can_stall;
186 struct usb_ctrlrequest setup;
187
188 wait_queue_head_t waitq;
189 } ev; /* the whole structure, P: ev.waitq.lock */
190
191 /* Flags */
192 unsigned long flags;
193#define FFS_FL_CALL_CLOSED_CALLBACK 0
194#define FFS_FL_BOUND 1
195
196 /* Active function */
197 struct ffs_function *func;
198
199 /*
200 * Device name, write once when file system is mounted.
201 * Intended for user to read if she wants.
202 */
203 const char *dev_name;
204 /* Private data for our user (ie. gadget). Managed by user. */
205 void *private_data;
206
207 /* filled by __ffs_data_got_descs() */
208 /*
209 * raw_descs is what you kfree, real_descs points inside of raw_descs,
210 * where full speed, high speed and super speed descriptors start.
211 * real_descs_length is the length of all those descriptors.
212 */
213 const void *raw_descs_data;
214 const void *raw_descs;
215 unsigned raw_descs_length;
216 unsigned fs_descs_count;
217 unsigned hs_descs_count;
218 unsigned ss_descs_count;
219 unsigned ms_os_descs_count;
220 unsigned ms_os_descs_ext_prop_count;
221 unsigned ms_os_descs_ext_prop_name_len;
222 unsigned ms_os_descs_ext_prop_data_len;
223 void *ms_os_descs_ext_prop_avail;
224 void *ms_os_descs_ext_prop_name_avail;
225 void *ms_os_descs_ext_prop_data_avail;
226
227 unsigned short strings_count;
228 unsigned short interfaces_count;
229 unsigned short eps_count;
230 unsigned short _pad1;
231
232 /* filled by __ffs_data_got_strings() */
233 /* ids in stringtabs are set in functionfs_bind() */
234 const void *raw_strings;
235 struct usb_gadget_strings **stringtabs;
236
237 /*
238 * File system's super block, write once when file system is
239 * mounted.
240 */
241 struct super_block *sb;
242
243 /* File permissions, written once when fs is mounted */
244 struct ffs_file_perms {
245 umode_t mode;
246 kuid_t uid;
247 kgid_t gid;
248 } file_perms;
249
250 /*
251 * The endpoint files, filled by ffs_epfiles_create(),
252 * destroyed by ffs_epfiles_destroy().
253 */
254 struct ffs_epfile *epfiles;
255};
256
257
258struct f_fs_opts {
259 struct usb_function_instance func_inst;
260 struct ffs_dev *dev;
261 unsigned refcnt;
262 bool no_configfs;
263};
264
265static inline struct f_fs_opts *to_f_fs_opts(struct usb_function_instance *fi)
266{
267 return container_of(fi, struct f_fs_opts, func_inst);
268}
269
270#endif /* U_FFS_H */
diff --git a/drivers/usb/gadget/function/u_gether.h b/drivers/usb/gadget/function/u_gether.h
new file mode 100644
index 000000000000..d4078426ba5d
--- /dev/null
+++ b/drivers/usb/gadget/function/u_gether.h
@@ -0,0 +1,36 @@
1/*
2 * u_gether.h
3 *
4 * Utility definitions for the subset function
5 *
6 * Copyright (c) 2013 Samsung Electronics Co., Ltd.
7 * http://www.samsung.com
8 *
9 * Author: Andrzej Pietrasiewicz <andrzej.p@samsung.com>
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License version 2 as
13 * published by the Free Software Foundation.
14 */
15
16#ifndef U_GETHER_H
17#define U_GETHER_H
18
19#include <linux/usb/composite.h>
20
21struct f_gether_opts {
22 struct usb_function_instance func_inst;
23 struct net_device *net;
24 bool bound;
25
26 /*
27 * Read/write access to configfs attributes is handled by configfs.
28 *
29 * This is to protect the data from concurrent access by read/write
30 * and create symlink/remove symlink.
31 */
32 struct mutex lock;
33 int refcnt;
34};
35
36#endif /* U_GETHER_H */
diff --git a/drivers/usb/gadget/function/u_ncm.h b/drivers/usb/gadget/function/u_ncm.h
new file mode 100644
index 000000000000..ce0f3a78ca13
--- /dev/null
+++ b/drivers/usb/gadget/function/u_ncm.h
@@ -0,0 +1,36 @@
1/*
2 * u_ncm.h
3 *
4 * Utility definitions for the ncm function
5 *
6 * Copyright (c) 2013 Samsung Electronics Co., Ltd.
7 * http://www.samsung.com
8 *
9 * Author: Andrzej Pietrasiewicz <andrzej.p@samsung.com>
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License version 2 as
13 * published by the Free Software Foundation.
14 */
15
16#ifndef U_NCM_H
17#define U_NCM_H
18
19#include <linux/usb/composite.h>
20
21struct f_ncm_opts {
22 struct usb_function_instance func_inst;
23 struct net_device *net;
24 bool bound;
25
26 /*
27 * Read/write access to configfs attributes is handled by configfs.
28 *
29 * This is to protect the data from concurrent access by read/write
30 * and create symlink/remove symlink.
31 */
32 struct mutex lock;
33 int refcnt;
34};
35
36#endif /* U_NCM_H */
diff --git a/drivers/usb/gadget/function/u_phonet.h b/drivers/usb/gadget/function/u_phonet.h
new file mode 100644
index 000000000000..98ced18779ea
--- /dev/null
+++ b/drivers/usb/gadget/function/u_phonet.h
@@ -0,0 +1,29 @@
1/*
2 * u_phonet.h - interface to Phonet
3 *
4 * Copyright (C) 2007-2008 by Nokia Corporation
5 *
6 * This software is distributed under the terms of the GNU General
7 * Public License ("GPL") as published by the Free Software Foundation,
8 * either version 2 of that License or (at your option) any later version.
9 */
10
11#ifndef __U_PHONET_H
12#define __U_PHONET_H
13
14#include <linux/usb/composite.h>
15#include <linux/usb/cdc.h>
16
17struct f_phonet_opts {
18 struct usb_function_instance func_inst;
19 bool bound;
20 struct net_device *net;
21};
22
23struct net_device *gphonet_setup_default(void);
24void gphonet_set_gadget(struct net_device *net, struct usb_gadget *g);
25int gphonet_register_netdev(struct net_device *net);
26int phonet_bind_config(struct usb_configuration *c, struct net_device *dev);
27void gphonet_cleanup(struct net_device *dev);
28
29#endif /* __U_PHONET_H */
diff --git a/drivers/usb/gadget/function/u_rndis.h b/drivers/usb/gadget/function/u_rndis.h
new file mode 100644
index 000000000000..e902aa42a297
--- /dev/null
+++ b/drivers/usb/gadget/function/u_rndis.h
@@ -0,0 +1,46 @@
1/*
2 * u_rndis.h
3 *
4 * Utility definitions for the subset function
5 *
6 * Copyright (c) 2013 Samsung Electronics Co., Ltd.
7 * http://www.samsung.com
8 *
9 * Author: Andrzej Pietrasiewicz <andrzej.p@samsung.com>
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License version 2 as
13 * published by the Free Software Foundation.
14 */
15
16#ifndef U_RNDIS_H
17#define U_RNDIS_H
18
19#include <linux/usb/composite.h>
20
21struct f_rndis_opts {
22 struct usb_function_instance func_inst;
23 u32 vendor_id;
24 const char *manufacturer;
25 struct net_device *net;
26 bool bound;
27 bool borrowed_net;
28
29 struct usb_os_desc rndis_os_desc;
30 char rndis_ext_compat_id[16];
31
32 /*
33 * Read/write access to configfs attributes is handled by configfs.
34 *
35 * This is to protect the data from concurrent access by read/write
36 * and create symlink/remove symlink.
37 */
38 struct mutex lock;
39 int refcnt;
40};
41
42int rndis_init(void);
43void rndis_exit(void);
44void rndis_borrow_net(struct usb_function_instance *f, struct net_device *net);
45
46#endif /* U_RNDIS_H */
diff --git a/drivers/usb/gadget/function/u_serial.c b/drivers/usb/gadget/function/u_serial.c
new file mode 100644
index 000000000000..ad0aca812002
--- /dev/null
+++ b/drivers/usb/gadget/function/u_serial.c
@@ -0,0 +1,1347 @@
1/*
2 * u_serial.c - utilities for USB gadget "serial port"/TTY support
3 *
4 * Copyright (C) 2003 Al Borchers (alborchers@steinerpoint.com)
5 * Copyright (C) 2008 David Brownell
6 * Copyright (C) 2008 by Nokia Corporation
7 *
8 * This code also borrows from usbserial.c, which is
9 * Copyright (C) 1999 - 2002 Greg Kroah-Hartman (greg@kroah.com)
10 * Copyright (C) 2000 Peter Berger (pberger@brimson.com)
11 * Copyright (C) 2000 Al Borchers (alborchers@steinerpoint.com)
12 *
13 * This software is distributed under the terms of the GNU General
14 * Public License ("GPL") as published by the Free Software Foundation,
15 * either version 2 of that License or (at your option) any later version.
16 */
17
18/* #define VERBOSE_DEBUG */
19
20#include <linux/kernel.h>
21#include <linux/sched.h>
22#include <linux/interrupt.h>
23#include <linux/device.h>
24#include <linux/delay.h>
25#include <linux/tty.h>
26#include <linux/tty_flip.h>
27#include <linux/slab.h>
28#include <linux/export.h>
29#include <linux/module.h>
30
31#include "u_serial.h"
32
33
34/*
35 * This component encapsulates the TTY layer glue needed to provide basic
36 * "serial port" functionality through the USB gadget stack. Each such
37 * port is exposed through a /dev/ttyGS* node.
38 *
39 * After this module has been loaded, the individual TTY port can be requested
40 * (gserial_alloc_line()) and it will stay available until they are removed
41 * (gserial_free_line()). Each one may be connected to a USB function
42 * (gserial_connect), or disconnected (with gserial_disconnect) when the USB
43 * host issues a config change event. Data can only flow when the port is
44 * connected to the host.
45 *
46 * A given TTY port can be made available in multiple configurations.
47 * For example, each one might expose a ttyGS0 node which provides a
48 * login application. In one case that might use CDC ACM interface 0,
49 * while another configuration might use interface 3 for that. The
50 * work to handle that (including descriptor management) is not part
51 * of this component.
52 *
53 * Configurations may expose more than one TTY port. For example, if
54 * ttyGS0 provides login service, then ttyGS1 might provide dialer access
55 * for a telephone or fax link. And ttyGS2 might be something that just
56 * needs a simple byte stream interface for some messaging protocol that
57 * is managed in userspace ... OBEX, PTP, and MTP have been mentioned.
58 */
59
60#define PREFIX "ttyGS"
61
62/*
63 * gserial is the lifecycle interface, used by USB functions
64 * gs_port is the I/O nexus, used by the tty driver
65 * tty_struct links to the tty/filesystem framework
66 *
67 * gserial <---> gs_port ... links will be null when the USB link is
68 * inactive; managed by gserial_{connect,disconnect}(). each gserial
69 * instance can wrap its own USB control protocol.
70 * gserial->ioport == usb_ep->driver_data ... gs_port
71 * gs_port->port_usb ... gserial
72 *
73 * gs_port <---> tty_struct ... links will be null when the TTY file
74 * isn't opened; managed by gs_open()/gs_close()
75 * gserial->port_tty ... tty_struct
76 * tty_struct->driver_data ... gserial
77 */
78
79/* RX and TX queues can buffer QUEUE_SIZE packets before they hit the
80 * next layer of buffering. For TX that's a circular buffer; for RX
81 * consider it a NOP. A third layer is provided by the TTY code.
82 */
83#define QUEUE_SIZE 16
84#define WRITE_BUF_SIZE 8192 /* TX only */
85
86/* circular buffer */
87struct gs_buf {
88 unsigned buf_size;
89 char *buf_buf;
90 char *buf_get;
91 char *buf_put;
92};
93
94/*
95 * The port structure holds info for each port, one for each minor number
96 * (and thus for each /dev/ node).
97 */
98struct gs_port {
99 struct tty_port port;
100 spinlock_t port_lock; /* guard port_* access */
101
102 struct gserial *port_usb;
103
104 bool openclose; /* open/close in progress */
105 u8 port_num;
106
107 struct list_head read_pool;
108 int read_started;
109 int read_allocated;
110 struct list_head read_queue;
111 unsigned n_read;
112 struct tasklet_struct push;
113
114 struct list_head write_pool;
115 int write_started;
116 int write_allocated;
117 struct gs_buf port_write_buf;
118 wait_queue_head_t drain_wait; /* wait while writes drain */
119
120 /* REVISIT this state ... */
121 struct usb_cdc_line_coding port_line_coding; /* 8-N-1 etc */
122};
123
124static struct portmaster {
125 struct mutex lock; /* protect open/close */
126 struct gs_port *port;
127} ports[MAX_U_SERIAL_PORTS];
128
129#define GS_CLOSE_TIMEOUT 15 /* seconds */
130
131
132
133#ifdef VERBOSE_DEBUG
134#ifndef pr_vdebug
135#define pr_vdebug(fmt, arg...) \
136 pr_debug(fmt, ##arg)
137#endif /* pr_vdebug */
138#else
139#ifndef pr_vdebug
140#define pr_vdebug(fmt, arg...) \
141 ({ if (0) pr_debug(fmt, ##arg); })
142#endif /* pr_vdebug */
143#endif
144
145/*-------------------------------------------------------------------------*/
146
147/* Circular Buffer */
148
149/*
150 * gs_buf_alloc
151 *
152 * Allocate a circular buffer and all associated memory.
153 */
154static int gs_buf_alloc(struct gs_buf *gb, unsigned size)
155{
156 gb->buf_buf = kmalloc(size, GFP_KERNEL);
157 if (gb->buf_buf == NULL)
158 return -ENOMEM;
159
160 gb->buf_size = size;
161 gb->buf_put = gb->buf_buf;
162 gb->buf_get = gb->buf_buf;
163
164 return 0;
165}
166
167/*
168 * gs_buf_free
169 *
170 * Free the buffer and all associated memory.
171 */
172static void gs_buf_free(struct gs_buf *gb)
173{
174 kfree(gb->buf_buf);
175 gb->buf_buf = NULL;
176}
177
178/*
179 * gs_buf_clear
180 *
181 * Clear out all data in the circular buffer.
182 */
183static void gs_buf_clear(struct gs_buf *gb)
184{
185 gb->buf_get = gb->buf_put;
186 /* equivalent to a get of all data available */
187}
188
189/*
190 * gs_buf_data_avail
191 *
192 * Return the number of bytes of data written into the circular
193 * buffer.
194 */
195static unsigned gs_buf_data_avail(struct gs_buf *gb)
196{
197 return (gb->buf_size + gb->buf_put - gb->buf_get) % gb->buf_size;
198}
199
200/*
201 * gs_buf_space_avail
202 *
203 * Return the number of bytes of space available in the circular
204 * buffer.
205 */
206static unsigned gs_buf_space_avail(struct gs_buf *gb)
207{
208 return (gb->buf_size + gb->buf_get - gb->buf_put - 1) % gb->buf_size;
209}
210
211/*
212 * gs_buf_put
213 *
214 * Copy data data from a user buffer and put it into the circular buffer.
215 * Restrict to the amount of space available.
216 *
217 * Return the number of bytes copied.
218 */
219static unsigned
220gs_buf_put(struct gs_buf *gb, const char *buf, unsigned count)
221{
222 unsigned len;
223
224 len = gs_buf_space_avail(gb);
225 if (count > len)
226 count = len;
227
228 if (count == 0)
229 return 0;
230
231 len = gb->buf_buf + gb->buf_size - gb->buf_put;
232 if (count > len) {
233 memcpy(gb->buf_put, buf, len);
234 memcpy(gb->buf_buf, buf+len, count - len);
235 gb->buf_put = gb->buf_buf + count - len;
236 } else {
237 memcpy(gb->buf_put, buf, count);
238 if (count < len)
239 gb->buf_put += count;
240 else /* count == len */
241 gb->buf_put = gb->buf_buf;
242 }
243
244 return count;
245}
246
247/*
248 * gs_buf_get
249 *
250 * Get data from the circular buffer and copy to the given buffer.
251 * Restrict to the amount of data available.
252 *
253 * Return the number of bytes copied.
254 */
255static unsigned
256gs_buf_get(struct gs_buf *gb, char *buf, unsigned count)
257{
258 unsigned len;
259
260 len = gs_buf_data_avail(gb);
261 if (count > len)
262 count = len;
263
264 if (count == 0)
265 return 0;
266
267 len = gb->buf_buf + gb->buf_size - gb->buf_get;
268 if (count > len) {
269 memcpy(buf, gb->buf_get, len);
270 memcpy(buf+len, gb->buf_buf, count - len);
271 gb->buf_get = gb->buf_buf + count - len;
272 } else {
273 memcpy(buf, gb->buf_get, count);
274 if (count < len)
275 gb->buf_get += count;
276 else /* count == len */
277 gb->buf_get = gb->buf_buf;
278 }
279
280 return count;
281}
282
283/*-------------------------------------------------------------------------*/
284
285/* I/O glue between TTY (upper) and USB function (lower) driver layers */
286
287/*
288 * gs_alloc_req
289 *
290 * Allocate a usb_request and its buffer. Returns a pointer to the
291 * usb_request or NULL if there is an error.
292 */
293struct usb_request *
294gs_alloc_req(struct usb_ep *ep, unsigned len, gfp_t kmalloc_flags)
295{
296 struct usb_request *req;
297
298 req = usb_ep_alloc_request(ep, kmalloc_flags);
299
300 if (req != NULL) {
301 req->length = len;
302 req->buf = kmalloc(len, kmalloc_flags);
303 if (req->buf == NULL) {
304 usb_ep_free_request(ep, req);
305 return NULL;
306 }
307 }
308
309 return req;
310}
311EXPORT_SYMBOL_GPL(gs_alloc_req);
312
313/*
314 * gs_free_req
315 *
316 * Free a usb_request and its buffer.
317 */
318void gs_free_req(struct usb_ep *ep, struct usb_request *req)
319{
320 kfree(req->buf);
321 usb_ep_free_request(ep, req);
322}
323EXPORT_SYMBOL_GPL(gs_free_req);
324
325/*
326 * gs_send_packet
327 *
328 * If there is data to send, a packet is built in the given
329 * buffer and the size is returned. If there is no data to
330 * send, 0 is returned.
331 *
332 * Called with port_lock held.
333 */
334static unsigned
335gs_send_packet(struct gs_port *port, char *packet, unsigned size)
336{
337 unsigned len;
338
339 len = gs_buf_data_avail(&port->port_write_buf);
340 if (len < size)
341 size = len;
342 if (size != 0)
343 size = gs_buf_get(&port->port_write_buf, packet, size);
344 return size;
345}
346
347/*
348 * gs_start_tx
349 *
350 * This function finds available write requests, calls
351 * gs_send_packet to fill these packets with data, and
352 * continues until either there are no more write requests
353 * available or no more data to send. This function is
354 * run whenever data arrives or write requests are available.
355 *
356 * Context: caller owns port_lock; port_usb is non-null.
357 */
358static int gs_start_tx(struct gs_port *port)
359/*
360__releases(&port->port_lock)
361__acquires(&port->port_lock)
362*/
363{
364 struct list_head *pool = &port->write_pool;
365 struct usb_ep *in = port->port_usb->in;
366 int status = 0;
367 bool do_tty_wake = false;
368
369 while (!list_empty(pool)) {
370 struct usb_request *req;
371 int len;
372
373 if (port->write_started >= QUEUE_SIZE)
374 break;
375
376 req = list_entry(pool->next, struct usb_request, list);
377 len = gs_send_packet(port, req->buf, in->maxpacket);
378 if (len == 0) {
379 wake_up_interruptible(&port->drain_wait);
380 break;
381 }
382 do_tty_wake = true;
383
384 req->length = len;
385 list_del(&req->list);
386 req->zero = (gs_buf_data_avail(&port->port_write_buf) == 0);
387
388 pr_vdebug(PREFIX "%d: tx len=%d, 0x%02x 0x%02x 0x%02x ...\n",
389 port->port_num, len, *((u8 *)req->buf),
390 *((u8 *)req->buf+1), *((u8 *)req->buf+2));
391
392 /* Drop lock while we call out of driver; completions
393 * could be issued while we do so. Disconnection may
394 * happen too; maybe immediately before we queue this!
395 *
396 * NOTE that we may keep sending data for a while after
397 * the TTY closed (dev->ioport->port_tty is NULL).
398 */
399 spin_unlock(&port->port_lock);
400 status = usb_ep_queue(in, req, GFP_ATOMIC);
401 spin_lock(&port->port_lock);
402
403 if (status) {
404 pr_debug("%s: %s %s err %d\n",
405 __func__, "queue", in->name, status);
406 list_add(&req->list, pool);
407 break;
408 }
409
410 port->write_started++;
411
412 /* abort immediately after disconnect */
413 if (!port->port_usb)
414 break;
415 }
416
417 if (do_tty_wake && port->port.tty)
418 tty_wakeup(port->port.tty);
419 return status;
420}
421
422/*
423 * Context: caller owns port_lock, and port_usb is set
424 */
425static unsigned gs_start_rx(struct gs_port *port)
426/*
427__releases(&port->port_lock)
428__acquires(&port->port_lock)
429*/
430{
431 struct list_head *pool = &port->read_pool;
432 struct usb_ep *out = port->port_usb->out;
433
434 while (!list_empty(pool)) {
435 struct usb_request *req;
436 int status;
437 struct tty_struct *tty;
438
439 /* no more rx if closed */
440 tty = port->port.tty;
441 if (!tty)
442 break;
443
444 if (port->read_started >= QUEUE_SIZE)
445 break;
446
447 req = list_entry(pool->next, struct usb_request, list);
448 list_del(&req->list);
449 req->length = out->maxpacket;
450
451 /* drop lock while we call out; the controller driver
452 * may need to call us back (e.g. for disconnect)
453 */
454 spin_unlock(&port->port_lock);
455 status = usb_ep_queue(out, req, GFP_ATOMIC);
456 spin_lock(&port->port_lock);
457
458 if (status) {
459 pr_debug("%s: %s %s err %d\n",
460 __func__, "queue", out->name, status);
461 list_add(&req->list, pool);
462 break;
463 }
464 port->read_started++;
465
466 /* abort immediately after disconnect */
467 if (!port->port_usb)
468 break;
469 }
470 return port->read_started;
471}
472
473/*
474 * RX tasklet takes data out of the RX queue and hands it up to the TTY
475 * layer until it refuses to take any more data (or is throttled back).
476 * Then it issues reads for any further data.
477 *
478 * If the RX queue becomes full enough that no usb_request is queued,
479 * the OUT endpoint may begin NAKing as soon as its FIFO fills up.
480 * So QUEUE_SIZE packets plus however many the FIFO holds (usually two)
481 * can be buffered before the TTY layer's buffers (currently 64 KB).
482 */
483static void gs_rx_push(unsigned long _port)
484{
485 struct gs_port *port = (void *)_port;
486 struct tty_struct *tty;
487 struct list_head *queue = &port->read_queue;
488 bool disconnect = false;
489 bool do_push = false;
490
491 /* hand any queued data to the tty */
492 spin_lock_irq(&port->port_lock);
493 tty = port->port.tty;
494 while (!list_empty(queue)) {
495 struct usb_request *req;
496
497 req = list_first_entry(queue, struct usb_request, list);
498
499 /* leave data queued if tty was rx throttled */
500 if (tty && test_bit(TTY_THROTTLED, &tty->flags))
501 break;
502
503 switch (req->status) {
504 case -ESHUTDOWN:
505 disconnect = true;
506 pr_vdebug(PREFIX "%d: shutdown\n", port->port_num);
507 break;
508
509 default:
510 /* presumably a transient fault */
511 pr_warning(PREFIX "%d: unexpected RX status %d\n",
512 port->port_num, req->status);
513 /* FALLTHROUGH */
514 case 0:
515 /* normal completion */
516 break;
517 }
518
519 /* push data to (open) tty */
520 if (req->actual) {
521 char *packet = req->buf;
522 unsigned size = req->actual;
523 unsigned n;
524 int count;
525
526 /* we may have pushed part of this packet already... */
527 n = port->n_read;
528 if (n) {
529 packet += n;
530 size -= n;
531 }
532
533 count = tty_insert_flip_string(&port->port, packet,
534 size);
535 if (count)
536 do_push = true;
537 if (count != size) {
538 /* stop pushing; TTY layer can't handle more */
539 port->n_read += count;
540 pr_vdebug(PREFIX "%d: rx block %d/%d\n",
541 port->port_num,
542 count, req->actual);
543 break;
544 }
545 port->n_read = 0;
546 }
547
548 list_move(&req->list, &port->read_pool);
549 port->read_started--;
550 }
551
552 /* Push from tty to ldisc; this is handled by a workqueue,
553 * so we won't get callbacks and can hold port_lock
554 */
555 if (do_push)
556 tty_flip_buffer_push(&port->port);
557
558
559 /* We want our data queue to become empty ASAP, keeping data
560 * in the tty and ldisc (not here). If we couldn't push any
561 * this time around, there may be trouble unless there's an
562 * implicit tty_unthrottle() call on its way...
563 *
564 * REVISIT we should probably add a timer to keep the tasklet
565 * from starving ... but it's not clear that case ever happens.
566 */
567 if (!list_empty(queue) && tty) {
568 if (!test_bit(TTY_THROTTLED, &tty->flags)) {
569 if (do_push)
570 tasklet_schedule(&port->push);
571 else
572 pr_warning(PREFIX "%d: RX not scheduled?\n",
573 port->port_num);
574 }
575 }
576
577 /* If we're still connected, refill the USB RX queue. */
578 if (!disconnect && port->port_usb)
579 gs_start_rx(port);
580
581 spin_unlock_irq(&port->port_lock);
582}
583
584static void gs_read_complete(struct usb_ep *ep, struct usb_request *req)
585{
586 struct gs_port *port = ep->driver_data;
587
588 /* Queue all received data until the tty layer is ready for it. */
589 spin_lock(&port->port_lock);
590 list_add_tail(&req->list, &port->read_queue);
591 tasklet_schedule(&port->push);
592 spin_unlock(&port->port_lock);
593}
594
595static void gs_write_complete(struct usb_ep *ep, struct usb_request *req)
596{
597 struct gs_port *port = ep->driver_data;
598
599 spin_lock(&port->port_lock);
600 list_add(&req->list, &port->write_pool);
601 port->write_started--;
602
603 switch (req->status) {
604 default:
605 /* presumably a transient fault */
606 pr_warning("%s: unexpected %s status %d\n",
607 __func__, ep->name, req->status);
608 /* FALL THROUGH */
609 case 0:
610 /* normal completion */
611 gs_start_tx(port);
612 break;
613
614 case -ESHUTDOWN:
615 /* disconnect */
616 pr_vdebug("%s: %s shutdown\n", __func__, ep->name);
617 break;
618 }
619
620 spin_unlock(&port->port_lock);
621}
622
623static void gs_free_requests(struct usb_ep *ep, struct list_head *head,
624 int *allocated)
625{
626 struct usb_request *req;
627
628 while (!list_empty(head)) {
629 req = list_entry(head->next, struct usb_request, list);
630 list_del(&req->list);
631 gs_free_req(ep, req);
632 if (allocated)
633 (*allocated)--;
634 }
635}
636
637static int gs_alloc_requests(struct usb_ep *ep, struct list_head *head,
638 void (*fn)(struct usb_ep *, struct usb_request *),
639 int *allocated)
640{
641 int i;
642 struct usb_request *req;
643 int n = allocated ? QUEUE_SIZE - *allocated : QUEUE_SIZE;
644
645 /* Pre-allocate up to QUEUE_SIZE transfers, but if we can't
646 * do quite that many this time, don't fail ... we just won't
647 * be as speedy as we might otherwise be.
648 */
649 for (i = 0; i < n; i++) {
650 req = gs_alloc_req(ep, ep->maxpacket, GFP_ATOMIC);
651 if (!req)
652 return list_empty(head) ? -ENOMEM : 0;
653 req->complete = fn;
654 list_add_tail(&req->list, head);
655 if (allocated)
656 (*allocated)++;
657 }
658 return 0;
659}
660
661/**
662 * gs_start_io - start USB I/O streams
663 * @dev: encapsulates endpoints to use
664 * Context: holding port_lock; port_tty and port_usb are non-null
665 *
666 * We only start I/O when something is connected to both sides of
667 * this port. If nothing is listening on the host side, we may
668 * be pointlessly filling up our TX buffers and FIFO.
669 */
670static int gs_start_io(struct gs_port *port)
671{
672 struct list_head *head = &port->read_pool;
673 struct usb_ep *ep = port->port_usb->out;
674 int status;
675 unsigned started;
676
677 /* Allocate RX and TX I/O buffers. We can't easily do this much
678 * earlier (with GFP_KERNEL) because the requests are coupled to
679 * endpoints, as are the packet sizes we'll be using. Different
680 * configurations may use different endpoints with a given port;
681 * and high speed vs full speed changes packet sizes too.
682 */
683 status = gs_alloc_requests(ep, head, gs_read_complete,
684 &port->read_allocated);
685 if (status)
686 return status;
687
688 status = gs_alloc_requests(port->port_usb->in, &port->write_pool,
689 gs_write_complete, &port->write_allocated);
690 if (status) {
691 gs_free_requests(ep, head, &port->read_allocated);
692 return status;
693 }
694
695 /* queue read requests */
696 port->n_read = 0;
697 started = gs_start_rx(port);
698
699 /* unblock any pending writes into our circular buffer */
700 if (started) {
701 tty_wakeup(port->port.tty);
702 } else {
703 gs_free_requests(ep, head, &port->read_allocated);
704 gs_free_requests(port->port_usb->in, &port->write_pool,
705 &port->write_allocated);
706 status = -EIO;
707 }
708
709 return status;
710}
711
712/*-------------------------------------------------------------------------*/
713
714/* TTY Driver */
715
716/*
717 * gs_open sets up the link between a gs_port and its associated TTY.
718 * That link is broken *only* by TTY close(), and all driver methods
719 * know that.
720 */
721static int gs_open(struct tty_struct *tty, struct file *file)
722{
723 int port_num = tty->index;
724 struct gs_port *port;
725 int status;
726
727 do {
728 mutex_lock(&ports[port_num].lock);
729 port = ports[port_num].port;
730 if (!port)
731 status = -ENODEV;
732 else {
733 spin_lock_irq(&port->port_lock);
734
735 /* already open? Great. */
736 if (port->port.count) {
737 status = 0;
738 port->port.count++;
739
740 /* currently opening/closing? wait ... */
741 } else if (port->openclose) {
742 status = -EBUSY;
743
744 /* ... else we do the work */
745 } else {
746 status = -EAGAIN;
747 port->openclose = true;
748 }
749 spin_unlock_irq(&port->port_lock);
750 }
751 mutex_unlock(&ports[port_num].lock);
752
753 switch (status) {
754 default:
755 /* fully handled */
756 return status;
757 case -EAGAIN:
758 /* must do the work */
759 break;
760 case -EBUSY:
761 /* wait for EAGAIN task to finish */
762 msleep(1);
763 /* REVISIT could have a waitchannel here, if
764 * concurrent open performance is important
765 */
766 break;
767 }
768 } while (status != -EAGAIN);
769
770 /* Do the "real open" */
771 spin_lock_irq(&port->port_lock);
772
773 /* allocate circular buffer on first open */
774 if (port->port_write_buf.buf_buf == NULL) {
775
776 spin_unlock_irq(&port->port_lock);
777 status = gs_buf_alloc(&port->port_write_buf, WRITE_BUF_SIZE);
778 spin_lock_irq(&port->port_lock);
779
780 if (status) {
781 pr_debug("gs_open: ttyGS%d (%p,%p) no buffer\n",
782 port->port_num, tty, file);
783 port->openclose = false;
784 goto exit_unlock_port;
785 }
786 }
787
788 /* REVISIT if REMOVED (ports[].port NULL), abort the open
789 * to let rmmod work faster (but this way isn't wrong).
790 */
791
792 /* REVISIT maybe wait for "carrier detect" */
793
794 tty->driver_data = port;
795 port->port.tty = tty;
796
797 port->port.count = 1;
798 port->openclose = false;
799
800 /* if connected, start the I/O stream */
801 if (port->port_usb) {
802 struct gserial *gser = port->port_usb;
803
804 pr_debug("gs_open: start ttyGS%d\n", port->port_num);
805 gs_start_io(port);
806
807 if (gser->connect)
808 gser->connect(gser);
809 }
810
811 pr_debug("gs_open: ttyGS%d (%p,%p)\n", port->port_num, tty, file);
812
813 status = 0;
814
815exit_unlock_port:
816 spin_unlock_irq(&port->port_lock);
817 return status;
818}
819
820static int gs_writes_finished(struct gs_port *p)
821{
822 int cond;
823
824 /* return true on disconnect or empty buffer */
825 spin_lock_irq(&p->port_lock);
826 cond = (p->port_usb == NULL) || !gs_buf_data_avail(&p->port_write_buf);
827 spin_unlock_irq(&p->port_lock);
828
829 return cond;
830}
831
832static void gs_close(struct tty_struct *tty, struct file *file)
833{
834 struct gs_port *port = tty->driver_data;
835 struct gserial *gser;
836
837 spin_lock_irq(&port->port_lock);
838
839 if (port->port.count != 1) {
840 if (port->port.count == 0)
841 WARN_ON(1);
842 else
843 --port->port.count;
844 goto exit;
845 }
846
847 pr_debug("gs_close: ttyGS%d (%p,%p) ...\n", port->port_num, tty, file);
848
849 /* mark port as closing but in use; we can drop port lock
850 * and sleep if necessary
851 */
852 port->openclose = true;
853 port->port.count = 0;
854
855 gser = port->port_usb;
856 if (gser && gser->disconnect)
857 gser->disconnect(gser);
858
859 /* wait for circular write buffer to drain, disconnect, or at
860 * most GS_CLOSE_TIMEOUT seconds; then discard the rest
861 */
862 if (gs_buf_data_avail(&port->port_write_buf) > 0 && gser) {
863 spin_unlock_irq(&port->port_lock);
864 wait_event_interruptible_timeout(port->drain_wait,
865 gs_writes_finished(port),
866 GS_CLOSE_TIMEOUT * HZ);
867 spin_lock_irq(&port->port_lock);
868 gser = port->port_usb;
869 }
870
871 /* Iff we're disconnected, there can be no I/O in flight so it's
872 * ok to free the circular buffer; else just scrub it. And don't
873 * let the push tasklet fire again until we're re-opened.
874 */
875 if (gser == NULL)
876 gs_buf_free(&port->port_write_buf);
877 else
878 gs_buf_clear(&port->port_write_buf);
879
880 tty->driver_data = NULL;
881 port->port.tty = NULL;
882
883 port->openclose = false;
884
885 pr_debug("gs_close: ttyGS%d (%p,%p) done!\n",
886 port->port_num, tty, file);
887
888 wake_up(&port->port.close_wait);
889exit:
890 spin_unlock_irq(&port->port_lock);
891}
892
893static int gs_write(struct tty_struct *tty, const unsigned char *buf, int count)
894{
895 struct gs_port *port = tty->driver_data;
896 unsigned long flags;
897 int status;
898
899 pr_vdebug("gs_write: ttyGS%d (%p) writing %d bytes\n",
900 port->port_num, tty, count);
901
902 spin_lock_irqsave(&port->port_lock, flags);
903 if (count)
904 count = gs_buf_put(&port->port_write_buf, buf, count);
905 /* treat count == 0 as flush_chars() */
906 if (port->port_usb)
907 status = gs_start_tx(port);
908 spin_unlock_irqrestore(&port->port_lock, flags);
909
910 return count;
911}
912
913static int gs_put_char(struct tty_struct *tty, unsigned char ch)
914{
915 struct gs_port *port = tty->driver_data;
916 unsigned long flags;
917 int status;
918
919 pr_vdebug("gs_put_char: (%d,%p) char=0x%x, called from %pf\n",
920 port->port_num, tty, ch, __builtin_return_address(0));
921
922 spin_lock_irqsave(&port->port_lock, flags);
923 status = gs_buf_put(&port->port_write_buf, &ch, 1);
924 spin_unlock_irqrestore(&port->port_lock, flags);
925
926 return status;
927}
928
929static void gs_flush_chars(struct tty_struct *tty)
930{
931 struct gs_port *port = tty->driver_data;
932 unsigned long flags;
933
934 pr_vdebug("gs_flush_chars: (%d,%p)\n", port->port_num, tty);
935
936 spin_lock_irqsave(&port->port_lock, flags);
937 if (port->port_usb)
938 gs_start_tx(port);
939 spin_unlock_irqrestore(&port->port_lock, flags);
940}
941
942static int gs_write_room(struct tty_struct *tty)
943{
944 struct gs_port *port = tty->driver_data;
945 unsigned long flags;
946 int room = 0;
947
948 spin_lock_irqsave(&port->port_lock, flags);
949 if (port->port_usb)
950 room = gs_buf_space_avail(&port->port_write_buf);
951 spin_unlock_irqrestore(&port->port_lock, flags);
952
953 pr_vdebug("gs_write_room: (%d,%p) room=%d\n",
954 port->port_num, tty, room);
955
956 return room;
957}
958
959static int gs_chars_in_buffer(struct tty_struct *tty)
960{
961 struct gs_port *port = tty->driver_data;
962 unsigned long flags;
963 int chars = 0;
964
965 spin_lock_irqsave(&port->port_lock, flags);
966 chars = gs_buf_data_avail(&port->port_write_buf);
967 spin_unlock_irqrestore(&port->port_lock, flags);
968
969 pr_vdebug("gs_chars_in_buffer: (%d,%p) chars=%d\n",
970 port->port_num, tty, chars);
971
972 return chars;
973}
974
975/* undo side effects of setting TTY_THROTTLED */
976static void gs_unthrottle(struct tty_struct *tty)
977{
978 struct gs_port *port = tty->driver_data;
979 unsigned long flags;
980
981 spin_lock_irqsave(&port->port_lock, flags);
982 if (port->port_usb) {
983 /* Kickstart read queue processing. We don't do xon/xoff,
984 * rts/cts, or other handshaking with the host, but if the
985 * read queue backs up enough we'll be NAKing OUT packets.
986 */
987 tasklet_schedule(&port->push);
988 pr_vdebug(PREFIX "%d: unthrottle\n", port->port_num);
989 }
990 spin_unlock_irqrestore(&port->port_lock, flags);
991}
992
993static int gs_break_ctl(struct tty_struct *tty, int duration)
994{
995 struct gs_port *port = tty->driver_data;
996 int status = 0;
997 struct gserial *gser;
998
999 pr_vdebug("gs_break_ctl: ttyGS%d, send break (%d) \n",
1000 port->port_num, duration);
1001
1002 spin_lock_irq(&port->port_lock);
1003 gser = port->port_usb;
1004 if (gser && gser->send_break)
1005 status = gser->send_break(gser, duration);
1006 spin_unlock_irq(&port->port_lock);
1007
1008 return status;
1009}
1010
1011static const struct tty_operations gs_tty_ops = {
1012 .open = gs_open,
1013 .close = gs_close,
1014 .write = gs_write,
1015 .put_char = gs_put_char,
1016 .flush_chars = gs_flush_chars,
1017 .write_room = gs_write_room,
1018 .chars_in_buffer = gs_chars_in_buffer,
1019 .unthrottle = gs_unthrottle,
1020 .break_ctl = gs_break_ctl,
1021};
1022
1023/*-------------------------------------------------------------------------*/
1024
1025static struct tty_driver *gs_tty_driver;
1026
1027static int
1028gs_port_alloc(unsigned port_num, struct usb_cdc_line_coding *coding)
1029{
1030 struct gs_port *port;
1031 int ret = 0;
1032
1033 mutex_lock(&ports[port_num].lock);
1034 if (ports[port_num].port) {
1035 ret = -EBUSY;
1036 goto out;
1037 }
1038
1039 port = kzalloc(sizeof(struct gs_port), GFP_KERNEL);
1040 if (port == NULL) {
1041 ret = -ENOMEM;
1042 goto out;
1043 }
1044
1045 tty_port_init(&port->port);
1046 spin_lock_init(&port->port_lock);
1047 init_waitqueue_head(&port->drain_wait);
1048
1049 tasklet_init(&port->push, gs_rx_push, (unsigned long) port);
1050
1051 INIT_LIST_HEAD(&port->read_pool);
1052 INIT_LIST_HEAD(&port->read_queue);
1053 INIT_LIST_HEAD(&port->write_pool);
1054
1055 port->port_num = port_num;
1056 port->port_line_coding = *coding;
1057
1058 ports[port_num].port = port;
1059out:
1060 mutex_unlock(&ports[port_num].lock);
1061 return ret;
1062}
1063
1064static int gs_closed(struct gs_port *port)
1065{
1066 int cond;
1067
1068 spin_lock_irq(&port->port_lock);
1069 cond = (port->port.count == 0) && !port->openclose;
1070 spin_unlock_irq(&port->port_lock);
1071 return cond;
1072}
1073
1074static void gserial_free_port(struct gs_port *port)
1075{
1076 tasklet_kill(&port->push);
1077 /* wait for old opens to finish */
1078 wait_event(port->port.close_wait, gs_closed(port));
1079 WARN_ON(port->port_usb != NULL);
1080 tty_port_destroy(&port->port);
1081 kfree(port);
1082}
1083
1084void gserial_free_line(unsigned char port_num)
1085{
1086 struct gs_port *port;
1087
1088 mutex_lock(&ports[port_num].lock);
1089 if (WARN_ON(!ports[port_num].port)) {
1090 mutex_unlock(&ports[port_num].lock);
1091 return;
1092 }
1093 port = ports[port_num].port;
1094 ports[port_num].port = NULL;
1095 mutex_unlock(&ports[port_num].lock);
1096
1097 gserial_free_port(port);
1098 tty_unregister_device(gs_tty_driver, port_num);
1099}
1100EXPORT_SYMBOL_GPL(gserial_free_line);
1101
1102int gserial_alloc_line(unsigned char *line_num)
1103{
1104 struct usb_cdc_line_coding coding;
1105 struct device *tty_dev;
1106 int ret;
1107 int port_num;
1108
1109 coding.dwDTERate = cpu_to_le32(9600);
1110 coding.bCharFormat = 8;
1111 coding.bParityType = USB_CDC_NO_PARITY;
1112 coding.bDataBits = USB_CDC_1_STOP_BITS;
1113
1114 for (port_num = 0; port_num < MAX_U_SERIAL_PORTS; port_num++) {
1115 ret = gs_port_alloc(port_num, &coding);
1116 if (ret == -EBUSY)
1117 continue;
1118 if (ret)
1119 return ret;
1120 break;
1121 }
1122 if (ret)
1123 return ret;
1124
1125 /* ... and sysfs class devices, so mdev/udev make /dev/ttyGS* */
1126
1127 tty_dev = tty_port_register_device(&ports[port_num].port->port,
1128 gs_tty_driver, port_num, NULL);
1129 if (IS_ERR(tty_dev)) {
1130 struct gs_port *port;
1131 pr_err("%s: failed to register tty for port %d, err %ld\n",
1132 __func__, port_num, PTR_ERR(tty_dev));
1133
1134 ret = PTR_ERR(tty_dev);
1135 port = ports[port_num].port;
1136 ports[port_num].port = NULL;
1137 gserial_free_port(port);
1138 goto err;
1139 }
1140 *line_num = port_num;
1141err:
1142 return ret;
1143}
1144EXPORT_SYMBOL_GPL(gserial_alloc_line);
1145
1146/**
1147 * gserial_connect - notify TTY I/O glue that USB link is active
1148 * @gser: the function, set up with endpoints and descriptors
1149 * @port_num: which port is active
1150 * Context: any (usually from irq)
1151 *
1152 * This is called activate endpoints and let the TTY layer know that
1153 * the connection is active ... not unlike "carrier detect". It won't
1154 * necessarily start I/O queues; unless the TTY is held open by any
1155 * task, there would be no point. However, the endpoints will be
1156 * activated so the USB host can perform I/O, subject to basic USB
1157 * hardware flow control.
1158 *
1159 * Caller needs to have set up the endpoints and USB function in @dev
1160 * before calling this, as well as the appropriate (speed-specific)
1161 * endpoint descriptors, and also have allocate @port_num by calling
1162 * @gserial_alloc_line().
1163 *
1164 * Returns negative errno or zero.
1165 * On success, ep->driver_data will be overwritten.
1166 */
1167int gserial_connect(struct gserial *gser, u8 port_num)
1168{
1169 struct gs_port *port;
1170 unsigned long flags;
1171 int status;
1172
1173 if (port_num >= MAX_U_SERIAL_PORTS)
1174 return -ENXIO;
1175
1176 port = ports[port_num].port;
1177 if (!port) {
1178 pr_err("serial line %d not allocated.\n", port_num);
1179 return -EINVAL;
1180 }
1181 if (port->port_usb) {
1182 pr_err("serial line %d is in use.\n", port_num);
1183 return -EBUSY;
1184 }
1185
1186 /* activate the endpoints */
1187 status = usb_ep_enable(gser->in);
1188 if (status < 0)
1189 return status;
1190 gser->in->driver_data = port;
1191
1192 status = usb_ep_enable(gser->out);
1193 if (status < 0)
1194 goto fail_out;
1195 gser->out->driver_data = port;
1196
1197 /* then tell the tty glue that I/O can work */
1198 spin_lock_irqsave(&port->port_lock, flags);
1199 gser->ioport = port;
1200 port->port_usb = gser;
1201
1202 /* REVISIT unclear how best to handle this state...
1203 * we don't really couple it with the Linux TTY.
1204 */
1205 gser->port_line_coding = port->port_line_coding;
1206
1207 /* REVISIT if waiting on "carrier detect", signal. */
1208
1209 /* if it's already open, start I/O ... and notify the serial
1210 * protocol about open/close status (connect/disconnect).
1211 */
1212 if (port->port.count) {
1213 pr_debug("gserial_connect: start ttyGS%d\n", port->port_num);
1214 gs_start_io(port);
1215 if (gser->connect)
1216 gser->connect(gser);
1217 } else {
1218 if (gser->disconnect)
1219 gser->disconnect(gser);
1220 }
1221
1222 spin_unlock_irqrestore(&port->port_lock, flags);
1223
1224 return status;
1225
1226fail_out:
1227 usb_ep_disable(gser->in);
1228 gser->in->driver_data = NULL;
1229 return status;
1230}
1231EXPORT_SYMBOL_GPL(gserial_connect);
1232/**
1233 * gserial_disconnect - notify TTY I/O glue that USB link is inactive
1234 * @gser: the function, on which gserial_connect() was called
1235 * Context: any (usually from irq)
1236 *
1237 * This is called to deactivate endpoints and let the TTY layer know
1238 * that the connection went inactive ... not unlike "hangup".
1239 *
1240 * On return, the state is as if gserial_connect() had never been called;
1241 * there is no active USB I/O on these endpoints.
1242 */
1243void gserial_disconnect(struct gserial *gser)
1244{
1245 struct gs_port *port = gser->ioport;
1246 unsigned long flags;
1247
1248 if (!port)
1249 return;
1250
1251 /* tell the TTY glue not to do I/O here any more */
1252 spin_lock_irqsave(&port->port_lock, flags);
1253
1254 /* REVISIT as above: how best to track this? */
1255 port->port_line_coding = gser->port_line_coding;
1256
1257 port->port_usb = NULL;
1258 gser->ioport = NULL;
1259 if (port->port.count > 0 || port->openclose) {
1260 wake_up_interruptible(&port->drain_wait);
1261 if (port->port.tty)
1262 tty_hangup(port->port.tty);
1263 }
1264 spin_unlock_irqrestore(&port->port_lock, flags);
1265
1266 /* disable endpoints, aborting down any active I/O */
1267 usb_ep_disable(gser->out);
1268 gser->out->driver_data = NULL;
1269
1270 usb_ep_disable(gser->in);
1271 gser->in->driver_data = NULL;
1272
1273 /* finally, free any unused/unusable I/O buffers */
1274 spin_lock_irqsave(&port->port_lock, flags);
1275 if (port->port.count == 0 && !port->openclose)
1276 gs_buf_free(&port->port_write_buf);
1277 gs_free_requests(gser->out, &port->read_pool, NULL);
1278 gs_free_requests(gser->out, &port->read_queue, NULL);
1279 gs_free_requests(gser->in, &port->write_pool, NULL);
1280
1281 port->read_allocated = port->read_started =
1282 port->write_allocated = port->write_started = 0;
1283
1284 spin_unlock_irqrestore(&port->port_lock, flags);
1285}
1286EXPORT_SYMBOL_GPL(gserial_disconnect);
1287
1288static int userial_init(void)
1289{
1290 unsigned i;
1291 int status;
1292
1293 gs_tty_driver = alloc_tty_driver(MAX_U_SERIAL_PORTS);
1294 if (!gs_tty_driver)
1295 return -ENOMEM;
1296
1297 gs_tty_driver->driver_name = "g_serial";
1298 gs_tty_driver->name = PREFIX;
1299 /* uses dynamically assigned dev_t values */
1300
1301 gs_tty_driver->type = TTY_DRIVER_TYPE_SERIAL;
1302 gs_tty_driver->subtype = SERIAL_TYPE_NORMAL;
1303 gs_tty_driver->flags = TTY_DRIVER_REAL_RAW | TTY_DRIVER_DYNAMIC_DEV;
1304 gs_tty_driver->init_termios = tty_std_termios;
1305
1306 /* 9600-8-N-1 ... matches defaults expected by "usbser.sys" on
1307 * MS-Windows. Otherwise, most of these flags shouldn't affect
1308 * anything unless we were to actually hook up to a serial line.
1309 */
1310 gs_tty_driver->init_termios.c_cflag =
1311 B9600 | CS8 | CREAD | HUPCL | CLOCAL;
1312 gs_tty_driver->init_termios.c_ispeed = 9600;
1313 gs_tty_driver->init_termios.c_ospeed = 9600;
1314
1315 tty_set_operations(gs_tty_driver, &gs_tty_ops);
1316 for (i = 0; i < MAX_U_SERIAL_PORTS; i++)
1317 mutex_init(&ports[i].lock);
1318
1319 /* export the driver ... */
1320 status = tty_register_driver(gs_tty_driver);
1321 if (status) {
1322 pr_err("%s: cannot register, err %d\n",
1323 __func__, status);
1324 goto fail;
1325 }
1326
1327 pr_debug("%s: registered %d ttyGS* device%s\n", __func__,
1328 MAX_U_SERIAL_PORTS,
1329 (MAX_U_SERIAL_PORTS == 1) ? "" : "s");
1330
1331 return status;
1332fail:
1333 put_tty_driver(gs_tty_driver);
1334 gs_tty_driver = NULL;
1335 return status;
1336}
1337module_init(userial_init);
1338
1339static void userial_cleanup(void)
1340{
1341 tty_unregister_driver(gs_tty_driver);
1342 put_tty_driver(gs_tty_driver);
1343 gs_tty_driver = NULL;
1344}
1345module_exit(userial_cleanup);
1346
1347MODULE_LICENSE("GPL");
diff --git a/drivers/usb/gadget/function/u_serial.h b/drivers/usb/gadget/function/u_serial.h
new file mode 100644
index 000000000000..c20210c0babd
--- /dev/null
+++ b/drivers/usb/gadget/function/u_serial.h
@@ -0,0 +1,71 @@
1/*
2 * u_serial.h - interface to USB gadget "serial port"/TTY utilities
3 *
4 * Copyright (C) 2008 David Brownell
5 * Copyright (C) 2008 by Nokia Corporation
6 *
7 * This software is distributed under the terms of the GNU General
8 * Public License ("GPL") as published by the Free Software Foundation,
9 * either version 2 of that License or (at your option) any later version.
10 */
11
12#ifndef __U_SERIAL_H
13#define __U_SERIAL_H
14
15#include <linux/usb/composite.h>
16#include <linux/usb/cdc.h>
17
18#define MAX_U_SERIAL_PORTS 4
19
20struct f_serial_opts {
21 struct usb_function_instance func_inst;
22 u8 port_num;
23};
24
25/*
26 * One non-multiplexed "serial" I/O port ... there can be several of these
27 * on any given USB peripheral device, if it provides enough endpoints.
28 *
29 * The "u_serial" utility component exists to do one thing: manage TTY
30 * style I/O using the USB peripheral endpoints listed here, including
31 * hookups to sysfs and /dev for each logical "tty" device.
32 *
33 * REVISIT at least ACM could support tiocmget() if needed.
34 *
35 * REVISIT someday, allow multiplexing several TTYs over these endpoints.
36 */
37struct gserial {
38 struct usb_function func;
39
40 /* port is managed by gserial_{connect,disconnect} */
41 struct gs_port *ioport;
42
43 struct usb_ep *in;
44 struct usb_ep *out;
45
46 /* REVISIT avoid this CDC-ACM support harder ... */
47 struct usb_cdc_line_coding port_line_coding; /* 9600-8-N-1 etc */
48
49 /* notification callbacks */
50 void (*connect)(struct gserial *p);
51 void (*disconnect)(struct gserial *p);
52 int (*send_break)(struct gserial *p, int duration);
53};
54
55/* utilities to allocate/free request and buffer */
56struct usb_request *gs_alloc_req(struct usb_ep *ep, unsigned len, gfp_t flags);
57void gs_free_req(struct usb_ep *, struct usb_request *req);
58
59/* management of individual TTY ports */
60int gserial_alloc_line(unsigned char *port_line);
61void gserial_free_line(unsigned char port_line);
62
63/* connect/disconnect is handled by individual functions */
64int gserial_connect(struct gserial *, u8 port_num);
65void gserial_disconnect(struct gserial *);
66
67/* functions are bound to configurations by a config or gadget driver */
68int gser_bind_config(struct usb_configuration *c, u8 port_num);
69int obex_bind_config(struct usb_configuration *c, u8 port_num);
70
71#endif /* __U_SERIAL_H */
diff --git a/drivers/usb/gadget/function/u_uac1.c b/drivers/usb/gadget/function/u_uac1.c
new file mode 100644
index 000000000000..7a55fea43430
--- /dev/null
+++ b/drivers/usb/gadget/function/u_uac1.c
@@ -0,0 +1,330 @@
1/*
2 * u_uac1.c -- ALSA audio utilities for Gadget stack
3 *
4 * Copyright (C) 2008 Bryan Wu <cooloney@kernel.org>
5 * Copyright (C) 2008 Analog Devices, Inc
6 *
7 * Enter bugs at http://blackfin.uclinux.org/
8 *
9 * Licensed under the GPL-2 or later.
10 */
11
12#include <linux/kernel.h>
13#include <linux/slab.h>
14#include <linux/device.h>
15#include <linux/delay.h>
16#include <linux/ctype.h>
17#include <linux/random.h>
18#include <linux/syscalls.h>
19
20#include "u_uac1.h"
21
22/*
23 * This component encapsulates the ALSA devices for USB audio gadget
24 */
25
26#define FILE_PCM_PLAYBACK "/dev/snd/pcmC0D0p"
27#define FILE_PCM_CAPTURE "/dev/snd/pcmC0D0c"
28#define FILE_CONTROL "/dev/snd/controlC0"
29
30static char *fn_play = FILE_PCM_PLAYBACK;
31module_param(fn_play, charp, S_IRUGO);
32MODULE_PARM_DESC(fn_play, "Playback PCM device file name");
33
34static char *fn_cap = FILE_PCM_CAPTURE;
35module_param(fn_cap, charp, S_IRUGO);
36MODULE_PARM_DESC(fn_cap, "Capture PCM device file name");
37
38static char *fn_cntl = FILE_CONTROL;
39module_param(fn_cntl, charp, S_IRUGO);
40MODULE_PARM_DESC(fn_cntl, "Control device file name");
41
42/*-------------------------------------------------------------------------*/
43
44/**
45 * Some ALSA internal helper functions
46 */
47static int snd_interval_refine_set(struct snd_interval *i, unsigned int val)
48{
49 struct snd_interval t;
50 t.empty = 0;
51 t.min = t.max = val;
52 t.openmin = t.openmax = 0;
53 t.integer = 1;
54 return snd_interval_refine(i, &t);
55}
56
57static int _snd_pcm_hw_param_set(struct snd_pcm_hw_params *params,
58 snd_pcm_hw_param_t var, unsigned int val,
59 int dir)
60{
61 int changed;
62 if (hw_is_mask(var)) {
63 struct snd_mask *m = hw_param_mask(params, var);
64 if (val == 0 && dir < 0) {
65 changed = -EINVAL;
66 snd_mask_none(m);
67 } else {
68 if (dir > 0)
69 val++;
70 else if (dir < 0)
71 val--;
72 changed = snd_mask_refine_set(
73 hw_param_mask(params, var), val);
74 }
75 } else if (hw_is_interval(var)) {
76 struct snd_interval *i = hw_param_interval(params, var);
77 if (val == 0 && dir < 0) {
78 changed = -EINVAL;
79 snd_interval_none(i);
80 } else if (dir == 0)
81 changed = snd_interval_refine_set(i, val);
82 else {
83 struct snd_interval t;
84 t.openmin = 1;
85 t.openmax = 1;
86 t.empty = 0;
87 t.integer = 0;
88 if (dir < 0) {
89 t.min = val - 1;
90 t.max = val;
91 } else {
92 t.min = val;
93 t.max = val+1;
94 }
95 changed = snd_interval_refine(i, &t);
96 }
97 } else
98 return -EINVAL;
99 if (changed) {
100 params->cmask |= 1 << var;
101 params->rmask |= 1 << var;
102 }
103 return changed;
104}
105/*-------------------------------------------------------------------------*/
106
107/**
108 * Set default hardware params
109 */
110static int playback_default_hw_params(struct gaudio_snd_dev *snd)
111{
112 struct snd_pcm_substream *substream = snd->substream;
113 struct snd_pcm_hw_params *params;
114 snd_pcm_sframes_t result;
115
116 /*
117 * SNDRV_PCM_ACCESS_RW_INTERLEAVED,
118 * SNDRV_PCM_FORMAT_S16_LE
119 * CHANNELS: 2
120 * RATE: 48000
121 */
122 snd->access = SNDRV_PCM_ACCESS_RW_INTERLEAVED;
123 snd->format = SNDRV_PCM_FORMAT_S16_LE;
124 snd->channels = 2;
125 snd->rate = 48000;
126
127 params = kzalloc(sizeof(*params), GFP_KERNEL);
128 if (!params)
129 return -ENOMEM;
130
131 _snd_pcm_hw_params_any(params);
132 _snd_pcm_hw_param_set(params, SNDRV_PCM_HW_PARAM_ACCESS,
133 snd->access, 0);
134 _snd_pcm_hw_param_set(params, SNDRV_PCM_HW_PARAM_FORMAT,
135 snd->format, 0);
136 _snd_pcm_hw_param_set(params, SNDRV_PCM_HW_PARAM_CHANNELS,
137 snd->channels, 0);
138 _snd_pcm_hw_param_set(params, SNDRV_PCM_HW_PARAM_RATE,
139 snd->rate, 0);
140
141 snd_pcm_kernel_ioctl(substream, SNDRV_PCM_IOCTL_DROP, NULL);
142 snd_pcm_kernel_ioctl(substream, SNDRV_PCM_IOCTL_HW_PARAMS, params);
143
144 result = snd_pcm_kernel_ioctl(substream, SNDRV_PCM_IOCTL_PREPARE, NULL);
145 if (result < 0) {
146 ERROR(snd->card,
147 "Preparing sound card failed: %d\n", (int)result);
148 kfree(params);
149 return result;
150 }
151
152 /* Store the hardware parameters */
153 snd->access = params_access(params);
154 snd->format = params_format(params);
155 snd->channels = params_channels(params);
156 snd->rate = params_rate(params);
157
158 kfree(params);
159
160 INFO(snd->card,
161 "Hardware params: access %x, format %x, channels %d, rate %d\n",
162 snd->access, snd->format, snd->channels, snd->rate);
163
164 return 0;
165}
166
167/**
168 * Playback audio buffer data by ALSA PCM device
169 */
170static size_t u_audio_playback(struct gaudio *card, void *buf, size_t count)
171{
172 struct gaudio_snd_dev *snd = &card->playback;
173 struct snd_pcm_substream *substream = snd->substream;
174 struct snd_pcm_runtime *runtime = substream->runtime;
175 mm_segment_t old_fs;
176 ssize_t result;
177 snd_pcm_sframes_t frames;
178
179try_again:
180 if (runtime->status->state == SNDRV_PCM_STATE_XRUN ||
181 runtime->status->state == SNDRV_PCM_STATE_SUSPENDED) {
182 result = snd_pcm_kernel_ioctl(substream,
183 SNDRV_PCM_IOCTL_PREPARE, NULL);
184 if (result < 0) {
185 ERROR(card, "Preparing sound card failed: %d\n",
186 (int)result);
187 return result;
188 }
189 }
190
191 frames = bytes_to_frames(runtime, count);
192 old_fs = get_fs();
193 set_fs(KERNEL_DS);
194 result = snd_pcm_lib_write(snd->substream, (void __user *)buf, frames);
195 if (result != frames) {
196 ERROR(card, "Playback error: %d\n", (int)result);
197 set_fs(old_fs);
198 goto try_again;
199 }
200 set_fs(old_fs);
201
202 return 0;
203}
204
205static int u_audio_get_playback_channels(struct gaudio *card)
206{
207 return card->playback.channels;
208}
209
210static int u_audio_get_playback_rate(struct gaudio *card)
211{
212 return card->playback.rate;
213}
214
215/**
216 * Open ALSA PCM and control device files
217 * Initial the PCM or control device
218 */
219static int gaudio_open_snd_dev(struct gaudio *card)
220{
221 struct snd_pcm_file *pcm_file;
222 struct gaudio_snd_dev *snd;
223
224 if (!card)
225 return -ENODEV;
226
227 /* Open control device */
228 snd = &card->control;
229 snd->filp = filp_open(fn_cntl, O_RDWR, 0);
230 if (IS_ERR(snd->filp)) {
231 int ret = PTR_ERR(snd->filp);
232 ERROR(card, "unable to open sound control device file: %s\n",
233 fn_cntl);
234 snd->filp = NULL;
235 return ret;
236 }
237 snd->card = card;
238
239 /* Open PCM playback device and setup substream */
240 snd = &card->playback;
241 snd->filp = filp_open(fn_play, O_WRONLY, 0);
242 if (IS_ERR(snd->filp)) {
243 int ret = PTR_ERR(snd->filp);
244
245 ERROR(card, "No such PCM playback device: %s\n", fn_play);
246 snd->filp = NULL;
247 return ret;
248 }
249 pcm_file = snd->filp->private_data;
250 snd->substream = pcm_file->substream;
251 snd->card = card;
252 playback_default_hw_params(snd);
253
254 /* Open PCM capture device and setup substream */
255 snd = &card->capture;
256 snd->filp = filp_open(fn_cap, O_RDONLY, 0);
257 if (IS_ERR(snd->filp)) {
258 ERROR(card, "No such PCM capture device: %s\n", fn_cap);
259 snd->substream = NULL;
260 snd->card = NULL;
261 snd->filp = NULL;
262 } else {
263 pcm_file = snd->filp->private_data;
264 snd->substream = pcm_file->substream;
265 snd->card = card;
266 }
267
268 return 0;
269}
270
271/**
272 * Close ALSA PCM and control device files
273 */
274static int gaudio_close_snd_dev(struct gaudio *gau)
275{
276 struct gaudio_snd_dev *snd;
277
278 /* Close control device */
279 snd = &gau->control;
280 if (snd->filp)
281 filp_close(snd->filp, NULL);
282
283 /* Close PCM playback device and setup substream */
284 snd = &gau->playback;
285 if (snd->filp)
286 filp_close(snd->filp, NULL);
287
288 /* Close PCM capture device and setup substream */
289 snd = &gau->capture;
290 if (snd->filp)
291 filp_close(snd->filp, NULL);
292
293 return 0;
294}
295
296static struct gaudio *the_card;
297/**
298 * gaudio_setup - setup ALSA interface and preparing for USB transfer
299 *
300 * This sets up PCM, mixer or MIDI ALSA devices fore USB gadget using.
301 *
302 * Returns negative errno, or zero on success
303 */
304int __init gaudio_setup(struct gaudio *card)
305{
306 int ret;
307
308 ret = gaudio_open_snd_dev(card);
309 if (ret)
310 ERROR(card, "we need at least one control device\n");
311 else if (!the_card)
312 the_card = card;
313
314 return ret;
315
316}
317
318/**
319 * gaudio_cleanup - remove ALSA device interface
320 *
321 * This is called to free all resources allocated by @gaudio_setup().
322 */
323void gaudio_cleanup(void)
324{
325 if (the_card) {
326 gaudio_close_snd_dev(the_card);
327 the_card = NULL;
328 }
329}
330
diff --git a/drivers/usb/gadget/function/u_uac1.h b/drivers/usb/gadget/function/u_uac1.h
new file mode 100644
index 000000000000..18c2e729faf6
--- /dev/null
+++ b/drivers/usb/gadget/function/u_uac1.h
@@ -0,0 +1,56 @@
1/*
2 * u_uac1.h -- interface to USB gadget "ALSA AUDIO" utilities
3 *
4 * Copyright (C) 2008 Bryan Wu <cooloney@kernel.org>
5 * Copyright (C) 2008 Analog Devices, Inc
6 *
7 * Enter bugs at http://blackfin.uclinux.org/
8 *
9 * Licensed under the GPL-2 or later.
10 */
11
12#ifndef __U_AUDIO_H
13#define __U_AUDIO_H
14
15#include <linux/device.h>
16#include <linux/err.h>
17#include <linux/usb/audio.h>
18#include <linux/usb/composite.h>
19
20#include <sound/core.h>
21#include <sound/pcm.h>
22#include <sound/pcm_params.h>
23
24#include "gadget_chips.h"
25
26/*
27 * This represents the USB side of an audio card device, managed by a USB
28 * function which provides control and stream interfaces.
29 */
30
31struct gaudio_snd_dev {
32 struct gaudio *card;
33 struct file *filp;
34 struct snd_pcm_substream *substream;
35 int access;
36 int format;
37 int channels;
38 int rate;
39};
40
41struct gaudio {
42 struct usb_function func;
43 struct usb_gadget *gadget;
44
45 /* ALSA sound device interfaces */
46 struct gaudio_snd_dev control;
47 struct gaudio_snd_dev playback;
48 struct gaudio_snd_dev capture;
49
50 /* TODO */
51};
52
53int gaudio_setup(struct gaudio *card);
54void gaudio_cleanup(void);
55
56#endif /* __U_AUDIO_H */
diff --git a/drivers/usb/gadget/function/uvc.h b/drivers/usb/gadget/function/uvc.h
new file mode 100644
index 000000000000..7a9111de8054
--- /dev/null
+++ b/drivers/usb/gadget/function/uvc.h
@@ -0,0 +1,202 @@
1/*
2 * uvc_gadget.h -- USB Video Class Gadget driver
3 *
4 * Copyright (C) 2009-2010
5 * Laurent Pinchart (laurent.pinchart@ideasonboard.com)
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 */
12
13#ifndef _UVC_GADGET_H_
14#define _UVC_GADGET_H_
15
16#include <linux/ioctl.h>
17#include <linux/types.h>
18#include <linux/usb/ch9.h>
19
20#define UVC_EVENT_FIRST (V4L2_EVENT_PRIVATE_START + 0)
21#define UVC_EVENT_CONNECT (V4L2_EVENT_PRIVATE_START + 0)
22#define UVC_EVENT_DISCONNECT (V4L2_EVENT_PRIVATE_START + 1)
23#define UVC_EVENT_STREAMON (V4L2_EVENT_PRIVATE_START + 2)
24#define UVC_EVENT_STREAMOFF (V4L2_EVENT_PRIVATE_START + 3)
25#define UVC_EVENT_SETUP (V4L2_EVENT_PRIVATE_START + 4)
26#define UVC_EVENT_DATA (V4L2_EVENT_PRIVATE_START + 5)
27#define UVC_EVENT_LAST (V4L2_EVENT_PRIVATE_START + 5)
28
29struct uvc_request_data
30{
31 __s32 length;
32 __u8 data[60];
33};
34
35struct uvc_event
36{
37 union {
38 enum usb_device_speed speed;
39 struct usb_ctrlrequest req;
40 struct uvc_request_data data;
41 };
42};
43
44#define UVCIOC_SEND_RESPONSE _IOW('U', 1, struct uvc_request_data)
45
46#define UVC_INTF_CONTROL 0
47#define UVC_INTF_STREAMING 1
48
49/* ------------------------------------------------------------------------
50 * Debugging, printing and logging
51 */
52
53#ifdef __KERNEL__
54
55#include <linux/usb.h> /* For usb_endpoint_* */
56#include <linux/usb/gadget.h>
57#include <linux/videodev2.h>
58#include <linux/version.h>
59#include <media/v4l2-fh.h>
60#include <media/v4l2-device.h>
61
62#include "uvc_queue.h"
63
64#define UVC_TRACE_PROBE (1 << 0)
65#define UVC_TRACE_DESCR (1 << 1)
66#define UVC_TRACE_CONTROL (1 << 2)
67#define UVC_TRACE_FORMAT (1 << 3)
68#define UVC_TRACE_CAPTURE (1 << 4)
69#define UVC_TRACE_CALLS (1 << 5)
70#define UVC_TRACE_IOCTL (1 << 6)
71#define UVC_TRACE_FRAME (1 << 7)
72#define UVC_TRACE_SUSPEND (1 << 8)
73#define UVC_TRACE_STATUS (1 << 9)
74
75#define UVC_WARN_MINMAX 0
76#define UVC_WARN_PROBE_DEF 1
77
78extern unsigned int uvc_gadget_trace_param;
79
80#define uvc_trace(flag, msg...) \
81 do { \
82 if (uvc_gadget_trace_param & flag) \
83 printk(KERN_DEBUG "uvcvideo: " msg); \
84 } while (0)
85
86#define uvc_warn_once(dev, warn, msg...) \
87 do { \
88 if (!test_and_set_bit(warn, &dev->warnings)) \
89 printk(KERN_INFO "uvcvideo: " msg); \
90 } while (0)
91
92#define uvc_printk(level, msg...) \
93 printk(level "uvcvideo: " msg)
94
95/* ------------------------------------------------------------------------
96 * Driver specific constants
97 */
98
99#define DRIVER_VERSION "0.1.0"
100#define DRIVER_VERSION_NUMBER KERNEL_VERSION(0, 1, 0)
101
102#define UVC_NUM_REQUESTS 4
103#define UVC_MAX_REQUEST_SIZE 64
104#define UVC_MAX_EVENTS 4
105
106/* ------------------------------------------------------------------------
107 * Structures
108 */
109
110struct uvc_video
111{
112 struct usb_ep *ep;
113
114 /* Frame parameters */
115 u8 bpp;
116 u32 fcc;
117 unsigned int width;
118 unsigned int height;
119 unsigned int imagesize;
120
121 /* Requests */
122 unsigned int req_size;
123 struct usb_request *req[UVC_NUM_REQUESTS];
124 __u8 *req_buffer[UVC_NUM_REQUESTS];
125 struct list_head req_free;
126 spinlock_t req_lock;
127
128 void (*encode) (struct usb_request *req, struct uvc_video *video,
129 struct uvc_buffer *buf);
130
131 /* Context data used by the completion handler */
132 __u32 payload_size;
133 __u32 max_payload_size;
134
135 struct uvc_video_queue queue;
136 unsigned int fid;
137};
138
139enum uvc_state
140{
141 UVC_STATE_DISCONNECTED,
142 UVC_STATE_CONNECTED,
143 UVC_STATE_STREAMING,
144};
145
146struct uvc_device
147{
148 struct video_device *vdev;
149 struct v4l2_device v4l2_dev;
150 enum uvc_state state;
151 struct usb_function func;
152 struct uvc_video video;
153
154 /* Descriptors */
155 struct {
156 const struct uvc_descriptor_header * const *fs_control;
157 const struct uvc_descriptor_header * const *ss_control;
158 const struct uvc_descriptor_header * const *fs_streaming;
159 const struct uvc_descriptor_header * const *hs_streaming;
160 const struct uvc_descriptor_header * const *ss_streaming;
161 } desc;
162
163 unsigned int control_intf;
164 struct usb_ep *control_ep;
165 struct usb_request *control_req;
166 void *control_buf;
167
168 unsigned int streaming_intf;
169
170 /* Events */
171 unsigned int event_length;
172 unsigned int event_setup_out : 1;
173};
174
175static inline struct uvc_device *to_uvc(struct usb_function *f)
176{
177 return container_of(f, struct uvc_device, func);
178}
179
180struct uvc_file_handle
181{
182 struct v4l2_fh vfh;
183 struct uvc_video *device;
184};
185
186#define to_uvc_file_handle(handle) \
187 container_of(handle, struct uvc_file_handle, vfh)
188
189/* ------------------------------------------------------------------------
190 * Functions
191 */
192
193extern void uvc_function_setup_continue(struct uvc_device *uvc);
194extern void uvc_endpoint_stream(struct uvc_device *dev);
195
196extern void uvc_function_connect(struct uvc_device *uvc);
197extern void uvc_function_disconnect(struct uvc_device *uvc);
198
199#endif /* __KERNEL__ */
200
201#endif /* _UVC_GADGET_H_ */
202
diff --git a/drivers/usb/gadget/function/uvc_queue.c b/drivers/usb/gadget/function/uvc_queue.c
new file mode 100644
index 000000000000..1c29bc954db9
--- /dev/null
+++ b/drivers/usb/gadget/function/uvc_queue.c
@@ -0,0 +1,407 @@
1/*
2 * uvc_queue.c -- USB Video Class driver - Buffers management
3 *
4 * Copyright (C) 2005-2010
5 * Laurent Pinchart (laurent.pinchart@ideasonboard.com)
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 */
12
13#include <linux/atomic.h>
14#include <linux/kernel.h>
15#include <linux/mm.h>
16#include <linux/list.h>
17#include <linux/module.h>
18#include <linux/usb.h>
19#include <linux/videodev2.h>
20#include <linux/vmalloc.h>
21#include <linux/wait.h>
22
23#include <media/v4l2-common.h>
24#include <media/videobuf2-vmalloc.h>
25
26#include "uvc.h"
27
28/* ------------------------------------------------------------------------
29 * Video buffers queue management.
30 *
31 * Video queues is initialized by uvc_queue_init(). The function performs
32 * basic initialization of the uvc_video_queue struct and never fails.
33 *
34 * Video buffers are managed by videobuf2. The driver uses a mutex to protect
35 * the videobuf2 queue operations by serializing calls to videobuf2 and a
36 * spinlock to protect the IRQ queue that holds the buffers to be processed by
37 * the driver.
38 */
39
40/* -----------------------------------------------------------------------------
41 * videobuf2 queue operations
42 */
43
44static int uvc_queue_setup(struct vb2_queue *vq, const struct v4l2_format *fmt,
45 unsigned int *nbuffers, unsigned int *nplanes,
46 unsigned int sizes[], void *alloc_ctxs[])
47{
48 struct uvc_video_queue *queue = vb2_get_drv_priv(vq);
49 struct uvc_video *video = container_of(queue, struct uvc_video, queue);
50
51 if (*nbuffers > UVC_MAX_VIDEO_BUFFERS)
52 *nbuffers = UVC_MAX_VIDEO_BUFFERS;
53
54 *nplanes = 1;
55
56 sizes[0] = video->imagesize;
57
58 return 0;
59}
60
61static int uvc_buffer_prepare(struct vb2_buffer *vb)
62{
63 struct uvc_video_queue *queue = vb2_get_drv_priv(vb->vb2_queue);
64 struct uvc_buffer *buf = container_of(vb, struct uvc_buffer, buf);
65
66 if (vb->v4l2_buf.type == V4L2_BUF_TYPE_VIDEO_OUTPUT &&
67 vb2_get_plane_payload(vb, 0) > vb2_plane_size(vb, 0)) {
68 uvc_trace(UVC_TRACE_CAPTURE, "[E] Bytes used out of bounds.\n");
69 return -EINVAL;
70 }
71
72 if (unlikely(queue->flags & UVC_QUEUE_DISCONNECTED))
73 return -ENODEV;
74
75 buf->state = UVC_BUF_STATE_QUEUED;
76 buf->mem = vb2_plane_vaddr(vb, 0);
77 buf->length = vb2_plane_size(vb, 0);
78 if (vb->v4l2_buf.type == V4L2_BUF_TYPE_VIDEO_CAPTURE)
79 buf->bytesused = 0;
80 else
81 buf->bytesused = vb2_get_plane_payload(vb, 0);
82
83 return 0;
84}
85
86static void uvc_buffer_queue(struct vb2_buffer *vb)
87{
88 struct uvc_video_queue *queue = vb2_get_drv_priv(vb->vb2_queue);
89 struct uvc_buffer *buf = container_of(vb, struct uvc_buffer, buf);
90 unsigned long flags;
91
92 spin_lock_irqsave(&queue->irqlock, flags);
93
94 if (likely(!(queue->flags & UVC_QUEUE_DISCONNECTED))) {
95 list_add_tail(&buf->queue, &queue->irqqueue);
96 } else {
97 /* If the device is disconnected return the buffer to userspace
98 * directly. The next QBUF call will fail with -ENODEV.
99 */
100 buf->state = UVC_BUF_STATE_ERROR;
101 vb2_buffer_done(&buf->buf, VB2_BUF_STATE_ERROR);
102 }
103
104 spin_unlock_irqrestore(&queue->irqlock, flags);
105}
106
107static void uvc_wait_prepare(struct vb2_queue *vq)
108{
109 struct uvc_video_queue *queue = vb2_get_drv_priv(vq);
110
111 mutex_unlock(&queue->mutex);
112}
113
114static void uvc_wait_finish(struct vb2_queue *vq)
115{
116 struct uvc_video_queue *queue = vb2_get_drv_priv(vq);
117
118 mutex_lock(&queue->mutex);
119}
120
121static struct vb2_ops uvc_queue_qops = {
122 .queue_setup = uvc_queue_setup,
123 .buf_prepare = uvc_buffer_prepare,
124 .buf_queue = uvc_buffer_queue,
125 .wait_prepare = uvc_wait_prepare,
126 .wait_finish = uvc_wait_finish,
127};
128
129static int uvc_queue_init(struct uvc_video_queue *queue,
130 enum v4l2_buf_type type)
131{
132 int ret;
133
134 queue->queue.type = type;
135 queue->queue.io_modes = VB2_MMAP | VB2_USERPTR;
136 queue->queue.drv_priv = queue;
137 queue->queue.buf_struct_size = sizeof(struct uvc_buffer);
138 queue->queue.ops = &uvc_queue_qops;
139 queue->queue.mem_ops = &vb2_vmalloc_memops;
140 queue->queue.timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC
141 | V4L2_BUF_FLAG_TSTAMP_SRC_EOF;
142 ret = vb2_queue_init(&queue->queue);
143 if (ret)
144 return ret;
145
146 mutex_init(&queue->mutex);
147 spin_lock_init(&queue->irqlock);
148 INIT_LIST_HEAD(&queue->irqqueue);
149 queue->flags = 0;
150
151 return 0;
152}
153
154/*
155 * Free the video buffers.
156 */
157static void uvc_free_buffers(struct uvc_video_queue *queue)
158{
159 mutex_lock(&queue->mutex);
160 vb2_queue_release(&queue->queue);
161 mutex_unlock(&queue->mutex);
162}
163
164/*
165 * Allocate the video buffers.
166 */
167static int uvc_alloc_buffers(struct uvc_video_queue *queue,
168 struct v4l2_requestbuffers *rb)
169{
170 int ret;
171
172 mutex_lock(&queue->mutex);
173 ret = vb2_reqbufs(&queue->queue, rb);
174 mutex_unlock(&queue->mutex);
175
176 return ret ? ret : rb->count;
177}
178
179static int uvc_query_buffer(struct uvc_video_queue *queue,
180 struct v4l2_buffer *buf)
181{
182 int ret;
183
184 mutex_lock(&queue->mutex);
185 ret = vb2_querybuf(&queue->queue, buf);
186 mutex_unlock(&queue->mutex);
187
188 return ret;
189}
190
191static int uvc_queue_buffer(struct uvc_video_queue *queue,
192 struct v4l2_buffer *buf)
193{
194 unsigned long flags;
195 int ret;
196
197 mutex_lock(&queue->mutex);
198 ret = vb2_qbuf(&queue->queue, buf);
199 if (ret < 0)
200 goto done;
201
202 spin_lock_irqsave(&queue->irqlock, flags);
203 ret = (queue->flags & UVC_QUEUE_PAUSED) != 0;
204 queue->flags &= ~UVC_QUEUE_PAUSED;
205 spin_unlock_irqrestore(&queue->irqlock, flags);
206
207done:
208 mutex_unlock(&queue->mutex);
209 return ret;
210}
211
212/*
213 * Dequeue a video buffer. If nonblocking is false, block until a buffer is
214 * available.
215 */
216static int uvc_dequeue_buffer(struct uvc_video_queue *queue,
217 struct v4l2_buffer *buf, int nonblocking)
218{
219 int ret;
220
221 mutex_lock(&queue->mutex);
222 ret = vb2_dqbuf(&queue->queue, buf, nonblocking);
223 mutex_unlock(&queue->mutex);
224
225 return ret;
226}
227
228/*
229 * Poll the video queue.
230 *
231 * This function implements video queue polling and is intended to be used by
232 * the device poll handler.
233 */
234static unsigned int uvc_queue_poll(struct uvc_video_queue *queue,
235 struct file *file, poll_table *wait)
236{
237 unsigned int ret;
238
239 mutex_lock(&queue->mutex);
240 ret = vb2_poll(&queue->queue, file, wait);
241 mutex_unlock(&queue->mutex);
242
243 return ret;
244}
245
246static int uvc_queue_mmap(struct uvc_video_queue *queue,
247 struct vm_area_struct *vma)
248{
249 int ret;
250
251 mutex_lock(&queue->mutex);
252 ret = vb2_mmap(&queue->queue, vma);
253 mutex_unlock(&queue->mutex);
254
255 return ret;
256}
257
258#ifndef CONFIG_MMU
259/*
260 * Get unmapped area.
261 *
262 * NO-MMU arch need this function to make mmap() work correctly.
263 */
264static unsigned long uvc_queue_get_unmapped_area(struct uvc_video_queue *queue,
265 unsigned long pgoff)
266{
267 unsigned long ret;
268
269 mutex_lock(&queue->mutex);
270 ret = vb2_get_unmapped_area(&queue->queue, 0, 0, pgoff, 0);
271 mutex_unlock(&queue->mutex);
272 return ret;
273}
274#endif
275
276/*
277 * Cancel the video buffers queue.
278 *
279 * Cancelling the queue marks all buffers on the irq queue as erroneous,
280 * wakes them up and removes them from the queue.
281 *
282 * If the disconnect parameter is set, further calls to uvc_queue_buffer will
283 * fail with -ENODEV.
284 *
285 * This function acquires the irq spinlock and can be called from interrupt
286 * context.
287 */
288static void uvc_queue_cancel(struct uvc_video_queue *queue, int disconnect)
289{
290 struct uvc_buffer *buf;
291 unsigned long flags;
292
293 spin_lock_irqsave(&queue->irqlock, flags);
294 while (!list_empty(&queue->irqqueue)) {
295 buf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
296 queue);
297 list_del(&buf->queue);
298 buf->state = UVC_BUF_STATE_ERROR;
299 vb2_buffer_done(&buf->buf, VB2_BUF_STATE_ERROR);
300 }
301 /* This must be protected by the irqlock spinlock to avoid race
302 * conditions between uvc_queue_buffer and the disconnection event that
303 * could result in an interruptible wait in uvc_dequeue_buffer. Do not
304 * blindly replace this logic by checking for the UVC_DEV_DISCONNECTED
305 * state outside the queue code.
306 */
307 if (disconnect)
308 queue->flags |= UVC_QUEUE_DISCONNECTED;
309 spin_unlock_irqrestore(&queue->irqlock, flags);
310}
311
312/*
313 * Enable or disable the video buffers queue.
314 *
315 * The queue must be enabled before starting video acquisition and must be
316 * disabled after stopping it. This ensures that the video buffers queue
317 * state can be properly initialized before buffers are accessed from the
318 * interrupt handler.
319 *
320 * Enabling the video queue initializes parameters (such as sequence number,
321 * sync pattern, ...). If the queue is already enabled, return -EBUSY.
322 *
323 * Disabling the video queue cancels the queue and removes all buffers from
324 * the main queue.
325 *
326 * This function can't be called from interrupt context. Use
327 * uvc_queue_cancel() instead.
328 */
329static int uvc_queue_enable(struct uvc_video_queue *queue, int enable)
330{
331 unsigned long flags;
332 int ret = 0;
333
334 mutex_lock(&queue->mutex);
335 if (enable) {
336 ret = vb2_streamon(&queue->queue, queue->queue.type);
337 if (ret < 0)
338 goto done;
339
340 queue->sequence = 0;
341 queue->buf_used = 0;
342 } else {
343 ret = vb2_streamoff(&queue->queue, queue->queue.type);
344 if (ret < 0)
345 goto done;
346
347 spin_lock_irqsave(&queue->irqlock, flags);
348 INIT_LIST_HEAD(&queue->irqqueue);
349
350 /*
351 * FIXME: We need to clear the DISCONNECTED flag to ensure that
352 * applications will be able to queue buffers for the next
353 * streaming run. However, clearing it here doesn't guarantee
354 * that the device will be reconnected in the meantime.
355 */
356 queue->flags &= ~UVC_QUEUE_DISCONNECTED;
357 spin_unlock_irqrestore(&queue->irqlock, flags);
358 }
359
360done:
361 mutex_unlock(&queue->mutex);
362 return ret;
363}
364
365/* called with &queue_irqlock held.. */
366static struct uvc_buffer *uvc_queue_next_buffer(struct uvc_video_queue *queue,
367 struct uvc_buffer *buf)
368{
369 struct uvc_buffer *nextbuf;
370
371 if ((queue->flags & UVC_QUEUE_DROP_INCOMPLETE) &&
372 buf->length != buf->bytesused) {
373 buf->state = UVC_BUF_STATE_QUEUED;
374 vb2_set_plane_payload(&buf->buf, 0, 0);
375 return buf;
376 }
377
378 list_del(&buf->queue);
379 if (!list_empty(&queue->irqqueue))
380 nextbuf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
381 queue);
382 else
383 nextbuf = NULL;
384
385 buf->buf.v4l2_buf.field = V4L2_FIELD_NONE;
386 buf->buf.v4l2_buf.sequence = queue->sequence++;
387 v4l2_get_timestamp(&buf->buf.v4l2_buf.timestamp);
388
389 vb2_set_plane_payload(&buf->buf, 0, buf->bytesused);
390 vb2_buffer_done(&buf->buf, VB2_BUF_STATE_DONE);
391
392 return nextbuf;
393}
394
395static struct uvc_buffer *uvc_queue_head(struct uvc_video_queue *queue)
396{
397 struct uvc_buffer *buf = NULL;
398
399 if (!list_empty(&queue->irqqueue))
400 buf = list_first_entry(&queue->irqqueue, struct uvc_buffer,
401 queue);
402 else
403 queue->flags |= UVC_QUEUE_PAUSED;
404
405 return buf;
406}
407
diff --git a/drivers/usb/gadget/function/uvc_queue.h b/drivers/usb/gadget/function/uvc_queue.h
new file mode 100644
index 000000000000..8e76ce982f1e
--- /dev/null
+++ b/drivers/usb/gadget/function/uvc_queue.h
@@ -0,0 +1,63 @@
1#ifndef _UVC_QUEUE_H_
2#define _UVC_QUEUE_H_
3
4#ifdef __KERNEL__
5
6#include <linux/kernel.h>
7#include <linux/poll.h>
8#include <linux/videodev2.h>
9#include <media/videobuf2-core.h>
10
11/* Maximum frame size in bytes, for sanity checking. */
12#define UVC_MAX_FRAME_SIZE (16*1024*1024)
13/* Maximum number of video buffers. */
14#define UVC_MAX_VIDEO_BUFFERS 32
15
16/* ------------------------------------------------------------------------
17 * Structures.
18 */
19
20enum uvc_buffer_state {
21 UVC_BUF_STATE_IDLE = 0,
22 UVC_BUF_STATE_QUEUED = 1,
23 UVC_BUF_STATE_ACTIVE = 2,
24 UVC_BUF_STATE_DONE = 3,
25 UVC_BUF_STATE_ERROR = 4,
26};
27
28struct uvc_buffer {
29 struct vb2_buffer buf;
30 struct list_head queue;
31
32 enum uvc_buffer_state state;
33 void *mem;
34 unsigned int length;
35 unsigned int bytesused;
36};
37
38#define UVC_QUEUE_DISCONNECTED (1 << 0)
39#define UVC_QUEUE_DROP_INCOMPLETE (1 << 1)
40#define UVC_QUEUE_PAUSED (1 << 2)
41
42struct uvc_video_queue {
43 struct vb2_queue queue;
44 struct mutex mutex; /* Protects queue */
45
46 unsigned int flags;
47 __u32 sequence;
48
49 unsigned int buf_used;
50
51 spinlock_t irqlock; /* Protects flags and irqqueue */
52 struct list_head irqqueue;
53};
54
55static inline int uvc_queue_streaming(struct uvc_video_queue *queue)
56{
57 return vb2_is_streaming(&queue->queue);
58}
59
60#endif /* __KERNEL__ */
61
62#endif /* _UVC_QUEUE_H_ */
63
diff --git a/drivers/usb/gadget/function/uvc_v4l2.c b/drivers/usb/gadget/function/uvc_v4l2.c
new file mode 100644
index 000000000000..ad48e81155e2
--- /dev/null
+++ b/drivers/usb/gadget/function/uvc_v4l2.c
@@ -0,0 +1,365 @@
1/*
2 * uvc_v4l2.c -- USB Video Class Gadget driver
3 *
4 * Copyright (C) 2009-2010
5 * Laurent Pinchart (laurent.pinchart@ideasonboard.com)
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 */
12
13#include <linux/kernel.h>
14#include <linux/device.h>
15#include <linux/errno.h>
16#include <linux/list.h>
17#include <linux/mutex.h>
18#include <linux/videodev2.h>
19#include <linux/vmalloc.h>
20#include <linux/wait.h>
21
22#include <media/v4l2-dev.h>
23#include <media/v4l2-event.h>
24#include <media/v4l2-ioctl.h>
25
26#include "uvc.h"
27#include "uvc_queue.h"
28
29/* --------------------------------------------------------------------------
30 * Requests handling
31 */
32
33static int
34uvc_send_response(struct uvc_device *uvc, struct uvc_request_data *data)
35{
36 struct usb_composite_dev *cdev = uvc->func.config->cdev;
37 struct usb_request *req = uvc->control_req;
38
39 if (data->length < 0)
40 return usb_ep_set_halt(cdev->gadget->ep0);
41
42 req->length = min_t(unsigned int, uvc->event_length, data->length);
43 req->zero = data->length < uvc->event_length;
44
45 memcpy(req->buf, data->data, req->length);
46
47 return usb_ep_queue(cdev->gadget->ep0, req, GFP_KERNEL);
48}
49
50/* --------------------------------------------------------------------------
51 * V4L2
52 */
53
54struct uvc_format
55{
56 u8 bpp;
57 u32 fcc;
58};
59
60static struct uvc_format uvc_formats[] = {
61 { 16, V4L2_PIX_FMT_YUYV },
62 { 0, V4L2_PIX_FMT_MJPEG },
63};
64
65static int
66uvc_v4l2_get_format(struct uvc_video *video, struct v4l2_format *fmt)
67{
68 fmt->fmt.pix.pixelformat = video->fcc;
69 fmt->fmt.pix.width = video->width;
70 fmt->fmt.pix.height = video->height;
71 fmt->fmt.pix.field = V4L2_FIELD_NONE;
72 fmt->fmt.pix.bytesperline = video->bpp * video->width / 8;
73 fmt->fmt.pix.sizeimage = video->imagesize;
74 fmt->fmt.pix.colorspace = V4L2_COLORSPACE_SRGB;
75 fmt->fmt.pix.priv = 0;
76
77 return 0;
78}
79
80static int
81uvc_v4l2_set_format(struct uvc_video *video, struct v4l2_format *fmt)
82{
83 struct uvc_format *format;
84 unsigned int imagesize;
85 unsigned int bpl;
86 unsigned int i;
87
88 for (i = 0; i < ARRAY_SIZE(uvc_formats); ++i) {
89 format = &uvc_formats[i];
90 if (format->fcc == fmt->fmt.pix.pixelformat)
91 break;
92 }
93
94 if (i == ARRAY_SIZE(uvc_formats)) {
95 printk(KERN_INFO "Unsupported format 0x%08x.\n",
96 fmt->fmt.pix.pixelformat);
97 return -EINVAL;
98 }
99
100 bpl = format->bpp * fmt->fmt.pix.width / 8;
101 imagesize = bpl ? bpl * fmt->fmt.pix.height : fmt->fmt.pix.sizeimage;
102
103 video->fcc = format->fcc;
104 video->bpp = format->bpp;
105 video->width = fmt->fmt.pix.width;
106 video->height = fmt->fmt.pix.height;
107 video->imagesize = imagesize;
108
109 fmt->fmt.pix.field = V4L2_FIELD_NONE;
110 fmt->fmt.pix.bytesperline = bpl;
111 fmt->fmt.pix.sizeimage = imagesize;
112 fmt->fmt.pix.colorspace = V4L2_COLORSPACE_SRGB;
113 fmt->fmt.pix.priv = 0;
114
115 return 0;
116}
117
118static int
119uvc_v4l2_open(struct file *file)
120{
121 struct video_device *vdev = video_devdata(file);
122 struct uvc_device *uvc = video_get_drvdata(vdev);
123 struct uvc_file_handle *handle;
124
125 handle = kzalloc(sizeof(*handle), GFP_KERNEL);
126 if (handle == NULL)
127 return -ENOMEM;
128
129 v4l2_fh_init(&handle->vfh, vdev);
130 v4l2_fh_add(&handle->vfh);
131
132 handle->device = &uvc->video;
133 file->private_data = &handle->vfh;
134
135 uvc_function_connect(uvc);
136 return 0;
137}
138
139static int
140uvc_v4l2_release(struct file *file)
141{
142 struct video_device *vdev = video_devdata(file);
143 struct uvc_device *uvc = video_get_drvdata(vdev);
144 struct uvc_file_handle *handle = to_uvc_file_handle(file->private_data);
145 struct uvc_video *video = handle->device;
146
147 uvc_function_disconnect(uvc);
148
149 uvc_video_enable(video, 0);
150 uvc_free_buffers(&video->queue);
151
152 file->private_data = NULL;
153 v4l2_fh_del(&handle->vfh);
154 v4l2_fh_exit(&handle->vfh);
155 kfree(handle);
156
157 return 0;
158}
159
160static long
161uvc_v4l2_do_ioctl(struct file *file, unsigned int cmd, void *arg)
162{
163 struct video_device *vdev = video_devdata(file);
164 struct uvc_device *uvc = video_get_drvdata(vdev);
165 struct uvc_file_handle *handle = to_uvc_file_handle(file->private_data);
166 struct usb_composite_dev *cdev = uvc->func.config->cdev;
167 struct uvc_video *video = &uvc->video;
168 int ret = 0;
169
170 switch (cmd) {
171 /* Query capabilities */
172 case VIDIOC_QUERYCAP:
173 {
174 struct v4l2_capability *cap = arg;
175
176 memset(cap, 0, sizeof *cap);
177 strlcpy(cap->driver, "g_uvc", sizeof(cap->driver));
178 strlcpy(cap->card, cdev->gadget->name, sizeof(cap->card));
179 strlcpy(cap->bus_info, dev_name(&cdev->gadget->dev),
180 sizeof cap->bus_info);
181 cap->version = DRIVER_VERSION_NUMBER;
182 cap->capabilities = V4L2_CAP_VIDEO_OUTPUT | V4L2_CAP_STREAMING;
183 break;
184 }
185
186 /* Get & Set format */
187 case VIDIOC_G_FMT:
188 {
189 struct v4l2_format *fmt = arg;
190
191 if (fmt->type != video->queue.queue.type)
192 return -EINVAL;
193
194 return uvc_v4l2_get_format(video, fmt);
195 }
196
197 case VIDIOC_S_FMT:
198 {
199 struct v4l2_format *fmt = arg;
200
201 if (fmt->type != video->queue.queue.type)
202 return -EINVAL;
203
204 return uvc_v4l2_set_format(video, fmt);
205 }
206
207 /* Buffers & streaming */
208 case VIDIOC_REQBUFS:
209 {
210 struct v4l2_requestbuffers *rb = arg;
211
212 if (rb->type != video->queue.queue.type)
213 return -EINVAL;
214
215 ret = uvc_alloc_buffers(&video->queue, rb);
216 if (ret < 0)
217 return ret;
218
219 ret = 0;
220 break;
221 }
222
223 case VIDIOC_QUERYBUF:
224 {
225 struct v4l2_buffer *buf = arg;
226
227 return uvc_query_buffer(&video->queue, buf);
228 }
229
230 case VIDIOC_QBUF:
231 if ((ret = uvc_queue_buffer(&video->queue, arg)) < 0)
232 return ret;
233
234 return uvc_video_pump(video);
235
236 case VIDIOC_DQBUF:
237 return uvc_dequeue_buffer(&video->queue, arg,
238 file->f_flags & O_NONBLOCK);
239
240 case VIDIOC_STREAMON:
241 {
242 int *type = arg;
243
244 if (*type != video->queue.queue.type)
245 return -EINVAL;
246
247 /* Enable UVC video. */
248 ret = uvc_video_enable(video, 1);
249 if (ret < 0)
250 return ret;
251
252 /*
253 * Complete the alternate setting selection setup phase now that
254 * userspace is ready to provide video frames.
255 */
256 uvc_function_setup_continue(uvc);
257 uvc->state = UVC_STATE_STREAMING;
258
259 return 0;
260 }
261
262 case VIDIOC_STREAMOFF:
263 {
264 int *type = arg;
265
266 if (*type != video->queue.queue.type)
267 return -EINVAL;
268
269 return uvc_video_enable(video, 0);
270 }
271
272 /* Events */
273 case VIDIOC_DQEVENT:
274 {
275 struct v4l2_event *event = arg;
276
277 ret = v4l2_event_dequeue(&handle->vfh, event,
278 file->f_flags & O_NONBLOCK);
279 if (ret == 0 && event->type == UVC_EVENT_SETUP) {
280 struct uvc_event *uvc_event = (void *)&event->u.data;
281
282 /* Tell the complete callback to generate an event for
283 * the next request that will be enqueued by
284 * uvc_event_write.
285 */
286 uvc->event_setup_out =
287 !(uvc_event->req.bRequestType & USB_DIR_IN);
288 uvc->event_length = uvc_event->req.wLength;
289 }
290
291 return ret;
292 }
293
294 case VIDIOC_SUBSCRIBE_EVENT:
295 {
296 struct v4l2_event_subscription *sub = arg;
297
298 if (sub->type < UVC_EVENT_FIRST || sub->type > UVC_EVENT_LAST)
299 return -EINVAL;
300
301 return v4l2_event_subscribe(&handle->vfh, arg, 2, NULL);
302 }
303
304 case VIDIOC_UNSUBSCRIBE_EVENT:
305 return v4l2_event_unsubscribe(&handle->vfh, arg);
306
307 case UVCIOC_SEND_RESPONSE:
308 ret = uvc_send_response(uvc, arg);
309 break;
310
311 default:
312 return -ENOIOCTLCMD;
313 }
314
315 return ret;
316}
317
318static long
319uvc_v4l2_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
320{
321 return video_usercopy(file, cmd, arg, uvc_v4l2_do_ioctl);
322}
323
324static int
325uvc_v4l2_mmap(struct file *file, struct vm_area_struct *vma)
326{
327 struct video_device *vdev = video_devdata(file);
328 struct uvc_device *uvc = video_get_drvdata(vdev);
329
330 return uvc_queue_mmap(&uvc->video.queue, vma);
331}
332
333static unsigned int
334uvc_v4l2_poll(struct file *file, poll_table *wait)
335{
336 struct video_device *vdev = video_devdata(file);
337 struct uvc_device *uvc = video_get_drvdata(vdev);
338
339 return uvc_queue_poll(&uvc->video.queue, file, wait);
340}
341
342#ifndef CONFIG_MMU
343static unsigned long uvc_v4l2_get_unmapped_area(struct file *file,
344 unsigned long addr, unsigned long len, unsigned long pgoff,
345 unsigned long flags)
346{
347 struct video_device *vdev = video_devdata(file);
348 struct uvc_device *uvc = video_get_drvdata(vdev);
349
350 return uvc_queue_get_unmapped_area(&uvc->video.queue, pgoff);
351}
352#endif
353
354static struct v4l2_file_operations uvc_v4l2_fops = {
355 .owner = THIS_MODULE,
356 .open = uvc_v4l2_open,
357 .release = uvc_v4l2_release,
358 .ioctl = uvc_v4l2_ioctl,
359 .mmap = uvc_v4l2_mmap,
360 .poll = uvc_v4l2_poll,
361#ifndef CONFIG_MMU
362 .get_unmapped_area = uvc_v4l2_get_unmapped_area,
363#endif
364};
365
diff --git a/drivers/usb/gadget/function/uvc_video.c b/drivers/usb/gadget/function/uvc_video.c
new file mode 100644
index 000000000000..71e896d4c5ae
--- /dev/null
+++ b/drivers/usb/gadget/function/uvc_video.c
@@ -0,0 +1,394 @@
1/*
2 * uvc_video.c -- USB Video Class Gadget driver
3 *
4 * Copyright (C) 2009-2010
5 * Laurent Pinchart (laurent.pinchart@ideasonboard.com)
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 */
12
13#include <linux/kernel.h>
14#include <linux/device.h>
15#include <linux/errno.h>
16#include <linux/usb/ch9.h>
17#include <linux/usb/gadget.h>
18
19#include <media/v4l2-dev.h>
20
21#include "uvc.h"
22#include "uvc_queue.h"
23
24/* --------------------------------------------------------------------------
25 * Video codecs
26 */
27
28static int
29uvc_video_encode_header(struct uvc_video *video, struct uvc_buffer *buf,
30 u8 *data, int len)
31{
32 data[0] = 2;
33 data[1] = UVC_STREAM_EOH | video->fid;
34
35 if (buf->bytesused - video->queue.buf_used <= len - 2)
36 data[1] |= UVC_STREAM_EOF;
37
38 return 2;
39}
40
41static int
42uvc_video_encode_data(struct uvc_video *video, struct uvc_buffer *buf,
43 u8 *data, int len)
44{
45 struct uvc_video_queue *queue = &video->queue;
46 unsigned int nbytes;
47 void *mem;
48
49 /* Copy video data to the USB buffer. */
50 mem = buf->mem + queue->buf_used;
51 nbytes = min((unsigned int)len, buf->bytesused - queue->buf_used);
52
53 memcpy(data, mem, nbytes);
54 queue->buf_used += nbytes;
55
56 return nbytes;
57}
58
59static void
60uvc_video_encode_bulk(struct usb_request *req, struct uvc_video *video,
61 struct uvc_buffer *buf)
62{
63 void *mem = req->buf;
64 int len = video->req_size;
65 int ret;
66
67 /* Add a header at the beginning of the payload. */
68 if (video->payload_size == 0) {
69 ret = uvc_video_encode_header(video, buf, mem, len);
70 video->payload_size += ret;
71 mem += ret;
72 len -= ret;
73 }
74
75 /* Process video data. */
76 len = min((int)(video->max_payload_size - video->payload_size), len);
77 ret = uvc_video_encode_data(video, buf, mem, len);
78
79 video->payload_size += ret;
80 len -= ret;
81
82 req->length = video->req_size - len;
83 req->zero = video->payload_size == video->max_payload_size;
84
85 if (buf->bytesused == video->queue.buf_used) {
86 video->queue.buf_used = 0;
87 buf->state = UVC_BUF_STATE_DONE;
88 uvc_queue_next_buffer(&video->queue, buf);
89 video->fid ^= UVC_STREAM_FID;
90
91 video->payload_size = 0;
92 }
93
94 if (video->payload_size == video->max_payload_size ||
95 buf->bytesused == video->queue.buf_used)
96 video->payload_size = 0;
97}
98
99static void
100uvc_video_encode_isoc(struct usb_request *req, struct uvc_video *video,
101 struct uvc_buffer *buf)
102{
103 void *mem = req->buf;
104 int len = video->req_size;
105 int ret;
106
107 /* Add the header. */
108 ret = uvc_video_encode_header(video, buf, mem, len);
109 mem += ret;
110 len -= ret;
111
112 /* Process video data. */
113 ret = uvc_video_encode_data(video, buf, mem, len);
114 len -= ret;
115
116 req->length = video->req_size - len;
117
118 if (buf->bytesused == video->queue.buf_used) {
119 video->queue.buf_used = 0;
120 buf->state = UVC_BUF_STATE_DONE;
121 uvc_queue_next_buffer(&video->queue, buf);
122 video->fid ^= UVC_STREAM_FID;
123 }
124}
125
126/* --------------------------------------------------------------------------
127 * Request handling
128 */
129
130/*
131 * I somehow feel that synchronisation won't be easy to achieve here. We have
132 * three events that control USB requests submission:
133 *
134 * - USB request completion: the completion handler will resubmit the request
135 * if a video buffer is available.
136 *
137 * - USB interface setting selection: in response to a SET_INTERFACE request,
138 * the handler will start streaming if a video buffer is available and if
139 * video is not currently streaming.
140 *
141 * - V4L2 buffer queueing: the driver will start streaming if video is not
142 * currently streaming.
143 *
144 * Race conditions between those 3 events might lead to deadlocks or other
145 * nasty side effects.
146 *
147 * The "video currently streaming" condition can't be detected by the irqqueue
148 * being empty, as a request can still be in flight. A separate "queue paused"
149 * flag is thus needed.
150 *
151 * The paused flag will be set when we try to retrieve the irqqueue head if the
152 * queue is empty, and cleared when we queue a buffer.
153 *
154 * The USB request completion handler will get the buffer at the irqqueue head
155 * under protection of the queue spinlock. If the queue is empty, the streaming
156 * paused flag will be set. Right after releasing the spinlock a userspace
157 * application can queue a buffer. The flag will then cleared, and the ioctl
158 * handler will restart the video stream.
159 */
160static void
161uvc_video_complete(struct usb_ep *ep, struct usb_request *req)
162{
163 struct uvc_video *video = req->context;
164 struct uvc_video_queue *queue = &video->queue;
165 struct uvc_buffer *buf;
166 unsigned long flags;
167 int ret;
168
169 switch (req->status) {
170 case 0:
171 break;
172
173 case -ESHUTDOWN: /* disconnect from host. */
174 printk(KERN_INFO "VS request cancelled.\n");
175 uvc_queue_cancel(queue, 1);
176 goto requeue;
177
178 default:
179 printk(KERN_INFO "VS request completed with status %d.\n",
180 req->status);
181 uvc_queue_cancel(queue, 0);
182 goto requeue;
183 }
184
185 spin_lock_irqsave(&video->queue.irqlock, flags);
186 buf = uvc_queue_head(&video->queue);
187 if (buf == NULL) {
188 spin_unlock_irqrestore(&video->queue.irqlock, flags);
189 goto requeue;
190 }
191
192 video->encode(req, video, buf);
193
194 if ((ret = usb_ep_queue(ep, req, GFP_ATOMIC)) < 0) {
195 printk(KERN_INFO "Failed to queue request (%d).\n", ret);
196 usb_ep_set_halt(ep);
197 spin_unlock_irqrestore(&video->queue.irqlock, flags);
198 goto requeue;
199 }
200 spin_unlock_irqrestore(&video->queue.irqlock, flags);
201
202 return;
203
204requeue:
205 spin_lock_irqsave(&video->req_lock, flags);
206 list_add_tail(&req->list, &video->req_free);
207 spin_unlock_irqrestore(&video->req_lock, flags);
208}
209
210static int
211uvc_video_free_requests(struct uvc_video *video)
212{
213 unsigned int i;
214
215 for (i = 0; i < UVC_NUM_REQUESTS; ++i) {
216 if (video->req[i]) {
217 usb_ep_free_request(video->ep, video->req[i]);
218 video->req[i] = NULL;
219 }
220
221 if (video->req_buffer[i]) {
222 kfree(video->req_buffer[i]);
223 video->req_buffer[i] = NULL;
224 }
225 }
226
227 INIT_LIST_HEAD(&video->req_free);
228 video->req_size = 0;
229 return 0;
230}
231
232static int
233uvc_video_alloc_requests(struct uvc_video *video)
234{
235 unsigned int req_size;
236 unsigned int i;
237 int ret = -ENOMEM;
238
239 BUG_ON(video->req_size);
240
241 req_size = video->ep->maxpacket
242 * max_t(unsigned int, video->ep->maxburst, 1)
243 * (video->ep->mult + 1);
244
245 for (i = 0; i < UVC_NUM_REQUESTS; ++i) {
246 video->req_buffer[i] = kmalloc(req_size, GFP_KERNEL);
247 if (video->req_buffer[i] == NULL)
248 goto error;
249
250 video->req[i] = usb_ep_alloc_request(video->ep, GFP_KERNEL);
251 if (video->req[i] == NULL)
252 goto error;
253
254 video->req[i]->buf = video->req_buffer[i];
255 video->req[i]->length = 0;
256 video->req[i]->complete = uvc_video_complete;
257 video->req[i]->context = video;
258
259 list_add_tail(&video->req[i]->list, &video->req_free);
260 }
261
262 video->req_size = req_size;
263
264 return 0;
265
266error:
267 uvc_video_free_requests(video);
268 return ret;
269}
270
271/* --------------------------------------------------------------------------
272 * Video streaming
273 */
274
275/*
276 * uvc_video_pump - Pump video data into the USB requests
277 *
278 * This function fills the available USB requests (listed in req_free) with
279 * video data from the queued buffers.
280 */
281static int
282uvc_video_pump(struct uvc_video *video)
283{
284 struct usb_request *req;
285 struct uvc_buffer *buf;
286 unsigned long flags;
287 int ret;
288
289 /* FIXME TODO Race between uvc_video_pump and requests completion
290 * handler ???
291 */
292
293 while (1) {
294 /* Retrieve the first available USB request, protected by the
295 * request lock.
296 */
297 spin_lock_irqsave(&video->req_lock, flags);
298 if (list_empty(&video->req_free)) {
299 spin_unlock_irqrestore(&video->req_lock, flags);
300 return 0;
301 }
302 req = list_first_entry(&video->req_free, struct usb_request,
303 list);
304 list_del(&req->list);
305 spin_unlock_irqrestore(&video->req_lock, flags);
306
307 /* Retrieve the first available video buffer and fill the
308 * request, protected by the video queue irqlock.
309 */
310 spin_lock_irqsave(&video->queue.irqlock, flags);
311 buf = uvc_queue_head(&video->queue);
312 if (buf == NULL) {
313 spin_unlock_irqrestore(&video->queue.irqlock, flags);
314 break;
315 }
316
317 video->encode(req, video, buf);
318
319 /* Queue the USB request */
320 ret = usb_ep_queue(video->ep, req, GFP_ATOMIC);
321 if (ret < 0) {
322 printk(KERN_INFO "Failed to queue request (%d)\n", ret);
323 usb_ep_set_halt(video->ep);
324 spin_unlock_irqrestore(&video->queue.irqlock, flags);
325 break;
326 }
327 spin_unlock_irqrestore(&video->queue.irqlock, flags);
328 }
329
330 spin_lock_irqsave(&video->req_lock, flags);
331 list_add_tail(&req->list, &video->req_free);
332 spin_unlock_irqrestore(&video->req_lock, flags);
333 return 0;
334}
335
336/*
337 * Enable or disable the video stream.
338 */
339static int
340uvc_video_enable(struct uvc_video *video, int enable)
341{
342 unsigned int i;
343 int ret;
344
345 if (video->ep == NULL) {
346 printk(KERN_INFO "Video enable failed, device is "
347 "uninitialized.\n");
348 return -ENODEV;
349 }
350
351 if (!enable) {
352 for (i = 0; i < UVC_NUM_REQUESTS; ++i)
353 usb_ep_dequeue(video->ep, video->req[i]);
354
355 uvc_video_free_requests(video);
356 uvc_queue_enable(&video->queue, 0);
357 return 0;
358 }
359
360 if ((ret = uvc_queue_enable(&video->queue, 1)) < 0)
361 return ret;
362
363 if ((ret = uvc_video_alloc_requests(video)) < 0)
364 return ret;
365
366 if (video->max_payload_size) {
367 video->encode = uvc_video_encode_bulk;
368 video->payload_size = 0;
369 } else
370 video->encode = uvc_video_encode_isoc;
371
372 return uvc_video_pump(video);
373}
374
375/*
376 * Initialize the UVC video stream.
377 */
378static int
379uvc_video_init(struct uvc_video *video)
380{
381 INIT_LIST_HEAD(&video->req_free);
382 spin_lock_init(&video->req_lock);
383
384 video->fcc = V4L2_PIX_FMT_YUYV;
385 video->bpp = 16;
386 video->width = 320;
387 video->height = 240;
388 video->imagesize = 320 * 240 * 2;
389
390 /* Initialize the video buffers queue. */
391 uvc_queue_init(&video->queue, V4L2_BUF_TYPE_VIDEO_OUTPUT);
392 return 0;
393}
394