xref: /linux/drivers/thunderbolt/ctl.c (revision 83a37b3292f4aca799b355179ad6fbdd78a08e10)
1 /*
2  * Thunderbolt Cactus Ridge driver - control channel and configuration commands
3  *
4  * Copyright (c) 2014 Andreas Noever <andreas.noever@gmail.com>
5  */
6 
7 #include <linux/crc32.h>
8 #include <linux/delay.h>
9 #include <linux/slab.h>
10 #include <linux/pci.h>
11 #include <linux/dmapool.h>
12 #include <linux/workqueue.h>
13 
14 #include "ctl.h"
15 
16 
17 #define TB_CTL_RX_PKG_COUNT	10
18 #define TB_CTL_RETRIES		4
19 
20 /**
21  * struct tb_cfg - thunderbolt control channel
22  */
23 struct tb_ctl {
24 	struct tb_nhi *nhi;
25 	struct tb_ring *tx;
26 	struct tb_ring *rx;
27 
28 	struct dma_pool *frame_pool;
29 	struct ctl_pkg *rx_packets[TB_CTL_RX_PKG_COUNT];
30 	struct mutex request_queue_lock;
31 	struct list_head request_queue;
32 	bool running;
33 
34 	event_cb callback;
35 	void *callback_data;
36 };
37 
38 
39 #define tb_ctl_WARN(ctl, format, arg...) \
40 	dev_WARN(&(ctl)->nhi->pdev->dev, format, ## arg)
41 
42 #define tb_ctl_err(ctl, format, arg...) \
43 	dev_err(&(ctl)->nhi->pdev->dev, format, ## arg)
44 
45 #define tb_ctl_warn(ctl, format, arg...) \
46 	dev_warn(&(ctl)->nhi->pdev->dev, format, ## arg)
47 
48 #define tb_ctl_info(ctl, format, arg...) \
49 	dev_info(&(ctl)->nhi->pdev->dev, format, ## arg)
50 
51 #define tb_ctl_dbg(ctl, format, arg...) \
52 	dev_dbg(&(ctl)->nhi->pdev->dev, format, ## arg)
53 
54 static DECLARE_WAIT_QUEUE_HEAD(tb_cfg_request_cancel_queue);
55 /* Serializes access to request kref_get/put */
56 static DEFINE_MUTEX(tb_cfg_request_lock);
57 
58 /**
59  * tb_cfg_request_alloc() - Allocates a new config request
60  *
61  * This is refcounted object so when you are done with this, call
62  * tb_cfg_request_put() to it.
63  */
64 struct tb_cfg_request *tb_cfg_request_alloc(void)
65 {
66 	struct tb_cfg_request *req;
67 
68 	req = kzalloc(sizeof(*req), GFP_KERNEL);
69 	if (!req)
70 		return NULL;
71 
72 	kref_init(&req->kref);
73 
74 	return req;
75 }
76 
77 /**
78  * tb_cfg_request_get() - Increase refcount of a request
79  * @req: Request whose refcount is increased
80  */
81 void tb_cfg_request_get(struct tb_cfg_request *req)
82 {
83 	mutex_lock(&tb_cfg_request_lock);
84 	kref_get(&req->kref);
85 	mutex_unlock(&tb_cfg_request_lock);
86 }
87 
88 static void tb_cfg_request_destroy(struct kref *kref)
89 {
90 	struct tb_cfg_request *req = container_of(kref, typeof(*req), kref);
91 
92 	kfree(req);
93 }
94 
95 /**
96  * tb_cfg_request_put() - Decrease refcount and possibly release the request
97  * @req: Request whose refcount is decreased
98  *
99  * Call this function when you are done with the request. When refcount
100  * goes to %0 the object is released.
101  */
102 void tb_cfg_request_put(struct tb_cfg_request *req)
103 {
104 	mutex_lock(&tb_cfg_request_lock);
105 	kref_put(&req->kref, tb_cfg_request_destroy);
106 	mutex_unlock(&tb_cfg_request_lock);
107 }
108 
109 static int tb_cfg_request_enqueue(struct tb_ctl *ctl,
110 				  struct tb_cfg_request *req)
111 {
112 	WARN_ON(test_bit(TB_CFG_REQUEST_ACTIVE, &req->flags));
113 	WARN_ON(req->ctl);
114 
115 	mutex_lock(&ctl->request_queue_lock);
116 	if (!ctl->running) {
117 		mutex_unlock(&ctl->request_queue_lock);
118 		return -ENOTCONN;
119 	}
120 	req->ctl = ctl;
121 	list_add_tail(&req->list, &ctl->request_queue);
122 	set_bit(TB_CFG_REQUEST_ACTIVE, &req->flags);
123 	mutex_unlock(&ctl->request_queue_lock);
124 	return 0;
125 }
126 
127 static void tb_cfg_request_dequeue(struct tb_cfg_request *req)
128 {
129 	struct tb_ctl *ctl = req->ctl;
130 
131 	mutex_lock(&ctl->request_queue_lock);
132 	list_del(&req->list);
133 	clear_bit(TB_CFG_REQUEST_ACTIVE, &req->flags);
134 	if (test_bit(TB_CFG_REQUEST_CANCELED, &req->flags))
135 		wake_up(&tb_cfg_request_cancel_queue);
136 	mutex_unlock(&ctl->request_queue_lock);
137 }
138 
139 static bool tb_cfg_request_is_active(struct tb_cfg_request *req)
140 {
141 	return test_bit(TB_CFG_REQUEST_ACTIVE, &req->flags);
142 }
143 
144 static struct tb_cfg_request *
145 tb_cfg_request_find(struct tb_ctl *ctl, struct ctl_pkg *pkg)
146 {
147 	struct tb_cfg_request *req;
148 	bool found = false;
149 
150 	mutex_lock(&pkg->ctl->request_queue_lock);
151 	list_for_each_entry(req, &pkg->ctl->request_queue, list) {
152 		tb_cfg_request_get(req);
153 		if (req->match(req, pkg)) {
154 			found = true;
155 			break;
156 		}
157 		tb_cfg_request_put(req);
158 	}
159 	mutex_unlock(&pkg->ctl->request_queue_lock);
160 
161 	return found ? req : NULL;
162 }
163 
164 /* utility functions */
165 
166 
167 static int check_header(const struct ctl_pkg *pkg, u32 len,
168 			enum tb_cfg_pkg_type type, u64 route)
169 {
170 	struct tb_cfg_header *header = pkg->buffer;
171 
172 	/* check frame, TODO: frame flags */
173 	if (WARN(len != pkg->frame.size,
174 			"wrong framesize (expected %#x, got %#x)\n",
175 			len, pkg->frame.size))
176 		return -EIO;
177 	if (WARN(type != pkg->frame.eof, "wrong eof (expected %#x, got %#x)\n",
178 			type, pkg->frame.eof))
179 		return -EIO;
180 	if (WARN(pkg->frame.sof, "wrong sof (expected 0x0, got %#x)\n",
181 			pkg->frame.sof))
182 		return -EIO;
183 
184 	/* check header */
185 	if (WARN(header->unknown != 1 << 9,
186 			"header->unknown is %#x\n", header->unknown))
187 		return -EIO;
188 	if (WARN(route != tb_cfg_get_route(header),
189 			"wrong route (expected %llx, got %llx)",
190 			route, tb_cfg_get_route(header)))
191 		return -EIO;
192 	return 0;
193 }
194 
195 static int check_config_address(struct tb_cfg_address addr,
196 				enum tb_cfg_space space, u32 offset,
197 				u32 length)
198 {
199 	if (WARN(addr.zero, "addr.zero is %#x\n", addr.zero))
200 		return -EIO;
201 	if (WARN(space != addr.space, "wrong space (expected %x, got %x\n)",
202 			space, addr.space))
203 		return -EIO;
204 	if (WARN(offset != addr.offset, "wrong offset (expected %x, got %x\n)",
205 			offset, addr.offset))
206 		return -EIO;
207 	if (WARN(length != addr.length, "wrong space (expected %x, got %x\n)",
208 			length, addr.length))
209 		return -EIO;
210 	/*
211 	 * We cannot check addr->port as it is set to the upstream port of the
212 	 * sender.
213 	 */
214 	return 0;
215 }
216 
217 static struct tb_cfg_result decode_error(const struct ctl_pkg *response)
218 {
219 	struct cfg_error_pkg *pkg = response->buffer;
220 	struct tb_cfg_result res = { 0 };
221 	res.response_route = tb_cfg_get_route(&pkg->header);
222 	res.response_port = 0;
223 	res.err = check_header(response, sizeof(*pkg), TB_CFG_PKG_ERROR,
224 			       tb_cfg_get_route(&pkg->header));
225 	if (res.err)
226 		return res;
227 
228 	WARN(pkg->zero1, "pkg->zero1 is %#x\n", pkg->zero1);
229 	WARN(pkg->zero2, "pkg->zero1 is %#x\n", pkg->zero1);
230 	WARN(pkg->zero3, "pkg->zero1 is %#x\n", pkg->zero1);
231 	res.err = 1;
232 	res.tb_error = pkg->error;
233 	res.response_port = pkg->port;
234 	return res;
235 
236 }
237 
238 static struct tb_cfg_result parse_header(const struct ctl_pkg *pkg, u32 len,
239 					 enum tb_cfg_pkg_type type, u64 route)
240 {
241 	struct tb_cfg_header *header = pkg->buffer;
242 	struct tb_cfg_result res = { 0 };
243 
244 	if (pkg->frame.eof == TB_CFG_PKG_ERROR)
245 		return decode_error(pkg);
246 
247 	res.response_port = 0; /* will be updated later for cfg_read/write */
248 	res.response_route = tb_cfg_get_route(header);
249 	res.err = check_header(pkg, len, type, route);
250 	return res;
251 }
252 
253 static void tb_cfg_print_error(struct tb_ctl *ctl,
254 			       const struct tb_cfg_result *res)
255 {
256 	WARN_ON(res->err != 1);
257 	switch (res->tb_error) {
258 	case TB_CFG_ERROR_PORT_NOT_CONNECTED:
259 		/* Port is not connected. This can happen during surprise
260 		 * removal. Do not warn. */
261 		return;
262 	case TB_CFG_ERROR_INVALID_CONFIG_SPACE:
263 		/*
264 		 * Invalid cfg_space/offset/length combination in
265 		 * cfg_read/cfg_write.
266 		 */
267 		tb_ctl_WARN(ctl,
268 			"CFG_ERROR(%llx:%x): Invalid config space or offset\n",
269 			res->response_route, res->response_port);
270 		return;
271 	case TB_CFG_ERROR_NO_SUCH_PORT:
272 		/*
273 		 * - The route contains a non-existent port.
274 		 * - The route contains a non-PHY port (e.g. PCIe).
275 		 * - The port in cfg_read/cfg_write does not exist.
276 		 */
277 		tb_ctl_WARN(ctl, "CFG_ERROR(%llx:%x): Invalid port\n",
278 			res->response_route, res->response_port);
279 		return;
280 	case TB_CFG_ERROR_LOOP:
281 		tb_ctl_WARN(ctl, "CFG_ERROR(%llx:%x): Route contains a loop\n",
282 			res->response_route, res->response_port);
283 		return;
284 	default:
285 		/* 5,6,7,9 and 11 are also valid error codes */
286 		tb_ctl_WARN(ctl, "CFG_ERROR(%llx:%x): Unknown error\n",
287 			res->response_route, res->response_port);
288 		return;
289 	}
290 }
291 
292 static __be32 tb_crc(const void *data, size_t len)
293 {
294 	return cpu_to_be32(~__crc32c_le(~0, data, len));
295 }
296 
297 static void tb_ctl_pkg_free(struct ctl_pkg *pkg)
298 {
299 	if (pkg) {
300 		dma_pool_free(pkg->ctl->frame_pool,
301 			      pkg->buffer, pkg->frame.buffer_phy);
302 		kfree(pkg);
303 	}
304 }
305 
306 static struct ctl_pkg *tb_ctl_pkg_alloc(struct tb_ctl *ctl)
307 {
308 	struct ctl_pkg *pkg = kzalloc(sizeof(*pkg), GFP_KERNEL);
309 	if (!pkg)
310 		return NULL;
311 	pkg->ctl = ctl;
312 	pkg->buffer = dma_pool_alloc(ctl->frame_pool, GFP_KERNEL,
313 				     &pkg->frame.buffer_phy);
314 	if (!pkg->buffer) {
315 		kfree(pkg);
316 		return NULL;
317 	}
318 	return pkg;
319 }
320 
321 
322 /* RX/TX handling */
323 
324 static void tb_ctl_tx_callback(struct tb_ring *ring, struct ring_frame *frame,
325 			       bool canceled)
326 {
327 	struct ctl_pkg *pkg = container_of(frame, typeof(*pkg), frame);
328 	tb_ctl_pkg_free(pkg);
329 }
330 
331 /**
332  * tb_cfg_tx() - transmit a packet on the control channel
333  *
334  * len must be a multiple of four.
335  *
336  * Return: Returns 0 on success or an error code on failure.
337  */
338 static int tb_ctl_tx(struct tb_ctl *ctl, const void *data, size_t len,
339 		     enum tb_cfg_pkg_type type)
340 {
341 	int res;
342 	struct ctl_pkg *pkg;
343 	if (len % 4 != 0) { /* required for le->be conversion */
344 		tb_ctl_WARN(ctl, "TX: invalid size: %zu\n", len);
345 		return -EINVAL;
346 	}
347 	if (len > TB_FRAME_SIZE - 4) { /* checksum is 4 bytes */
348 		tb_ctl_WARN(ctl, "TX: packet too large: %zu/%d\n",
349 			    len, TB_FRAME_SIZE - 4);
350 		return -EINVAL;
351 	}
352 	pkg = tb_ctl_pkg_alloc(ctl);
353 	if (!pkg)
354 		return -ENOMEM;
355 	pkg->frame.callback = tb_ctl_tx_callback;
356 	pkg->frame.size = len + 4;
357 	pkg->frame.sof = type;
358 	pkg->frame.eof = type;
359 	cpu_to_be32_array(pkg->buffer, data, len / 4);
360 	*(__be32 *) (pkg->buffer + len) = tb_crc(pkg->buffer, len);
361 
362 	res = tb_ring_tx(ctl->tx, &pkg->frame);
363 	if (res) /* ring is stopped */
364 		tb_ctl_pkg_free(pkg);
365 	return res;
366 }
367 
368 /**
369  * tb_ctl_handle_event() - acknowledge a plug event, invoke ctl->callback
370  */
371 static bool tb_ctl_handle_event(struct tb_ctl *ctl, enum tb_cfg_pkg_type type,
372 				struct ctl_pkg *pkg, size_t size)
373 {
374 	return ctl->callback(ctl->callback_data, type, pkg->buffer, size);
375 }
376 
377 static void tb_ctl_rx_submit(struct ctl_pkg *pkg)
378 {
379 	tb_ring_rx(pkg->ctl->rx, &pkg->frame); /*
380 					     * We ignore failures during stop.
381 					     * All rx packets are referenced
382 					     * from ctl->rx_packets, so we do
383 					     * not loose them.
384 					     */
385 }
386 
387 static int tb_async_error(const struct ctl_pkg *pkg)
388 {
389 	const struct cfg_error_pkg *error = (const struct cfg_error_pkg *)pkg;
390 
391 	if (pkg->frame.eof != TB_CFG_PKG_ERROR)
392 		return false;
393 
394 	switch (error->error) {
395 	case TB_CFG_ERROR_LINK_ERROR:
396 	case TB_CFG_ERROR_HEC_ERROR_DETECTED:
397 	case TB_CFG_ERROR_FLOW_CONTROL_ERROR:
398 		return true;
399 
400 	default:
401 		return false;
402 	}
403 }
404 
405 static void tb_ctl_rx_callback(struct tb_ring *ring, struct ring_frame *frame,
406 			       bool canceled)
407 {
408 	struct ctl_pkg *pkg = container_of(frame, typeof(*pkg), frame);
409 	struct tb_cfg_request *req;
410 	__be32 crc32;
411 
412 	if (canceled)
413 		return; /*
414 			 * ring is stopped, packet is referenced from
415 			 * ctl->rx_packets.
416 			 */
417 
418 	if (frame->size < 4 || frame->size % 4 != 0) {
419 		tb_ctl_err(pkg->ctl, "RX: invalid size %#x, dropping packet\n",
420 			   frame->size);
421 		goto rx;
422 	}
423 
424 	frame->size -= 4; /* remove checksum */
425 	crc32 = tb_crc(pkg->buffer, frame->size);
426 	be32_to_cpu_array(pkg->buffer, pkg->buffer, frame->size / 4);
427 
428 	switch (frame->eof) {
429 	case TB_CFG_PKG_READ:
430 	case TB_CFG_PKG_WRITE:
431 	case TB_CFG_PKG_ERROR:
432 	case TB_CFG_PKG_OVERRIDE:
433 	case TB_CFG_PKG_RESET:
434 		if (*(__be32 *)(pkg->buffer + frame->size) != crc32) {
435 			tb_ctl_err(pkg->ctl,
436 				   "RX: checksum mismatch, dropping packet\n");
437 			goto rx;
438 		}
439 		if (tb_async_error(pkg)) {
440 			tb_ctl_handle_event(pkg->ctl, frame->eof,
441 					    pkg, frame->size);
442 			goto rx;
443 		}
444 		break;
445 
446 	case TB_CFG_PKG_EVENT:
447 	case TB_CFG_PKG_XDOMAIN_RESP:
448 	case TB_CFG_PKG_XDOMAIN_REQ:
449 		if (*(__be32 *)(pkg->buffer + frame->size) != crc32) {
450 			tb_ctl_err(pkg->ctl,
451 				   "RX: checksum mismatch, dropping packet\n");
452 			goto rx;
453 		}
454 		/* Fall through */
455 	case TB_CFG_PKG_ICM_EVENT:
456 		if (tb_ctl_handle_event(pkg->ctl, frame->eof, pkg, frame->size))
457 			goto rx;
458 		break;
459 
460 	default:
461 		break;
462 	}
463 
464 	/*
465 	 * The received packet will be processed only if there is an
466 	 * active request and that the packet is what is expected. This
467 	 * prevents packets such as replies coming after timeout has
468 	 * triggered from messing with the active requests.
469 	 */
470 	req = tb_cfg_request_find(pkg->ctl, pkg);
471 	if (req) {
472 		if (req->copy(req, pkg))
473 			schedule_work(&req->work);
474 		tb_cfg_request_put(req);
475 	}
476 
477 rx:
478 	tb_ctl_rx_submit(pkg);
479 }
480 
481 static void tb_cfg_request_work(struct work_struct *work)
482 {
483 	struct tb_cfg_request *req = container_of(work, typeof(*req), work);
484 
485 	if (!test_bit(TB_CFG_REQUEST_CANCELED, &req->flags))
486 		req->callback(req->callback_data);
487 
488 	tb_cfg_request_dequeue(req);
489 	tb_cfg_request_put(req);
490 }
491 
492 /**
493  * tb_cfg_request() - Start control request not waiting for it to complete
494  * @ctl: Control channel to use
495  * @req: Request to start
496  * @callback: Callback called when the request is completed
497  * @callback_data: Data to be passed to @callback
498  *
499  * This queues @req on the given control channel without waiting for it
500  * to complete. When the request completes @callback is called.
501  */
502 int tb_cfg_request(struct tb_ctl *ctl, struct tb_cfg_request *req,
503 		   void (*callback)(void *), void *callback_data)
504 {
505 	int ret;
506 
507 	req->flags = 0;
508 	req->callback = callback;
509 	req->callback_data = callback_data;
510 	INIT_WORK(&req->work, tb_cfg_request_work);
511 	INIT_LIST_HEAD(&req->list);
512 
513 	tb_cfg_request_get(req);
514 	ret = tb_cfg_request_enqueue(ctl, req);
515 	if (ret)
516 		goto err_put;
517 
518 	ret = tb_ctl_tx(ctl, req->request, req->request_size,
519 			req->request_type);
520 	if (ret)
521 		goto err_dequeue;
522 
523 	if (!req->response)
524 		schedule_work(&req->work);
525 
526 	return 0;
527 
528 err_dequeue:
529 	tb_cfg_request_dequeue(req);
530 err_put:
531 	tb_cfg_request_put(req);
532 
533 	return ret;
534 }
535 
536 /**
537  * tb_cfg_request_cancel() - Cancel a control request
538  * @req: Request to cancel
539  * @err: Error to assign to the request
540  *
541  * This function can be used to cancel ongoing request. It will wait
542  * until the request is not active anymore.
543  */
544 void tb_cfg_request_cancel(struct tb_cfg_request *req, int err)
545 {
546 	set_bit(TB_CFG_REQUEST_CANCELED, &req->flags);
547 	schedule_work(&req->work);
548 	wait_event(tb_cfg_request_cancel_queue, !tb_cfg_request_is_active(req));
549 	req->result.err = err;
550 }
551 
552 static void tb_cfg_request_complete(void *data)
553 {
554 	complete(data);
555 }
556 
557 /**
558  * tb_cfg_request_sync() - Start control request and wait until it completes
559  * @ctl: Control channel to use
560  * @req: Request to start
561  * @timeout_msec: Timeout how long to wait @req to complete
562  *
563  * Starts a control request and waits until it completes. If timeout
564  * triggers the request is canceled before function returns. Note the
565  * caller needs to make sure only one message for given switch is active
566  * at a time.
567  */
568 struct tb_cfg_result tb_cfg_request_sync(struct tb_ctl *ctl,
569 					 struct tb_cfg_request *req,
570 					 int timeout_msec)
571 {
572 	unsigned long timeout = msecs_to_jiffies(timeout_msec);
573 	struct tb_cfg_result res = { 0 };
574 	DECLARE_COMPLETION_ONSTACK(done);
575 	int ret;
576 
577 	ret = tb_cfg_request(ctl, req, tb_cfg_request_complete, &done);
578 	if (ret) {
579 		res.err = ret;
580 		return res;
581 	}
582 
583 	if (!wait_for_completion_timeout(&done, timeout))
584 		tb_cfg_request_cancel(req, -ETIMEDOUT);
585 
586 	flush_work(&req->work);
587 
588 	return req->result;
589 }
590 
591 /* public interface, alloc/start/stop/free */
592 
593 /**
594  * tb_ctl_alloc() - allocate a control channel
595  *
596  * cb will be invoked once for every hot plug event.
597  *
598  * Return: Returns a pointer on success or NULL on failure.
599  */
600 struct tb_ctl *tb_ctl_alloc(struct tb_nhi *nhi, event_cb cb, void *cb_data)
601 {
602 	int i;
603 	struct tb_ctl *ctl = kzalloc(sizeof(*ctl), GFP_KERNEL);
604 	if (!ctl)
605 		return NULL;
606 	ctl->nhi = nhi;
607 	ctl->callback = cb;
608 	ctl->callback_data = cb_data;
609 
610 	mutex_init(&ctl->request_queue_lock);
611 	INIT_LIST_HEAD(&ctl->request_queue);
612 	ctl->frame_pool = dma_pool_create("thunderbolt_ctl", &nhi->pdev->dev,
613 					 TB_FRAME_SIZE, 4, 0);
614 	if (!ctl->frame_pool)
615 		goto err;
616 
617 	ctl->tx = tb_ring_alloc_tx(nhi, 0, 10, RING_FLAG_NO_SUSPEND);
618 	if (!ctl->tx)
619 		goto err;
620 
621 	ctl->rx = tb_ring_alloc_rx(nhi, 0, 10, RING_FLAG_NO_SUSPEND, 0xffff,
622 				0xffff, NULL, NULL);
623 	if (!ctl->rx)
624 		goto err;
625 
626 	for (i = 0; i < TB_CTL_RX_PKG_COUNT; i++) {
627 		ctl->rx_packets[i] = tb_ctl_pkg_alloc(ctl);
628 		if (!ctl->rx_packets[i])
629 			goto err;
630 		ctl->rx_packets[i]->frame.callback = tb_ctl_rx_callback;
631 	}
632 
633 	tb_ctl_info(ctl, "control channel created\n");
634 	return ctl;
635 err:
636 	tb_ctl_free(ctl);
637 	return NULL;
638 }
639 
640 /**
641  * tb_ctl_free() - free a control channel
642  *
643  * Must be called after tb_ctl_stop.
644  *
645  * Must NOT be called from ctl->callback.
646  */
647 void tb_ctl_free(struct tb_ctl *ctl)
648 {
649 	int i;
650 
651 	if (!ctl)
652 		return;
653 
654 	if (ctl->rx)
655 		tb_ring_free(ctl->rx);
656 	if (ctl->tx)
657 		tb_ring_free(ctl->tx);
658 
659 	/* free RX packets */
660 	for (i = 0; i < TB_CTL_RX_PKG_COUNT; i++)
661 		tb_ctl_pkg_free(ctl->rx_packets[i]);
662 
663 
664 	if (ctl->frame_pool)
665 		dma_pool_destroy(ctl->frame_pool);
666 	kfree(ctl);
667 }
668 
669 /**
670  * tb_cfg_start() - start/resume the control channel
671  */
672 void tb_ctl_start(struct tb_ctl *ctl)
673 {
674 	int i;
675 	tb_ctl_info(ctl, "control channel starting...\n");
676 	tb_ring_start(ctl->tx); /* is used to ack hotplug packets, start first */
677 	tb_ring_start(ctl->rx);
678 	for (i = 0; i < TB_CTL_RX_PKG_COUNT; i++)
679 		tb_ctl_rx_submit(ctl->rx_packets[i]);
680 
681 	ctl->running = true;
682 }
683 
684 /**
685  * control() - pause the control channel
686  *
687  * All invocations of ctl->callback will have finished after this method
688  * returns.
689  *
690  * Must NOT be called from ctl->callback.
691  */
692 void tb_ctl_stop(struct tb_ctl *ctl)
693 {
694 	mutex_lock(&ctl->request_queue_lock);
695 	ctl->running = false;
696 	mutex_unlock(&ctl->request_queue_lock);
697 
698 	tb_ring_stop(ctl->rx);
699 	tb_ring_stop(ctl->tx);
700 
701 	if (!list_empty(&ctl->request_queue))
702 		tb_ctl_WARN(ctl, "dangling request in request_queue\n");
703 	INIT_LIST_HEAD(&ctl->request_queue);
704 	tb_ctl_info(ctl, "control channel stopped\n");
705 }
706 
707 /* public interface, commands */
708 
709 /**
710  * tb_cfg_error() - send error packet
711  *
712  * Return: Returns 0 on success or an error code on failure.
713  */
714 int tb_cfg_error(struct tb_ctl *ctl, u64 route, u32 port,
715 		 enum tb_cfg_error error)
716 {
717 	struct cfg_error_pkg pkg = {
718 		.header = tb_cfg_make_header(route),
719 		.port = port,
720 		.error = error,
721 	};
722 	tb_ctl_info(ctl, "resetting error on %llx:%x.\n", route, port);
723 	return tb_ctl_tx(ctl, &pkg, sizeof(pkg), TB_CFG_PKG_ERROR);
724 }
725 
726 static bool tb_cfg_match(const struct tb_cfg_request *req,
727 			 const struct ctl_pkg *pkg)
728 {
729 	u64 route = tb_cfg_get_route(pkg->buffer) & ~BIT_ULL(63);
730 
731 	if (pkg->frame.eof == TB_CFG_PKG_ERROR)
732 		return true;
733 
734 	if (pkg->frame.eof != req->response_type)
735 		return false;
736 	if (route != tb_cfg_get_route(req->request))
737 		return false;
738 	if (pkg->frame.size != req->response_size)
739 		return false;
740 
741 	if (pkg->frame.eof == TB_CFG_PKG_READ ||
742 	    pkg->frame.eof == TB_CFG_PKG_WRITE) {
743 		const struct cfg_read_pkg *req_hdr = req->request;
744 		const struct cfg_read_pkg *res_hdr = pkg->buffer;
745 
746 		if (req_hdr->addr.seq != res_hdr->addr.seq)
747 			return false;
748 	}
749 
750 	return true;
751 }
752 
753 static bool tb_cfg_copy(struct tb_cfg_request *req, const struct ctl_pkg *pkg)
754 {
755 	struct tb_cfg_result res;
756 
757 	/* Now make sure it is in expected format */
758 	res = parse_header(pkg, req->response_size, req->response_type,
759 			   tb_cfg_get_route(req->request));
760 	if (!res.err)
761 		memcpy(req->response, pkg->buffer, req->response_size);
762 
763 	req->result = res;
764 
765 	/* Always complete when first response is received */
766 	return true;
767 }
768 
769 /**
770  * tb_cfg_reset() - send a reset packet and wait for a response
771  *
772  * If the switch at route is incorrectly configured then we will not receive a
773  * reply (even though the switch will reset). The caller should check for
774  * -ETIMEDOUT and attempt to reconfigure the switch.
775  */
776 struct tb_cfg_result tb_cfg_reset(struct tb_ctl *ctl, u64 route,
777 				  int timeout_msec)
778 {
779 	struct cfg_reset_pkg request = { .header = tb_cfg_make_header(route) };
780 	struct tb_cfg_result res = { 0 };
781 	struct tb_cfg_header reply;
782 	struct tb_cfg_request *req;
783 
784 	req = tb_cfg_request_alloc();
785 	if (!req) {
786 		res.err = -ENOMEM;
787 		return res;
788 	}
789 
790 	req->match = tb_cfg_match;
791 	req->copy = tb_cfg_copy;
792 	req->request = &request;
793 	req->request_size = sizeof(request);
794 	req->request_type = TB_CFG_PKG_RESET;
795 	req->response = &reply;
796 	req->response_size = sizeof(reply);
797 	req->response_type = TB_CFG_PKG_RESET;
798 
799 	res = tb_cfg_request_sync(ctl, req, timeout_msec);
800 
801 	tb_cfg_request_put(req);
802 
803 	return res;
804 }
805 
806 /**
807  * tb_cfg_read() - read from config space into buffer
808  *
809  * Offset and length are in dwords.
810  */
811 struct tb_cfg_result tb_cfg_read_raw(struct tb_ctl *ctl, void *buffer,
812 		u64 route, u32 port, enum tb_cfg_space space,
813 		u32 offset, u32 length, int timeout_msec)
814 {
815 	struct tb_cfg_result res = { 0 };
816 	struct cfg_read_pkg request = {
817 		.header = tb_cfg_make_header(route),
818 		.addr = {
819 			.port = port,
820 			.space = space,
821 			.offset = offset,
822 			.length = length,
823 		},
824 	};
825 	struct cfg_write_pkg reply;
826 	int retries = 0;
827 
828 	while (retries < TB_CTL_RETRIES) {
829 		struct tb_cfg_request *req;
830 
831 		req = tb_cfg_request_alloc();
832 		if (!req) {
833 			res.err = -ENOMEM;
834 			return res;
835 		}
836 
837 		request.addr.seq = retries++;
838 
839 		req->match = tb_cfg_match;
840 		req->copy = tb_cfg_copy;
841 		req->request = &request;
842 		req->request_size = sizeof(request);
843 		req->request_type = TB_CFG_PKG_READ;
844 		req->response = &reply;
845 		req->response_size = 12 + 4 * length;
846 		req->response_type = TB_CFG_PKG_READ;
847 
848 		res = tb_cfg_request_sync(ctl, req, timeout_msec);
849 
850 		tb_cfg_request_put(req);
851 
852 		if (res.err != -ETIMEDOUT)
853 			break;
854 
855 		/* Wait a bit (arbitrary time) until we send a retry */
856 		usleep_range(10, 100);
857 	}
858 
859 	if (res.err)
860 		return res;
861 
862 	res.response_port = reply.addr.port;
863 	res.err = check_config_address(reply.addr, space, offset, length);
864 	if (!res.err)
865 		memcpy(buffer, &reply.data, 4 * length);
866 	return res;
867 }
868 
869 /**
870  * tb_cfg_write() - write from buffer into config space
871  *
872  * Offset and length are in dwords.
873  */
874 struct tb_cfg_result tb_cfg_write_raw(struct tb_ctl *ctl, const void *buffer,
875 		u64 route, u32 port, enum tb_cfg_space space,
876 		u32 offset, u32 length, int timeout_msec)
877 {
878 	struct tb_cfg_result res = { 0 };
879 	struct cfg_write_pkg request = {
880 		.header = tb_cfg_make_header(route),
881 		.addr = {
882 			.port = port,
883 			.space = space,
884 			.offset = offset,
885 			.length = length,
886 		},
887 	};
888 	struct cfg_read_pkg reply;
889 	int retries = 0;
890 
891 	memcpy(&request.data, buffer, length * 4);
892 
893 	while (retries < TB_CTL_RETRIES) {
894 		struct tb_cfg_request *req;
895 
896 		req = tb_cfg_request_alloc();
897 		if (!req) {
898 			res.err = -ENOMEM;
899 			return res;
900 		}
901 
902 		request.addr.seq = retries++;
903 
904 		req->match = tb_cfg_match;
905 		req->copy = tb_cfg_copy;
906 		req->request = &request;
907 		req->request_size = 12 + 4 * length;
908 		req->request_type = TB_CFG_PKG_WRITE;
909 		req->response = &reply;
910 		req->response_size = sizeof(reply);
911 		req->response_type = TB_CFG_PKG_WRITE;
912 
913 		res = tb_cfg_request_sync(ctl, req, timeout_msec);
914 
915 		tb_cfg_request_put(req);
916 
917 		if (res.err != -ETIMEDOUT)
918 			break;
919 
920 		/* Wait a bit (arbitrary time) until we send a retry */
921 		usleep_range(10, 100);
922 	}
923 
924 	if (res.err)
925 		return res;
926 
927 	res.response_port = reply.addr.port;
928 	res.err = check_config_address(reply.addr, space, offset, length);
929 	return res;
930 }
931 
932 int tb_cfg_read(struct tb_ctl *ctl, void *buffer, u64 route, u32 port,
933 		enum tb_cfg_space space, u32 offset, u32 length)
934 {
935 	struct tb_cfg_result res = tb_cfg_read_raw(ctl, buffer, route, port,
936 			space, offset, length, TB_CFG_DEFAULT_TIMEOUT);
937 	switch (res.err) {
938 	case 0:
939 		/* Success */
940 		break;
941 
942 	case 1:
943 		/* Thunderbolt error, tb_error holds the actual number */
944 		tb_cfg_print_error(ctl, &res);
945 		return -EIO;
946 
947 	case -ETIMEDOUT:
948 		tb_ctl_warn(ctl, "timeout reading config space %u from %#x\n",
949 			    space, offset);
950 		break;
951 
952 	default:
953 		WARN(1, "tb_cfg_read: %d\n", res.err);
954 		break;
955 	}
956 	return res.err;
957 }
958 
959 int tb_cfg_write(struct tb_ctl *ctl, const void *buffer, u64 route, u32 port,
960 		 enum tb_cfg_space space, u32 offset, u32 length)
961 {
962 	struct tb_cfg_result res = tb_cfg_write_raw(ctl, buffer, route, port,
963 			space, offset, length, TB_CFG_DEFAULT_TIMEOUT);
964 	switch (res.err) {
965 	case 0:
966 		/* Success */
967 		break;
968 
969 	case 1:
970 		/* Thunderbolt error, tb_error holds the actual number */
971 		tb_cfg_print_error(ctl, &res);
972 		return -EIO;
973 
974 	case -ETIMEDOUT:
975 		tb_ctl_warn(ctl, "timeout writing config space %u to %#x\n",
976 			    space, offset);
977 		break;
978 
979 	default:
980 		WARN(1, "tb_cfg_write: %d\n", res.err);
981 		break;
982 	}
983 	return res.err;
984 }
985 
986 /**
987  * tb_cfg_get_upstream_port() - get upstream port number of switch at route
988  *
989  * Reads the first dword from the switches TB_CFG_SWITCH config area and
990  * returns the port number from which the reply originated.
991  *
992  * Return: Returns the upstream port number on success or an error code on
993  * failure.
994  */
995 int tb_cfg_get_upstream_port(struct tb_ctl *ctl, u64 route)
996 {
997 	u32 dummy;
998 	struct tb_cfg_result res = tb_cfg_read_raw(ctl, &dummy, route, 0,
999 						   TB_CFG_SWITCH, 0, 1,
1000 						   TB_CFG_DEFAULT_TIMEOUT);
1001 	if (res.err == 1)
1002 		return -EIO;
1003 	if (res.err)
1004 		return res.err;
1005 	return res.response_port;
1006 }
1007