thunderbolt: Handle ERR_LOCK notification
[linux-2.6-microblaze.git] / drivers / thunderbolt / ctl.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Thunderbolt driver - control channel and configuration commands
4  *
5  * Copyright (c) 2014 Andreas Noever <andreas.noever@gmail.com>
6  * Copyright (C) 2018, Intel Corporation
7  */
8
9 #include <linux/crc32.h>
10 #include <linux/delay.h>
11 #include <linux/slab.h>
12 #include <linux/pci.h>
13 #include <linux/dmapool.h>
14 #include <linux/workqueue.h>
15
16 #include "ctl.h"
17
18
19 #define TB_CTL_RX_PKG_COUNT     10
20 #define TB_CTL_RETRIES          4
21
22 /**
23  * struct tb_cfg - thunderbolt control channel
24  */
25 struct tb_ctl {
26         struct tb_nhi *nhi;
27         struct tb_ring *tx;
28         struct tb_ring *rx;
29
30         struct dma_pool *frame_pool;
31         struct ctl_pkg *rx_packets[TB_CTL_RX_PKG_COUNT];
32         struct mutex request_queue_lock;
33         struct list_head request_queue;
34         bool running;
35
36         event_cb callback;
37         void *callback_data;
38 };
39
40
41 #define tb_ctl_WARN(ctl, format, arg...) \
42         dev_WARN(&(ctl)->nhi->pdev->dev, format, ## arg)
43
44 #define tb_ctl_err(ctl, format, arg...) \
45         dev_err(&(ctl)->nhi->pdev->dev, format, ## arg)
46
47 #define tb_ctl_warn(ctl, format, arg...) \
48         dev_warn(&(ctl)->nhi->pdev->dev, format, ## arg)
49
50 #define tb_ctl_info(ctl, format, arg...) \
51         dev_info(&(ctl)->nhi->pdev->dev, format, ## arg)
52
53 #define tb_ctl_dbg(ctl, format, arg...) \
54         dev_dbg(&(ctl)->nhi->pdev->dev, format, ## arg)
55
56 static DECLARE_WAIT_QUEUE_HEAD(tb_cfg_request_cancel_queue);
57 /* Serializes access to request kref_get/put */
58 static DEFINE_MUTEX(tb_cfg_request_lock);
59
60 /**
61  * tb_cfg_request_alloc() - Allocates a new config request
62  *
63  * This is refcounted object so when you are done with this, call
64  * tb_cfg_request_put() to it.
65  */
66 struct tb_cfg_request *tb_cfg_request_alloc(void)
67 {
68         struct tb_cfg_request *req;
69
70         req = kzalloc(sizeof(*req), GFP_KERNEL);
71         if (!req)
72                 return NULL;
73
74         kref_init(&req->kref);
75
76         return req;
77 }
78
79 /**
80  * tb_cfg_request_get() - Increase refcount of a request
81  * @req: Request whose refcount is increased
82  */
83 void tb_cfg_request_get(struct tb_cfg_request *req)
84 {
85         mutex_lock(&tb_cfg_request_lock);
86         kref_get(&req->kref);
87         mutex_unlock(&tb_cfg_request_lock);
88 }
89
90 static void tb_cfg_request_destroy(struct kref *kref)
91 {
92         struct tb_cfg_request *req = container_of(kref, typeof(*req), kref);
93
94         kfree(req);
95 }
96
97 /**
98  * tb_cfg_request_put() - Decrease refcount and possibly release the request
99  * @req: Request whose refcount is decreased
100  *
101  * Call this function when you are done with the request. When refcount
102  * goes to %0 the object is released.
103  */
104 void tb_cfg_request_put(struct tb_cfg_request *req)
105 {
106         mutex_lock(&tb_cfg_request_lock);
107         kref_put(&req->kref, tb_cfg_request_destroy);
108         mutex_unlock(&tb_cfg_request_lock);
109 }
110
111 static int tb_cfg_request_enqueue(struct tb_ctl *ctl,
112                                   struct tb_cfg_request *req)
113 {
114         WARN_ON(test_bit(TB_CFG_REQUEST_ACTIVE, &req->flags));
115         WARN_ON(req->ctl);
116
117         mutex_lock(&ctl->request_queue_lock);
118         if (!ctl->running) {
119                 mutex_unlock(&ctl->request_queue_lock);
120                 return -ENOTCONN;
121         }
122         req->ctl = ctl;
123         list_add_tail(&req->list, &ctl->request_queue);
124         set_bit(TB_CFG_REQUEST_ACTIVE, &req->flags);
125         mutex_unlock(&ctl->request_queue_lock);
126         return 0;
127 }
128
129 static void tb_cfg_request_dequeue(struct tb_cfg_request *req)
130 {
131         struct tb_ctl *ctl = req->ctl;
132
133         mutex_lock(&ctl->request_queue_lock);
134         list_del(&req->list);
135         clear_bit(TB_CFG_REQUEST_ACTIVE, &req->flags);
136         if (test_bit(TB_CFG_REQUEST_CANCELED, &req->flags))
137                 wake_up(&tb_cfg_request_cancel_queue);
138         mutex_unlock(&ctl->request_queue_lock);
139 }
140
141 static bool tb_cfg_request_is_active(struct tb_cfg_request *req)
142 {
143         return test_bit(TB_CFG_REQUEST_ACTIVE, &req->flags);
144 }
145
146 static struct tb_cfg_request *
147 tb_cfg_request_find(struct tb_ctl *ctl, struct ctl_pkg *pkg)
148 {
149         struct tb_cfg_request *req;
150         bool found = false;
151
152         mutex_lock(&pkg->ctl->request_queue_lock);
153         list_for_each_entry(req, &pkg->ctl->request_queue, list) {
154                 tb_cfg_request_get(req);
155                 if (req->match(req, pkg)) {
156                         found = true;
157                         break;
158                 }
159                 tb_cfg_request_put(req);
160         }
161         mutex_unlock(&pkg->ctl->request_queue_lock);
162
163         return found ? req : NULL;
164 }
165
166 /* utility functions */
167
168
169 static int check_header(const struct ctl_pkg *pkg, u32 len,
170                         enum tb_cfg_pkg_type type, u64 route)
171 {
172         struct tb_cfg_header *header = pkg->buffer;
173
174         /* check frame, TODO: frame flags */
175         if (WARN(len != pkg->frame.size,
176                         "wrong framesize (expected %#x, got %#x)\n",
177                         len, pkg->frame.size))
178                 return -EIO;
179         if (WARN(type != pkg->frame.eof, "wrong eof (expected %#x, got %#x)\n",
180                         type, pkg->frame.eof))
181                 return -EIO;
182         if (WARN(pkg->frame.sof, "wrong sof (expected 0x0, got %#x)\n",
183                         pkg->frame.sof))
184                 return -EIO;
185
186         /* check header */
187         if (WARN(header->unknown != 1 << 9,
188                         "header->unknown is %#x\n", header->unknown))
189                 return -EIO;
190         if (WARN(route != tb_cfg_get_route(header),
191                         "wrong route (expected %llx, got %llx)",
192                         route, tb_cfg_get_route(header)))
193                 return -EIO;
194         return 0;
195 }
196
197 static int check_config_address(struct tb_cfg_address addr,
198                                 enum tb_cfg_space space, u32 offset,
199                                 u32 length)
200 {
201         if (WARN(addr.zero, "addr.zero is %#x\n", addr.zero))
202                 return -EIO;
203         if (WARN(space != addr.space, "wrong space (expected %x, got %x\n)",
204                         space, addr.space))
205                 return -EIO;
206         if (WARN(offset != addr.offset, "wrong offset (expected %x, got %x\n)",
207                         offset, addr.offset))
208                 return -EIO;
209         if (WARN(length != addr.length, "wrong space (expected %x, got %x\n)",
210                         length, addr.length))
211                 return -EIO;
212         /*
213          * We cannot check addr->port as it is set to the upstream port of the
214          * sender.
215          */
216         return 0;
217 }
218
219 static struct tb_cfg_result decode_error(const struct ctl_pkg *response)
220 {
221         struct cfg_error_pkg *pkg = response->buffer;
222         struct tb_cfg_result res = { 0 };
223         res.response_route = tb_cfg_get_route(&pkg->header);
224         res.response_port = 0;
225         res.err = check_header(response, sizeof(*pkg), TB_CFG_PKG_ERROR,
226                                tb_cfg_get_route(&pkg->header));
227         if (res.err)
228                 return res;
229
230         WARN(pkg->zero1, "pkg->zero1 is %#x\n", pkg->zero1);
231         WARN(pkg->zero2, "pkg->zero1 is %#x\n", pkg->zero1);
232         WARN(pkg->zero3, "pkg->zero1 is %#x\n", pkg->zero1);
233         res.err = 1;
234         res.tb_error = pkg->error;
235         res.response_port = pkg->port;
236         return res;
237
238 }
239
240 static struct tb_cfg_result parse_header(const struct ctl_pkg *pkg, u32 len,
241                                          enum tb_cfg_pkg_type type, u64 route)
242 {
243         struct tb_cfg_header *header = pkg->buffer;
244         struct tb_cfg_result res = { 0 };
245
246         if (pkg->frame.eof == TB_CFG_PKG_ERROR)
247                 return decode_error(pkg);
248
249         res.response_port = 0; /* will be updated later for cfg_read/write */
250         res.response_route = tb_cfg_get_route(header);
251         res.err = check_header(pkg, len, type, route);
252         return res;
253 }
254
255 static void tb_cfg_print_error(struct tb_ctl *ctl,
256                                const struct tb_cfg_result *res)
257 {
258         WARN_ON(res->err != 1);
259         switch (res->tb_error) {
260         case TB_CFG_ERROR_PORT_NOT_CONNECTED:
261                 /* Port is not connected. This can happen during surprise
262                  * removal. Do not warn. */
263                 return;
264         case TB_CFG_ERROR_INVALID_CONFIG_SPACE:
265                 /*
266                  * Invalid cfg_space/offset/length combination in
267                  * cfg_read/cfg_write.
268                  */
269                 tb_ctl_dbg(ctl, "%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         case TB_CFG_ERROR_LOCK:
286                 tb_ctl_warn(ctl, "%llx:%x: downstream port is locked\n",
287                             res->response_route, res->response_port);
288                 return;
289         default:
290                 /* 5,6,7,9 and 11 are also valid error codes */
291                 tb_ctl_WARN(ctl, "CFG_ERROR(%llx:%x): Unknown error\n",
292                         res->response_route, res->response_port);
293                 return;
294         }
295 }
296
297 static __be32 tb_crc(const void *data, size_t len)
298 {
299         return cpu_to_be32(~__crc32c_le(~0, data, len));
300 }
301
302 static void tb_ctl_pkg_free(struct ctl_pkg *pkg)
303 {
304         if (pkg) {
305                 dma_pool_free(pkg->ctl->frame_pool,
306                               pkg->buffer, pkg->frame.buffer_phy);
307                 kfree(pkg);
308         }
309 }
310
311 static struct ctl_pkg *tb_ctl_pkg_alloc(struct tb_ctl *ctl)
312 {
313         struct ctl_pkg *pkg = kzalloc(sizeof(*pkg), GFP_KERNEL);
314         if (!pkg)
315                 return NULL;
316         pkg->ctl = ctl;
317         pkg->buffer = dma_pool_alloc(ctl->frame_pool, GFP_KERNEL,
318                                      &pkg->frame.buffer_phy);
319         if (!pkg->buffer) {
320                 kfree(pkg);
321                 return NULL;
322         }
323         return pkg;
324 }
325
326
327 /* RX/TX handling */
328
329 static void tb_ctl_tx_callback(struct tb_ring *ring, struct ring_frame *frame,
330                                bool canceled)
331 {
332         struct ctl_pkg *pkg = container_of(frame, typeof(*pkg), frame);
333         tb_ctl_pkg_free(pkg);
334 }
335
336 /**
337  * tb_cfg_tx() - transmit a packet on the control channel
338  *
339  * len must be a multiple of four.
340  *
341  * Return: Returns 0 on success or an error code on failure.
342  */
343 static int tb_ctl_tx(struct tb_ctl *ctl, const void *data, size_t len,
344                      enum tb_cfg_pkg_type type)
345 {
346         int res;
347         struct ctl_pkg *pkg;
348         if (len % 4 != 0) { /* required for le->be conversion */
349                 tb_ctl_WARN(ctl, "TX: invalid size: %zu\n", len);
350                 return -EINVAL;
351         }
352         if (len > TB_FRAME_SIZE - 4) { /* checksum is 4 bytes */
353                 tb_ctl_WARN(ctl, "TX: packet too large: %zu/%d\n",
354                             len, TB_FRAME_SIZE - 4);
355                 return -EINVAL;
356         }
357         pkg = tb_ctl_pkg_alloc(ctl);
358         if (!pkg)
359                 return -ENOMEM;
360         pkg->frame.callback = tb_ctl_tx_callback;
361         pkg->frame.size = len + 4;
362         pkg->frame.sof = type;
363         pkg->frame.eof = type;
364         cpu_to_be32_array(pkg->buffer, data, len / 4);
365         *(__be32 *) (pkg->buffer + len) = tb_crc(pkg->buffer, len);
366
367         res = tb_ring_tx(ctl->tx, &pkg->frame);
368         if (res) /* ring is stopped */
369                 tb_ctl_pkg_free(pkg);
370         return res;
371 }
372
373 /**
374  * tb_ctl_handle_event() - acknowledge a plug event, invoke ctl->callback
375  */
376 static bool tb_ctl_handle_event(struct tb_ctl *ctl, enum tb_cfg_pkg_type type,
377                                 struct ctl_pkg *pkg, size_t size)
378 {
379         return ctl->callback(ctl->callback_data, type, pkg->buffer, size);
380 }
381
382 static void tb_ctl_rx_submit(struct ctl_pkg *pkg)
383 {
384         tb_ring_rx(pkg->ctl->rx, &pkg->frame); /*
385                                              * We ignore failures during stop.
386                                              * All rx packets are referenced
387                                              * from ctl->rx_packets, so we do
388                                              * not loose them.
389                                              */
390 }
391
392 static int tb_async_error(const struct ctl_pkg *pkg)
393 {
394         const struct cfg_error_pkg *error = (const struct cfg_error_pkg *)pkg;
395
396         if (pkg->frame.eof != TB_CFG_PKG_ERROR)
397                 return false;
398
399         switch (error->error) {
400         case TB_CFG_ERROR_LINK_ERROR:
401         case TB_CFG_ERROR_HEC_ERROR_DETECTED:
402         case TB_CFG_ERROR_FLOW_CONTROL_ERROR:
403                 return true;
404
405         default:
406                 return false;
407         }
408 }
409
410 static void tb_ctl_rx_callback(struct tb_ring *ring, struct ring_frame *frame,
411                                bool canceled)
412 {
413         struct ctl_pkg *pkg = container_of(frame, typeof(*pkg), frame);
414         struct tb_cfg_request *req;
415         __be32 crc32;
416
417         if (canceled)
418                 return; /*
419                          * ring is stopped, packet is referenced from
420                          * ctl->rx_packets.
421                          */
422
423         if (frame->size < 4 || frame->size % 4 != 0) {
424                 tb_ctl_err(pkg->ctl, "RX: invalid size %#x, dropping packet\n",
425                            frame->size);
426                 goto rx;
427         }
428
429         frame->size -= 4; /* remove checksum */
430         crc32 = tb_crc(pkg->buffer, frame->size);
431         be32_to_cpu_array(pkg->buffer, pkg->buffer, frame->size / 4);
432
433         switch (frame->eof) {
434         case TB_CFG_PKG_READ:
435         case TB_CFG_PKG_WRITE:
436         case TB_CFG_PKG_ERROR:
437         case TB_CFG_PKG_OVERRIDE:
438         case TB_CFG_PKG_RESET:
439                 if (*(__be32 *)(pkg->buffer + frame->size) != crc32) {
440                         tb_ctl_err(pkg->ctl,
441                                    "RX: checksum mismatch, dropping packet\n");
442                         goto rx;
443                 }
444                 if (tb_async_error(pkg)) {
445                         tb_ctl_handle_event(pkg->ctl, frame->eof,
446                                             pkg, frame->size);
447                         goto rx;
448                 }
449                 break;
450
451         case TB_CFG_PKG_EVENT:
452         case TB_CFG_PKG_XDOMAIN_RESP:
453         case TB_CFG_PKG_XDOMAIN_REQ:
454                 if (*(__be32 *)(pkg->buffer + frame->size) != crc32) {
455                         tb_ctl_err(pkg->ctl,
456                                    "RX: checksum mismatch, dropping packet\n");
457                         goto rx;
458                 }
459                 fallthrough;
460         case TB_CFG_PKG_ICM_EVENT:
461                 if (tb_ctl_handle_event(pkg->ctl, frame->eof, pkg, frame->size))
462                         goto rx;
463                 break;
464
465         default:
466                 break;
467         }
468
469         /*
470          * The received packet will be processed only if there is an
471          * active request and that the packet is what is expected. This
472          * prevents packets such as replies coming after timeout has
473          * triggered from messing with the active requests.
474          */
475         req = tb_cfg_request_find(pkg->ctl, pkg);
476         if (req) {
477                 if (req->copy(req, pkg))
478                         schedule_work(&req->work);
479                 tb_cfg_request_put(req);
480         }
481
482 rx:
483         tb_ctl_rx_submit(pkg);
484 }
485
486 static void tb_cfg_request_work(struct work_struct *work)
487 {
488         struct tb_cfg_request *req = container_of(work, typeof(*req), work);
489
490         if (!test_bit(TB_CFG_REQUEST_CANCELED, &req->flags))
491                 req->callback(req->callback_data);
492
493         tb_cfg_request_dequeue(req);
494         tb_cfg_request_put(req);
495 }
496
497 /**
498  * tb_cfg_request() - Start control request not waiting for it to complete
499  * @ctl: Control channel to use
500  * @req: Request to start
501  * @callback: Callback called when the request is completed
502  * @callback_data: Data to be passed to @callback
503  *
504  * This queues @req on the given control channel without waiting for it
505  * to complete. When the request completes @callback is called.
506  */
507 int tb_cfg_request(struct tb_ctl *ctl, struct tb_cfg_request *req,
508                    void (*callback)(void *), void *callback_data)
509 {
510         int ret;
511
512         req->flags = 0;
513         req->callback = callback;
514         req->callback_data = callback_data;
515         INIT_WORK(&req->work, tb_cfg_request_work);
516         INIT_LIST_HEAD(&req->list);
517
518         tb_cfg_request_get(req);
519         ret = tb_cfg_request_enqueue(ctl, req);
520         if (ret)
521                 goto err_put;
522
523         ret = tb_ctl_tx(ctl, req->request, req->request_size,
524                         req->request_type);
525         if (ret)
526                 goto err_dequeue;
527
528         if (!req->response)
529                 schedule_work(&req->work);
530
531         return 0;
532
533 err_dequeue:
534         tb_cfg_request_dequeue(req);
535 err_put:
536         tb_cfg_request_put(req);
537
538         return ret;
539 }
540
541 /**
542  * tb_cfg_request_cancel() - Cancel a control request
543  * @req: Request to cancel
544  * @err: Error to assign to the request
545  *
546  * This function can be used to cancel ongoing request. It will wait
547  * until the request is not active anymore.
548  */
549 void tb_cfg_request_cancel(struct tb_cfg_request *req, int err)
550 {
551         set_bit(TB_CFG_REQUEST_CANCELED, &req->flags);
552         schedule_work(&req->work);
553         wait_event(tb_cfg_request_cancel_queue, !tb_cfg_request_is_active(req));
554         req->result.err = err;
555 }
556
557 static void tb_cfg_request_complete(void *data)
558 {
559         complete(data);
560 }
561
562 /**
563  * tb_cfg_request_sync() - Start control request and wait until it completes
564  * @ctl: Control channel to use
565  * @req: Request to start
566  * @timeout_msec: Timeout how long to wait @req to complete
567  *
568  * Starts a control request and waits until it completes. If timeout
569  * triggers the request is canceled before function returns. Note the
570  * caller needs to make sure only one message for given switch is active
571  * at a time.
572  */
573 struct tb_cfg_result tb_cfg_request_sync(struct tb_ctl *ctl,
574                                          struct tb_cfg_request *req,
575                                          int timeout_msec)
576 {
577         unsigned long timeout = msecs_to_jiffies(timeout_msec);
578         struct tb_cfg_result res = { 0 };
579         DECLARE_COMPLETION_ONSTACK(done);
580         int ret;
581
582         ret = tb_cfg_request(ctl, req, tb_cfg_request_complete, &done);
583         if (ret) {
584                 res.err = ret;
585                 return res;
586         }
587
588         if (!wait_for_completion_timeout(&done, timeout))
589                 tb_cfg_request_cancel(req, -ETIMEDOUT);
590
591         flush_work(&req->work);
592
593         return req->result;
594 }
595
596 /* public interface, alloc/start/stop/free */
597
598 /**
599  * tb_ctl_alloc() - allocate a control channel
600  *
601  * cb will be invoked once for every hot plug event.
602  *
603  * Return: Returns a pointer on success or NULL on failure.
604  */
605 struct tb_ctl *tb_ctl_alloc(struct tb_nhi *nhi, event_cb cb, void *cb_data)
606 {
607         int i;
608         struct tb_ctl *ctl = kzalloc(sizeof(*ctl), GFP_KERNEL);
609         if (!ctl)
610                 return NULL;
611         ctl->nhi = nhi;
612         ctl->callback = cb;
613         ctl->callback_data = cb_data;
614
615         mutex_init(&ctl->request_queue_lock);
616         INIT_LIST_HEAD(&ctl->request_queue);
617         ctl->frame_pool = dma_pool_create("thunderbolt_ctl", &nhi->pdev->dev,
618                                          TB_FRAME_SIZE, 4, 0);
619         if (!ctl->frame_pool)
620                 goto err;
621
622         ctl->tx = tb_ring_alloc_tx(nhi, 0, 10, RING_FLAG_NO_SUSPEND);
623         if (!ctl->tx)
624                 goto err;
625
626         ctl->rx = tb_ring_alloc_rx(nhi, 0, 10, RING_FLAG_NO_SUSPEND, 0xffff,
627                                 0xffff, NULL, NULL);
628         if (!ctl->rx)
629                 goto err;
630
631         for (i = 0; i < TB_CTL_RX_PKG_COUNT; i++) {
632                 ctl->rx_packets[i] = tb_ctl_pkg_alloc(ctl);
633                 if (!ctl->rx_packets[i])
634                         goto err;
635                 ctl->rx_packets[i]->frame.callback = tb_ctl_rx_callback;
636         }
637
638         tb_ctl_dbg(ctl, "control channel created\n");
639         return ctl;
640 err:
641         tb_ctl_free(ctl);
642         return NULL;
643 }
644
645 /**
646  * tb_ctl_free() - free a control channel
647  *
648  * Must be called after tb_ctl_stop.
649  *
650  * Must NOT be called from ctl->callback.
651  */
652 void tb_ctl_free(struct tb_ctl *ctl)
653 {
654         int i;
655
656         if (!ctl)
657                 return;
658
659         if (ctl->rx)
660                 tb_ring_free(ctl->rx);
661         if (ctl->tx)
662                 tb_ring_free(ctl->tx);
663
664         /* free RX packets */
665         for (i = 0; i < TB_CTL_RX_PKG_COUNT; i++)
666                 tb_ctl_pkg_free(ctl->rx_packets[i]);
667
668
669         dma_pool_destroy(ctl->frame_pool);
670         kfree(ctl);
671 }
672
673 /**
674  * tb_cfg_start() - start/resume the control channel
675  */
676 void tb_ctl_start(struct tb_ctl *ctl)
677 {
678         int i;
679         tb_ctl_dbg(ctl, "control channel starting...\n");
680         tb_ring_start(ctl->tx); /* is used to ack hotplug packets, start first */
681         tb_ring_start(ctl->rx);
682         for (i = 0; i < TB_CTL_RX_PKG_COUNT; i++)
683                 tb_ctl_rx_submit(ctl->rx_packets[i]);
684
685         ctl->running = true;
686 }
687
688 /**
689  * control() - pause the control channel
690  *
691  * All invocations of ctl->callback will have finished after this method
692  * returns.
693  *
694  * Must NOT be called from ctl->callback.
695  */
696 void tb_ctl_stop(struct tb_ctl *ctl)
697 {
698         mutex_lock(&ctl->request_queue_lock);
699         ctl->running = false;
700         mutex_unlock(&ctl->request_queue_lock);
701
702         tb_ring_stop(ctl->rx);
703         tb_ring_stop(ctl->tx);
704
705         if (!list_empty(&ctl->request_queue))
706                 tb_ctl_WARN(ctl, "dangling request in request_queue\n");
707         INIT_LIST_HEAD(&ctl->request_queue);
708         tb_ctl_dbg(ctl, "control channel stopped\n");
709 }
710
711 /* public interface, commands */
712
713 /**
714  * tb_cfg_ack_plug() - Ack hot plug/unplug event
715  * @ctl: Control channel to use
716  * @route: Router that originated the event
717  * @port: Port where the hot plug/unplug happened
718  * @unplug: Ack hot plug or unplug
719  *
720  * Call this as response for hot plug/unplug event to ack it.
721  * Returns %0 on success or an error code on failure.
722  */
723 int tb_cfg_ack_plug(struct tb_ctl *ctl, u64 route, u32 port, bool unplug)
724 {
725         struct cfg_error_pkg pkg = {
726                 .header = tb_cfg_make_header(route),
727                 .port = port,
728                 .error = TB_CFG_ERROR_ACK_PLUG_EVENT,
729                 .pg = unplug ? TB_CFG_ERROR_PG_HOT_UNPLUG
730                              : TB_CFG_ERROR_PG_HOT_PLUG,
731         };
732         tb_ctl_dbg(ctl, "acking hot %splug event on %llx:%x\n",
733                    unplug ? "un" : "", 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 static int tb_cfg_get_error(struct tb_ctl *ctl, enum tb_cfg_space space,
944                             const struct tb_cfg_result *res)
945 {
946         /*
947          * For unimplemented ports access to port config space may return
948          * TB_CFG_ERROR_INVALID_CONFIG_SPACE (alternatively their type is
949          * set to TB_TYPE_INACTIVE). In the former case return -ENODEV so
950          * that the caller can mark the port as disabled.
951          */
952         if (space == TB_CFG_PORT &&
953             res->tb_error == TB_CFG_ERROR_INVALID_CONFIG_SPACE)
954                 return -ENODEV;
955
956         tb_cfg_print_error(ctl, res);
957
958         if (res->tb_error == TB_CFG_ERROR_LOCK)
959                 return -EACCES;
960         return -EIO;
961 }
962
963 int tb_cfg_read(struct tb_ctl *ctl, void *buffer, u64 route, u32 port,
964                 enum tb_cfg_space space, u32 offset, u32 length)
965 {
966         struct tb_cfg_result res = tb_cfg_read_raw(ctl, buffer, route, port,
967                         space, offset, length, TB_CFG_DEFAULT_TIMEOUT);
968         switch (res.err) {
969         case 0:
970                 /* Success */
971                 break;
972
973         case 1:
974                 /* Thunderbolt error, tb_error holds the actual number */
975                 return tb_cfg_get_error(ctl, space, &res);
976
977         case -ETIMEDOUT:
978                 tb_ctl_warn(ctl, "%llx: timeout reading config space %u from %#x\n",
979                             route, space, offset);
980                 break;
981
982         default:
983                 WARN(1, "tb_cfg_read: %d\n", res.err);
984                 break;
985         }
986         return res.err;
987 }
988
989 int tb_cfg_write(struct tb_ctl *ctl, const void *buffer, u64 route, u32 port,
990                  enum tb_cfg_space space, u32 offset, u32 length)
991 {
992         struct tb_cfg_result res = tb_cfg_write_raw(ctl, buffer, route, port,
993                         space, offset, length, TB_CFG_DEFAULT_TIMEOUT);
994         switch (res.err) {
995         case 0:
996                 /* Success */
997                 break;
998
999         case 1:
1000                 /* Thunderbolt error, tb_error holds the actual number */
1001                 return tb_cfg_get_error(ctl, space, &res);
1002
1003         case -ETIMEDOUT:
1004                 tb_ctl_warn(ctl, "%llx: timeout writing config space %u to %#x\n",
1005                             route, space, offset);
1006                 break;
1007
1008         default:
1009                 WARN(1, "tb_cfg_write: %d\n", res.err);
1010                 break;
1011         }
1012         return res.err;
1013 }
1014
1015 /**
1016  * tb_cfg_get_upstream_port() - get upstream port number of switch at route
1017  *
1018  * Reads the first dword from the switches TB_CFG_SWITCH config area and
1019  * returns the port number from which the reply originated.
1020  *
1021  * Return: Returns the upstream port number on success or an error code on
1022  * failure.
1023  */
1024 int tb_cfg_get_upstream_port(struct tb_ctl *ctl, u64 route)
1025 {
1026         u32 dummy;
1027         struct tb_cfg_result res = tb_cfg_read_raw(ctl, &dummy, route, 0,
1028                                                    TB_CFG_SWITCH, 0, 1,
1029                                                    TB_CFG_DEFAULT_TIMEOUT);
1030         if (res.err == 1)
1031                 return -EIO;
1032         if (res.err)
1033                 return res.err;
1034         return res.response_port;
1035 }