1 /*
2  * Copyright (c) 2017 Intel Corporation
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/logging/log.h>
8 LOG_MODULE_REGISTER(usb_ecm, CONFIG_USB_DEVICE_NETWORK_LOG_LEVEL);
9 
10 /* Enable verbose debug printing extra hexdumps */
11 #define VERBOSE_DEBUG	0
12 
13 #include <zephyr/net/net_pkt.h>
14 #include <zephyr/net/ethernet.h>
15 #include <net_private.h>
16 
17 #include <zephyr/usb/usb_device.h>
18 #include <zephyr/usb/class/usb_cdc.h>
19 #include <usb_descriptor.h>
20 
21 #include "netusb.h"
22 
23 #define USB_CDC_ECM_REQ_TYPE		0x21
24 #define USB_CDC_SET_ETH_PKT_FILTER	0x43
25 
26 #define ECM_INT_EP_IDX			0
27 #define ECM_OUT_EP_IDX			1
28 #define ECM_IN_EP_IDX			2
29 
30 
31 static uint8_t tx_buf[NET_ETH_MAX_FRAME_SIZE], rx_buf[NET_ETH_MAX_FRAME_SIZE];
32 
33 struct usb_cdc_ecm_config {
34 	struct usb_association_descriptor iad;
35 	struct usb_if_descriptor if0;
36 	struct cdc_header_descriptor if0_header;
37 	struct cdc_union_descriptor if0_union;
38 	struct cdc_ecm_descriptor if0_netfun_ecm;
39 	struct usb_ep_descriptor if0_int_ep;
40 
41 	struct usb_if_descriptor if1_0;
42 
43 	struct usb_if_descriptor if1_1;
44 	struct usb_ep_descriptor if1_1_in_ep;
45 	struct usb_ep_descriptor if1_1_out_ep;
46 } __packed;
47 
48 USBD_CLASS_DESCR_DEFINE(primary, 0) struct usb_cdc_ecm_config cdc_ecm_cfg = {
49 	.iad = {
50 		.bLength = sizeof(struct usb_association_descriptor),
51 		.bDescriptorType = USB_DESC_INTERFACE_ASSOC,
52 		.bFirstInterface = 0,
53 		.bInterfaceCount = 0x02,
54 		.bFunctionClass = USB_BCC_CDC_CONTROL,
55 		.bFunctionSubClass = ECM_SUBCLASS,
56 		.bFunctionProtocol = 0,
57 		.iFunction = 0,
58 	},
59 	/* Interface descriptor 0 */
60 	/* CDC Communication interface */
61 	.if0 = {
62 		.bLength = sizeof(struct usb_if_descriptor),
63 		.bDescriptorType = USB_DESC_INTERFACE,
64 		.bInterfaceNumber = 0,
65 		.bAlternateSetting = 0,
66 		.bNumEndpoints = 1,
67 		.bInterfaceClass = USB_BCC_CDC_CONTROL,
68 		.bInterfaceSubClass = ECM_SUBCLASS,
69 		.bInterfaceProtocol = 0,
70 		.iInterface = 0,
71 	},
72 	/* Header Functional Descriptor */
73 	.if0_header = {
74 		.bFunctionLength = sizeof(struct cdc_header_descriptor),
75 		.bDescriptorType = USB_DESC_CS_INTERFACE,
76 		.bDescriptorSubtype = HEADER_FUNC_DESC,
77 		.bcdCDC = sys_cpu_to_le16(USB_SRN_1_1),
78 	},
79 	/* Union Functional Descriptor */
80 	.if0_union = {
81 		.bFunctionLength = sizeof(struct cdc_union_descriptor),
82 		.bDescriptorType = USB_DESC_CS_INTERFACE,
83 		.bDescriptorSubtype = UNION_FUNC_DESC,
84 		.bControlInterface = 0,
85 		.bSubordinateInterface0 = 1,
86 	},
87 	/* Ethernet Networking Functional descriptor */
88 	.if0_netfun_ecm = {
89 		.bFunctionLength = sizeof(struct cdc_ecm_descriptor),
90 		.bDescriptorType = USB_DESC_CS_INTERFACE,
91 		.bDescriptorSubtype = ETHERNET_FUNC_DESC,
92 		.iMACAddress = 4,
93 		.bmEthernetStatistics = sys_cpu_to_le32(0), /* None */
94 		.wMaxSegmentSize = sys_cpu_to_le16(NET_ETH_MAX_FRAME_SIZE),
95 		.wNumberMCFilters = sys_cpu_to_le16(0), /* None */
96 		.bNumberPowerFilters = 0, /* No wake up */
97 	},
98 	/* Notification EP Descriptor */
99 	.if0_int_ep = {
100 		.bLength = sizeof(struct usb_ep_descriptor),
101 		.bDescriptorType = USB_DESC_ENDPOINT,
102 		.bEndpointAddress = CDC_ECM_INT_EP_ADDR,
103 		.bmAttributes = USB_DC_EP_INTERRUPT,
104 		.wMaxPacketSize =
105 			sys_cpu_to_le16(
106 			CONFIG_CDC_ECM_INTERRUPT_EP_MPS),
107 		.bInterval = 0x09,
108 	},
109 
110 	/* Interface descriptor 1/0 */
111 	/* CDC Data Interface */
112 	.if1_0 = {
113 		.bLength = sizeof(struct usb_if_descriptor),
114 		.bDescriptorType = USB_DESC_INTERFACE,
115 		.bInterfaceNumber = 1,
116 		.bAlternateSetting = 0,
117 		.bNumEndpoints = 0,
118 		.bInterfaceClass = USB_BCC_CDC_DATA,
119 		.bInterfaceSubClass = 0,
120 		.bInterfaceProtocol = 0,
121 		.iInterface = 0,
122 	},
123 
124 	/* Interface descriptor 1/1 */
125 	/* CDC Data Interface */
126 	.if1_1 = {
127 		.bLength = sizeof(struct usb_if_descriptor),
128 		.bDescriptorType = USB_DESC_INTERFACE,
129 		.bInterfaceNumber = 1,
130 		.bAlternateSetting = 1,
131 		.bNumEndpoints = 2,
132 		.bInterfaceClass = USB_BCC_CDC_DATA,
133 		.bInterfaceSubClass = ECM_SUBCLASS,
134 		.bInterfaceProtocol = 0,
135 		.iInterface = 0,
136 	},
137 	/* Data Endpoint IN */
138 	.if1_1_in_ep = {
139 		.bLength = sizeof(struct usb_ep_descriptor),
140 		.bDescriptorType = USB_DESC_ENDPOINT,
141 		.bEndpointAddress = CDC_ECM_IN_EP_ADDR,
142 		.bmAttributes = USB_DC_EP_BULK,
143 		.wMaxPacketSize =
144 			sys_cpu_to_le16(
145 			CONFIG_CDC_ECM_BULK_EP_MPS),
146 		.bInterval = 0x00,
147 	},
148 	/* Data Endpoint OUT */
149 	.if1_1_out_ep = {
150 		.bLength = sizeof(struct usb_ep_descriptor),
151 		.bDescriptorType = USB_DESC_ENDPOINT,
152 		.bEndpointAddress = CDC_ECM_OUT_EP_ADDR,
153 		.bmAttributes = USB_DC_EP_BULK,
154 		.wMaxPacketSize =
155 			sys_cpu_to_le16(
156 			CONFIG_CDC_ECM_BULK_EP_MPS),
157 		.bInterval = 0x00,
158 	},
159 };
160 
ecm_get_first_iface_number(void)161 static uint8_t ecm_get_first_iface_number(void)
162 {
163 	return cdc_ecm_cfg.if0.bInterfaceNumber;
164 }
165 
ecm_int_in(uint8_t ep,enum usb_dc_ep_cb_status_code ep_status)166 static void ecm_int_in(uint8_t ep, enum usb_dc_ep_cb_status_code ep_status)
167 {
168 	LOG_DBG("EP 0x%x status %d", ep, ep_status);
169 }
170 
171 static struct usb_ep_cfg_data ecm_ep_data[] = {
172 	/* Configuration ECM */
173 	{
174 		.ep_cb = ecm_int_in,
175 		.ep_addr = CDC_ECM_INT_EP_ADDR
176 	},
177 	{
178 		/* high-level transfer mgmt */
179 		.ep_cb = usb_transfer_ep_callback,
180 		.ep_addr = CDC_ECM_OUT_EP_ADDR
181 	},
182 	{
183 		/* high-level transfer mgmt */
184 		.ep_cb = usb_transfer_ep_callback,
185 		.ep_addr = CDC_ECM_IN_EP_ADDR
186 	},
187 };
188 
ecm_class_handler(struct usb_setup_packet * setup,int32_t * len,uint8_t ** data)189 static int ecm_class_handler(struct usb_setup_packet *setup, int32_t *len,
190 			     uint8_t **data)
191 {
192 	LOG_DBG("len %d req_type 0x%x req 0x%x enabled %u",
193 		*len, setup->bmRequestType, setup->bRequest,
194 		netusb_enabled());
195 
196 	if (!netusb_enabled()) {
197 		LOG_ERR("interface disabled");
198 		return -ENODEV;
199 	}
200 
201 	if (setup->bmRequestType != USB_CDC_ECM_REQ_TYPE) {
202 		/*
203 		 * Only host-to-device, type class, recipient interface
204 		 * requests are accepted.
205 		 */
206 		return -EINVAL;
207 	}
208 
209 	if (setup->bRequest == USB_CDC_SET_ETH_PKT_FILTER) {
210 		LOG_INF("Set Interface %u Packet Filter 0x%04x not supported",
211 			setup->wIndex, setup->wValue);
212 		return 0;
213 	}
214 
215 	return -ENOTSUP;
216 }
217 
218 /* Retrieve expected pkt size from ethernet/ip header */
ecm_eth_size(void * ecm_pkt,size_t len)219 static size_t ecm_eth_size(void *ecm_pkt, size_t len)
220 {
221 	struct net_eth_hdr *hdr = (void *)ecm_pkt;
222 	uint8_t *ip_data = (uint8_t *)ecm_pkt + sizeof(struct net_eth_hdr);
223 	uint16_t ip_len;
224 
225 	if (len < NET_IPV6H_LEN + sizeof(struct net_eth_hdr)) {
226 		/* Too short */
227 		return 0;
228 	}
229 
230 	switch (ntohs(hdr->type)) {
231 	case NET_ETH_PTYPE_IP:
232 	case NET_ETH_PTYPE_ARP:
233 		ip_len = ntohs(((struct net_ipv4_hdr *)ip_data)->len);
234 		break;
235 	case NET_ETH_PTYPE_IPV6:
236 		ip_len = ntohs(((struct net_ipv6_hdr *)ip_data)->len);
237 		break;
238 	default:
239 		LOG_DBG("Unknown hdr type 0x%04x", hdr->type);
240 		return 0;
241 	}
242 
243 	return sizeof(struct net_eth_hdr) + ip_len;
244 }
245 
ecm_send(struct net_pkt * pkt)246 static int ecm_send(struct net_pkt *pkt)
247 {
248 	size_t len = net_pkt_get_len(pkt);
249 	int ret;
250 
251 	if (VERBOSE_DEBUG) {
252 		net_pkt_hexdump(pkt, "<");
253 	}
254 
255 	if (len > sizeof(tx_buf)) {
256 		LOG_WRN("Trying to send too large packet, drop");
257 		return -ENOMEM;
258 	}
259 
260 	if (net_pkt_read(pkt, tx_buf, len)) {
261 		return -ENOBUFS;
262 	}
263 
264 	/* transfer data to host */
265 	ret = usb_transfer_sync(ecm_ep_data[ECM_IN_EP_IDX].ep_addr,
266 				tx_buf, len, USB_TRANS_WRITE);
267 	if (ret != len) {
268 		LOG_ERR("Transfer failure");
269 		return -EINVAL;
270 	}
271 
272 	return 0;
273 }
274 
ecm_read_cb(uint8_t ep,int size,void * priv)275 static void ecm_read_cb(uint8_t ep, int size, void *priv)
276 {
277 	struct net_pkt *pkt;
278 
279 	if (size <= 0) {
280 		goto done;
281 	}
282 
283 	/* Linux considers by default that network usb device controllers are
284 	 * not able to handle Zero Length Packet (ZLP) and then generates
285 	 * a short packet containing a null byte. Handle by checking the IP
286 	 * header length and dropping the extra byte.
287 	 */
288 	if (rx_buf[size - 1] == 0U) { /* last byte is null */
289 		if (ecm_eth_size(rx_buf, size) == (size - 1)) {
290 			/* last byte has been appended as delimiter, drop it */
291 			size--;
292 		}
293 	}
294 
295 	pkt = net_pkt_rx_alloc_with_buffer(netusb_net_iface(), size, AF_UNSPEC,
296 					   0, K_FOREVER);
297 	if (!pkt) {
298 		LOG_ERR("no memory for network packet");
299 		goto done;
300 	}
301 
302 	if (net_pkt_write(pkt, rx_buf, size)) {
303 		LOG_ERR("Unable to write into pkt");
304 		net_pkt_unref(pkt);
305 		goto done;
306 	}
307 
308 	if (VERBOSE_DEBUG) {
309 		net_pkt_hexdump(pkt, ">");
310 	}
311 
312 	netusb_recv(pkt);
313 
314 done:
315 	usb_transfer(ecm_ep_data[ECM_OUT_EP_IDX].ep_addr, rx_buf,
316 		     sizeof(rx_buf), USB_TRANS_READ, ecm_read_cb, NULL);
317 }
318 
ecm_connect(bool connected)319 static int ecm_connect(bool connected)
320 {
321 	if (connected) {
322 		ecm_read_cb(ecm_ep_data[ECM_OUT_EP_IDX].ep_addr, 0, NULL);
323 	} else {
324 		/* Cancel any transfer */
325 		usb_cancel_transfer(ecm_ep_data[ECM_OUT_EP_IDX].ep_addr);
326 		usb_cancel_transfer(ecm_ep_data[ECM_IN_EP_IDX].ep_addr);
327 	}
328 
329 	return 0;
330 }
331 
332 static struct netusb_function ecm_function = {
333 	.connect_media = ecm_connect,
334 	.send_pkt = ecm_send,
335 };
336 
ecm_status_interface(const uint8_t * desc)337 static inline void ecm_status_interface(const uint8_t *desc)
338 {
339 	const struct usb_if_descriptor *if_desc = (void *)desc;
340 	uint8_t iface_num = if_desc->bInterfaceNumber;
341 	uint8_t alt_set = if_desc->bAlternateSetting;
342 
343 	LOG_DBG("iface %u alt_set %u", iface_num, if_desc->bAlternateSetting);
344 
345 	/* First interface is CDC Comm interface */
346 	if (iface_num != ecm_get_first_iface_number() + 1 || !alt_set) {
347 		LOG_DBG("Skip iface_num %u alt_set %u", iface_num, alt_set);
348 		return;
349 	}
350 
351 	netusb_enable(&ecm_function);
352 }
353 
ecm_status_cb(struct usb_cfg_data * cfg,enum usb_dc_status_code status,const uint8_t * param)354 static void ecm_status_cb(struct usb_cfg_data *cfg,
355 			  enum usb_dc_status_code status,
356 			  const uint8_t *param)
357 {
358 	ARG_UNUSED(cfg);
359 
360 	/* Check the USB status and do needed action if required */
361 	switch (status) {
362 	case USB_DC_DISCONNECTED:
363 		LOG_DBG("USB device disconnected");
364 		netusb_disable();
365 		break;
366 
367 	case USB_DC_INTERFACE:
368 		LOG_DBG("USB interface selected");
369 		ecm_status_interface(param);
370 		break;
371 
372 	case USB_DC_ERROR:
373 	case USB_DC_RESET:
374 	case USB_DC_CONNECTED:
375 	case USB_DC_CONFIGURED:
376 	case USB_DC_SUSPEND:
377 	case USB_DC_RESUME:
378 		LOG_DBG("USB unhandled state: %d", status);
379 		break;
380 
381 	case USB_DC_SOF:
382 		break;
383 
384 	case USB_DC_UNKNOWN:
385 	default:
386 		LOG_DBG("USB unknown state: %d", status);
387 		break;
388 	}
389 }
390 
391 struct usb_cdc_ecm_mac_descr {
392 	uint8_t bLength;
393 	uint8_t bDescriptorType;
394 	uint8_t bString[USB_BSTRING_LENGTH(CONFIG_USB_DEVICE_NETWORK_ECM_MAC)];
395 } __packed;
396 
397 USBD_STRING_DESCR_USER_DEFINE(primary) struct usb_cdc_ecm_mac_descr utf16le_mac = {
398 	.bLength = USB_STRING_DESCRIPTOR_LENGTH(
399 			CONFIG_USB_DEVICE_NETWORK_ECM_MAC),
400 	.bDescriptorType = USB_DESC_STRING,
401 	.bString = CONFIG_USB_DEVICE_NETWORK_ECM_MAC
402 };
403 
ecm_interface_config(struct usb_desc_header * head,uint8_t bInterfaceNumber)404 static void ecm_interface_config(struct usb_desc_header *head,
405 				 uint8_t bInterfaceNumber)
406 {
407 	int idx = usb_get_str_descriptor_idx(&utf16le_mac);
408 
409 	ARG_UNUSED(head);
410 
411 	if (idx) {
412 		LOG_DBG("fixup string %d", idx);
413 		cdc_ecm_cfg.if0_netfun_ecm.iMACAddress = idx;
414 	}
415 
416 	cdc_ecm_cfg.if0.bInterfaceNumber = bInterfaceNumber;
417 	cdc_ecm_cfg.if0_union.bControlInterface = bInterfaceNumber;
418 	cdc_ecm_cfg.if0_union.bSubordinateInterface0 = bInterfaceNumber + 1;
419 	cdc_ecm_cfg.if1_0.bInterfaceNumber = bInterfaceNumber + 1;
420 	cdc_ecm_cfg.if1_1.bInterfaceNumber = bInterfaceNumber + 1;
421 	cdc_ecm_cfg.iad.bFirstInterface = bInterfaceNumber;
422 }
423 
424 USBD_DEFINE_CFG_DATA(cdc_ecm_config) = {
425 	.usb_device_description = NULL,
426 	.interface_config = ecm_interface_config,
427 	.interface_descriptor = &cdc_ecm_cfg.if0,
428 	.cb_usb_status = ecm_status_cb,
429 	.interface = {
430 		.class_handler = ecm_class_handler,
431 		.custom_handler = NULL,
432 		.vendor_handler = NULL,
433 	},
434 	.num_endpoints = ARRAY_SIZE(ecm_ep_data),
435 	.endpoint = ecm_ep_data,
436 };
437