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