GNU Linux-libre 4.19.264-gnu1
[releases.git] / drivers / thunderbolt / switch.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Thunderbolt Cactus Ridge driver - switch/port utility functions
4  *
5  * Copyright (c) 2014 Andreas Noever <andreas.noever@gmail.com>
6  */
7
8 #include <linux/delay.h>
9 #include <linux/idr.h>
10 #include <linux/nvmem-provider.h>
11 #include <linux/pm_runtime.h>
12 #include <linux/sched/signal.h>
13 #include <linux/sizes.h>
14 #include <linux/slab.h>
15 #include <linux/vmalloc.h>
16
17 #include "tb.h"
18
19 /* Switch NVM support */
20
21 #define NVM_DEVID               0x05
22 #define NVM_VERSION             0x08
23 #define NVM_CSS                 0x10
24 #define NVM_FLASH_SIZE          0x45
25
26 #define NVM_MIN_SIZE            SZ_32K
27 #define NVM_MAX_SIZE            SZ_512K
28
29 static DEFINE_IDA(nvm_ida);
30
31 struct nvm_auth_status {
32         struct list_head list;
33         uuid_t uuid;
34         u32 status;
35 };
36
37 /*
38  * Hold NVM authentication failure status per switch This information
39  * needs to stay around even when the switch gets power cycled so we
40  * keep it separately.
41  */
42 static LIST_HEAD(nvm_auth_status_cache);
43 static DEFINE_MUTEX(nvm_auth_status_lock);
44
45 static struct nvm_auth_status *__nvm_get_auth_status(const struct tb_switch *sw)
46 {
47         struct nvm_auth_status *st;
48
49         list_for_each_entry(st, &nvm_auth_status_cache, list) {
50                 if (uuid_equal(&st->uuid, sw->uuid))
51                         return st;
52         }
53
54         return NULL;
55 }
56
57 static void nvm_get_auth_status(const struct tb_switch *sw, u32 *status)
58 {
59         struct nvm_auth_status *st;
60
61         mutex_lock(&nvm_auth_status_lock);
62         st = __nvm_get_auth_status(sw);
63         mutex_unlock(&nvm_auth_status_lock);
64
65         *status = st ? st->status : 0;
66 }
67
68 static void nvm_set_auth_status(const struct tb_switch *sw, u32 status)
69 {
70         struct nvm_auth_status *st;
71
72         if (WARN_ON(!sw->uuid))
73                 return;
74
75         mutex_lock(&nvm_auth_status_lock);
76         st = __nvm_get_auth_status(sw);
77
78         if (!st) {
79                 st = kzalloc(sizeof(*st), GFP_KERNEL);
80                 if (!st)
81                         goto unlock;
82
83                 memcpy(&st->uuid, sw->uuid, sizeof(st->uuid));
84                 INIT_LIST_HEAD(&st->list);
85                 list_add_tail(&st->list, &nvm_auth_status_cache);
86         }
87
88         st->status = status;
89 unlock:
90         mutex_unlock(&nvm_auth_status_lock);
91 }
92
93 static void nvm_clear_auth_status(const struct tb_switch *sw)
94 {
95         struct nvm_auth_status *st;
96
97         mutex_lock(&nvm_auth_status_lock);
98         st = __nvm_get_auth_status(sw);
99         if (st) {
100                 list_del(&st->list);
101                 kfree(st);
102         }
103         mutex_unlock(&nvm_auth_status_lock);
104 }
105
106 static int nvm_validate_and_write(struct tb_switch *sw)
107 {
108         unsigned int image_size, hdr_size;
109         const u8 *buf = sw->nvm->buf;
110         u16 ds_size;
111         int ret;
112
113         if (!buf)
114                 return -EINVAL;
115
116         image_size = sw->nvm->buf_data_size;
117         if (image_size < NVM_MIN_SIZE || image_size > NVM_MAX_SIZE)
118                 return -EINVAL;
119
120         /*
121          * FARB pointer must point inside the image and must at least
122          * contain parts of the digital section we will be reading here.
123          */
124         hdr_size = (*(u32 *)buf) & 0xffffff;
125         if (hdr_size + NVM_DEVID + 2 >= image_size)
126                 return -EINVAL;
127
128         /* Digital section start should be aligned to 4k page */
129         if (!IS_ALIGNED(hdr_size, SZ_4K))
130                 return -EINVAL;
131
132         /*
133          * Read digital section size and check that it also fits inside
134          * the image.
135          */
136         ds_size = *(u16 *)(buf + hdr_size);
137         if (ds_size >= image_size)
138                 return -EINVAL;
139
140         if (!sw->safe_mode) {
141                 u16 device_id;
142
143                 /*
144                  * Make sure the device ID in the image matches the one
145                  * we read from the switch config space.
146                  */
147                 device_id = *(u16 *)(buf + hdr_size + NVM_DEVID);
148                 if (device_id != sw->config.device_id)
149                         return -EINVAL;
150
151                 if (sw->generation < 3) {
152                         /* Write CSS headers first */
153                         ret = dma_port_flash_write(sw->dma_port,
154                                 DMA_PORT_CSS_ADDRESS, buf + NVM_CSS,
155                                 DMA_PORT_CSS_MAX_SIZE);
156                         if (ret)
157                                 return ret;
158                 }
159
160                 /* Skip headers in the image */
161                 buf += hdr_size;
162                 image_size -= hdr_size;
163         }
164
165         return dma_port_flash_write(sw->dma_port, 0, buf, image_size);
166 }
167
168 static int nvm_authenticate_host(struct tb_switch *sw)
169 {
170         int ret = 0;
171
172         /*
173          * Root switch NVM upgrade requires that we disconnect the
174          * existing paths first (in case it is not in safe mode
175          * already).
176          */
177         if (!sw->safe_mode) {
178                 u32 status;
179
180                 ret = tb_domain_disconnect_all_paths(sw->tb);
181                 if (ret)
182                         return ret;
183                 /*
184                  * The host controller goes away pretty soon after this if
185                  * everything goes well so getting timeout is expected.
186                  */
187                 ret = dma_port_flash_update_auth(sw->dma_port);
188                 if (!ret || ret == -ETIMEDOUT)
189                         return 0;
190
191                 /*
192                  * Any error from update auth operation requires power
193                  * cycling of the host router.
194                  */
195                 tb_sw_warn(sw, "failed to authenticate NVM, power cycling\n");
196                 if (dma_port_flash_update_auth_status(sw->dma_port, &status) > 0)
197                         nvm_set_auth_status(sw, status);
198         }
199
200         /*
201          * From safe mode we can get out by just power cycling the
202          * switch.
203          */
204         dma_port_power_cycle(sw->dma_port);
205         return ret;
206 }
207
208 static int nvm_authenticate_device(struct tb_switch *sw)
209 {
210         int ret, retries = 10;
211
212         ret = dma_port_flash_update_auth(sw->dma_port);
213         switch (ret) {
214         case 0:
215         case -ETIMEDOUT:
216         case -EACCES:
217         case -EINVAL:
218                 /* Power cycle is required */
219                 break;
220         default:
221                 return ret;
222         }
223
224         /*
225          * Poll here for the authentication status. It takes some time
226          * for the device to respond (we get timeout for a while). Once
227          * we get response the device needs to be power cycled in order
228          * to the new NVM to be taken into use.
229          */
230         do {
231                 u32 status;
232
233                 ret = dma_port_flash_update_auth_status(sw->dma_port, &status);
234                 if (ret < 0 && ret != -ETIMEDOUT)
235                         return ret;
236                 if (ret > 0) {
237                         if (status) {
238                                 tb_sw_warn(sw, "failed to authenticate NVM\n");
239                                 nvm_set_auth_status(sw, status);
240                         }
241
242                         tb_sw_info(sw, "power cycling the switch now\n");
243                         dma_port_power_cycle(sw->dma_port);
244                         return 0;
245                 }
246
247                 msleep(500);
248         } while (--retries);
249
250         return -ETIMEDOUT;
251 }
252
253 static int tb_switch_nvm_read(void *priv, unsigned int offset, void *val,
254                               size_t bytes)
255 {
256         struct tb_switch *sw = priv;
257         int ret;
258
259         pm_runtime_get_sync(&sw->dev);
260         ret = dma_port_flash_read(sw->dma_port, offset, val, bytes);
261         pm_runtime_mark_last_busy(&sw->dev);
262         pm_runtime_put_autosuspend(&sw->dev);
263
264         return ret;
265 }
266
267 static int tb_switch_nvm_no_read(void *priv, unsigned int offset, void *val,
268                                  size_t bytes)
269 {
270         return -EPERM;
271 }
272
273 static int tb_switch_nvm_write(void *priv, unsigned int offset, void *val,
274                                size_t bytes)
275 {
276         struct tb_switch *sw = priv;
277         int ret = 0;
278
279         if (!mutex_trylock(&sw->tb->lock))
280                 return restart_syscall();
281
282         /*
283          * Since writing the NVM image might require some special steps,
284          * for example when CSS headers are written, we cache the image
285          * locally here and handle the special cases when the user asks
286          * us to authenticate the image.
287          */
288         if (!sw->nvm->buf) {
289                 sw->nvm->buf = vmalloc(NVM_MAX_SIZE);
290                 if (!sw->nvm->buf) {
291                         ret = -ENOMEM;
292                         goto unlock;
293                 }
294         }
295
296         sw->nvm->buf_data_size = offset + bytes;
297         memcpy(sw->nvm->buf + offset, val, bytes);
298
299 unlock:
300         mutex_unlock(&sw->tb->lock);
301
302         return ret;
303 }
304
305 static struct nvmem_device *register_nvmem(struct tb_switch *sw, int id,
306                                            size_t size, bool active)
307 {
308         struct nvmem_config config;
309
310         memset(&config, 0, sizeof(config));
311
312         if (active) {
313                 config.name = "nvm_active";
314                 config.reg_read = tb_switch_nvm_read;
315                 config.read_only = true;
316         } else {
317                 config.name = "nvm_non_active";
318                 config.reg_read = tb_switch_nvm_no_read;
319                 config.reg_write = tb_switch_nvm_write;
320                 config.root_only = true;
321         }
322
323         config.id = id;
324         config.stride = 4;
325         config.word_size = 4;
326         config.size = size;
327         config.dev = &sw->dev;
328         config.owner = THIS_MODULE;
329         config.priv = sw;
330
331         return nvmem_register(&config);
332 }
333
334 static int tb_switch_nvm_add(struct tb_switch *sw)
335 {
336         struct nvmem_device *nvm_dev;
337         struct tb_switch_nvm *nvm;
338         u32 val;
339         int ret;
340
341         if (!sw->dma_port)
342                 return 0;
343
344         nvm = kzalloc(sizeof(*nvm), GFP_KERNEL);
345         if (!nvm)
346                 return -ENOMEM;
347
348         nvm->id = ida_simple_get(&nvm_ida, 0, 0, GFP_KERNEL);
349
350         /*
351          * If the switch is in safe-mode the only accessible portion of
352          * the NVM is the non-active one where userspace is expected to
353          * write new functional NVM.
354          */
355         if (!sw->safe_mode) {
356                 u32 nvm_size, hdr_size;
357
358                 ret = dma_port_flash_read(sw->dma_port, NVM_FLASH_SIZE, &val,
359                                           sizeof(val));
360                 if (ret)
361                         goto err_ida;
362
363                 hdr_size = sw->generation < 3 ? SZ_8K : SZ_16K;
364                 nvm_size = (SZ_1M << (val & 7)) / 8;
365                 nvm_size = (nvm_size - hdr_size) / 2;
366
367                 ret = dma_port_flash_read(sw->dma_port, NVM_VERSION, &val,
368                                           sizeof(val));
369                 if (ret)
370                         goto err_ida;
371
372                 nvm->major = val >> 16;
373                 nvm->minor = val >> 8;
374
375                 nvm_dev = register_nvmem(sw, nvm->id, nvm_size, true);
376                 if (IS_ERR(nvm_dev)) {
377                         ret = PTR_ERR(nvm_dev);
378                         goto err_ida;
379                 }
380                 nvm->active = nvm_dev;
381         }
382
383         nvm_dev = register_nvmem(sw, nvm->id, NVM_MAX_SIZE, false);
384         if (IS_ERR(nvm_dev)) {
385                 ret = PTR_ERR(nvm_dev);
386                 goto err_nvm_active;
387         }
388         nvm->non_active = nvm_dev;
389
390         sw->nvm = nvm;
391         return 0;
392
393 err_nvm_active:
394         if (nvm->active)
395                 nvmem_unregister(nvm->active);
396 err_ida:
397         ida_simple_remove(&nvm_ida, nvm->id);
398         kfree(nvm);
399
400         return ret;
401 }
402
403 static void tb_switch_nvm_remove(struct tb_switch *sw)
404 {
405         struct tb_switch_nvm *nvm;
406
407         nvm = sw->nvm;
408         sw->nvm = NULL;
409
410         if (!nvm)
411                 return;
412
413         /* Remove authentication status in case the switch is unplugged */
414         if (!nvm->authenticating)
415                 nvm_clear_auth_status(sw);
416
417         nvmem_unregister(nvm->non_active);
418         if (nvm->active)
419                 nvmem_unregister(nvm->active);
420         ida_simple_remove(&nvm_ida, nvm->id);
421         vfree(nvm->buf);
422         kfree(nvm);
423 }
424
425 /* port utility functions */
426
427 static const char *tb_port_type(struct tb_regs_port_header *port)
428 {
429         switch (port->type >> 16) {
430         case 0:
431                 switch ((u8) port->type) {
432                 case 0:
433                         return "Inactive";
434                 case 1:
435                         return "Port";
436                 case 2:
437                         return "NHI";
438                 default:
439                         return "unknown";
440                 }
441         case 0x2:
442                 return "Ethernet";
443         case 0x8:
444                 return "SATA";
445         case 0xe:
446                 return "DP/HDMI";
447         case 0x10:
448                 return "PCIe";
449         case 0x20:
450                 return "USB";
451         default:
452                 return "unknown";
453         }
454 }
455
456 static void tb_dump_port(struct tb *tb, struct tb_regs_port_header *port)
457 {
458         tb_info(tb,
459                 " Port %d: %x:%x (Revision: %d, TB Version: %d, Type: %s (%#x))\n",
460                 port->port_number, port->vendor_id, port->device_id,
461                 port->revision, port->thunderbolt_version, tb_port_type(port),
462                 port->type);
463         tb_info(tb, "  Max hop id (in/out): %d/%d\n",
464                 port->max_in_hop_id, port->max_out_hop_id);
465         tb_info(tb, "  Max counters: %d\n", port->max_counters);
466         tb_info(tb, "  NFC Credits: %#x\n", port->nfc_credits);
467 }
468
469 /**
470  * tb_port_state() - get connectedness state of a port
471  *
472  * The port must have a TB_CAP_PHY (i.e. it should be a real port).
473  *
474  * Return: Returns an enum tb_port_state on success or an error code on failure.
475  */
476 static int tb_port_state(struct tb_port *port)
477 {
478         struct tb_cap_phy phy;
479         int res;
480         if (port->cap_phy == 0) {
481                 tb_port_WARN(port, "does not have a PHY\n");
482                 return -EINVAL;
483         }
484         res = tb_port_read(port, &phy, TB_CFG_PORT, port->cap_phy, 2);
485         if (res)
486                 return res;
487         return phy.state;
488 }
489
490 /**
491  * tb_wait_for_port() - wait for a port to become ready
492  *
493  * Wait up to 1 second for a port to reach state TB_PORT_UP. If
494  * wait_if_unplugged is set then we also wait if the port is in state
495  * TB_PORT_UNPLUGGED (it takes a while for the device to be registered after
496  * switch resume). Otherwise we only wait if a device is registered but the link
497  * has not yet been established.
498  *
499  * Return: Returns an error code on failure. Returns 0 if the port is not
500  * connected or failed to reach state TB_PORT_UP within one second. Returns 1
501  * if the port is connected and in state TB_PORT_UP.
502  */
503 int tb_wait_for_port(struct tb_port *port, bool wait_if_unplugged)
504 {
505         int retries = 10;
506         int state;
507         if (!port->cap_phy) {
508                 tb_port_WARN(port, "does not have PHY\n");
509                 return -EINVAL;
510         }
511         if (tb_is_upstream_port(port)) {
512                 tb_port_WARN(port, "is the upstream port\n");
513                 return -EINVAL;
514         }
515
516         while (retries--) {
517                 state = tb_port_state(port);
518                 if (state < 0)
519                         return state;
520                 if (state == TB_PORT_DISABLED) {
521                         tb_port_info(port, "is disabled (state: 0)\n");
522                         return 0;
523                 }
524                 if (state == TB_PORT_UNPLUGGED) {
525                         if (wait_if_unplugged) {
526                                 /* used during resume */
527                                 tb_port_info(port,
528                                              "is unplugged (state: 7), retrying...\n");
529                                 msleep(100);
530                                 continue;
531                         }
532                         tb_port_info(port, "is unplugged (state: 7)\n");
533                         return 0;
534                 }
535                 if (state == TB_PORT_UP) {
536                         tb_port_info(port,
537                                      "is connected, link is up (state: 2)\n");
538                         return 1;
539                 }
540
541                 /*
542                  * After plug-in the state is TB_PORT_CONNECTING. Give it some
543                  * time.
544                  */
545                 tb_port_info(port,
546                              "is connected, link is not up (state: %d), retrying...\n",
547                              state);
548                 msleep(100);
549         }
550         tb_port_warn(port,
551                      "failed to reach state TB_PORT_UP. Ignoring port...\n");
552         return 0;
553 }
554
555 /**
556  * tb_port_add_nfc_credits() - add/remove non flow controlled credits to port
557  *
558  * Change the number of NFC credits allocated to @port by @credits. To remove
559  * NFC credits pass a negative amount of credits.
560  *
561  * Return: Returns 0 on success or an error code on failure.
562  */
563 int tb_port_add_nfc_credits(struct tb_port *port, int credits)
564 {
565         if (credits == 0)
566                 return 0;
567         tb_port_info(port,
568                      "adding %#x NFC credits (%#x -> %#x)",
569                      credits,
570                      port->config.nfc_credits,
571                      port->config.nfc_credits + credits);
572         port->config.nfc_credits += credits;
573         return tb_port_write(port, &port->config.nfc_credits,
574                              TB_CFG_PORT, 4, 1);
575 }
576
577 /**
578  * tb_port_clear_counter() - clear a counter in TB_CFG_COUNTER
579  *
580  * Return: Returns 0 on success or an error code on failure.
581  */
582 int tb_port_clear_counter(struct tb_port *port, int counter)
583 {
584         u32 zero[3] = { 0, 0, 0 };
585         tb_port_info(port, "clearing counter %d\n", counter);
586         return tb_port_write(port, zero, TB_CFG_COUNTERS, 3 * counter, 3);
587 }
588
589 /**
590  * tb_init_port() - initialize a port
591  *
592  * This is a helper method for tb_switch_alloc. Does not check or initialize
593  * any downstream switches.
594  *
595  * Return: Returns 0 on success or an error code on failure.
596  */
597 static int tb_init_port(struct tb_port *port)
598 {
599         int res;
600         int cap;
601
602         res = tb_port_read(port, &port->config, TB_CFG_PORT, 0, 8);
603         if (res)
604                 return res;
605
606         /* Port 0 is the switch itself and has no PHY. */
607         if (port->config.type == TB_TYPE_PORT && port->port != 0) {
608                 cap = tb_port_find_cap(port, TB_PORT_CAP_PHY);
609
610                 if (cap > 0)
611                         port->cap_phy = cap;
612                 else
613                         tb_port_WARN(port, "non switch port without a PHY\n");
614         }
615
616         tb_dump_port(port->sw->tb, &port->config);
617
618         /* TODO: Read dual link port, DP port and more from EEPROM. */
619         return 0;
620
621 }
622
623 /* switch utility functions */
624
625 static void tb_dump_switch(struct tb *tb, struct tb_regs_switch_header *sw)
626 {
627         tb_info(tb,
628                 " Switch: %x:%x (Revision: %d, TB Version: %d)\n",
629                 sw->vendor_id, sw->device_id, sw->revision,
630                 sw->thunderbolt_version);
631         tb_info(tb, "  Max Port Number: %d\n", sw->max_port_number);
632         tb_info(tb, "  Config:\n");
633         tb_info(tb,
634                 "   Upstream Port Number: %d Depth: %d Route String: %#llx Enabled: %d, PlugEventsDelay: %dms\n",
635                 sw->upstream_port_number, sw->depth,
636                 (((u64) sw->route_hi) << 32) | sw->route_lo,
637                 sw->enabled, sw->plug_events_delay);
638         tb_info(tb,
639                 "   unknown1: %#x unknown4: %#x\n",
640                 sw->__unknown1, sw->__unknown4);
641 }
642
643 /**
644  * reset_switch() - reconfigure route, enable and send TB_CFG_PKG_RESET
645  *
646  * Return: Returns 0 on success or an error code on failure.
647  */
648 int tb_switch_reset(struct tb *tb, u64 route)
649 {
650         struct tb_cfg_result res;
651         struct tb_regs_switch_header header = {
652                 header.route_hi = route >> 32,
653                 header.route_lo = route,
654                 header.enabled = true,
655         };
656         tb_info(tb, "resetting switch at %llx\n", route);
657         res.err = tb_cfg_write(tb->ctl, ((u32 *) &header) + 2, route,
658                         0, 2, 2, 2);
659         if (res.err)
660                 return res.err;
661         res = tb_cfg_reset(tb->ctl, route, TB_CFG_DEFAULT_TIMEOUT);
662         if (res.err > 0)
663                 return -EIO;
664         return res.err;
665 }
666
667 /**
668  * tb_plug_events_active() - enable/disable plug events on a switch
669  *
670  * Also configures a sane plug_events_delay of 255ms.
671  *
672  * Return: Returns 0 on success or an error code on failure.
673  */
674 static int tb_plug_events_active(struct tb_switch *sw, bool active)
675 {
676         u32 data;
677         int res;
678
679         if (!sw->config.enabled)
680                 return 0;
681
682         sw->config.plug_events_delay = 0xff;
683         res = tb_sw_write(sw, ((u32 *) &sw->config) + 4, TB_CFG_SWITCH, 4, 1);
684         if (res)
685                 return res;
686
687         res = tb_sw_read(sw, &data, TB_CFG_SWITCH, sw->cap_plug_events + 1, 1);
688         if (res)
689                 return res;
690
691         if (active) {
692                 data = data & 0xFFFFFF83;
693                 switch (sw->config.device_id) {
694                 case PCI_DEVICE_ID_INTEL_LIGHT_RIDGE:
695                 case PCI_DEVICE_ID_INTEL_EAGLE_RIDGE:
696                 case PCI_DEVICE_ID_INTEL_PORT_RIDGE:
697                         break;
698                 default:
699                         data |= 4;
700                 }
701         } else {
702                 data = data | 0x7c;
703         }
704         return tb_sw_write(sw, &data, TB_CFG_SWITCH,
705                            sw->cap_plug_events + 1, 1);
706 }
707
708 static ssize_t authorized_show(struct device *dev,
709                                struct device_attribute *attr,
710                                char *buf)
711 {
712         struct tb_switch *sw = tb_to_switch(dev);
713
714         return sprintf(buf, "%u\n", sw->authorized);
715 }
716
717 static int tb_switch_set_authorized(struct tb_switch *sw, unsigned int val)
718 {
719         int ret = -EINVAL;
720
721         if (!mutex_trylock(&sw->tb->lock))
722                 return restart_syscall();
723
724         if (sw->authorized)
725                 goto unlock;
726
727         /*
728          * Make sure there is no PCIe rescan ongoing when a new PCIe
729          * tunnel is created. Otherwise the PCIe rescan code might find
730          * the new tunnel too early.
731          */
732         pci_lock_rescan_remove();
733         pm_runtime_get_sync(&sw->dev);
734
735         switch (val) {
736         /* Approve switch */
737         case 1:
738                 if (sw->key)
739                         ret = tb_domain_approve_switch_key(sw->tb, sw);
740                 else
741                         ret = tb_domain_approve_switch(sw->tb, sw);
742                 break;
743
744         /* Challenge switch */
745         case 2:
746                 if (sw->key)
747                         ret = tb_domain_challenge_switch_key(sw->tb, sw);
748                 break;
749
750         default:
751                 break;
752         }
753
754         pm_runtime_mark_last_busy(&sw->dev);
755         pm_runtime_put_autosuspend(&sw->dev);
756         pci_unlock_rescan_remove();
757
758         if (!ret) {
759                 sw->authorized = val;
760                 /* Notify status change to the userspace */
761                 kobject_uevent(&sw->dev.kobj, KOBJ_CHANGE);
762         }
763
764 unlock:
765         mutex_unlock(&sw->tb->lock);
766         return ret;
767 }
768
769 static ssize_t authorized_store(struct device *dev,
770                                 struct device_attribute *attr,
771                                 const char *buf, size_t count)
772 {
773         struct tb_switch *sw = tb_to_switch(dev);
774         unsigned int val;
775         ssize_t ret;
776
777         ret = kstrtouint(buf, 0, &val);
778         if (ret)
779                 return ret;
780         if (val > 2)
781                 return -EINVAL;
782
783         ret = tb_switch_set_authorized(sw, val);
784
785         return ret ? ret : count;
786 }
787 static DEVICE_ATTR_RW(authorized);
788
789 static ssize_t boot_show(struct device *dev, struct device_attribute *attr,
790                          char *buf)
791 {
792         struct tb_switch *sw = tb_to_switch(dev);
793
794         return sprintf(buf, "%u\n", sw->boot);
795 }
796 static DEVICE_ATTR_RO(boot);
797
798 static ssize_t device_show(struct device *dev, struct device_attribute *attr,
799                            char *buf)
800 {
801         struct tb_switch *sw = tb_to_switch(dev);
802
803         return sprintf(buf, "%#x\n", sw->device);
804 }
805 static DEVICE_ATTR_RO(device);
806
807 static ssize_t
808 device_name_show(struct device *dev, struct device_attribute *attr, char *buf)
809 {
810         struct tb_switch *sw = tb_to_switch(dev);
811
812         return sprintf(buf, "%s\n", sw->device_name ? sw->device_name : "");
813 }
814 static DEVICE_ATTR_RO(device_name);
815
816 static ssize_t key_show(struct device *dev, struct device_attribute *attr,
817                         char *buf)
818 {
819         struct tb_switch *sw = tb_to_switch(dev);
820         ssize_t ret;
821
822         if (!mutex_trylock(&sw->tb->lock))
823                 return restart_syscall();
824
825         if (sw->key)
826                 ret = sprintf(buf, "%*phN\n", TB_SWITCH_KEY_SIZE, sw->key);
827         else
828                 ret = sprintf(buf, "\n");
829
830         mutex_unlock(&sw->tb->lock);
831         return ret;
832 }
833
834 static ssize_t key_store(struct device *dev, struct device_attribute *attr,
835                          const char *buf, size_t count)
836 {
837         struct tb_switch *sw = tb_to_switch(dev);
838         u8 key[TB_SWITCH_KEY_SIZE];
839         ssize_t ret = count;
840         bool clear = false;
841
842         if (!strcmp(buf, "\n"))
843                 clear = true;
844         else if (hex2bin(key, buf, sizeof(key)))
845                 return -EINVAL;
846
847         if (!mutex_trylock(&sw->tb->lock))
848                 return restart_syscall();
849
850         if (sw->authorized) {
851                 ret = -EBUSY;
852         } else {
853                 kfree(sw->key);
854                 if (clear) {
855                         sw->key = NULL;
856                 } else {
857                         sw->key = kmemdup(key, sizeof(key), GFP_KERNEL);
858                         if (!sw->key)
859                                 ret = -ENOMEM;
860                 }
861         }
862
863         mutex_unlock(&sw->tb->lock);
864         return ret;
865 }
866 static DEVICE_ATTR(key, 0600, key_show, key_store);
867
868 static void nvm_authenticate_start(struct tb_switch *sw)
869 {
870         struct pci_dev *root_port;
871
872         /*
873          * During host router NVM upgrade we should not allow root port to
874          * go into D3cold because some root ports cannot trigger PME
875          * itself. To be on the safe side keep the root port in D0 during
876          * the whole upgrade process.
877          */
878         root_port = pci_find_pcie_root_port(sw->tb->nhi->pdev);
879         if (root_port)
880                 pm_runtime_get_noresume(&root_port->dev);
881 }
882
883 static void nvm_authenticate_complete(struct tb_switch *sw)
884 {
885         struct pci_dev *root_port;
886
887         root_port = pci_find_pcie_root_port(sw->tb->nhi->pdev);
888         if (root_port)
889                 pm_runtime_put(&root_port->dev);
890 }
891
892 static ssize_t nvm_authenticate_show(struct device *dev,
893         struct device_attribute *attr, char *buf)
894 {
895         struct tb_switch *sw = tb_to_switch(dev);
896         u32 status;
897
898         nvm_get_auth_status(sw, &status);
899         return sprintf(buf, "%#x\n", status);
900 }
901
902 static ssize_t nvm_authenticate_store(struct device *dev,
903         struct device_attribute *attr, const char *buf, size_t count)
904 {
905         struct tb_switch *sw = tb_to_switch(dev);
906         bool val;
907         int ret;
908
909         if (!mutex_trylock(&sw->tb->lock))
910                 return restart_syscall();
911
912         /* If NVMem devices are not yet added */
913         if (!sw->nvm) {
914                 ret = -EAGAIN;
915                 goto exit_unlock;
916         }
917
918         ret = kstrtobool(buf, &val);
919         if (ret)
920                 goto exit_unlock;
921
922         /* Always clear the authentication status */
923         nvm_clear_auth_status(sw);
924
925         if (val) {
926                 if (!sw->nvm->buf) {
927                         ret = -EINVAL;
928                         goto exit_unlock;
929                 }
930
931                 pm_runtime_get_sync(&sw->dev);
932                 ret = nvm_validate_and_write(sw);
933                 if (ret) {
934                         pm_runtime_mark_last_busy(&sw->dev);
935                         pm_runtime_put_autosuspend(&sw->dev);
936                         goto exit_unlock;
937                 }
938
939                 sw->nvm->authenticating = true;
940
941                 if (!tb_route(sw)) {
942                         /*
943                          * Keep root port from suspending as long as the
944                          * NVM upgrade process is running.
945                          */
946                         nvm_authenticate_start(sw);
947                         ret = nvm_authenticate_host(sw);
948                 } else {
949                         ret = nvm_authenticate_device(sw);
950                 }
951                 pm_runtime_mark_last_busy(&sw->dev);
952                 pm_runtime_put_autosuspend(&sw->dev);
953         }
954
955 exit_unlock:
956         mutex_unlock(&sw->tb->lock);
957
958         if (ret)
959                 return ret;
960         return count;
961 }
962 static DEVICE_ATTR_RW(nvm_authenticate);
963
964 static ssize_t nvm_version_show(struct device *dev,
965                                 struct device_attribute *attr, char *buf)
966 {
967         struct tb_switch *sw = tb_to_switch(dev);
968         int ret;
969
970         if (!mutex_trylock(&sw->tb->lock))
971                 return restart_syscall();
972
973         if (sw->safe_mode)
974                 ret = -ENODATA;
975         else if (!sw->nvm)
976                 ret = -EAGAIN;
977         else
978                 ret = sprintf(buf, "%x.%x\n", sw->nvm->major, sw->nvm->minor);
979
980         mutex_unlock(&sw->tb->lock);
981
982         return ret;
983 }
984 static DEVICE_ATTR_RO(nvm_version);
985
986 static ssize_t vendor_show(struct device *dev, struct device_attribute *attr,
987                            char *buf)
988 {
989         struct tb_switch *sw = tb_to_switch(dev);
990
991         return sprintf(buf, "%#x\n", sw->vendor);
992 }
993 static DEVICE_ATTR_RO(vendor);
994
995 static ssize_t
996 vendor_name_show(struct device *dev, struct device_attribute *attr, char *buf)
997 {
998         struct tb_switch *sw = tb_to_switch(dev);
999
1000         return sprintf(buf, "%s\n", sw->vendor_name ? sw->vendor_name : "");
1001 }
1002 static DEVICE_ATTR_RO(vendor_name);
1003
1004 static ssize_t unique_id_show(struct device *dev, struct device_attribute *attr,
1005                               char *buf)
1006 {
1007         struct tb_switch *sw = tb_to_switch(dev);
1008
1009         return sprintf(buf, "%pUb\n", sw->uuid);
1010 }
1011 static DEVICE_ATTR_RO(unique_id);
1012
1013 static struct attribute *switch_attrs[] = {
1014         &dev_attr_authorized.attr,
1015         &dev_attr_boot.attr,
1016         &dev_attr_device.attr,
1017         &dev_attr_device_name.attr,
1018         &dev_attr_key.attr,
1019         &dev_attr_nvm_authenticate.attr,
1020         &dev_attr_nvm_version.attr,
1021         &dev_attr_vendor.attr,
1022         &dev_attr_vendor_name.attr,
1023         &dev_attr_unique_id.attr,
1024         NULL,
1025 };
1026
1027 static umode_t switch_attr_is_visible(struct kobject *kobj,
1028                                       struct attribute *attr, int n)
1029 {
1030         struct device *dev = container_of(kobj, struct device, kobj);
1031         struct tb_switch *sw = tb_to_switch(dev);
1032
1033         if (attr == &dev_attr_key.attr) {
1034                 if (tb_route(sw) &&
1035                     sw->tb->security_level == TB_SECURITY_SECURE &&
1036                     sw->security_level == TB_SECURITY_SECURE)
1037                         return attr->mode;
1038                 return 0;
1039         } else if (attr == &dev_attr_nvm_authenticate.attr ||
1040                    attr == &dev_attr_nvm_version.attr) {
1041                 if (sw->dma_port)
1042                         return attr->mode;
1043                 return 0;
1044         } else if (attr == &dev_attr_boot.attr) {
1045                 if (tb_route(sw))
1046                         return attr->mode;
1047                 return 0;
1048         }
1049
1050         return sw->safe_mode ? 0 : attr->mode;
1051 }
1052
1053 static struct attribute_group switch_group = {
1054         .is_visible = switch_attr_is_visible,
1055         .attrs = switch_attrs,
1056 };
1057
1058 static const struct attribute_group *switch_groups[] = {
1059         &switch_group,
1060         NULL,
1061 };
1062
1063 static void tb_switch_release(struct device *dev)
1064 {
1065         struct tb_switch *sw = tb_to_switch(dev);
1066
1067         dma_port_free(sw->dma_port);
1068
1069         kfree(sw->uuid);
1070         kfree(sw->device_name);
1071         kfree(sw->vendor_name);
1072         kfree(sw->ports);
1073         kfree(sw->drom);
1074         kfree(sw->key);
1075         kfree(sw);
1076 }
1077
1078 /*
1079  * Currently only need to provide the callbacks. Everything else is handled
1080  * in the connection manager.
1081  */
1082 static int __maybe_unused tb_switch_runtime_suspend(struct device *dev)
1083 {
1084         return 0;
1085 }
1086
1087 static int __maybe_unused tb_switch_runtime_resume(struct device *dev)
1088 {
1089         return 0;
1090 }
1091
1092 static const struct dev_pm_ops tb_switch_pm_ops = {
1093         SET_RUNTIME_PM_OPS(tb_switch_runtime_suspend, tb_switch_runtime_resume,
1094                            NULL)
1095 };
1096
1097 struct device_type tb_switch_type = {
1098         .name = "thunderbolt_device",
1099         .release = tb_switch_release,
1100         .pm = &tb_switch_pm_ops,
1101 };
1102
1103 static int tb_switch_get_generation(struct tb_switch *sw)
1104 {
1105         switch (sw->config.device_id) {
1106         case PCI_DEVICE_ID_INTEL_LIGHT_RIDGE:
1107         case PCI_DEVICE_ID_INTEL_EAGLE_RIDGE:
1108         case PCI_DEVICE_ID_INTEL_LIGHT_PEAK:
1109         case PCI_DEVICE_ID_INTEL_CACTUS_RIDGE_2C:
1110         case PCI_DEVICE_ID_INTEL_CACTUS_RIDGE_4C:
1111         case PCI_DEVICE_ID_INTEL_PORT_RIDGE:
1112         case PCI_DEVICE_ID_INTEL_REDWOOD_RIDGE_2C_BRIDGE:
1113         case PCI_DEVICE_ID_INTEL_REDWOOD_RIDGE_4C_BRIDGE:
1114                 return 1;
1115
1116         case PCI_DEVICE_ID_INTEL_WIN_RIDGE_2C_BRIDGE:
1117         case PCI_DEVICE_ID_INTEL_FALCON_RIDGE_2C_BRIDGE:
1118         case PCI_DEVICE_ID_INTEL_FALCON_RIDGE_4C_BRIDGE:
1119                 return 2;
1120
1121         case PCI_DEVICE_ID_INTEL_ALPINE_RIDGE_LP_BRIDGE:
1122         case PCI_DEVICE_ID_INTEL_ALPINE_RIDGE_2C_BRIDGE:
1123         case PCI_DEVICE_ID_INTEL_ALPINE_RIDGE_4C_BRIDGE:
1124         case PCI_DEVICE_ID_INTEL_ALPINE_RIDGE_C_2C_BRIDGE:
1125         case PCI_DEVICE_ID_INTEL_ALPINE_RIDGE_C_4C_BRIDGE:
1126         case PCI_DEVICE_ID_INTEL_TITAN_RIDGE_2C_BRIDGE:
1127         case PCI_DEVICE_ID_INTEL_TITAN_RIDGE_4C_BRIDGE:
1128         case PCI_DEVICE_ID_INTEL_TITAN_RIDGE_DD_BRIDGE:
1129                 return 3;
1130
1131         default:
1132                 /*
1133                  * For unknown switches assume generation to be 1 to be
1134                  * on the safe side.
1135                  */
1136                 tb_sw_warn(sw, "unsupported switch device id %#x\n",
1137                            sw->config.device_id);
1138                 return 1;
1139         }
1140 }
1141
1142 /**
1143  * tb_switch_alloc() - allocate a switch
1144  * @tb: Pointer to the owning domain
1145  * @parent: Parent device for this switch
1146  * @route: Route string for this switch
1147  *
1148  * Allocates and initializes a switch. Will not upload configuration to
1149  * the switch. For that you need to call tb_switch_configure()
1150  * separately. The returned switch should be released by calling
1151  * tb_switch_put().
1152  *
1153  * Return: Pointer to the allocated switch or %NULL in case of failure
1154  */
1155 struct tb_switch *tb_switch_alloc(struct tb *tb, struct device *parent,
1156                                   u64 route)
1157 {
1158         int i;
1159         int cap;
1160         struct tb_switch *sw;
1161         int upstream_port = tb_cfg_get_upstream_port(tb->ctl, route);
1162         if (upstream_port < 0)
1163                 return NULL;
1164
1165         sw = kzalloc(sizeof(*sw), GFP_KERNEL);
1166         if (!sw)
1167                 return NULL;
1168
1169         sw->tb = tb;
1170         if (tb_cfg_read(tb->ctl, &sw->config, route, 0, TB_CFG_SWITCH, 0, 5))
1171                 goto err_free_sw_ports;
1172
1173         tb_info(tb, "current switch config:\n");
1174         tb_dump_switch(tb, &sw->config);
1175
1176         /* configure switch */
1177         sw->config.upstream_port_number = upstream_port;
1178         sw->config.depth = tb_route_length(route);
1179         sw->config.route_lo = route;
1180         sw->config.route_hi = route >> 32;
1181         sw->config.enabled = 0;
1182
1183         /* initialize ports */
1184         sw->ports = kcalloc(sw->config.max_port_number + 1, sizeof(*sw->ports),
1185                                 GFP_KERNEL);
1186         if (!sw->ports)
1187                 goto err_free_sw_ports;
1188
1189         for (i = 0; i <= sw->config.max_port_number; i++) {
1190                 /* minimum setup for tb_find_cap and tb_drom_read to work */
1191                 sw->ports[i].sw = sw;
1192                 sw->ports[i].port = i;
1193         }
1194
1195         sw->generation = tb_switch_get_generation(sw);
1196
1197         cap = tb_switch_find_vse_cap(sw, TB_VSE_CAP_PLUG_EVENTS);
1198         if (cap < 0) {
1199                 tb_sw_warn(sw, "cannot find TB_VSE_CAP_PLUG_EVENTS aborting\n");
1200                 goto err_free_sw_ports;
1201         }
1202         sw->cap_plug_events = cap;
1203
1204         /* Root switch is always authorized */
1205         if (!route)
1206                 sw->authorized = true;
1207
1208         device_initialize(&sw->dev);
1209         sw->dev.parent = parent;
1210         sw->dev.bus = &tb_bus_type;
1211         sw->dev.type = &tb_switch_type;
1212         sw->dev.groups = switch_groups;
1213         dev_set_name(&sw->dev, "%u-%llx", tb->index, tb_route(sw));
1214
1215         return sw;
1216
1217 err_free_sw_ports:
1218         kfree(sw->ports);
1219         kfree(sw);
1220
1221         return NULL;
1222 }
1223
1224 /**
1225  * tb_switch_alloc_safe_mode() - allocate a switch that is in safe mode
1226  * @tb: Pointer to the owning domain
1227  * @parent: Parent device for this switch
1228  * @route: Route string for this switch
1229  *
1230  * This creates a switch in safe mode. This means the switch pretty much
1231  * lacks all capabilities except DMA configuration port before it is
1232  * flashed with a valid NVM firmware.
1233  *
1234  * The returned switch must be released by calling tb_switch_put().
1235  *
1236  * Return: Pointer to the allocated switch or %NULL in case of failure
1237  */
1238 struct tb_switch *
1239 tb_switch_alloc_safe_mode(struct tb *tb, struct device *parent, u64 route)
1240 {
1241         struct tb_switch *sw;
1242
1243         sw = kzalloc(sizeof(*sw), GFP_KERNEL);
1244         if (!sw)
1245                 return NULL;
1246
1247         sw->tb = tb;
1248         sw->config.depth = tb_route_length(route);
1249         sw->config.route_hi = upper_32_bits(route);
1250         sw->config.route_lo = lower_32_bits(route);
1251         sw->safe_mode = true;
1252
1253         device_initialize(&sw->dev);
1254         sw->dev.parent = parent;
1255         sw->dev.bus = &tb_bus_type;
1256         sw->dev.type = &tb_switch_type;
1257         sw->dev.groups = switch_groups;
1258         dev_set_name(&sw->dev, "%u-%llx", tb->index, tb_route(sw));
1259
1260         return sw;
1261 }
1262
1263 /**
1264  * tb_switch_configure() - Uploads configuration to the switch
1265  * @sw: Switch to configure
1266  *
1267  * Call this function before the switch is added to the system. It will
1268  * upload configuration to the switch and makes it available for the
1269  * connection manager to use.
1270  *
1271  * Return: %0 in case of success and negative errno in case of failure
1272  */
1273 int tb_switch_configure(struct tb_switch *sw)
1274 {
1275         struct tb *tb = sw->tb;
1276         u64 route;
1277         int ret;
1278
1279         route = tb_route(sw);
1280         tb_info(tb,
1281                 "initializing Switch at %#llx (depth: %d, up port: %d)\n",
1282                 route, tb_route_length(route), sw->config.upstream_port_number);
1283
1284         if (sw->config.vendor_id != PCI_VENDOR_ID_INTEL)
1285                 tb_sw_warn(sw, "unknown switch vendor id %#x\n",
1286                            sw->config.vendor_id);
1287
1288         sw->config.enabled = 1;
1289
1290         /* upload configuration */
1291         ret = tb_sw_write(sw, 1 + (u32 *)&sw->config, TB_CFG_SWITCH, 1, 3);
1292         if (ret)
1293                 return ret;
1294
1295         return tb_plug_events_active(sw, true);
1296 }
1297
1298 static int tb_switch_set_uuid(struct tb_switch *sw)
1299 {
1300         u32 uuid[4];
1301         int cap, ret;
1302
1303         ret = 0;
1304         if (sw->uuid)
1305                 return ret;
1306
1307         /*
1308          * The newer controllers include fused UUID as part of link
1309          * controller specific registers
1310          */
1311         cap = tb_switch_find_vse_cap(sw, TB_VSE_CAP_LINK_CONTROLLER);
1312         if (cap > 0) {
1313                 ret = tb_sw_read(sw, uuid, TB_CFG_SWITCH, cap + 3, 4);
1314                 if (ret)
1315                         return ret;
1316         } else {
1317                 /*
1318                  * ICM generates UUID based on UID and fills the upper
1319                  * two words with ones. This is not strictly following
1320                  * UUID format but we want to be compatible with it so
1321                  * we do the same here.
1322                  */
1323                 uuid[0] = sw->uid & 0xffffffff;
1324                 uuid[1] = (sw->uid >> 32) & 0xffffffff;
1325                 uuid[2] = 0xffffffff;
1326                 uuid[3] = 0xffffffff;
1327         }
1328
1329         sw->uuid = kmemdup(uuid, sizeof(uuid), GFP_KERNEL);
1330         if (!sw->uuid)
1331                 ret = -ENOMEM;
1332         return ret;
1333 }
1334
1335 static int tb_switch_add_dma_port(struct tb_switch *sw)
1336 {
1337         u32 status;
1338         int ret;
1339
1340         switch (sw->generation) {
1341         case 2:
1342                 /* Only root switch can be upgraded */
1343                 if (tb_route(sw))
1344                         return 0;
1345
1346                 /* fallthrough */
1347         case 3:
1348                 ret = tb_switch_set_uuid(sw);
1349                 if (ret)
1350                         return ret;
1351                 break;
1352
1353         default:
1354                 /*
1355                  * DMA port is the only thing available when the switch
1356                  * is in safe mode.
1357                  */
1358                 if (!sw->safe_mode)
1359                         return 0;
1360                 break;
1361         }
1362
1363         if (sw->no_nvm_upgrade)
1364                 return 0;
1365
1366         sw->dma_port = dma_port_alloc(sw);
1367         if (!sw->dma_port)
1368                 return 0;
1369
1370         /*
1371          * If there is status already set then authentication failed
1372          * when the dma_port_flash_update_auth() returned. Power cycling
1373          * is not needed (it was done already) so only thing we do here
1374          * is to unblock runtime PM of the root port.
1375          */
1376         nvm_get_auth_status(sw, &status);
1377         if (status) {
1378                 if (!tb_route(sw))
1379                         nvm_authenticate_complete(sw);
1380                 return 0;
1381         }
1382
1383         /*
1384          * Check status of the previous flash authentication. If there
1385          * is one we need to power cycle the switch in any case to make
1386          * it functional again.
1387          */
1388         ret = dma_port_flash_update_auth_status(sw->dma_port, &status);
1389         if (ret <= 0)
1390                 return ret;
1391
1392         /* Now we can allow root port to suspend again */
1393         if (!tb_route(sw))
1394                 nvm_authenticate_complete(sw);
1395
1396         if (status) {
1397                 tb_sw_info(sw, "switch flash authentication failed\n");
1398                 nvm_set_auth_status(sw, status);
1399         }
1400
1401         tb_sw_info(sw, "power cycling the switch now\n");
1402         dma_port_power_cycle(sw->dma_port);
1403
1404         /*
1405          * We return error here which causes the switch adding failure.
1406          * It should appear back after power cycle is complete.
1407          */
1408         return -ESHUTDOWN;
1409 }
1410
1411 /**
1412  * tb_switch_add() - Add a switch to the domain
1413  * @sw: Switch to add
1414  *
1415  * This is the last step in adding switch to the domain. It will read
1416  * identification information from DROM and initializes ports so that
1417  * they can be used to connect other switches. The switch will be
1418  * exposed to the userspace when this function successfully returns. To
1419  * remove and release the switch, call tb_switch_remove().
1420  *
1421  * Return: %0 in case of success and negative errno in case of failure
1422  */
1423 int tb_switch_add(struct tb_switch *sw)
1424 {
1425         int i, ret;
1426
1427         /*
1428          * Initialize DMA control port now before we read DROM. Recent
1429          * host controllers have more complete DROM on NVM that includes
1430          * vendor and model identification strings which we then expose
1431          * to the userspace. NVM can be accessed through DMA
1432          * configuration based mailbox.
1433          */
1434         ret = tb_switch_add_dma_port(sw);
1435         if (ret)
1436                 return ret;
1437
1438         if (!sw->safe_mode) {
1439                 /* read drom */
1440                 ret = tb_drom_read(sw);
1441                 if (ret) {
1442                         tb_sw_warn(sw, "tb_eeprom_read_rom failed\n");
1443                         return ret;
1444                 }
1445                 tb_sw_info(sw, "uid: %#llx\n", sw->uid);
1446
1447                 ret = tb_switch_set_uuid(sw);
1448                 if (ret)
1449                         return ret;
1450
1451                 for (i = 0; i <= sw->config.max_port_number; i++) {
1452                         if (sw->ports[i].disabled) {
1453                                 tb_port_info(&sw->ports[i], "disabled by eeprom\n");
1454                                 continue;
1455                         }
1456                         ret = tb_init_port(&sw->ports[i]);
1457                         if (ret)
1458                                 return ret;
1459                 }
1460         }
1461
1462         ret = device_add(&sw->dev);
1463         if (ret)
1464                 return ret;
1465
1466         ret = tb_switch_nvm_add(sw);
1467         if (ret) {
1468                 device_del(&sw->dev);
1469                 return ret;
1470         }
1471
1472         pm_runtime_set_active(&sw->dev);
1473         if (sw->rpm) {
1474                 pm_runtime_set_autosuspend_delay(&sw->dev, TB_AUTOSUSPEND_DELAY);
1475                 pm_runtime_use_autosuspend(&sw->dev);
1476                 pm_runtime_mark_last_busy(&sw->dev);
1477                 pm_runtime_enable(&sw->dev);
1478                 pm_request_autosuspend(&sw->dev);
1479         }
1480
1481         return 0;
1482 }
1483
1484 /**
1485  * tb_switch_remove() - Remove and release a switch
1486  * @sw: Switch to remove
1487  *
1488  * This will remove the switch from the domain and release it after last
1489  * reference count drops to zero. If there are switches connected below
1490  * this switch, they will be removed as well.
1491  */
1492 void tb_switch_remove(struct tb_switch *sw)
1493 {
1494         int i;
1495
1496         if (sw->rpm) {
1497                 pm_runtime_get_sync(&sw->dev);
1498                 pm_runtime_disable(&sw->dev);
1499         }
1500
1501         /* port 0 is the switch itself and never has a remote */
1502         for (i = 1; i <= sw->config.max_port_number; i++) {
1503                 if (tb_is_upstream_port(&sw->ports[i]))
1504                         continue;
1505                 if (sw->ports[i].remote)
1506                         tb_switch_remove(sw->ports[i].remote->sw);
1507                 sw->ports[i].remote = NULL;
1508                 if (sw->ports[i].xdomain)
1509                         tb_xdomain_remove(sw->ports[i].xdomain);
1510                 sw->ports[i].xdomain = NULL;
1511         }
1512
1513         if (!sw->is_unplugged)
1514                 tb_plug_events_active(sw, false);
1515
1516         tb_switch_nvm_remove(sw);
1517         device_unregister(&sw->dev);
1518 }
1519
1520 /**
1521  * tb_sw_set_unplugged() - set is_unplugged on switch and downstream switches
1522  */
1523 void tb_sw_set_unplugged(struct tb_switch *sw)
1524 {
1525         int i;
1526         if (sw == sw->tb->root_switch) {
1527                 tb_sw_WARN(sw, "cannot unplug root switch\n");
1528                 return;
1529         }
1530         if (sw->is_unplugged) {
1531                 tb_sw_WARN(sw, "is_unplugged already set\n");
1532                 return;
1533         }
1534         sw->is_unplugged = true;
1535         for (i = 0; i <= sw->config.max_port_number; i++) {
1536                 if (!tb_is_upstream_port(&sw->ports[i]) && sw->ports[i].remote)
1537                         tb_sw_set_unplugged(sw->ports[i].remote->sw);
1538         }
1539 }
1540
1541 int tb_switch_resume(struct tb_switch *sw)
1542 {
1543         int i, err;
1544         tb_sw_info(sw, "resuming switch\n");
1545
1546         /*
1547          * Check for UID of the connected switches except for root
1548          * switch which we assume cannot be removed.
1549          */
1550         if (tb_route(sw)) {
1551                 u64 uid;
1552
1553                 err = tb_drom_read_uid_only(sw, &uid);
1554                 if (err) {
1555                         tb_sw_warn(sw, "uid read failed\n");
1556                         return err;
1557                 }
1558                 if (sw->uid != uid) {
1559                         tb_sw_info(sw,
1560                                 "changed while suspended (uid %#llx -> %#llx)\n",
1561                                 sw->uid, uid);
1562                         return -ENODEV;
1563                 }
1564         }
1565
1566         /* upload configuration */
1567         err = tb_sw_write(sw, 1 + (u32 *) &sw->config, TB_CFG_SWITCH, 1, 3);
1568         if (err)
1569                 return err;
1570
1571         err = tb_plug_events_active(sw, true);
1572         if (err)
1573                 return err;
1574
1575         /* check for surviving downstream switches */
1576         for (i = 1; i <= sw->config.max_port_number; i++) {
1577                 struct tb_port *port = &sw->ports[i];
1578                 if (tb_is_upstream_port(port))
1579                         continue;
1580                 if (!port->remote)
1581                         continue;
1582                 if (tb_wait_for_port(port, true) <= 0
1583                         || tb_switch_resume(port->remote->sw)) {
1584                         tb_port_warn(port,
1585                                      "lost during suspend, disconnecting\n");
1586                         tb_sw_set_unplugged(port->remote->sw);
1587                 }
1588         }
1589         return 0;
1590 }
1591
1592 void tb_switch_suspend(struct tb_switch *sw)
1593 {
1594         int i, err;
1595         err = tb_plug_events_active(sw, false);
1596         if (err)
1597                 return;
1598
1599         for (i = 1; i <= sw->config.max_port_number; i++) {
1600                 if (!tb_is_upstream_port(&sw->ports[i]) && sw->ports[i].remote)
1601                         tb_switch_suspend(sw->ports[i].remote->sw);
1602         }
1603         /*
1604          * TODO: invoke tb_cfg_prepare_to_sleep here? does not seem to have any
1605          * effect?
1606          */
1607 }
1608
1609 struct tb_sw_lookup {
1610         struct tb *tb;
1611         u8 link;
1612         u8 depth;
1613         const uuid_t *uuid;
1614         u64 route;
1615 };
1616
1617 static int tb_switch_match(struct device *dev, void *data)
1618 {
1619         struct tb_switch *sw = tb_to_switch(dev);
1620         struct tb_sw_lookup *lookup = data;
1621
1622         if (!sw)
1623                 return 0;
1624         if (sw->tb != lookup->tb)
1625                 return 0;
1626
1627         if (lookup->uuid)
1628                 return !memcmp(sw->uuid, lookup->uuid, sizeof(*lookup->uuid));
1629
1630         if (lookup->route) {
1631                 return sw->config.route_lo == lower_32_bits(lookup->route) &&
1632                        sw->config.route_hi == upper_32_bits(lookup->route);
1633         }
1634
1635         /* Root switch is matched only by depth */
1636         if (!lookup->depth)
1637                 return !sw->depth;
1638
1639         return sw->link == lookup->link && sw->depth == lookup->depth;
1640 }
1641
1642 /**
1643  * tb_switch_find_by_link_depth() - Find switch by link and depth
1644  * @tb: Domain the switch belongs
1645  * @link: Link number the switch is connected
1646  * @depth: Depth of the switch in link
1647  *
1648  * Returned switch has reference count increased so the caller needs to
1649  * call tb_switch_put() when done with the switch.
1650  */
1651 struct tb_switch *tb_switch_find_by_link_depth(struct tb *tb, u8 link, u8 depth)
1652 {
1653         struct tb_sw_lookup lookup;
1654         struct device *dev;
1655
1656         memset(&lookup, 0, sizeof(lookup));
1657         lookup.tb = tb;
1658         lookup.link = link;
1659         lookup.depth = depth;
1660
1661         dev = bus_find_device(&tb_bus_type, NULL, &lookup, tb_switch_match);
1662         if (dev)
1663                 return tb_to_switch(dev);
1664
1665         return NULL;
1666 }
1667
1668 /**
1669  * tb_switch_find_by_uuid() - Find switch by UUID
1670  * @tb: Domain the switch belongs
1671  * @uuid: UUID to look for
1672  *
1673  * Returned switch has reference count increased so the caller needs to
1674  * call tb_switch_put() when done with the switch.
1675  */
1676 struct tb_switch *tb_switch_find_by_uuid(struct tb *tb, const uuid_t *uuid)
1677 {
1678         struct tb_sw_lookup lookup;
1679         struct device *dev;
1680
1681         memset(&lookup, 0, sizeof(lookup));
1682         lookup.tb = tb;
1683         lookup.uuid = uuid;
1684
1685         dev = bus_find_device(&tb_bus_type, NULL, &lookup, tb_switch_match);
1686         if (dev)
1687                 return tb_to_switch(dev);
1688
1689         return NULL;
1690 }
1691
1692 /**
1693  * tb_switch_find_by_route() - Find switch by route string
1694  * @tb: Domain the switch belongs
1695  * @route: Route string to look for
1696  *
1697  * Returned switch has reference count increased so the caller needs to
1698  * call tb_switch_put() when done with the switch.
1699  */
1700 struct tb_switch *tb_switch_find_by_route(struct tb *tb, u64 route)
1701 {
1702         struct tb_sw_lookup lookup;
1703         struct device *dev;
1704
1705         if (!route)
1706                 return tb_switch_get(tb->root_switch);
1707
1708         memset(&lookup, 0, sizeof(lookup));
1709         lookup.tb = tb;
1710         lookup.route = route;
1711
1712         dev = bus_find_device(&tb_bus_type, NULL, &lookup, tb_switch_match);
1713         if (dev)
1714                 return tb_to_switch(dev);
1715
1716         return NULL;
1717 }
1718
1719 void tb_switch_exit(void)
1720 {
1721         ida_destroy(&nvm_ida);
1722 }