xref: /linux/drivers/net/thunderbolt/main.c (revision 26ba30221c03364d6ed9910be8da4c1fd871b07b)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Networking over Thunderbolt/USB4 cables using USB4NET protocol
4  * (formerly Apple ThunderboltIP).
5  *
6  * Copyright (C) 2017, Intel Corporation
7  * Authors: Amir Levy <amir.jer.levy@intel.com>
8  *          Michael Jamet <michael.jamet@intel.com>
9  *          Mika Westerberg <mika.westerberg@linux.intel.com>
10  */
11 
12 #include <linux/atomic.h>
13 #include <linux/ethtool.h>
14 #include <linux/highmem.h>
15 #include <linux/if_vlan.h>
16 #include <linux/jhash.h>
17 #include <linux/module.h>
18 #include <linux/etherdevice.h>
19 #include <linux/rtnetlink.h>
20 #include <linux/sizes.h>
21 #include <linux/thunderbolt.h>
22 #include <linux/uuid.h>
23 #include <linux/workqueue.h>
24 
25 #include <net/ip6_checksum.h>
26 
27 #include "trace.h"
28 
29 /* Protocol timeouts in ms */
30 #define TBNET_LOGIN_DELAY	4500
31 #define TBNET_LOGIN_TIMEOUT	500
32 #define TBNET_LOGOUT_TIMEOUT	1000
33 
34 #define TBNET_RING_SIZE		256
35 #define TBNET_LOGIN_RETRIES	60
36 #define TBNET_LOGOUT_RETRIES	10
37 #define TBNET_THROTTLING	128000
38 #define TBNET_E2E		BIT(0)
39 #define TBNET_MATCH_FRAGS_ID	BIT(1)
40 #define TBNET_64K_FRAMES	BIT(2)
41 #define TBNET_MAX_MTU		SZ_64K
42 #define TBNET_FRAME_SIZE	TB_MAX_FRAME_SIZE
43 #define TBNET_MAX_PAYLOAD_SIZE	\
44 	(TBNET_FRAME_SIZE - sizeof(struct thunderbolt_ip_frame_header))
45 /* Rx packets need to hold space for skb_shared_info */
46 #define TBNET_RX_MAX_SIZE	\
47 	(TBNET_FRAME_SIZE + SKB_DATA_ALIGN(sizeof(struct skb_shared_info)))
48 #define TBNET_RX_PAGE_ORDER	get_order(TBNET_RX_MAX_SIZE)
49 #define TBNET_RX_PAGE_SIZE	(PAGE_SIZE << TBNET_RX_PAGE_ORDER)
50 
51 #define TBNET_L0_PORT_NUM(route) ((route) & GENMASK(5, 0))
52 
53 /**
54  * struct thunderbolt_ip_frame_header - Header for each Thunderbolt frame
55  * @frame_size: size of the data with the frame
56  * @frame_index: running index on the frames
57  * @frame_id: ID of the frame to match frames to specific packet
58  * @frame_count: how many frames assembles a full packet
59  *
60  * Each data frame passed to the high-speed DMA ring has this header. If
61  * the XDomain network directory announces that %TBNET_MATCH_FRAGS_ID is
62  * supported then @frame_id is filled, otherwise it stays %0.
63  */
64 struct thunderbolt_ip_frame_header {
65 	__le32 frame_size;
66 	__le16 frame_index;
67 	__le16 frame_id;
68 	__le32 frame_count;
69 };
70 
71 enum thunderbolt_ip_frame_pdf {
72 	TBIP_PDF_FRAME_START = 1,
73 	TBIP_PDF_FRAME_END,
74 };
75 
76 enum thunderbolt_ip_type {
77 	TBIP_LOGIN,
78 	TBIP_LOGIN_RESPONSE,
79 	TBIP_LOGOUT,
80 	TBIP_STATUS,
81 };
82 
83 struct thunderbolt_ip_header {
84 	u32 route_hi;
85 	u32 route_lo;
86 	u32 length_sn;
87 	uuid_t uuid;
88 	uuid_t initiator_uuid;
89 	uuid_t target_uuid;
90 	u32 type;
91 	u32 command_id;
92 };
93 
94 #define TBIP_HDR_LENGTH_MASK		GENMASK(5, 0)
95 #define TBIP_HDR_SN_MASK		GENMASK(28, 27)
96 #define TBIP_HDR_SN_SHIFT		27
97 
98 struct thunderbolt_ip_login {
99 	struct thunderbolt_ip_header hdr;
100 	u32 proto_version;
101 	u32 transmit_path;
102 	u32 reserved[4];
103 };
104 
105 #define TBIP_LOGIN_PROTO_VERSION	1
106 
107 struct thunderbolt_ip_login_response {
108 	struct thunderbolt_ip_header hdr;
109 	u32 status;
110 	u32 receiver_mac[2];
111 	u32 receiver_mac_len;
112 	u32 reserved[4];
113 };
114 
115 struct thunderbolt_ip_logout {
116 	struct thunderbolt_ip_header hdr;
117 };
118 
119 struct thunderbolt_ip_status {
120 	struct thunderbolt_ip_header hdr;
121 	u32 status;
122 };
123 
124 struct tbnet_stats {
125 	u64 tx_packets;
126 	u64 rx_packets;
127 	u64 tx_bytes;
128 	u64 rx_bytes;
129 	u64 rx_errors;
130 	u64 tx_errors;
131 	u64 rx_length_errors;
132 	u64 rx_over_errors;
133 	u64 rx_crc_errors;
134 	u64 rx_missed_errors;
135 };
136 
137 struct tbnet_frame {
138 	struct net_device *dev;
139 	struct page *page;
140 	struct ring_frame frame;
141 };
142 
143 struct tbnet_ring {
144 	struct tbnet_frame frames[TBNET_RING_SIZE];
145 	unsigned int cons;
146 	unsigned int prod;
147 	struct tb_ring *ring;
148 };
149 
150 /**
151  * struct tbnet - ThunderboltIP network driver private data
152  * @svc: XDomain service the driver is bound to
153  * @xd: XDomain the service belongs to
154  * @handler: ThunderboltIP configuration protocol handler
155  * @dev: Networking device
156  * @napi: NAPI structure for Rx polling
157  * @stats: Network statistics
158  * @skb: Network packet that is currently processed on Rx path
159  * @command_id: ID used for next configuration protocol packet
160  * @login_sent: ThunderboltIP login message successfully sent
161  * @login_received: ThunderboltIP login message received from the remote
162  *		    host
163  * @local_transmit_path: HopID we are using to send out packets
164  * @remote_transmit_path: HopID the other end is using to send packets to us
165  * @connection_lock: Lock serializing access to @login_sent,
166  *		     @login_received and @transmit_path.
167  * @login_retries: Number of login retries currently done
168  * @login_work: Worker to send ThunderboltIP login packets
169  * @connected_work: Worker that finalizes the ThunderboltIP connection
170  *		    setup and enables DMA paths for high speed data
171  *		    transfers
172  * @disconnect_work: Worker that handles tearing down the ThunderboltIP
173  *		     connection
174  * @rx_hdr: Copy of the currently processed Rx frame. Used when a
175  *	    network packet consists of multiple Thunderbolt frames.
176  *	    In host byte order.
177  * @rx_ring: Software ring holding Rx frames
178  * @frame_id: Frame ID use for next Tx packet
179  *            (if %TBNET_MATCH_FRAGS_ID is supported in both ends)
180  * @tx_ring: Software ring holding Tx frames
181  */
182 struct tbnet {
183 	const struct tb_service *svc;
184 	struct tb_xdomain *xd;
185 	struct tb_protocol_handler handler;
186 	struct net_device *dev;
187 	struct napi_struct napi;
188 	struct tbnet_stats stats;
189 	struct sk_buff *skb;
190 	atomic_t command_id;
191 	bool login_sent;
192 	bool login_received;
193 	int local_transmit_path;
194 	int remote_transmit_path;
195 	struct mutex connection_lock;
196 	int login_retries;
197 	struct delayed_work login_work;
198 	struct work_struct connected_work;
199 	struct work_struct disconnect_work;
200 	struct thunderbolt_ip_frame_header rx_hdr;
201 	struct tbnet_ring rx_ring;
202 	atomic_t frame_id;
203 	struct tbnet_ring tx_ring;
204 };
205 
206 /* Network property directory UUID: c66189ca-1cce-4195-bdb8-49592e5f5a4f */
207 static const uuid_t tbnet_dir_uuid =
208 	UUID_INIT(0xc66189ca, 0x1cce, 0x4195,
209 		  0xbd, 0xb8, 0x49, 0x59, 0x2e, 0x5f, 0x5a, 0x4f);
210 
211 /* ThunderboltIP protocol UUID: 798f589e-3616-8a47-97c6-5664a920c8dd */
212 static const uuid_t tbnet_svc_uuid =
213 	UUID_INIT(0x798f589e, 0x3616, 0x8a47,
214 		  0x97, 0xc6, 0x56, 0x64, 0xa9, 0x20, 0xc8, 0xdd);
215 
216 static struct tb_property_dir *tbnet_dir;
217 
218 static bool tbnet_e2e = true;
219 module_param_named(e2e, tbnet_e2e, bool, 0444);
220 MODULE_PARM_DESC(e2e, "USB4NET full end-to-end flow control (default: true)");
221 
222 static void tbnet_fill_header(struct thunderbolt_ip_header *hdr, u64 route,
223 	u8 sequence, const uuid_t *initiator_uuid, const uuid_t *target_uuid,
224 	enum thunderbolt_ip_type type, size_t size, u32 command_id)
225 {
226 	u32 length_sn;
227 
228 	/* Length does not include route_hi/lo and length_sn fields */
229 	length_sn = (size - 3 * 4) / 4;
230 	length_sn |= (sequence << TBIP_HDR_SN_SHIFT) & TBIP_HDR_SN_MASK;
231 
232 	hdr->route_hi = upper_32_bits(route);
233 	hdr->route_lo = lower_32_bits(route);
234 	hdr->length_sn = length_sn;
235 	uuid_copy(&hdr->uuid, &tbnet_svc_uuid);
236 	uuid_copy(&hdr->initiator_uuid, initiator_uuid);
237 	uuid_copy(&hdr->target_uuid, target_uuid);
238 	hdr->type = type;
239 	hdr->command_id = command_id;
240 }
241 
242 static int tbnet_login_response(struct tbnet *net, u64 route, u8 sequence,
243 				u32 command_id)
244 {
245 	struct thunderbolt_ip_login_response reply;
246 	struct tb_xdomain *xd = net->xd;
247 
248 	memset(&reply, 0, sizeof(reply));
249 	tbnet_fill_header(&reply.hdr, route, sequence, xd->local_uuid,
250 			  xd->remote_uuid, TBIP_LOGIN_RESPONSE, sizeof(reply),
251 			  command_id);
252 	memcpy(reply.receiver_mac, net->dev->dev_addr, ETH_ALEN);
253 	reply.receiver_mac_len = ETH_ALEN;
254 
255 	return tb_xdomain_response(xd, &reply, sizeof(reply),
256 				   TB_CFG_PKG_XDOMAIN_RESP);
257 }
258 
259 static int tbnet_login_request(struct tbnet *net, u8 sequence)
260 {
261 	struct thunderbolt_ip_login_response reply;
262 	struct thunderbolt_ip_login request;
263 	struct tb_xdomain *xd = net->xd;
264 
265 	memset(&request, 0, sizeof(request));
266 	tbnet_fill_header(&request.hdr, xd->route, sequence, xd->local_uuid,
267 			  xd->remote_uuid, TBIP_LOGIN, sizeof(request),
268 			  atomic_inc_return(&net->command_id));
269 
270 	request.proto_version = TBIP_LOGIN_PROTO_VERSION;
271 	request.transmit_path = net->local_transmit_path;
272 
273 	return tb_xdomain_request(xd, &request, sizeof(request),
274 				  TB_CFG_PKG_XDOMAIN_RESP, &reply,
275 				  sizeof(reply), TB_CFG_PKG_XDOMAIN_RESP,
276 				  TBNET_LOGIN_TIMEOUT);
277 }
278 
279 static int tbnet_logout_response(struct tbnet *net, u64 route, u8 sequence,
280 				 u32 command_id)
281 {
282 	struct thunderbolt_ip_status reply;
283 	struct tb_xdomain *xd = net->xd;
284 
285 	memset(&reply, 0, sizeof(reply));
286 	tbnet_fill_header(&reply.hdr, route, sequence, xd->local_uuid,
287 			  xd->remote_uuid, TBIP_STATUS, sizeof(reply),
288 			  atomic_inc_return(&net->command_id));
289 	return tb_xdomain_response(xd, &reply, sizeof(reply),
290 				   TB_CFG_PKG_XDOMAIN_RESP);
291 }
292 
293 static int tbnet_logout_request(struct tbnet *net)
294 {
295 	struct thunderbolt_ip_logout request;
296 	struct thunderbolt_ip_status reply;
297 	struct tb_xdomain *xd = net->xd;
298 
299 	memset(&request, 0, sizeof(request));
300 	tbnet_fill_header(&request.hdr, xd->route, 0, xd->local_uuid,
301 			  xd->remote_uuid, TBIP_LOGOUT, sizeof(request),
302 			  atomic_inc_return(&net->command_id));
303 
304 	return tb_xdomain_request(xd, &request, sizeof(request),
305 				  TB_CFG_PKG_XDOMAIN_RESP, &reply,
306 				  sizeof(reply), TB_CFG_PKG_XDOMAIN_RESP,
307 				  TBNET_LOGOUT_TIMEOUT);
308 }
309 
310 static void start_login(struct tbnet *net)
311 {
312 	netdev_dbg(net->dev, "login started\n");
313 
314 	mutex_lock(&net->connection_lock);
315 	net->login_sent = false;
316 	net->login_received = false;
317 	mutex_unlock(&net->connection_lock);
318 
319 	queue_delayed_work(system_long_wq, &net->login_work,
320 			   msecs_to_jiffies(1000));
321 }
322 
323 static void stop_login(struct tbnet *net)
324 {
325 	cancel_delayed_work_sync(&net->login_work);
326 	cancel_work_sync(&net->connected_work);
327 
328 	netdev_dbg(net->dev, "login stopped\n");
329 }
330 
331 static void tbnet_free_buffers(struct tbnet_ring *ring)
332 {
333 	unsigned int i;
334 
335 	for (i = 0; i < TBNET_RING_SIZE; i++) {
336 		struct device *dma_dev = tb_ring_dma_device(ring->ring);
337 		struct tbnet_frame *tf = &ring->frames[i];
338 		enum dma_data_direction dir;
339 		unsigned int order;
340 		size_t size;
341 
342 		if (!tf->page)
343 			continue;
344 
345 		if (ring->ring->is_tx) {
346 			dir = DMA_TO_DEVICE;
347 			order = 0;
348 			size = TBNET_FRAME_SIZE;
349 		} else {
350 			dir = DMA_FROM_DEVICE;
351 			order = TBNET_RX_PAGE_ORDER;
352 			size = TBNET_RX_PAGE_SIZE;
353 		}
354 
355 		trace_tbnet_free_frame(i, tf->page, tf->frame.buffer_phy, dir);
356 
357 		if (tf->frame.buffer_phy)
358 			dma_unmap_page(dma_dev, tf->frame.buffer_phy, size,
359 				       dir);
360 
361 		__free_pages(tf->page, order);
362 		tf->page = NULL;
363 	}
364 
365 	ring->cons = 0;
366 	ring->prod = 0;
367 }
368 
369 static void tbnet_tear_down(struct tbnet *net, bool send_logout)
370 {
371 	netif_carrier_off(net->dev);
372 	netif_stop_queue(net->dev);
373 
374 	stop_login(net);
375 
376 	mutex_lock(&net->connection_lock);
377 
378 	if (net->login_sent && net->login_received) {
379 		int ret, retries = TBNET_LOGOUT_RETRIES;
380 
381 		while (send_logout && retries-- > 0) {
382 			netdev_dbg(net->dev, "sending logout request %u\n",
383 				   retries);
384 			ret = tbnet_logout_request(net);
385 			if (ret != -ETIMEDOUT)
386 				break;
387 		}
388 
389 		/* Tear the paths down before stopping the rings.  This mirrors
390 		 * tbnet_connected_work(), which enables the paths last so the
391 		 * Rx ring is primed before packets can arrive.  Stopping a
392 		 * ring zeroes its descriptor base and tbnet_free_buffers()
393 		 * unmaps and frees the frame buffers, leaving anything still
394 		 * in flight with nowhere to drain to;
395 		 * __tb_path_deactivate_hop() then waits for the hop's
396 		 * 'pending' bit, which on some host routers never clears in
397 		 * that state.
398 		 */
399 		ret = tb_xdomain_disable_paths(net->xd,
400 					       net->local_transmit_path,
401 					       net->tx_ring.ring->hop,
402 					       net->remote_transmit_path,
403 					       net->rx_ring.ring->hop);
404 		if (ret)
405 			netdev_warn(net->dev, "failed to disable DMA paths\n");
406 
407 		tb_ring_stop(net->rx_ring.ring);
408 		tb_ring_stop(net->tx_ring.ring);
409 		tbnet_free_buffers(&net->rx_ring);
410 		tbnet_free_buffers(&net->tx_ring);
411 
412 		tb_xdomain_release_in_hopid(net->xd, net->remote_transmit_path);
413 		net->remote_transmit_path = 0;
414 	}
415 
416 	net->login_retries = 0;
417 	net->login_sent = false;
418 	net->login_received = false;
419 
420 	netdev_dbg(net->dev, "network traffic stopped\n");
421 
422 	mutex_unlock(&net->connection_lock);
423 }
424 
425 static int tbnet_handle_packet(const void *buf, size_t size, void *data)
426 {
427 	const struct thunderbolt_ip_login *pkg = buf;
428 	struct tbnet *net = data;
429 	u32 command_id;
430 	int ret = 0;
431 	u32 sequence;
432 	u64 route;
433 
434 	/* Make sure the packet is for us */
435 	if (size < sizeof(struct thunderbolt_ip_header))
436 		return 0;
437 	if (!uuid_equal(&pkg->hdr.initiator_uuid, net->xd->remote_uuid))
438 		return 0;
439 	if (!uuid_equal(&pkg->hdr.target_uuid, net->xd->local_uuid))
440 		return 0;
441 
442 	route = ((u64)pkg->hdr.route_hi << 32) | pkg->hdr.route_lo;
443 	route &= ~BIT_ULL(63);
444 	if (route != net->xd->route)
445 		return 0;
446 
447 	sequence = pkg->hdr.length_sn & TBIP_HDR_SN_MASK;
448 	sequence >>= TBIP_HDR_SN_SHIFT;
449 	command_id = pkg->hdr.command_id;
450 
451 	switch (pkg->hdr.type) {
452 	case TBIP_LOGIN:
453 		netdev_dbg(net->dev, "remote login request received\n");
454 		if (!netif_running(net->dev))
455 			break;
456 
457 		ret = tbnet_login_response(net, route, sequence,
458 					   pkg->hdr.command_id);
459 		if (!ret) {
460 			netdev_dbg(net->dev, "remote login response sent\n");
461 
462 			mutex_lock(&net->connection_lock);
463 			net->login_received = true;
464 			net->remote_transmit_path = pkg->transmit_path;
465 
466 			/* If we reached the number of max retries or
467 			 * previous logout, schedule another round of
468 			 * login retries
469 			 */
470 			if (net->login_retries >= TBNET_LOGIN_RETRIES ||
471 			    !net->login_sent) {
472 				net->login_retries = 0;
473 				queue_delayed_work(system_long_wq,
474 						   &net->login_work, 0);
475 			}
476 			mutex_unlock(&net->connection_lock);
477 
478 			queue_work(system_long_wq, &net->connected_work);
479 		}
480 		break;
481 
482 	case TBIP_LOGOUT:
483 		netdev_dbg(net->dev, "remote logout request received\n");
484 		ret = tbnet_logout_response(net, route, sequence, command_id);
485 		if (!ret) {
486 			netdev_dbg(net->dev, "remote logout response sent\n");
487 			queue_work(system_long_wq, &net->disconnect_work);
488 		}
489 		break;
490 
491 	default:
492 		return 0;
493 	}
494 
495 	if (ret)
496 		netdev_warn(net->dev, "failed to send ThunderboltIP response\n");
497 
498 	return 1;
499 }
500 
501 static unsigned int tbnet_available_buffers(const struct tbnet_ring *ring)
502 {
503 	return ring->prod - ring->cons;
504 }
505 
506 static int tbnet_alloc_rx_buffers(struct tbnet *net, unsigned int nbuffers)
507 {
508 	struct tbnet_ring *ring = &net->rx_ring;
509 	int ret;
510 
511 	while (nbuffers--) {
512 		struct device *dma_dev = tb_ring_dma_device(ring->ring);
513 		unsigned int index = ring->prod & (TBNET_RING_SIZE - 1);
514 		struct tbnet_frame *tf = &ring->frames[index];
515 		dma_addr_t dma_addr;
516 
517 		if (tf->page)
518 			break;
519 
520 		/* Allocate page (order > 0) so that it can hold maximum
521 		 * ThunderboltIP frame (4kB) and the additional room for
522 		 * SKB shared info required by build_skb().
523 		 */
524 		tf->page = dev_alloc_pages(TBNET_RX_PAGE_ORDER);
525 		if (!tf->page) {
526 			ret = -ENOMEM;
527 			goto err_free;
528 		}
529 
530 		dma_addr = dma_map_page(dma_dev, tf->page, 0,
531 					TBNET_RX_PAGE_SIZE, DMA_FROM_DEVICE);
532 		if (dma_mapping_error(dma_dev, dma_addr)) {
533 			ret = -ENOMEM;
534 			goto err_free;
535 		}
536 
537 		tf->frame.buffer_phy = dma_addr;
538 		tf->dev = net->dev;
539 
540 		trace_tbnet_alloc_rx_frame(index, tf->page, dma_addr,
541 					   DMA_FROM_DEVICE);
542 
543 		tb_ring_rx(ring->ring, &tf->frame);
544 
545 		ring->prod++;
546 	}
547 
548 	return 0;
549 
550 err_free:
551 	tbnet_free_buffers(ring);
552 	return ret;
553 }
554 
555 static struct tbnet_frame *tbnet_get_tx_buffer(struct tbnet *net)
556 {
557 	struct tbnet_ring *ring = &net->tx_ring;
558 	struct device *dma_dev = tb_ring_dma_device(ring->ring);
559 	struct tbnet_frame *tf;
560 	unsigned int index;
561 
562 	if (!tbnet_available_buffers(ring))
563 		return NULL;
564 
565 	index = ring->cons++ & (TBNET_RING_SIZE - 1);
566 
567 	tf = &ring->frames[index];
568 	tf->frame.size = 0;
569 
570 	dma_sync_single_for_cpu(dma_dev, tf->frame.buffer_phy,
571 				tb_ring_frame_size(&tf->frame), DMA_TO_DEVICE);
572 
573 	return tf;
574 }
575 
576 static void tbnet_tx_callback(struct tb_ring *ring, struct ring_frame *frame,
577 			      bool canceled)
578 {
579 	struct tbnet_frame *tf = container_of(frame, typeof(*tf), frame);
580 	struct tbnet *net = netdev_priv(tf->dev);
581 
582 	/* Return buffer to the ring */
583 	net->tx_ring.prod++;
584 
585 	if (tbnet_available_buffers(&net->tx_ring) >= TBNET_RING_SIZE / 2)
586 		netif_wake_queue(net->dev);
587 }
588 
589 static int tbnet_alloc_tx_buffers(struct tbnet *net)
590 {
591 	struct tbnet_ring *ring = &net->tx_ring;
592 	struct device *dma_dev = tb_ring_dma_device(ring->ring);
593 	unsigned int i;
594 
595 	for (i = 0; i < TBNET_RING_SIZE; i++) {
596 		struct tbnet_frame *tf = &ring->frames[i];
597 		dma_addr_t dma_addr;
598 
599 		tf->page = alloc_page(GFP_KERNEL);
600 		if (!tf->page) {
601 			tbnet_free_buffers(ring);
602 			return -ENOMEM;
603 		}
604 
605 		dma_addr = dma_map_page(dma_dev, tf->page, 0, TBNET_FRAME_SIZE,
606 					DMA_TO_DEVICE);
607 		if (dma_mapping_error(dma_dev, dma_addr)) {
608 			__free_page(tf->page);
609 			tf->page = NULL;
610 			tbnet_free_buffers(ring);
611 			return -ENOMEM;
612 		}
613 
614 		tf->dev = net->dev;
615 		tf->frame.buffer_phy = dma_addr;
616 		tf->frame.callback = tbnet_tx_callback;
617 		tf->frame.sof = TBIP_PDF_FRAME_START;
618 		tf->frame.eof = TBIP_PDF_FRAME_END;
619 
620 		trace_tbnet_alloc_tx_frame(i, tf->page, dma_addr, DMA_TO_DEVICE);
621 	}
622 
623 	ring->cons = 0;
624 	ring->prod = TBNET_RING_SIZE - 1;
625 
626 	return 0;
627 }
628 
629 static void tbnet_connected_work(struct work_struct *work)
630 {
631 	struct tbnet *net = container_of(work, typeof(*net), connected_work);
632 	bool connected;
633 	int ret;
634 
635 	if (netif_carrier_ok(net->dev))
636 		return;
637 
638 	mutex_lock(&net->connection_lock);
639 	connected = net->login_sent && net->login_received;
640 	mutex_unlock(&net->connection_lock);
641 
642 	if (!connected)
643 		return;
644 
645 	netdev_dbg(net->dev, "login successful, enabling paths\n");
646 
647 	ret = tb_xdomain_alloc_in_hopid(net->xd, net->remote_transmit_path);
648 	if (ret != net->remote_transmit_path) {
649 		netdev_err(net->dev, "failed to allocate Rx HopID\n");
650 		return;
651 	}
652 
653 	/* Both logins successful so enable the rings, high-speed DMA
654 	 * paths and start the network device queue.
655 	 *
656 	 * Note we enable the DMA paths last to make sure we have primed
657 	 * the Rx ring before any incoming packets are allowed to
658 	 * arrive.
659 	 */
660 	tb_ring_start(net->tx_ring.ring);
661 	tb_ring_start(net->rx_ring.ring);
662 
663 	ret = tbnet_alloc_rx_buffers(net, TBNET_RING_SIZE);
664 	if (ret)
665 		goto err_stop_rings;
666 
667 	ret = tbnet_alloc_tx_buffers(net);
668 	if (ret)
669 		goto err_free_rx_buffers;
670 
671 	ret = tb_xdomain_enable_paths(net->xd, net->local_transmit_path,
672 				      net->tx_ring.ring->hop,
673 				      net->remote_transmit_path,
674 				      net->rx_ring.ring->hop);
675 	if (ret) {
676 		netdev_err(net->dev, "failed to enable DMA paths\n");
677 		goto err_free_tx_buffers;
678 	}
679 
680 	netif_carrier_on(net->dev);
681 	netif_start_queue(net->dev);
682 
683 	netdev_dbg(net->dev, "network traffic started\n");
684 	return;
685 
686 err_free_tx_buffers:
687 	tbnet_free_buffers(&net->tx_ring);
688 err_free_rx_buffers:
689 	tbnet_free_buffers(&net->rx_ring);
690 err_stop_rings:
691 	tb_ring_stop(net->rx_ring.ring);
692 	tb_ring_stop(net->tx_ring.ring);
693 	tb_xdomain_release_in_hopid(net->xd, net->remote_transmit_path);
694 }
695 
696 static void tbnet_login_work(struct work_struct *work)
697 {
698 	struct tbnet *net = container_of(work, typeof(*net), login_work.work);
699 	unsigned long delay = msecs_to_jiffies(TBNET_LOGIN_DELAY);
700 	int ret;
701 
702 	if (netif_carrier_ok(net->dev))
703 		return;
704 
705 	netdev_dbg(net->dev, "sending login request, retries=%u\n",
706 		   net->login_retries);
707 
708 	ret = tbnet_login_request(net, net->login_retries % 4);
709 	if (ret) {
710 		netdev_dbg(net->dev, "sending login request failed, ret=%d\n",
711 			   ret);
712 		if (net->login_retries++ < TBNET_LOGIN_RETRIES) {
713 			queue_delayed_work(system_long_wq, &net->login_work,
714 					   delay);
715 		} else {
716 			netdev_info(net->dev, "ThunderboltIP login timed out\n");
717 		}
718 	} else {
719 		netdev_dbg(net->dev, "received login reply\n");
720 
721 		net->login_retries = 0;
722 
723 		mutex_lock(&net->connection_lock);
724 		net->login_sent = true;
725 		mutex_unlock(&net->connection_lock);
726 
727 		queue_work(system_long_wq, &net->connected_work);
728 	}
729 }
730 
731 static void tbnet_disconnect_work(struct work_struct *work)
732 {
733 	struct tbnet *net = container_of(work, typeof(*net), disconnect_work);
734 
735 	tbnet_tear_down(net, false);
736 }
737 
738 static bool tbnet_check_frame(struct tbnet *net, const struct tbnet_frame *tf,
739 			      const struct thunderbolt_ip_frame_header *hdr)
740 {
741 	u32 frame_id, frame_count, frame_size, frame_index;
742 	unsigned int size;
743 
744 	if (tf->frame.flags & RING_DESC_CRC_ERROR) {
745 		net->stats.rx_crc_errors++;
746 		return false;
747 	} else if (tf->frame.flags & RING_DESC_BUFFER_OVERRUN) {
748 		net->stats.rx_over_errors++;
749 		return false;
750 	}
751 
752 	/* Should be greater than just header i.e. contains data */
753 	size = tb_ring_frame_size(&tf->frame);
754 	if (size <= sizeof(*hdr)) {
755 		net->stats.rx_length_errors++;
756 		return false;
757 	}
758 
759 	frame_count = le32_to_cpu(hdr->frame_count);
760 	frame_size = le32_to_cpu(hdr->frame_size);
761 	frame_index = le16_to_cpu(hdr->frame_index);
762 	frame_id = le16_to_cpu(hdr->frame_id);
763 
764 	if ((frame_size > size - sizeof(*hdr)) || !frame_size) {
765 		net->stats.rx_length_errors++;
766 		return false;
767 	}
768 
769 	/* In case we're in the middle of packet, validate the frame
770 	 * header based on first fragment of the packet.
771 	 */
772 	if (net->skb && net->rx_hdr.frame_count) {
773 		/* Check the frame count fits the count field */
774 		if (frame_count != le32_to_cpu(net->rx_hdr.frame_count)) {
775 			net->stats.rx_length_errors++;
776 			return false;
777 		}
778 
779 		/* Check the frame identifiers are incremented correctly,
780 		 * and id is matching.
781 		 */
782 		if (frame_index != le16_to_cpu(net->rx_hdr.frame_index) + 1 ||
783 		    frame_id != le16_to_cpu(net->rx_hdr.frame_id)) {
784 			net->stats.rx_missed_errors++;
785 			return false;
786 		}
787 
788 		if (net->skb->len + frame_size > TBNET_MAX_MTU) {
789 			net->stats.rx_length_errors++;
790 			return false;
791 		}
792 
793 		return true;
794 	}
795 
796 	/* Start of packet, validate the frame header. tbnet_poll() puts the
797 	 * first frame in the skb linear area and every further frame in a page
798 	 * fragment, so a packet may not span more than MAX_SKB_FRAGS + 1 frames
799 	 * without overflowing skb_shinfo()->frags[].
800 	 */
801 	if (frame_count == 0 || frame_count > MAX_SKB_FRAGS + 1) {
802 		net->stats.rx_length_errors++;
803 		return false;
804 	}
805 	if (frame_index != 0) {
806 		net->stats.rx_missed_errors++;
807 		return false;
808 	}
809 
810 	return true;
811 }
812 
813 static int tbnet_poll(struct napi_struct *napi, int budget)
814 {
815 	struct tbnet *net = container_of(napi, struct tbnet, napi);
816 	unsigned int cleaned_count = tbnet_available_buffers(&net->rx_ring);
817 	struct device *dma_dev = tb_ring_dma_device(net->rx_ring.ring);
818 	unsigned int rx_packets = 0;
819 
820 	while (rx_packets < budget) {
821 		const struct thunderbolt_ip_frame_header *hdr;
822 		unsigned int hdr_size = sizeof(*hdr);
823 		struct sk_buff *skb = NULL;
824 		struct ring_frame *frame;
825 		struct tbnet_frame *tf;
826 		struct page *page;
827 		bool last = true;
828 		u32 frame_size;
829 
830 		/* Return some buffers to hardware, one at a time is too
831 		 * slow so allocate MAX_SKB_FRAGS buffers at the same
832 		 * time.
833 		 */
834 		if (cleaned_count >= MAX_SKB_FRAGS) {
835 			tbnet_alloc_rx_buffers(net, cleaned_count);
836 			cleaned_count = 0;
837 		}
838 
839 		frame = tb_ring_poll(net->rx_ring.ring);
840 		if (!frame)
841 			break;
842 
843 		dma_unmap_page(dma_dev, frame->buffer_phy,
844 			       TBNET_RX_PAGE_SIZE, DMA_FROM_DEVICE);
845 
846 		tf = container_of(frame, typeof(*tf), frame);
847 
848 		page = tf->page;
849 		tf->page = NULL;
850 		net->rx_ring.cons++;
851 		cleaned_count++;
852 
853 		hdr = page_address(page);
854 		if (!tbnet_check_frame(net, tf, hdr)) {
855 			trace_tbnet_invalid_rx_ip_frame(hdr->frame_size,
856 				hdr->frame_id, hdr->frame_index, hdr->frame_count);
857 			__free_pages(page, TBNET_RX_PAGE_ORDER);
858 			dev_kfree_skb_any(net->skb);
859 			net->skb = NULL;
860 			continue;
861 		}
862 
863 		trace_tbnet_rx_ip_frame(hdr->frame_size, hdr->frame_id,
864 					hdr->frame_index, hdr->frame_count);
865 		frame_size = le32_to_cpu(hdr->frame_size);
866 
867 		skb = net->skb;
868 		if (!skb) {
869 			skb = build_skb(page_address(page),
870 					TBNET_RX_PAGE_SIZE);
871 			if (!skb) {
872 				__free_pages(page, TBNET_RX_PAGE_ORDER);
873 				net->stats.rx_errors++;
874 				break;
875 			}
876 
877 			skb_reserve(skb, hdr_size);
878 			skb_put(skb, frame_size);
879 
880 			net->skb = skb;
881 		} else {
882 			skb_add_rx_frag(skb, skb_shinfo(skb)->nr_frags,
883 					page, hdr_size, frame_size,
884 					TBNET_RX_PAGE_SIZE - hdr_size);
885 		}
886 
887 		net->rx_hdr.frame_size = hdr->frame_size;
888 		net->rx_hdr.frame_count = hdr->frame_count;
889 		net->rx_hdr.frame_index = hdr->frame_index;
890 		net->rx_hdr.frame_id = hdr->frame_id;
891 		last = le16_to_cpu(net->rx_hdr.frame_index) ==
892 		       le32_to_cpu(net->rx_hdr.frame_count) - 1;
893 
894 		rx_packets++;
895 		net->stats.rx_bytes += frame_size;
896 
897 		if (last) {
898 			skb->protocol = eth_type_trans(skb, net->dev);
899 			trace_tbnet_rx_skb(skb);
900 			napi_gro_receive(&net->napi, skb);
901 			net->skb = NULL;
902 		}
903 	}
904 
905 	net->stats.rx_packets += rx_packets;
906 
907 	if (cleaned_count)
908 		tbnet_alloc_rx_buffers(net, cleaned_count);
909 
910 	if (rx_packets >= budget)
911 		return budget;
912 
913 	napi_complete_done(napi, rx_packets);
914 	/* Re-enable the ring interrupt */
915 	tb_ring_poll_complete(net->rx_ring.ring);
916 
917 	return rx_packets;
918 }
919 
920 static void tbnet_start_poll(void *data)
921 {
922 	struct tbnet *net = data;
923 
924 	napi_schedule(&net->napi);
925 }
926 
927 static int tbnet_open(struct net_device *dev)
928 {
929 	struct tbnet *net = netdev_priv(dev);
930 	struct tb_xdomain *xd = net->xd;
931 	u16 sof_mask, eof_mask;
932 	struct tb_ring *ring;
933 	unsigned int flags;
934 	int hopid;
935 
936 	netif_carrier_off(dev);
937 
938 	ring = tb_ring_alloc_tx(xd->tb->nhi, -1, TBNET_RING_SIZE,
939 				RING_FLAG_FRAME);
940 	if (!ring) {
941 		netdev_err(dev, "failed to allocate Tx ring\n");
942 		return -ENOMEM;
943 	}
944 	net->tx_ring.ring = ring;
945 
946 	hopid = tb_xdomain_alloc_out_hopid(xd, -1);
947 	if (hopid < 0) {
948 		netdev_err(dev, "failed to allocate Tx HopID\n");
949 		tb_ring_free(net->tx_ring.ring);
950 		net->tx_ring.ring = NULL;
951 		return hopid;
952 	}
953 	net->local_transmit_path = hopid;
954 
955 	sof_mask = BIT(TBIP_PDF_FRAME_START);
956 	eof_mask = BIT(TBIP_PDF_FRAME_END);
957 
958 	flags = RING_FLAG_FRAME;
959 	/* Only enable full E2E if the other end supports it too */
960 	if (tbnet_e2e && net->svc->prtcstns & TBNET_E2E)
961 		flags |= RING_FLAG_E2E;
962 
963 	ring = tb_ring_alloc_rx(xd->tb->nhi, -1, TBNET_RING_SIZE, flags,
964 				net->tx_ring.ring->hop, sof_mask,
965 				eof_mask, tbnet_start_poll, net);
966 	if (!ring) {
967 		netdev_err(dev, "failed to allocate Rx ring\n");
968 		tb_xdomain_release_out_hopid(xd, hopid);
969 		tb_ring_free(net->tx_ring.ring);
970 		net->tx_ring.ring = NULL;
971 		return -ENOMEM;
972 	}
973 	net->rx_ring.ring = ring;
974 
975 	tb_ring_throttling(net->tx_ring.ring, TBNET_THROTTLING);
976 	tb_ring_throttling(net->rx_ring.ring, TBNET_THROTTLING);
977 
978 	napi_enable(&net->napi);
979 	start_login(net);
980 
981 	return 0;
982 }
983 
984 static int tbnet_stop(struct net_device *dev)
985 {
986 	struct tbnet *net = netdev_priv(dev);
987 
988 	napi_disable(&net->napi);
989 
990 	cancel_work_sync(&net->disconnect_work);
991 	tbnet_tear_down(net, true);
992 
993 	tb_ring_free(net->rx_ring.ring);
994 	net->rx_ring.ring = NULL;
995 
996 	tb_xdomain_release_out_hopid(net->xd, net->local_transmit_path);
997 	tb_ring_free(net->tx_ring.ring);
998 	net->tx_ring.ring = NULL;
999 
1000 	return 0;
1001 }
1002 
1003 static bool tbnet_xmit_csum_and_map(struct tbnet *net, struct sk_buff *skb,
1004 	struct tbnet_frame **frames, u32 frame_count)
1005 {
1006 	struct thunderbolt_ip_frame_header *hdr = page_address(frames[0]->page);
1007 	struct device *dma_dev = tb_ring_dma_device(net->tx_ring.ring);
1008 	unsigned int i, len, offset = skb_transport_offset(skb);
1009 	/* Remove payload length from checksum */
1010 	u32 paylen = skb->len - skb_transport_offset(skb);
1011 	__wsum wsum = (__force __wsum)htonl(paylen);
1012 	__be16 protocol = skb->protocol;
1013 	void *data = skb->data;
1014 	void *dest = hdr + 1;
1015 	__sum16 *tucso;
1016 
1017 	if (skb->ip_summed != CHECKSUM_PARTIAL) {
1018 		/* No need to calculate checksum so we just update the
1019 		 * total frame count and sync the frames for DMA.
1020 		 */
1021 		for (i = 0; i < frame_count; i++) {
1022 			hdr = page_address(frames[i]->page);
1023 			hdr->frame_count = cpu_to_le32(frame_count);
1024 			trace_tbnet_tx_ip_frame(hdr->frame_size, hdr->frame_id,
1025 						hdr->frame_index, hdr->frame_count);
1026 			dma_sync_single_for_device(dma_dev,
1027 				frames[i]->frame.buffer_phy,
1028 				tb_ring_frame_size(&frames[i]->frame),
1029 						   DMA_TO_DEVICE);
1030 		}
1031 
1032 		return true;
1033 	}
1034 
1035 	if (protocol == htons(ETH_P_8021Q)) {
1036 		struct vlan_hdr *vhdr, vh;
1037 
1038 		vhdr = skb_header_pointer(skb, ETH_HLEN, sizeof(vh), &vh);
1039 		if (!vhdr)
1040 			return false;
1041 
1042 		protocol = vhdr->h_vlan_encapsulated_proto;
1043 	}
1044 
1045 	/* Data points on the beginning of packet.
1046 	 * Check is the checksum absolute place in the packet.
1047 	 * ipcso will update IP checksum.
1048 	 * tucso will update TCP/UDP checksum.
1049 	 */
1050 	if (protocol == htons(ETH_P_IP)) {
1051 		__sum16 *ipcso = dest + ((void *)&(ip_hdr(skb)->check) - data);
1052 
1053 		*ipcso = 0;
1054 		*ipcso = ip_fast_csum(dest + skb_network_offset(skb),
1055 				      ip_hdr(skb)->ihl);
1056 
1057 		if (ip_hdr(skb)->protocol == IPPROTO_TCP)
1058 			tucso = dest + ((void *)&(tcp_hdr(skb)->check) - data);
1059 		else if (ip_hdr(skb)->protocol == IPPROTO_UDP)
1060 			tucso = dest + ((void *)&(udp_hdr(skb)->check) - data);
1061 		else
1062 			return false;
1063 
1064 		*tucso = ~csum_tcpudp_magic(ip_hdr(skb)->saddr,
1065 					    ip_hdr(skb)->daddr, 0,
1066 					    ip_hdr(skb)->protocol, 0);
1067 	} else if (skb_is_gso(skb) && skb_is_gso_v6(skb)) {
1068 		tucso = dest + ((void *)&(tcp_hdr(skb)->check) - data);
1069 		*tucso = ~csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
1070 					  &ipv6_hdr(skb)->daddr, 0,
1071 					  IPPROTO_TCP, 0);
1072 	} else if (protocol == htons(ETH_P_IPV6)) {
1073 		tucso = dest + skb_checksum_start_offset(skb) + skb->csum_offset;
1074 		*tucso = ~csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
1075 					  &ipv6_hdr(skb)->daddr, 0,
1076 					  ipv6_hdr(skb)->nexthdr, 0);
1077 	} else {
1078 		return false;
1079 	}
1080 
1081 	/* First frame was headers, rest of the frames contain data.
1082 	 * Calculate checksum over each frame.
1083 	 */
1084 	for (i = 0; i < frame_count; i++) {
1085 		hdr = page_address(frames[i]->page);
1086 		dest = (void *)(hdr + 1) + offset;
1087 		len = le32_to_cpu(hdr->frame_size) - offset;
1088 		wsum = csum_partial(dest, len, wsum);
1089 		hdr->frame_count = cpu_to_le32(frame_count);
1090 		trace_tbnet_tx_ip_frame(hdr->frame_size, hdr->frame_id,
1091 					hdr->frame_index, hdr->frame_count);
1092 
1093 		offset = 0;
1094 	}
1095 
1096 	*tucso = csum_fold(wsum);
1097 
1098 	/* Checksum is finally calculated and we don't touch the memory
1099 	 * anymore, so DMA sync the frames now.
1100 	 */
1101 	for (i = 0; i < frame_count; i++) {
1102 		dma_sync_single_for_device(dma_dev, frames[i]->frame.buffer_phy,
1103 			tb_ring_frame_size(&frames[i]->frame), DMA_TO_DEVICE);
1104 	}
1105 
1106 	return true;
1107 }
1108 
1109 static void *tbnet_kmap_frag(struct sk_buff *skb, unsigned int frag_num,
1110 			     unsigned int *len)
1111 {
1112 	const skb_frag_t *frag = &skb_shinfo(skb)->frags[frag_num];
1113 
1114 	*len = skb_frag_size(frag);
1115 	return kmap_local_page(skb_frag_page(frag)) + skb_frag_off(frag);
1116 }
1117 
1118 static netdev_tx_t tbnet_start_xmit(struct sk_buff *skb,
1119 				    struct net_device *dev)
1120 {
1121 	struct tbnet *net = netdev_priv(dev);
1122 	struct tbnet_frame *frames[MAX_SKB_FRAGS];
1123 	u16 frame_id = atomic_read(&net->frame_id);
1124 	struct thunderbolt_ip_frame_header *hdr;
1125 	unsigned int len = skb_headlen(skb);
1126 	unsigned int data_len = skb->len;
1127 	unsigned int nframes, i;
1128 	unsigned int frag = 0;
1129 	void *src = skb->data;
1130 	u32 frame_index = 0;
1131 	bool unmap = false;
1132 	void *dest;
1133 
1134 	trace_tbnet_tx_skb(skb);
1135 
1136 	nframes = DIV_ROUND_UP(data_len, TBNET_MAX_PAYLOAD_SIZE);
1137 	if (tbnet_available_buffers(&net->tx_ring) < nframes) {
1138 		netif_stop_queue(net->dev);
1139 		return NETDEV_TX_BUSY;
1140 	}
1141 
1142 	frames[frame_index] = tbnet_get_tx_buffer(net);
1143 	if (!frames[frame_index])
1144 		goto err_drop;
1145 
1146 	hdr = page_address(frames[frame_index]->page);
1147 	dest = hdr + 1;
1148 
1149 	/* If overall packet is bigger than the frame data size */
1150 	while (data_len > TBNET_MAX_PAYLOAD_SIZE) {
1151 		unsigned int size_left = TBNET_MAX_PAYLOAD_SIZE;
1152 
1153 		hdr->frame_size = cpu_to_le32(TBNET_MAX_PAYLOAD_SIZE);
1154 		hdr->frame_index = cpu_to_le16(frame_index);
1155 		hdr->frame_id = cpu_to_le16(frame_id);
1156 
1157 		do {
1158 			if (len > size_left) {
1159 				/* Copy data onto Tx buffer data with
1160 				 * full frame size then break and go to
1161 				 * next frame
1162 				 */
1163 				memcpy(dest, src, size_left);
1164 				len -= size_left;
1165 				dest += size_left;
1166 				src += size_left;
1167 				break;
1168 			}
1169 
1170 			memcpy(dest, src, len);
1171 			size_left -= len;
1172 			dest += len;
1173 
1174 			if (unmap) {
1175 				kunmap_local(src);
1176 				unmap = false;
1177 			}
1178 
1179 			/* Ensure all fragments have been processed */
1180 			if (frag < skb_shinfo(skb)->nr_frags) {
1181 				/* Map and then unmap quickly */
1182 				src = tbnet_kmap_frag(skb, frag++, &len);
1183 				unmap = true;
1184 			} else if (unlikely(size_left > 0)) {
1185 				goto err_drop;
1186 			}
1187 		} while (size_left > 0);
1188 
1189 		data_len -= TBNET_MAX_PAYLOAD_SIZE;
1190 		frame_index++;
1191 
1192 		frames[frame_index] = tbnet_get_tx_buffer(net);
1193 		if (!frames[frame_index])
1194 			goto err_drop;
1195 
1196 		hdr = page_address(frames[frame_index]->page);
1197 		dest = hdr + 1;
1198 	}
1199 
1200 	hdr->frame_size = cpu_to_le32(data_len);
1201 	hdr->frame_index = cpu_to_le16(frame_index);
1202 	hdr->frame_id = cpu_to_le16(frame_id);
1203 
1204 	frames[frame_index]->frame.size = data_len + sizeof(*hdr);
1205 
1206 	/* In case the remaining data_len is smaller than a frame */
1207 	while (len < data_len) {
1208 		memcpy(dest, src, len);
1209 		data_len -= len;
1210 		dest += len;
1211 
1212 		if (unmap) {
1213 			kunmap_local(src);
1214 			unmap = false;
1215 		}
1216 
1217 		if (frag < skb_shinfo(skb)->nr_frags) {
1218 			src = tbnet_kmap_frag(skb, frag++, &len);
1219 			unmap = true;
1220 		} else if (unlikely(data_len > 0)) {
1221 			goto err_drop;
1222 		}
1223 	}
1224 
1225 	memcpy(dest, src, data_len);
1226 
1227 	if (unmap)
1228 		kunmap_local(src);
1229 
1230 	if (!tbnet_xmit_csum_and_map(net, skb, frames, frame_index + 1))
1231 		goto err_drop;
1232 
1233 	for (i = 0; i < frame_index + 1; i++)
1234 		tb_ring_tx(net->tx_ring.ring, &frames[i]->frame);
1235 
1236 	if (net->svc->prtcstns & TBNET_MATCH_FRAGS_ID)
1237 		atomic_inc(&net->frame_id);
1238 
1239 	net->stats.tx_packets++;
1240 	net->stats.tx_bytes += skb->len;
1241 
1242 	trace_tbnet_consume_skb(skb);
1243 	dev_consume_skb_any(skb);
1244 
1245 	return NETDEV_TX_OK;
1246 
1247 err_drop:
1248 	/* We can re-use the buffers */
1249 	net->tx_ring.cons -= frame_index;
1250 
1251 	dev_kfree_skb_any(skb);
1252 	net->stats.tx_errors++;
1253 
1254 	return NETDEV_TX_OK;
1255 }
1256 
1257 static void tbnet_get_stats64(struct net_device *dev,
1258 			      struct rtnl_link_stats64 *stats)
1259 {
1260 	struct tbnet *net = netdev_priv(dev);
1261 
1262 	stats->tx_packets = net->stats.tx_packets;
1263 	stats->rx_packets = net->stats.rx_packets;
1264 	stats->tx_bytes = net->stats.tx_bytes;
1265 	stats->rx_bytes = net->stats.rx_bytes;
1266 	stats->rx_errors = net->stats.rx_errors + net->stats.rx_length_errors +
1267 		net->stats.rx_over_errors + net->stats.rx_crc_errors +
1268 		net->stats.rx_missed_errors;
1269 	stats->tx_errors = net->stats.tx_errors;
1270 	stats->rx_length_errors = net->stats.rx_length_errors;
1271 	stats->rx_over_errors = net->stats.rx_over_errors;
1272 	stats->rx_crc_errors = net->stats.rx_crc_errors;
1273 	stats->rx_missed_errors = net->stats.rx_missed_errors;
1274 }
1275 
1276 static const struct net_device_ops tbnet_netdev_ops = {
1277 	.ndo_open = tbnet_open,
1278 	.ndo_stop = tbnet_stop,
1279 	.ndo_start_xmit = tbnet_start_xmit,
1280 	.ndo_set_mac_address = eth_mac_addr,
1281 	.ndo_get_stats64 = tbnet_get_stats64,
1282 };
1283 
1284 static int tbnet_get_link_ksettings(struct net_device *dev,
1285 				    struct ethtool_link_ksettings *cmd)
1286 {
1287 	const struct tbnet *net = netdev_priv(dev);
1288 	const struct tb_xdomain *xd = net->xd;
1289 	int speed;
1290 
1291 	ethtool_link_ksettings_zero_link_mode(cmd, supported);
1292 	ethtool_link_ksettings_zero_link_mode(cmd, advertising);
1293 
1294 	/* Figure out the current link speed and width */
1295 	switch (xd->link_speed) {
1296 	case 40:
1297 		speed = SPEED_80000;
1298 		break;
1299 
1300 	case 20:
1301 		if (xd->link_width == 2)
1302 			speed = SPEED_40000;
1303 		else
1304 			speed = SPEED_20000;
1305 		break;
1306 
1307 	case 10:
1308 		if (xd->link_width == 2) {
1309 			speed = SPEED_20000;
1310 			break;
1311 		}
1312 		fallthrough;
1313 
1314 	default:
1315 		speed = SPEED_10000;
1316 		break;
1317 	}
1318 
1319 	cmd->base.speed = speed;
1320 	cmd->base.duplex = DUPLEX_FULL;
1321 	cmd->base.autoneg = AUTONEG_DISABLE;
1322 	cmd->base.port = PORT_OTHER;
1323 
1324 	return 0;
1325 }
1326 
1327 static const struct ethtool_ops tbnet_ethtool_ops = {
1328 	.get_link_ksettings = tbnet_get_link_ksettings,
1329 };
1330 
1331 static void tbnet_generate_mac(struct net_device *dev)
1332 {
1333 	const struct tbnet *net = netdev_priv(dev);
1334 	const struct tb_xdomain *xd = net->xd;
1335 	u8 addr[ETH_ALEN];
1336 	u8 phy_port;
1337 	u32 hash;
1338 
1339 	phy_port = tb_phy_port_from_link(TBNET_L0_PORT_NUM(xd->route));
1340 
1341 	/* Unicast and locally administered MAC */
1342 	addr[0] = phy_port << 4 | 0x02;
1343 	hash = jhash2((u32 *)xd->local_uuid, 4, 0);
1344 	memcpy(addr + 1, &hash, sizeof(hash));
1345 	hash = jhash2((u32 *)xd->local_uuid, 4, hash);
1346 	addr[5] = hash & 0xff;
1347 	eth_hw_addr_set(dev, addr);
1348 
1349 	/* Allow changing it if needed */
1350 	dev->priv_flags |= IFF_LIVE_ADDR_CHANGE;
1351 }
1352 
1353 static int tbnet_probe(struct tb_service *svc, const struct tb_service_id *id)
1354 {
1355 	struct tb_xdomain *xd = tb_service_parent(svc);
1356 	struct net_device *dev;
1357 	struct tbnet *net;
1358 	int ret;
1359 
1360 	dev = alloc_etherdev(sizeof(*net));
1361 	if (!dev)
1362 		return -ENOMEM;
1363 
1364 	SET_NETDEV_DEV(dev, &svc->dev);
1365 
1366 	net = netdev_priv(dev);
1367 	INIT_DELAYED_WORK(&net->login_work, tbnet_login_work);
1368 	INIT_WORK(&net->connected_work, tbnet_connected_work);
1369 	INIT_WORK(&net->disconnect_work, tbnet_disconnect_work);
1370 	mutex_init(&net->connection_lock);
1371 	atomic_set(&net->command_id, 0);
1372 	atomic_set(&net->frame_id, 0);
1373 	net->svc = svc;
1374 	net->dev = dev;
1375 	net->xd = xd;
1376 
1377 	tbnet_generate_mac(dev);
1378 
1379 	strcpy(dev->name, "thunderbolt%d");
1380 	dev->netdev_ops = &tbnet_netdev_ops;
1381 	dev->ethtool_ops = &tbnet_ethtool_ops;
1382 
1383 	/* ThunderboltIP takes advantage of TSO packets but instead of
1384 	 * segmenting them we just split the packet into Thunderbolt
1385 	 * frames (maximum payload size of each frame is 4084 bytes) and
1386 	 * calculate checksum over the whole packet here.
1387 	 *
1388 	 * The receiving side does the opposite if the host OS supports
1389 	 * LRO, otherwise it needs to split the large packet into MTU
1390 	 * sized smaller packets.
1391 	 *
1392 	 * In order to receive large packets from the networking stack,
1393 	 * we need to announce support for most of the offloading
1394 	 * features here.
1395 	 */
1396 	dev->hw_features = NETIF_F_SG | NETIF_F_ALL_TSO | NETIF_F_GRO |
1397 			   NETIF_F_IP_CSUM | NETIF_F_IPV6_CSUM;
1398 	dev->features = dev->hw_features | NETIF_F_HIGHDMA;
1399 	dev->hard_header_len += sizeof(struct thunderbolt_ip_frame_header);
1400 
1401 	netif_napi_add(dev, &net->napi, tbnet_poll);
1402 
1403 	/* MTU range: 68 - 65522 */
1404 	dev->min_mtu = ETH_MIN_MTU;
1405 	dev->max_mtu = TBNET_MAX_MTU - ETH_HLEN;
1406 
1407 	net->handler.uuid = &tbnet_svc_uuid;
1408 	net->handler.callback = tbnet_handle_packet;
1409 	net->handler.data = net;
1410 	tb_register_protocol_handler(&net->handler);
1411 
1412 	tb_service_set_drvdata(svc, net);
1413 
1414 	ret = register_netdev(dev);
1415 	if (ret) {
1416 		tb_unregister_protocol_handler(&net->handler);
1417 		free_netdev(dev);
1418 		return ret;
1419 	}
1420 
1421 	return 0;
1422 }
1423 
1424 static void tbnet_remove(struct tb_service *svc)
1425 {
1426 	struct tbnet *net = tb_service_get_drvdata(svc);
1427 
1428 	unregister_netdev(net->dev);
1429 	tb_unregister_protocol_handler(&net->handler);
1430 	free_netdev(net->dev);
1431 }
1432 
1433 static void tbnet_shutdown(struct tb_service *svc)
1434 {
1435 	tbnet_tear_down(tb_service_get_drvdata(svc), true);
1436 }
1437 
1438 static int tbnet_suspend(struct device *dev)
1439 {
1440 	struct tb_service *svc = tb_to_service(dev);
1441 	struct tbnet *net = tb_service_get_drvdata(svc);
1442 
1443 	stop_login(net);
1444 	if (netif_running(net->dev)) {
1445 		netif_device_detach(net->dev);
1446 		tbnet_tear_down(net, true);
1447 	}
1448 
1449 	tb_unregister_protocol_handler(&net->handler);
1450 	return 0;
1451 }
1452 
1453 static int tbnet_resume(struct device *dev)
1454 {
1455 	struct tb_service *svc = tb_to_service(dev);
1456 	struct tbnet *net = tb_service_get_drvdata(svc);
1457 
1458 	tb_register_protocol_handler(&net->handler);
1459 
1460 	netif_carrier_off(net->dev);
1461 	if (netif_running(net->dev)) {
1462 		netif_device_attach(net->dev);
1463 		start_login(net);
1464 	}
1465 
1466 	return 0;
1467 }
1468 
1469 static DEFINE_SIMPLE_DEV_PM_OPS(tbnet_pm_ops, tbnet_suspend, tbnet_resume);
1470 
1471 static const struct tb_service_id tbnet_ids[] = {
1472 	{ TB_SERVICE("network", 1) },
1473 	{ },
1474 };
1475 MODULE_DEVICE_TABLE(tbsvc, tbnet_ids);
1476 
1477 static struct tb_service_driver tbnet_driver = {
1478 	.driver = {
1479 		.owner = THIS_MODULE,
1480 		.name = "thunderbolt-net",
1481 		.pm = pm_sleep_ptr(&tbnet_pm_ops),
1482 	},
1483 	.probe = tbnet_probe,
1484 	.remove = tbnet_remove,
1485 	.shutdown = tbnet_shutdown,
1486 	.id_table = tbnet_ids,
1487 };
1488 
1489 static int __init tbnet_init(void)
1490 {
1491 	unsigned int flags;
1492 	int ret;
1493 
1494 	tbnet_dir = tb_property_create_dir(&tbnet_dir_uuid);
1495 	if (!tbnet_dir)
1496 		return -ENOMEM;
1497 
1498 	tb_property_add_immediate(tbnet_dir, "prtcid", 1);
1499 	tb_property_add_immediate(tbnet_dir, "prtcvers", 1);
1500 	tb_property_add_immediate(tbnet_dir, "prtcrevs", 1);
1501 
1502 	flags = TBNET_MATCH_FRAGS_ID | TBNET_64K_FRAMES;
1503 	if (tbnet_e2e)
1504 		flags |= TBNET_E2E;
1505 	tb_property_add_immediate(tbnet_dir, "prtcstns", flags);
1506 
1507 	ret = tb_register_property_dir("network", tbnet_dir);
1508 	if (ret)
1509 		goto err_free_dir;
1510 
1511 	ret = tb_register_service_driver(&tbnet_driver);
1512 	if (ret)
1513 		goto err_unregister;
1514 
1515 	return 0;
1516 
1517 err_unregister:
1518 	tb_unregister_property_dir("network", tbnet_dir);
1519 err_free_dir:
1520 	tb_property_free_dir(tbnet_dir);
1521 
1522 	return ret;
1523 }
1524 module_init(tbnet_init);
1525 
1526 static void __exit tbnet_exit(void)
1527 {
1528 	tb_unregister_service_driver(&tbnet_driver);
1529 	tb_unregister_property_dir("network", tbnet_dir);
1530 	tb_property_free_dir(tbnet_dir);
1531 }
1532 module_exit(tbnet_exit);
1533 
1534 MODULE_AUTHOR("Amir Levy <amir.jer.levy@intel.com>");
1535 MODULE_AUTHOR("Michael Jamet <michael.jamet@intel.com>");
1536 MODULE_AUTHOR("Mika Westerberg <mika.westerberg@linux.intel.com>");
1537 MODULE_DESCRIPTION("Thunderbolt/USB4 network driver");
1538 MODULE_LICENSE("GPL v2");
1539