GNU Linux-libre 5.10.217-gnu1
[releases.git] / drivers / thunderbolt / usb4.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * USB4 specific functionality
4  *
5  * Copyright (C) 2019, Intel Corporation
6  * Authors: Mika Westerberg <mika.westerberg@linux.intel.com>
7  *          Rajmohan Mani <rajmohan.mani@intel.com>
8  */
9
10 #include <linux/delay.h>
11 #include <linux/ktime.h>
12
13 #include "sb_regs.h"
14 #include "tb.h"
15
16 #define USB4_DATA_DWORDS                16
17 #define USB4_DATA_RETRIES               3
18
19 enum usb4_switch_op {
20         USB4_SWITCH_OP_QUERY_DP_RESOURCE = 0x10,
21         USB4_SWITCH_OP_ALLOC_DP_RESOURCE = 0x11,
22         USB4_SWITCH_OP_DEALLOC_DP_RESOURCE = 0x12,
23         USB4_SWITCH_OP_NVM_WRITE = 0x20,
24         USB4_SWITCH_OP_NVM_AUTH = 0x21,
25         USB4_SWITCH_OP_NVM_READ = 0x22,
26         USB4_SWITCH_OP_NVM_SET_OFFSET = 0x23,
27         USB4_SWITCH_OP_DROM_READ = 0x24,
28         USB4_SWITCH_OP_NVM_SECTOR_SIZE = 0x25,
29 };
30
31 enum usb4_sb_target {
32         USB4_SB_TARGET_ROUTER,
33         USB4_SB_TARGET_PARTNER,
34         USB4_SB_TARGET_RETIMER,
35 };
36
37 #define USB4_NVM_READ_OFFSET_MASK       GENMASK(23, 2)
38 #define USB4_NVM_READ_OFFSET_SHIFT      2
39 #define USB4_NVM_READ_LENGTH_MASK       GENMASK(27, 24)
40 #define USB4_NVM_READ_LENGTH_SHIFT      24
41
42 #define USB4_NVM_SET_OFFSET_MASK        USB4_NVM_READ_OFFSET_MASK
43 #define USB4_NVM_SET_OFFSET_SHIFT       USB4_NVM_READ_OFFSET_SHIFT
44
45 #define USB4_DROM_ADDRESS_MASK          GENMASK(14, 2)
46 #define USB4_DROM_ADDRESS_SHIFT         2
47 #define USB4_DROM_SIZE_MASK             GENMASK(19, 15)
48 #define USB4_DROM_SIZE_SHIFT            15
49
50 #define USB4_NVM_SECTOR_SIZE_MASK       GENMASK(23, 0)
51
52 typedef int (*read_block_fn)(void *, unsigned int, void *, size_t);
53 typedef int (*write_block_fn)(void *, const void *, size_t);
54
55 static int usb4_switch_wait_for_bit(struct tb_switch *sw, u32 offset, u32 bit,
56                                     u32 value, int timeout_msec)
57 {
58         ktime_t timeout = ktime_add_ms(ktime_get(), timeout_msec);
59
60         do {
61                 u32 val;
62                 int ret;
63
64                 ret = tb_sw_read(sw, &val, TB_CFG_SWITCH, offset, 1);
65                 if (ret)
66                         return ret;
67
68                 if ((val & bit) == value)
69                         return 0;
70
71                 usleep_range(50, 100);
72         } while (ktime_before(ktime_get(), timeout));
73
74         return -ETIMEDOUT;
75 }
76
77 static int usb4_switch_op_read_data(struct tb_switch *sw, void *data,
78                                     size_t dwords)
79 {
80         if (dwords > USB4_DATA_DWORDS)
81                 return -EINVAL;
82
83         return tb_sw_read(sw, data, TB_CFG_SWITCH, ROUTER_CS_9, dwords);
84 }
85
86 static int usb4_switch_op_write_data(struct tb_switch *sw, const void *data,
87                                      size_t dwords)
88 {
89         if (dwords > USB4_DATA_DWORDS)
90                 return -EINVAL;
91
92         return tb_sw_write(sw, data, TB_CFG_SWITCH, ROUTER_CS_9, dwords);
93 }
94
95 static int usb4_switch_op_read_metadata(struct tb_switch *sw, u32 *metadata)
96 {
97         return tb_sw_read(sw, metadata, TB_CFG_SWITCH, ROUTER_CS_25, 1);
98 }
99
100 static int usb4_switch_op_write_metadata(struct tb_switch *sw, u32 metadata)
101 {
102         return tb_sw_write(sw, &metadata, TB_CFG_SWITCH, ROUTER_CS_25, 1);
103 }
104
105 static int usb4_do_read_data(u16 address, void *buf, size_t size,
106                              read_block_fn read_block, void *read_block_data)
107 {
108         unsigned int retries = USB4_DATA_RETRIES;
109         unsigned int offset;
110
111         do {
112                 unsigned int dwaddress, dwords;
113                 u8 data[USB4_DATA_DWORDS * 4];
114                 size_t nbytes;
115                 int ret;
116
117                 offset = address & 3;
118                 nbytes = min_t(size_t, size + offset, USB4_DATA_DWORDS * 4);
119
120                 dwaddress = address / 4;
121                 dwords = ALIGN(nbytes, 4) / 4;
122
123                 ret = read_block(read_block_data, dwaddress, data, dwords);
124                 if (ret) {
125                         if (ret != -ENODEV && retries--)
126                                 continue;
127                         return ret;
128                 }
129
130                 nbytes -= offset;
131                 memcpy(buf, data + offset, nbytes);
132
133                 size -= nbytes;
134                 address += nbytes;
135                 buf += nbytes;
136         } while (size > 0);
137
138         return 0;
139 }
140
141 static int usb4_do_write_data(unsigned int address, const void *buf, size_t size,
142         write_block_fn write_next_block, void *write_block_data)
143 {
144         unsigned int retries = USB4_DATA_RETRIES;
145         unsigned int offset;
146
147         offset = address & 3;
148         address = address & ~3;
149
150         do {
151                 u32 nbytes = min_t(u32, size, USB4_DATA_DWORDS * 4);
152                 u8 data[USB4_DATA_DWORDS * 4];
153                 int ret;
154
155                 memcpy(data + offset, buf, nbytes);
156
157                 ret = write_next_block(write_block_data, data, nbytes / 4);
158                 if (ret) {
159                         if (ret == -ETIMEDOUT) {
160                                 if (retries--)
161                                         continue;
162                                 ret = -EIO;
163                         }
164                         return ret;
165                 }
166
167                 size -= nbytes;
168                 address += nbytes;
169                 buf += nbytes;
170         } while (size > 0);
171
172         return 0;
173 }
174
175 static int usb4_switch_op(struct tb_switch *sw, u16 opcode, u8 *status)
176 {
177         u32 val;
178         int ret;
179
180         val = opcode | ROUTER_CS_26_OV;
181         ret = tb_sw_write(sw, &val, TB_CFG_SWITCH, ROUTER_CS_26, 1);
182         if (ret)
183                 return ret;
184
185         ret = usb4_switch_wait_for_bit(sw, ROUTER_CS_26, ROUTER_CS_26_OV, 0, 500);
186         if (ret)
187                 return ret;
188
189         ret = tb_sw_read(sw, &val, TB_CFG_SWITCH, ROUTER_CS_26, 1);
190         if (ret)
191                 return ret;
192
193         if (val & ROUTER_CS_26_ONS)
194                 return -EOPNOTSUPP;
195
196         *status = (val & ROUTER_CS_26_STATUS_MASK) >> ROUTER_CS_26_STATUS_SHIFT;
197         return 0;
198 }
199
200 /**
201  * usb4_switch_check_wakes() - Check for wakes and notify PM core about them
202  * @sw: Router whose wakes to check
203  *
204  * Checks wakes occurred during suspend and notify the PM core about them.
205  */
206 void usb4_switch_check_wakes(struct tb_switch *sw)
207 {
208         struct tb_port *port;
209         bool wakeup = false;
210         u32 val;
211
212         if (tb_route(sw)) {
213                 if (tb_sw_read(sw, &val, TB_CFG_SWITCH, ROUTER_CS_6, 1))
214                         return;
215
216                 tb_sw_dbg(sw, "PCIe wake: %s, USB3 wake: %s\n",
217                           (val & ROUTER_CS_6_WOPS) ? "yes" : "no",
218                           (val & ROUTER_CS_6_WOUS) ? "yes" : "no");
219
220                 wakeup = val & (ROUTER_CS_6_WOPS | ROUTER_CS_6_WOUS);
221         }
222
223         /* Check for any connected downstream ports for USB4 wake */
224         tb_switch_for_each_port(sw, port) {
225                 if (!tb_port_has_remote(port))
226                         continue;
227
228                 if (tb_port_read(port, &val, TB_CFG_PORT,
229                                  port->cap_usb4 + PORT_CS_18, 1))
230                         break;
231
232                 tb_port_dbg(port, "USB4 wake: %s\n",
233                             (val & PORT_CS_18_WOU4S) ? "yes" : "no");
234
235                 if (val & PORT_CS_18_WOU4S)
236                         wakeup = true;
237         }
238
239         if (wakeup)
240                 pm_wakeup_event(&sw->dev, 0);
241 }
242
243 static bool link_is_usb4(struct tb_port *port)
244 {
245         u32 val;
246
247         if (!port->cap_usb4)
248                 return false;
249
250         if (tb_port_read(port, &val, TB_CFG_PORT,
251                          port->cap_usb4 + PORT_CS_18, 1))
252                 return false;
253
254         return !(val & PORT_CS_18_TCM);
255 }
256
257 /**
258  * usb4_switch_setup() - Additional setup for USB4 device
259  * @sw: USB4 router to setup
260  *
261  * USB4 routers need additional settings in order to enable all the
262  * tunneling. This function enables USB and PCIe tunneling if it can be
263  * enabled (e.g the parent switch also supports them). If USB tunneling
264  * is not available for some reason (like that there is Thunderbolt 3
265  * switch upstream) then the internal xHCI controller is enabled
266  * instead.
267  */
268 int usb4_switch_setup(struct tb_switch *sw)
269 {
270         struct tb_port *downstream_port;
271         struct tb_switch *parent;
272         bool tbt3, xhci;
273         u32 val = 0;
274         int ret;
275
276         if (!tb_route(sw))
277                 return 0;
278
279         ret = tb_sw_read(sw, &val, TB_CFG_SWITCH, ROUTER_CS_6, 1);
280         if (ret)
281                 return ret;
282
283         parent = tb_switch_parent(sw);
284         downstream_port = tb_port_at(tb_route(sw), parent);
285         sw->link_usb4 = link_is_usb4(downstream_port);
286         tb_sw_dbg(sw, "link: %s\n", sw->link_usb4 ? "USB4" : "TBT3");
287
288         xhci = val & ROUTER_CS_6_HCI;
289         tbt3 = !(val & ROUTER_CS_6_TNS);
290
291         tb_sw_dbg(sw, "TBT3 support: %s, xHCI: %s\n",
292                   tbt3 ? "yes" : "no", xhci ? "yes" : "no");
293
294         ret = tb_sw_read(sw, &val, TB_CFG_SWITCH, ROUTER_CS_5, 1);
295         if (ret)
296                 return ret;
297
298         if (sw->link_usb4 && tb_switch_find_port(parent, TB_TYPE_USB3_DOWN)) {
299                 val |= ROUTER_CS_5_UTO;
300                 xhci = false;
301         }
302
303         /* Only enable PCIe tunneling if the parent router supports it */
304         if (tb_switch_find_port(parent, TB_TYPE_PCIE_DOWN)) {
305                 val |= ROUTER_CS_5_PTO;
306                 /*
307                  * xHCI can be enabled if PCIe tunneling is supported
308                  * and the parent does not have any USB3 dowstream
309                  * adapters (so we cannot do USB 3.x tunneling).
310                  */
311                 if (xhci)
312                         val |= ROUTER_CS_5_HCO;
313         }
314
315         /* TBT3 supported by the CM */
316         val |= ROUTER_CS_5_C3S;
317         /* Tunneling configuration is ready now */
318         val |= ROUTER_CS_5_CV;
319
320         ret = tb_sw_write(sw, &val, TB_CFG_SWITCH, ROUTER_CS_5, 1);
321         if (ret)
322                 return ret;
323
324         return usb4_switch_wait_for_bit(sw, ROUTER_CS_6, ROUTER_CS_6_CR,
325                                         ROUTER_CS_6_CR, 50);
326 }
327
328 /**
329  * usb4_switch_read_uid() - Read UID from USB4 router
330  * @sw: USB4 router
331  * @uid: UID is stored here
332  *
333  * Reads 64-bit UID from USB4 router config space.
334  */
335 int usb4_switch_read_uid(struct tb_switch *sw, u64 *uid)
336 {
337         return tb_sw_read(sw, uid, TB_CFG_SWITCH, ROUTER_CS_7, 2);
338 }
339
340 static int usb4_switch_drom_read_block(void *data,
341                                        unsigned int dwaddress, void *buf,
342                                        size_t dwords)
343 {
344         struct tb_switch *sw = data;
345         u8 status = 0;
346         u32 metadata;
347         int ret;
348
349         metadata = (dwords << USB4_DROM_SIZE_SHIFT) & USB4_DROM_SIZE_MASK;
350         metadata |= (dwaddress << USB4_DROM_ADDRESS_SHIFT) &
351                 USB4_DROM_ADDRESS_MASK;
352
353         ret = usb4_switch_op_write_metadata(sw, metadata);
354         if (ret)
355                 return ret;
356
357         ret = usb4_switch_op(sw, USB4_SWITCH_OP_DROM_READ, &status);
358         if (ret)
359                 return ret;
360
361         if (status)
362                 return -EIO;
363
364         return usb4_switch_op_read_data(sw, buf, dwords);
365 }
366
367 /**
368  * usb4_switch_drom_read() - Read arbitrary bytes from USB4 router DROM
369  * @sw: USB4 router
370  * @address: Byte address inside DROM to start reading
371  * @buf: Buffer where the DROM content is stored
372  * @size: Number of bytes to read from DROM
373  *
374  * Uses USB4 router operations to read router DROM. For devices this
375  * should always work but for hosts it may return %-EOPNOTSUPP in which
376  * case the host router does not have DROM.
377  */
378 int usb4_switch_drom_read(struct tb_switch *sw, unsigned int address, void *buf,
379                           size_t size)
380 {
381         return usb4_do_read_data(address, buf, size,
382                                  usb4_switch_drom_read_block, sw);
383 }
384
385 /**
386  * usb4_switch_lane_bonding_possible() - Are conditions met for lane bonding
387  * @sw: USB4 router
388  *
389  * Checks whether conditions are met so that lane bonding can be
390  * established with the upstream router. Call only for device routers.
391  */
392 bool usb4_switch_lane_bonding_possible(struct tb_switch *sw)
393 {
394         struct tb_port *up;
395         int ret;
396         u32 val;
397
398         up = tb_upstream_port(sw);
399         ret = tb_port_read(up, &val, TB_CFG_PORT, up->cap_usb4 + PORT_CS_18, 1);
400         if (ret)
401                 return false;
402
403         return !!(val & PORT_CS_18_BE);
404 }
405
406 /**
407  * usb4_switch_set_wake() - Enabled/disable wake
408  * @sw: USB4 router
409  * @flags: Wakeup flags (%0 to disable)
410  *
411  * Enables/disables router to wake up from sleep.
412  */
413 int usb4_switch_set_wake(struct tb_switch *sw, unsigned int flags)
414 {
415         struct tb_port *port;
416         u64 route = tb_route(sw);
417         u32 val;
418         int ret;
419
420         /*
421          * Enable wakes coming from all USB4 downstream ports (from
422          * child routers). For device routers do this also for the
423          * upstream USB4 port.
424          */
425         tb_switch_for_each_port(sw, port) {
426                 if (!tb_port_is_null(port))
427                         continue;
428                 if (!route && tb_is_upstream_port(port))
429                         continue;
430                 if (!port->cap_usb4)
431                         continue;
432
433                 ret = tb_port_read(port, &val, TB_CFG_PORT,
434                                    port->cap_usb4 + PORT_CS_19, 1);
435                 if (ret)
436                         return ret;
437
438                 val &= ~(PORT_CS_19_WOC | PORT_CS_19_WOD | PORT_CS_19_WOU4);
439
440                 if (flags & TB_WAKE_ON_CONNECT)
441                         val |= PORT_CS_19_WOC;
442                 if (flags & TB_WAKE_ON_DISCONNECT)
443                         val |= PORT_CS_19_WOD;
444                 if (flags & TB_WAKE_ON_USB4)
445                         val |= PORT_CS_19_WOU4;
446
447                 ret = tb_port_write(port, &val, TB_CFG_PORT,
448                                     port->cap_usb4 + PORT_CS_19, 1);
449                 if (ret)
450                         return ret;
451         }
452
453         /*
454          * Enable wakes from PCIe and USB 3.x on this router. Only
455          * needed for device routers.
456          */
457         if (route) {
458                 ret = tb_sw_read(sw, &val, TB_CFG_SWITCH, ROUTER_CS_5, 1);
459                 if (ret)
460                         return ret;
461
462                 val &= ~(ROUTER_CS_5_WOP | ROUTER_CS_5_WOU);
463                 if (flags & TB_WAKE_ON_USB3)
464                         val |= ROUTER_CS_5_WOU;
465                 if (flags & TB_WAKE_ON_PCIE)
466                         val |= ROUTER_CS_5_WOP;
467
468                 ret = tb_sw_write(sw, &val, TB_CFG_SWITCH, ROUTER_CS_5, 1);
469                 if (ret)
470                         return ret;
471         }
472
473         return 0;
474 }
475
476 /**
477  * usb4_switch_set_sleep() - Prepare the router to enter sleep
478  * @sw: USB4 router
479  *
480  * Sets sleep bit for the router. Returns when the router sleep ready
481  * bit has been asserted.
482  */
483 int usb4_switch_set_sleep(struct tb_switch *sw)
484 {
485         int ret;
486         u32 val;
487
488         /* Set sleep bit and wait for sleep ready to be asserted */
489         ret = tb_sw_read(sw, &val, TB_CFG_SWITCH, ROUTER_CS_5, 1);
490         if (ret)
491                 return ret;
492
493         val |= ROUTER_CS_5_SLP;
494
495         ret = tb_sw_write(sw, &val, TB_CFG_SWITCH, ROUTER_CS_5, 1);
496         if (ret)
497                 return ret;
498
499         return usb4_switch_wait_for_bit(sw, ROUTER_CS_6, ROUTER_CS_6_SLPR,
500                                         ROUTER_CS_6_SLPR, 500);
501 }
502
503 /**
504  * usb4_switch_nvm_sector_size() - Return router NVM sector size
505  * @sw: USB4 router
506  *
507  * If the router supports NVM operations this function returns the NVM
508  * sector size in bytes. If NVM operations are not supported returns
509  * %-EOPNOTSUPP.
510  */
511 int usb4_switch_nvm_sector_size(struct tb_switch *sw)
512 {
513         u32 metadata;
514         u8 status;
515         int ret;
516
517         ret = usb4_switch_op(sw, USB4_SWITCH_OP_NVM_SECTOR_SIZE, &status);
518         if (ret)
519                 return ret;
520
521         if (status)
522                 return status == 0x2 ? -EOPNOTSUPP : -EIO;
523
524         ret = usb4_switch_op_read_metadata(sw, &metadata);
525         if (ret)
526                 return ret;
527
528         return metadata & USB4_NVM_SECTOR_SIZE_MASK;
529 }
530
531 static int usb4_switch_nvm_read_block(void *data,
532         unsigned int dwaddress, void *buf, size_t dwords)
533 {
534         struct tb_switch *sw = data;
535         u8 status = 0;
536         u32 metadata;
537         int ret;
538
539         metadata = (dwords << USB4_NVM_READ_LENGTH_SHIFT) &
540                    USB4_NVM_READ_LENGTH_MASK;
541         metadata |= (dwaddress << USB4_NVM_READ_OFFSET_SHIFT) &
542                    USB4_NVM_READ_OFFSET_MASK;
543
544         ret = usb4_switch_op_write_metadata(sw, metadata);
545         if (ret)
546                 return ret;
547
548         ret = usb4_switch_op(sw, USB4_SWITCH_OP_NVM_READ, &status);
549         if (ret)
550                 return ret;
551
552         if (status)
553                 return -EIO;
554
555         return usb4_switch_op_read_data(sw, buf, dwords);
556 }
557
558 /**
559  * usb4_switch_nvm_read() - Read arbitrary bytes from router NVM
560  * @sw: USB4 router
561  * @address: Starting address in bytes
562  * @buf: Read data is placed here
563  * @size: How many bytes to read
564  *
565  * Reads NVM contents of the router. If NVM is not supported returns
566  * %-EOPNOTSUPP.
567  */
568 int usb4_switch_nvm_read(struct tb_switch *sw, unsigned int address, void *buf,
569                          size_t size)
570 {
571         return usb4_do_read_data(address, buf, size,
572                                  usb4_switch_nvm_read_block, sw);
573 }
574
575 static int usb4_switch_nvm_set_offset(struct tb_switch *sw,
576                                       unsigned int address)
577 {
578         u32 metadata, dwaddress;
579         u8 status = 0;
580         int ret;
581
582         dwaddress = address / 4;
583         metadata = (dwaddress << USB4_NVM_SET_OFFSET_SHIFT) &
584                    USB4_NVM_SET_OFFSET_MASK;
585
586         ret = usb4_switch_op_write_metadata(sw, metadata);
587         if (ret)
588                 return ret;
589
590         ret = usb4_switch_op(sw, USB4_SWITCH_OP_NVM_SET_OFFSET, &status);
591         if (ret)
592                 return ret;
593
594         return status ? -EIO : 0;
595 }
596
597 static int usb4_switch_nvm_write_next_block(void *data, const void *buf,
598                                             size_t dwords)
599 {
600         struct tb_switch *sw = data;
601         u8 status;
602         int ret;
603
604         ret = usb4_switch_op_write_data(sw, buf, dwords);
605         if (ret)
606                 return ret;
607
608         ret = usb4_switch_op(sw, USB4_SWITCH_OP_NVM_WRITE, &status);
609         if (ret)
610                 return ret;
611
612         return status ? -EIO : 0;
613 }
614
615 /**
616  * usb4_switch_nvm_write() - Write to the router NVM
617  * @sw: USB4 router
618  * @address: Start address where to write in bytes
619  * @buf: Pointer to the data to write
620  * @size: Size of @buf in bytes
621  *
622  * Writes @buf to the router NVM using USB4 router operations. If NVM
623  * write is not supported returns %-EOPNOTSUPP.
624  */
625 int usb4_switch_nvm_write(struct tb_switch *sw, unsigned int address,
626                           const void *buf, size_t size)
627 {
628         int ret;
629
630         ret = usb4_switch_nvm_set_offset(sw, address);
631         if (ret)
632                 return ret;
633
634         return usb4_do_write_data(address, buf, size,
635                                   usb4_switch_nvm_write_next_block, sw);
636 }
637
638 /**
639  * usb4_switch_nvm_authenticate() - Authenticate new NVM
640  * @sw: USB4 router
641  *
642  * After the new NVM has been written via usb4_switch_nvm_write(), this
643  * function triggers NVM authentication process. If the authentication
644  * is successful the router is power cycled and the new NVM starts
645  * running. In case of failure returns negative errno.
646  */
647 int usb4_switch_nvm_authenticate(struct tb_switch *sw)
648 {
649         u8 status = 0;
650         int ret;
651
652         ret = usb4_switch_op(sw, USB4_SWITCH_OP_NVM_AUTH, &status);
653         if (ret)
654                 return ret;
655
656         switch (status) {
657         case 0x0:
658                 tb_sw_dbg(sw, "NVM authentication successful\n");
659                 return 0;
660         case 0x1:
661                 return -EINVAL;
662         case 0x2:
663                 return -EAGAIN;
664         case 0x3:
665                 return -EOPNOTSUPP;
666         default:
667                 return -EIO;
668         }
669 }
670
671 /**
672  * usb4_switch_query_dp_resource() - Query availability of DP IN resource
673  * @sw: USB4 router
674  * @in: DP IN adapter
675  *
676  * For DP tunneling this function can be used to query availability of
677  * DP IN resource. Returns true if the resource is available for DP
678  * tunneling, false otherwise.
679  */
680 bool usb4_switch_query_dp_resource(struct tb_switch *sw, struct tb_port *in)
681 {
682         u8 status;
683         int ret;
684
685         ret = usb4_switch_op_write_metadata(sw, in->port);
686         if (ret)
687                 return false;
688
689         ret = usb4_switch_op(sw, USB4_SWITCH_OP_QUERY_DP_RESOURCE, &status);
690         /*
691          * If DP resource allocation is not supported assume it is
692          * always available.
693          */
694         if (ret == -EOPNOTSUPP)
695                 return true;
696         else if (ret)
697                 return false;
698
699         return !status;
700 }
701
702 /**
703  * usb4_switch_alloc_dp_resource() - Allocate DP IN resource
704  * @sw: USB4 router
705  * @in: DP IN adapter
706  *
707  * Allocates DP IN resource for DP tunneling using USB4 router
708  * operations. If the resource was allocated returns %0. Otherwise
709  * returns negative errno, in particular %-EBUSY if the resource is
710  * already allocated.
711  */
712 int usb4_switch_alloc_dp_resource(struct tb_switch *sw, struct tb_port *in)
713 {
714         u8 status;
715         int ret;
716
717         ret = usb4_switch_op_write_metadata(sw, in->port);
718         if (ret)
719                 return ret;
720
721         ret = usb4_switch_op(sw, USB4_SWITCH_OP_ALLOC_DP_RESOURCE, &status);
722         if (ret == -EOPNOTSUPP)
723                 return 0;
724         else if (ret)
725                 return ret;
726
727         return status ? -EBUSY : 0;
728 }
729
730 /**
731  * usb4_switch_dealloc_dp_resource() - Releases allocated DP IN resource
732  * @sw: USB4 router
733  * @in: DP IN adapter
734  *
735  * Releases the previously allocated DP IN resource.
736  */
737 int usb4_switch_dealloc_dp_resource(struct tb_switch *sw, struct tb_port *in)
738 {
739         u8 status;
740         int ret;
741
742         ret = usb4_switch_op_write_metadata(sw, in->port);
743         if (ret)
744                 return ret;
745
746         ret = usb4_switch_op(sw, USB4_SWITCH_OP_DEALLOC_DP_RESOURCE, &status);
747         if (ret == -EOPNOTSUPP)
748                 return 0;
749         else if (ret)
750                 return ret;
751
752         return status ? -EIO : 0;
753 }
754
755 static int usb4_port_idx(const struct tb_switch *sw, const struct tb_port *port)
756 {
757         struct tb_port *p;
758         int usb4_idx = 0;
759
760         /* Assume port is primary */
761         tb_switch_for_each_port(sw, p) {
762                 if (!tb_port_is_null(p))
763                         continue;
764                 if (tb_is_upstream_port(p))
765                         continue;
766                 if (!p->link_nr) {
767                         if (p == port)
768                                 break;
769                         usb4_idx++;
770                 }
771         }
772
773         return usb4_idx;
774 }
775
776 /**
777  * usb4_switch_map_pcie_down() - Map USB4 port to a PCIe downstream adapter
778  * @sw: USB4 router
779  * @port: USB4 port
780  *
781  * USB4 routers have direct mapping between USB4 ports and PCIe
782  * downstream adapters where the PCIe topology is extended. This
783  * function returns the corresponding downstream PCIe adapter or %NULL
784  * if no such mapping was possible.
785  */
786 struct tb_port *usb4_switch_map_pcie_down(struct tb_switch *sw,
787                                           const struct tb_port *port)
788 {
789         int usb4_idx = usb4_port_idx(sw, port);
790         struct tb_port *p;
791         int pcie_idx = 0;
792
793         /* Find PCIe down port matching usb4_port */
794         tb_switch_for_each_port(sw, p) {
795                 if (!tb_port_is_pcie_down(p))
796                         continue;
797
798                 if (pcie_idx == usb4_idx)
799                         return p;
800
801                 pcie_idx++;
802         }
803
804         return NULL;
805 }
806
807 /**
808  * usb4_switch_map_usb3_down() - Map USB4 port to a USB3 downstream adapter
809  * @sw: USB4 router
810  * @port: USB4 port
811  *
812  * USB4 routers have direct mapping between USB4 ports and USB 3.x
813  * downstream adapters where the USB 3.x topology is extended. This
814  * function returns the corresponding downstream USB 3.x adapter or
815  * %NULL if no such mapping was possible.
816  */
817 struct tb_port *usb4_switch_map_usb3_down(struct tb_switch *sw,
818                                           const struct tb_port *port)
819 {
820         int usb4_idx = usb4_port_idx(sw, port);
821         struct tb_port *p;
822         int usb_idx = 0;
823
824         /* Find USB3 down port matching usb4_port */
825         tb_switch_for_each_port(sw, p) {
826                 if (!tb_port_is_usb3_down(p))
827                         continue;
828
829                 if (usb_idx == usb4_idx)
830                         return p;
831
832                 usb_idx++;
833         }
834
835         return NULL;
836 }
837
838 /**
839  * usb4_port_unlock() - Unlock USB4 downstream port
840  * @port: USB4 port to unlock
841  *
842  * Unlocks USB4 downstream port so that the connection manager can
843  * access the router below this port.
844  */
845 int usb4_port_unlock(struct tb_port *port)
846 {
847         int ret;
848         u32 val;
849
850         ret = tb_port_read(port, &val, TB_CFG_PORT, ADP_CS_4, 1);
851         if (ret)
852                 return ret;
853
854         val &= ~ADP_CS_4_LCK;
855         return tb_port_write(port, &val, TB_CFG_PORT, ADP_CS_4, 1);
856 }
857
858 /**
859  * usb4_port_hotplug_enable() - Enables hotplug for a port
860  * @port: USB4 port to operate on
861  *
862  * Enables hot plug events on a given port. This is only intended
863  * to be used on lane, DP-IN, and DP-OUT adapters.
864  */
865 int usb4_port_hotplug_enable(struct tb_port *port)
866 {
867         int ret;
868         u32 val;
869
870         ret = tb_port_read(port, &val, TB_CFG_PORT, ADP_CS_5, 1);
871         if (ret)
872                 return ret;
873
874         val &= ~ADP_CS_5_DHP;
875         return tb_port_write(port, &val, TB_CFG_PORT, ADP_CS_5, 1);
876 }
877
878 static int usb4_port_set_configured(struct tb_port *port, bool configured)
879 {
880         int ret;
881         u32 val;
882
883         if (!port->cap_usb4)
884                 return -EINVAL;
885
886         ret = tb_port_read(port, &val, TB_CFG_PORT,
887                            port->cap_usb4 + PORT_CS_19, 1);
888         if (ret)
889                 return ret;
890
891         if (configured)
892                 val |= PORT_CS_19_PC;
893         else
894                 val &= ~PORT_CS_19_PC;
895
896         return tb_port_write(port, &val, TB_CFG_PORT,
897                              port->cap_usb4 + PORT_CS_19, 1);
898 }
899
900 /**
901  * usb4_port_configure() - Set USB4 port configured
902  * @port: USB4 router
903  *
904  * Sets the USB4 link to be configured for power management purposes.
905  */
906 int usb4_port_configure(struct tb_port *port)
907 {
908         return usb4_port_set_configured(port, true);
909 }
910
911 /**
912  * usb4_port_unconfigure() - Set USB4 port unconfigured
913  * @port: USB4 router
914  *
915  * Sets the USB4 link to be unconfigured for power management purposes.
916  */
917 void usb4_port_unconfigure(struct tb_port *port)
918 {
919         usb4_port_set_configured(port, false);
920 }
921
922 static int usb4_set_xdomain_configured(struct tb_port *port, bool configured)
923 {
924         int ret;
925         u32 val;
926
927         if (!port->cap_usb4)
928                 return -EINVAL;
929
930         ret = tb_port_read(port, &val, TB_CFG_PORT,
931                            port->cap_usb4 + PORT_CS_19, 1);
932         if (ret)
933                 return ret;
934
935         if (configured)
936                 val |= PORT_CS_19_PID;
937         else
938                 val &= ~PORT_CS_19_PID;
939
940         return tb_port_write(port, &val, TB_CFG_PORT,
941                              port->cap_usb4 + PORT_CS_19, 1);
942 }
943
944 /**
945  * usb4_port_configure_xdomain() - Configure port for XDomain
946  * @port: USB4 port connected to another host
947  *
948  * Marks the USB4 port as being connected to another host. Returns %0 in
949  * success and negative errno in failure.
950  */
951 int usb4_port_configure_xdomain(struct tb_port *port)
952 {
953         return usb4_set_xdomain_configured(port, true);
954 }
955
956 /**
957  * usb4_port_unconfigure_xdomain() - Unconfigure port for XDomain
958  * @port: USB4 port that was connected to another host
959  *
960  * Clears USB4 port from being marked as XDomain.
961  */
962 void usb4_port_unconfigure_xdomain(struct tb_port *port)
963 {
964         usb4_set_xdomain_configured(port, false);
965 }
966
967 static int usb4_port_wait_for_bit(struct tb_port *port, u32 offset, u32 bit,
968                                   u32 value, int timeout_msec)
969 {
970         ktime_t timeout = ktime_add_ms(ktime_get(), timeout_msec);
971
972         do {
973                 u32 val;
974                 int ret;
975
976                 ret = tb_port_read(port, &val, TB_CFG_PORT, offset, 1);
977                 if (ret)
978                         return ret;
979
980                 if ((val & bit) == value)
981                         return 0;
982
983                 usleep_range(50, 100);
984         } while (ktime_before(ktime_get(), timeout));
985
986         return -ETIMEDOUT;
987 }
988
989 static int usb4_port_read_data(struct tb_port *port, void *data, size_t dwords)
990 {
991         if (dwords > USB4_DATA_DWORDS)
992                 return -EINVAL;
993
994         return tb_port_read(port, data, TB_CFG_PORT, port->cap_usb4 + PORT_CS_2,
995                             dwords);
996 }
997
998 static int usb4_port_write_data(struct tb_port *port, const void *data,
999                                 size_t dwords)
1000 {
1001         if (dwords > USB4_DATA_DWORDS)
1002                 return -EINVAL;
1003
1004         return tb_port_write(port, data, TB_CFG_PORT, port->cap_usb4 + PORT_CS_2,
1005                              dwords);
1006 }
1007
1008 static int usb4_port_sb_read(struct tb_port *port, enum usb4_sb_target target,
1009                              u8 index, u8 reg, void *buf, u8 size)
1010 {
1011         size_t dwords = DIV_ROUND_UP(size, 4);
1012         int ret;
1013         u32 val;
1014
1015         if (!port->cap_usb4)
1016                 return -EINVAL;
1017
1018         val = reg;
1019         val |= size << PORT_CS_1_LENGTH_SHIFT;
1020         val |= (target << PORT_CS_1_TARGET_SHIFT) & PORT_CS_1_TARGET_MASK;
1021         if (target == USB4_SB_TARGET_RETIMER)
1022                 val |= (index << PORT_CS_1_RETIMER_INDEX_SHIFT);
1023         val |= PORT_CS_1_PND;
1024
1025         ret = tb_port_write(port, &val, TB_CFG_PORT,
1026                             port->cap_usb4 + PORT_CS_1, 1);
1027         if (ret)
1028                 return ret;
1029
1030         ret = usb4_port_wait_for_bit(port, port->cap_usb4 + PORT_CS_1,
1031                                      PORT_CS_1_PND, 0, 500);
1032         if (ret)
1033                 return ret;
1034
1035         ret = tb_port_read(port, &val, TB_CFG_PORT,
1036                             port->cap_usb4 + PORT_CS_1, 1);
1037         if (ret)
1038                 return ret;
1039
1040         if (val & PORT_CS_1_NR)
1041                 return -ENODEV;
1042         if (val & PORT_CS_1_RC)
1043                 return -EIO;
1044
1045         return buf ? usb4_port_read_data(port, buf, dwords) : 0;
1046 }
1047
1048 static int usb4_port_sb_write(struct tb_port *port, enum usb4_sb_target target,
1049                               u8 index, u8 reg, const void *buf, u8 size)
1050 {
1051         size_t dwords = DIV_ROUND_UP(size, 4);
1052         int ret;
1053         u32 val;
1054
1055         if (!port->cap_usb4)
1056                 return -EINVAL;
1057
1058         if (buf) {
1059                 ret = usb4_port_write_data(port, buf, dwords);
1060                 if (ret)
1061                         return ret;
1062         }
1063
1064         val = reg;
1065         val |= size << PORT_CS_1_LENGTH_SHIFT;
1066         val |= PORT_CS_1_WNR_WRITE;
1067         val |= (target << PORT_CS_1_TARGET_SHIFT) & PORT_CS_1_TARGET_MASK;
1068         if (target == USB4_SB_TARGET_RETIMER)
1069                 val |= (index << PORT_CS_1_RETIMER_INDEX_SHIFT);
1070         val |= PORT_CS_1_PND;
1071
1072         ret = tb_port_write(port, &val, TB_CFG_PORT,
1073                             port->cap_usb4 + PORT_CS_1, 1);
1074         if (ret)
1075                 return ret;
1076
1077         ret = usb4_port_wait_for_bit(port, port->cap_usb4 + PORT_CS_1,
1078                                      PORT_CS_1_PND, 0, 500);
1079         if (ret)
1080                 return ret;
1081
1082         ret = tb_port_read(port, &val, TB_CFG_PORT,
1083                             port->cap_usb4 + PORT_CS_1, 1);
1084         if (ret)
1085                 return ret;
1086
1087         if (val & PORT_CS_1_NR)
1088                 return -ENODEV;
1089         if (val & PORT_CS_1_RC)
1090                 return -EIO;
1091
1092         return 0;
1093 }
1094
1095 static int usb4_port_sb_op(struct tb_port *port, enum usb4_sb_target target,
1096                            u8 index, enum usb4_sb_opcode opcode, int timeout_msec)
1097 {
1098         ktime_t timeout;
1099         u32 val;
1100         int ret;
1101
1102         val = opcode;
1103         ret = usb4_port_sb_write(port, target, index, USB4_SB_OPCODE, &val,
1104                                  sizeof(val));
1105         if (ret)
1106                 return ret;
1107
1108         timeout = ktime_add_ms(ktime_get(), timeout_msec);
1109
1110         do {
1111                 /* Check results */
1112                 ret = usb4_port_sb_read(port, target, index, USB4_SB_OPCODE,
1113                                         &val, sizeof(val));
1114                 if (ret)
1115                         return ret;
1116
1117                 switch (val) {
1118                 case 0:
1119                         return 0;
1120
1121                 case USB4_SB_OPCODE_ERR:
1122                         return -EAGAIN;
1123
1124                 case USB4_SB_OPCODE_ONS:
1125                         return -EOPNOTSUPP;
1126
1127                 default:
1128                         if (val != opcode)
1129                                 return -EIO;
1130                         break;
1131                 }
1132         } while (ktime_before(ktime_get(), timeout));
1133
1134         return -ETIMEDOUT;
1135 }
1136
1137 /**
1138  * usb4_port_enumerate_retimers() - Send RT broadcast transaction
1139  * @port: USB4 port
1140  *
1141  * This forces the USB4 port to send broadcast RT transaction which
1142  * makes the retimers on the link to assign index to themselves. Returns
1143  * %0 in case of success and negative errno if there was an error.
1144  */
1145 int usb4_port_enumerate_retimers(struct tb_port *port)
1146 {
1147         u32 val;
1148
1149         val = USB4_SB_OPCODE_ENUMERATE_RETIMERS;
1150         return usb4_port_sb_write(port, USB4_SB_TARGET_ROUTER, 0,
1151                                   USB4_SB_OPCODE, &val, sizeof(val));
1152 }
1153
1154 static inline int usb4_port_retimer_op(struct tb_port *port, u8 index,
1155                                        enum usb4_sb_opcode opcode,
1156                                        int timeout_msec)
1157 {
1158         return usb4_port_sb_op(port, USB4_SB_TARGET_RETIMER, index, opcode,
1159                                timeout_msec);
1160 }
1161
1162 /**
1163  * usb4_port_retimer_read() - Read from retimer sideband registers
1164  * @port: USB4 port
1165  * @index: Retimer index
1166  * @reg: Sideband register to read
1167  * @buf: Data from @reg is stored here
1168  * @size: Number of bytes to read
1169  *
1170  * Function reads retimer sideband registers starting from @reg. The
1171  * retimer is connected to @port at @index. Returns %0 in case of
1172  * success, and read data is copied to @buf. If there is no retimer
1173  * present at given @index returns %-ENODEV. In any other failure
1174  * returns negative errno.
1175  */
1176 int usb4_port_retimer_read(struct tb_port *port, u8 index, u8 reg, void *buf,
1177                            u8 size)
1178 {
1179         return usb4_port_sb_read(port, USB4_SB_TARGET_RETIMER, index, reg, buf,
1180                                  size);
1181 }
1182
1183 /**
1184  * usb4_port_retimer_write() - Write to retimer sideband registers
1185  * @port: USB4 port
1186  * @index: Retimer index
1187  * @reg: Sideband register to write
1188  * @buf: Data that is written starting from @reg
1189  * @size: Number of bytes to write
1190  *
1191  * Writes retimer sideband registers starting from @reg. The retimer is
1192  * connected to @port at @index. Returns %0 in case of success. If there
1193  * is no retimer present at given @index returns %-ENODEV. In any other
1194  * failure returns negative errno.
1195  */
1196 int usb4_port_retimer_write(struct tb_port *port, u8 index, u8 reg,
1197                             const void *buf, u8 size)
1198 {
1199         return usb4_port_sb_write(port, USB4_SB_TARGET_RETIMER, index, reg, buf,
1200                                   size);
1201 }
1202
1203 /**
1204  * usb4_port_retimer_is_last() - Is the retimer last on-board retimer
1205  * @port: USB4 port
1206  * @index: Retimer index
1207  *
1208  * If the retimer at @index is last one (connected directly to the
1209  * Type-C port) this function returns %1. If it is not returns %0. If
1210  * the retimer is not present returns %-ENODEV. Otherwise returns
1211  * negative errno.
1212  */
1213 int usb4_port_retimer_is_last(struct tb_port *port, u8 index)
1214 {
1215         u32 metadata;
1216         int ret;
1217
1218         ret = usb4_port_retimer_op(port, index, USB4_SB_OPCODE_QUERY_LAST_RETIMER,
1219                                    500);
1220         if (ret)
1221                 return ret;
1222
1223         ret = usb4_port_retimer_read(port, index, USB4_SB_METADATA, &metadata,
1224                                      sizeof(metadata));
1225         return ret ? ret : metadata & 1;
1226 }
1227
1228 /**
1229  * usb4_port_retimer_nvm_sector_size() - Read retimer NVM sector size
1230  * @port: USB4 port
1231  * @index: Retimer index
1232  *
1233  * Reads NVM sector size (in bytes) of a retimer at @index. This
1234  * operation can be used to determine whether the retimer supports NVM
1235  * upgrade for example. Returns sector size in bytes or negative errno
1236  * in case of error. Specifically returns %-ENODEV if there is no
1237  * retimer at @index.
1238  */
1239 int usb4_port_retimer_nvm_sector_size(struct tb_port *port, u8 index)
1240 {
1241         u32 metadata;
1242         int ret;
1243
1244         ret = usb4_port_retimer_op(port, index, USB4_SB_OPCODE_GET_NVM_SECTOR_SIZE,
1245                                    500);
1246         if (ret)
1247                 return ret;
1248
1249         ret = usb4_port_retimer_read(port, index, USB4_SB_METADATA, &metadata,
1250                                      sizeof(metadata));
1251         return ret ? ret : metadata & USB4_NVM_SECTOR_SIZE_MASK;
1252 }
1253
1254 static int usb4_port_retimer_nvm_set_offset(struct tb_port *port, u8 index,
1255                                             unsigned int address)
1256 {
1257         u32 metadata, dwaddress;
1258         int ret;
1259
1260         dwaddress = address / 4;
1261         metadata = (dwaddress << USB4_NVM_SET_OFFSET_SHIFT) &
1262                   USB4_NVM_SET_OFFSET_MASK;
1263
1264         ret = usb4_port_retimer_write(port, index, USB4_SB_METADATA, &metadata,
1265                                       sizeof(metadata));
1266         if (ret)
1267                 return ret;
1268
1269         return usb4_port_retimer_op(port, index, USB4_SB_OPCODE_NVM_SET_OFFSET,
1270                                     500);
1271 }
1272
1273 struct retimer_info {
1274         struct tb_port *port;
1275         u8 index;
1276 };
1277
1278 static int usb4_port_retimer_nvm_write_next_block(void *data, const void *buf,
1279                                                   size_t dwords)
1280
1281 {
1282         const struct retimer_info *info = data;
1283         struct tb_port *port = info->port;
1284         u8 index = info->index;
1285         int ret;
1286
1287         ret = usb4_port_retimer_write(port, index, USB4_SB_DATA,
1288                                       buf, dwords * 4);
1289         if (ret)
1290                 return ret;
1291
1292         return usb4_port_retimer_op(port, index,
1293                         USB4_SB_OPCODE_NVM_BLOCK_WRITE, 1000);
1294 }
1295
1296 /**
1297  * usb4_port_retimer_nvm_write() - Write to retimer NVM
1298  * @port: USB4 port
1299  * @index: Retimer index
1300  * @address: Byte address where to start the write
1301  * @buf: Data to write
1302  * @size: Size in bytes how much to write
1303  *
1304  * Writes @size bytes from @buf to the retimer NVM. Used for NVM
1305  * upgrade. Returns %0 if the data was written successfully and negative
1306  * errno in case of failure. Specifically returns %-ENODEV if there is
1307  * no retimer at @index.
1308  */
1309 int usb4_port_retimer_nvm_write(struct tb_port *port, u8 index, unsigned int address,
1310                                 const void *buf, size_t size)
1311 {
1312         struct retimer_info info = { .port = port, .index = index };
1313         int ret;
1314
1315         ret = usb4_port_retimer_nvm_set_offset(port, index, address);
1316         if (ret)
1317                 return ret;
1318
1319         return usb4_do_write_data(address, buf, size,
1320                         usb4_port_retimer_nvm_write_next_block, &info);
1321 }
1322
1323 /**
1324  * usb4_port_retimer_nvm_authenticate() - Start retimer NVM upgrade
1325  * @port: USB4 port
1326  * @index: Retimer index
1327  *
1328  * After the new NVM image has been written via usb4_port_retimer_nvm_write()
1329  * this function can be used to trigger the NVM upgrade process. If
1330  * successful the retimer restarts with the new NVM and may not have the
1331  * index set so one needs to call usb4_port_enumerate_retimers() to
1332  * force index to be assigned.
1333  */
1334 int usb4_port_retimer_nvm_authenticate(struct tb_port *port, u8 index)
1335 {
1336         u32 val;
1337
1338         /*
1339          * We need to use the raw operation here because once the
1340          * authentication completes the retimer index is not set anymore
1341          * so we do not get back the status now.
1342          */
1343         val = USB4_SB_OPCODE_NVM_AUTH_WRITE;
1344         return usb4_port_sb_write(port, USB4_SB_TARGET_RETIMER, index,
1345                                   USB4_SB_OPCODE, &val, sizeof(val));
1346 }
1347
1348 /**
1349  * usb4_port_retimer_nvm_authenticate_status() - Read status of NVM upgrade
1350  * @port: USB4 port
1351  * @index: Retimer index
1352  * @status: Raw status code read from metadata
1353  *
1354  * This can be called after usb4_port_retimer_nvm_authenticate() and
1355  * usb4_port_enumerate_retimers() to fetch status of the NVM upgrade.
1356  *
1357  * Returns %0 if the authentication status was successfully read. The
1358  * completion metadata (the result) is then stored into @status. If
1359  * reading the status fails, returns negative errno.
1360  */
1361 int usb4_port_retimer_nvm_authenticate_status(struct tb_port *port, u8 index,
1362                                               u32 *status)
1363 {
1364         u32 metadata, val;
1365         int ret;
1366
1367         ret = usb4_port_retimer_read(port, index, USB4_SB_OPCODE, &val,
1368                                      sizeof(val));
1369         if (ret)
1370                 return ret;
1371
1372         switch (val) {
1373         case 0:
1374                 *status = 0;
1375                 return 0;
1376
1377         case USB4_SB_OPCODE_ERR:
1378                 ret = usb4_port_retimer_read(port, index, USB4_SB_METADATA,
1379                                              &metadata, sizeof(metadata));
1380                 if (ret)
1381                         return ret;
1382
1383                 *status = metadata & USB4_SB_METADATA_NVM_AUTH_WRITE_MASK;
1384                 return 0;
1385
1386         case USB4_SB_OPCODE_ONS:
1387                 return -EOPNOTSUPP;
1388
1389         default:
1390                 return -EIO;
1391         }
1392 }
1393
1394 static int usb4_port_retimer_nvm_read_block(void *data, unsigned int dwaddress,
1395                                             void *buf, size_t dwords)
1396 {
1397         const struct retimer_info *info = data;
1398         struct tb_port *port = info->port;
1399         u8 index = info->index;
1400         u32 metadata;
1401         int ret;
1402
1403         metadata = dwaddress << USB4_NVM_READ_OFFSET_SHIFT;
1404         if (dwords < USB4_DATA_DWORDS)
1405                 metadata |= dwords << USB4_NVM_READ_LENGTH_SHIFT;
1406
1407         ret = usb4_port_retimer_write(port, index, USB4_SB_METADATA, &metadata,
1408                                       sizeof(metadata));
1409         if (ret)
1410                 return ret;
1411
1412         ret = usb4_port_retimer_op(port, index, USB4_SB_OPCODE_NVM_READ, 500);
1413         if (ret)
1414                 return ret;
1415
1416         return usb4_port_retimer_read(port, index, USB4_SB_DATA, buf,
1417                                       dwords * 4);
1418 }
1419
1420 /**
1421  * usb4_port_retimer_nvm_read() - Read contents of retimer NVM
1422  * @port: USB4 port
1423  * @index: Retimer index
1424  * @address: NVM address (in bytes) to start reading
1425  * @buf: Data read from NVM is stored here
1426  * @size: Number of bytes to read
1427  *
1428  * Reads retimer NVM and copies the contents to @buf. Returns %0 if the
1429  * read was successful and negative errno in case of failure.
1430  * Specifically returns %-ENODEV if there is no retimer at @index.
1431  */
1432 int usb4_port_retimer_nvm_read(struct tb_port *port, u8 index,
1433                                unsigned int address, void *buf, size_t size)
1434 {
1435         struct retimer_info info = { .port = port, .index = index };
1436
1437         return usb4_do_read_data(address, buf, size,
1438                         usb4_port_retimer_nvm_read_block, &info);
1439 }
1440
1441 /**
1442  * usb4_usb3_port_max_link_rate() - Maximum support USB3 link rate
1443  * @port: USB3 adapter port
1444  *
1445  * Return maximum supported link rate of a USB3 adapter in Mb/s.
1446  * Negative errno in case of error.
1447  */
1448 int usb4_usb3_port_max_link_rate(struct tb_port *port)
1449 {
1450         int ret, lr;
1451         u32 val;
1452
1453         if (!tb_port_is_usb3_down(port) && !tb_port_is_usb3_up(port))
1454                 return -EINVAL;
1455
1456         ret = tb_port_read(port, &val, TB_CFG_PORT,
1457                            port->cap_adap + ADP_USB3_CS_4, 1);
1458         if (ret)
1459                 return ret;
1460
1461         lr = (val & ADP_USB3_CS_4_MSLR_MASK) >> ADP_USB3_CS_4_MSLR_SHIFT;
1462         return lr == ADP_USB3_CS_4_MSLR_20G ? 20000 : 10000;
1463 }
1464
1465 /**
1466  * usb4_usb3_port_actual_link_rate() - Established USB3 link rate
1467  * @port: USB3 adapter port
1468  *
1469  * Return actual established link rate of a USB3 adapter in Mb/s. If the
1470  * link is not up returns %0 and negative errno in case of failure.
1471  */
1472 int usb4_usb3_port_actual_link_rate(struct tb_port *port)
1473 {
1474         int ret, lr;
1475         u32 val;
1476
1477         if (!tb_port_is_usb3_down(port) && !tb_port_is_usb3_up(port))
1478                 return -EINVAL;
1479
1480         ret = tb_port_read(port, &val, TB_CFG_PORT,
1481                            port->cap_adap + ADP_USB3_CS_4, 1);
1482         if (ret)
1483                 return ret;
1484
1485         if (!(val & ADP_USB3_CS_4_ULV))
1486                 return 0;
1487
1488         lr = val & ADP_USB3_CS_4_ALR_MASK;
1489         return lr == ADP_USB3_CS_4_ALR_20G ? 20000 : 10000;
1490 }
1491
1492 static int usb4_usb3_port_cm_request(struct tb_port *port, bool request)
1493 {
1494         int ret;
1495         u32 val;
1496
1497         if (!tb_port_is_usb3_down(port))
1498                 return -EINVAL;
1499         if (tb_route(port->sw))
1500                 return -EINVAL;
1501
1502         ret = tb_port_read(port, &val, TB_CFG_PORT,
1503                            port->cap_adap + ADP_USB3_CS_2, 1);
1504         if (ret)
1505                 return ret;
1506
1507         if (request)
1508                 val |= ADP_USB3_CS_2_CMR;
1509         else
1510                 val &= ~ADP_USB3_CS_2_CMR;
1511
1512         ret = tb_port_write(port, &val, TB_CFG_PORT,
1513                             port->cap_adap + ADP_USB3_CS_2, 1);
1514         if (ret)
1515                 return ret;
1516
1517         /*
1518          * We can use val here directly as the CMR bit is in the same place
1519          * as HCA. Just mask out others.
1520          */
1521         val &= ADP_USB3_CS_2_CMR;
1522         return usb4_port_wait_for_bit(port, port->cap_adap + ADP_USB3_CS_1,
1523                                       ADP_USB3_CS_1_HCA, val, 1500);
1524 }
1525
1526 static inline int usb4_usb3_port_set_cm_request(struct tb_port *port)
1527 {
1528         return usb4_usb3_port_cm_request(port, true);
1529 }
1530
1531 static inline int usb4_usb3_port_clear_cm_request(struct tb_port *port)
1532 {
1533         return usb4_usb3_port_cm_request(port, false);
1534 }
1535
1536 static unsigned int usb3_bw_to_mbps(u32 bw, u8 scale)
1537 {
1538         unsigned long uframes;
1539
1540         uframes = bw * 512UL << scale;
1541         return DIV_ROUND_CLOSEST(uframes * 8000, 1000 * 1000);
1542 }
1543
1544 static u32 mbps_to_usb3_bw(unsigned int mbps, u8 scale)
1545 {
1546         unsigned long uframes;
1547
1548         /* 1 uframe is 1/8 ms (125 us) -> 1 / 8000 s */
1549         uframes = ((unsigned long)mbps * 1000 *  1000) / 8000;
1550         return DIV_ROUND_UP(uframes, 512UL << scale);
1551 }
1552
1553 static int usb4_usb3_port_read_allocated_bandwidth(struct tb_port *port,
1554                                                    int *upstream_bw,
1555                                                    int *downstream_bw)
1556 {
1557         u32 val, bw, scale;
1558         int ret;
1559
1560         ret = tb_port_read(port, &val, TB_CFG_PORT,
1561                            port->cap_adap + ADP_USB3_CS_2, 1);
1562         if (ret)
1563                 return ret;
1564
1565         ret = tb_port_read(port, &scale, TB_CFG_PORT,
1566                            port->cap_adap + ADP_USB3_CS_3, 1);
1567         if (ret)
1568                 return ret;
1569
1570         scale &= ADP_USB3_CS_3_SCALE_MASK;
1571
1572         bw = val & ADP_USB3_CS_2_AUBW_MASK;
1573         *upstream_bw = usb3_bw_to_mbps(bw, scale);
1574
1575         bw = (val & ADP_USB3_CS_2_ADBW_MASK) >> ADP_USB3_CS_2_ADBW_SHIFT;
1576         *downstream_bw = usb3_bw_to_mbps(bw, scale);
1577
1578         return 0;
1579 }
1580
1581 /**
1582  * usb4_usb3_port_allocated_bandwidth() - Bandwidth allocated for USB3
1583  * @port: USB3 adapter port
1584  * @upstream_bw: Allocated upstream bandwidth is stored here
1585  * @downstream_bw: Allocated downstream bandwidth is stored here
1586  *
1587  * Stores currently allocated USB3 bandwidth into @upstream_bw and
1588  * @downstream_bw in Mb/s. Returns %0 in case of success and negative
1589  * errno in failure.
1590  */
1591 int usb4_usb3_port_allocated_bandwidth(struct tb_port *port, int *upstream_bw,
1592                                        int *downstream_bw)
1593 {
1594         int ret;
1595
1596         ret = usb4_usb3_port_set_cm_request(port);
1597         if (ret)
1598                 return ret;
1599
1600         ret = usb4_usb3_port_read_allocated_bandwidth(port, upstream_bw,
1601                                                       downstream_bw);
1602         usb4_usb3_port_clear_cm_request(port);
1603
1604         return ret;
1605 }
1606
1607 static int usb4_usb3_port_read_consumed_bandwidth(struct tb_port *port,
1608                                                   int *upstream_bw,
1609                                                   int *downstream_bw)
1610 {
1611         u32 val, bw, scale;
1612         int ret;
1613
1614         ret = tb_port_read(port, &val, TB_CFG_PORT,
1615                            port->cap_adap + ADP_USB3_CS_1, 1);
1616         if (ret)
1617                 return ret;
1618
1619         ret = tb_port_read(port, &scale, TB_CFG_PORT,
1620                            port->cap_adap + ADP_USB3_CS_3, 1);
1621         if (ret)
1622                 return ret;
1623
1624         scale &= ADP_USB3_CS_3_SCALE_MASK;
1625
1626         bw = val & ADP_USB3_CS_1_CUBW_MASK;
1627         *upstream_bw = usb3_bw_to_mbps(bw, scale);
1628
1629         bw = (val & ADP_USB3_CS_1_CDBW_MASK) >> ADP_USB3_CS_1_CDBW_SHIFT;
1630         *downstream_bw = usb3_bw_to_mbps(bw, scale);
1631
1632         return 0;
1633 }
1634
1635 static int usb4_usb3_port_write_allocated_bandwidth(struct tb_port *port,
1636                                                     int upstream_bw,
1637                                                     int downstream_bw)
1638 {
1639         u32 val, ubw, dbw, scale;
1640         int ret, max_bw;
1641
1642         /* Figure out suitable scale */
1643         scale = 0;
1644         max_bw = max(upstream_bw, downstream_bw);
1645         while (scale < 64) {
1646                 if (mbps_to_usb3_bw(max_bw, scale) < 4096)
1647                         break;
1648                 scale++;
1649         }
1650
1651         if (WARN_ON(scale >= 64))
1652                 return -EINVAL;
1653
1654         ret = tb_port_write(port, &scale, TB_CFG_PORT,
1655                             port->cap_adap + ADP_USB3_CS_3, 1);
1656         if (ret)
1657                 return ret;
1658
1659         ubw = mbps_to_usb3_bw(upstream_bw, scale);
1660         dbw = mbps_to_usb3_bw(downstream_bw, scale);
1661
1662         tb_port_dbg(port, "scaled bandwidth %u/%u, scale %u\n", ubw, dbw, scale);
1663
1664         ret = tb_port_read(port, &val, TB_CFG_PORT,
1665                            port->cap_adap + ADP_USB3_CS_2, 1);
1666         if (ret)
1667                 return ret;
1668
1669         val &= ~(ADP_USB3_CS_2_AUBW_MASK | ADP_USB3_CS_2_ADBW_MASK);
1670         val |= dbw << ADP_USB3_CS_2_ADBW_SHIFT;
1671         val |= ubw;
1672
1673         return tb_port_write(port, &val, TB_CFG_PORT,
1674                              port->cap_adap + ADP_USB3_CS_2, 1);
1675 }
1676
1677 /**
1678  * usb4_usb3_port_allocate_bandwidth() - Allocate bandwidth for USB3
1679  * @port: USB3 adapter port
1680  * @upstream_bw: New upstream bandwidth
1681  * @downstream_bw: New downstream bandwidth
1682  *
1683  * This can be used to set how much bandwidth is allocated for the USB3
1684  * tunneled isochronous traffic. @upstream_bw and @downstream_bw are the
1685  * new values programmed to the USB3 adapter allocation registers. If
1686  * the values are lower than what is currently consumed the allocation
1687  * is set to what is currently consumed instead (consumed bandwidth
1688  * cannot be taken away by CM). The actual new values are returned in
1689  * @upstream_bw and @downstream_bw.
1690  *
1691  * Returns %0 in case of success and negative errno if there was a
1692  * failure.
1693  */
1694 int usb4_usb3_port_allocate_bandwidth(struct tb_port *port, int *upstream_bw,
1695                                       int *downstream_bw)
1696 {
1697         int ret, consumed_up, consumed_down, allocate_up, allocate_down;
1698
1699         ret = usb4_usb3_port_set_cm_request(port);
1700         if (ret)
1701                 return ret;
1702
1703         ret = usb4_usb3_port_read_consumed_bandwidth(port, &consumed_up,
1704                                                      &consumed_down);
1705         if (ret)
1706                 goto err_request;
1707
1708         /* Don't allow it go lower than what is consumed */
1709         allocate_up = max(*upstream_bw, consumed_up);
1710         allocate_down = max(*downstream_bw, consumed_down);
1711
1712         ret = usb4_usb3_port_write_allocated_bandwidth(port, allocate_up,
1713                                                        allocate_down);
1714         if (ret)
1715                 goto err_request;
1716
1717         *upstream_bw = allocate_up;
1718         *downstream_bw = allocate_down;
1719
1720 err_request:
1721         usb4_usb3_port_clear_cm_request(port);
1722         return ret;
1723 }
1724
1725 /**
1726  * usb4_usb3_port_release_bandwidth() - Release allocated USB3 bandwidth
1727  * @port: USB3 adapter port
1728  * @upstream_bw: New allocated upstream bandwidth
1729  * @downstream_bw: New allocated downstream bandwidth
1730  *
1731  * Releases USB3 allocated bandwidth down to what is actually consumed.
1732  * The new bandwidth is returned in @upstream_bw and @downstream_bw.
1733  *
1734  * Returns 0% in success and negative errno in case of failure.
1735  */
1736 int usb4_usb3_port_release_bandwidth(struct tb_port *port, int *upstream_bw,
1737                                      int *downstream_bw)
1738 {
1739         int ret, consumed_up, consumed_down;
1740
1741         ret = usb4_usb3_port_set_cm_request(port);
1742         if (ret)
1743                 return ret;
1744
1745         ret = usb4_usb3_port_read_consumed_bandwidth(port, &consumed_up,
1746                                                      &consumed_down);
1747         if (ret)
1748                 goto err_request;
1749
1750         /*
1751          * Always keep 1000 Mb/s to make sure xHCI has at least some
1752          * bandwidth available for isochronous traffic.
1753          */
1754         if (consumed_up < 1000)
1755                 consumed_up = 1000;
1756         if (consumed_down < 1000)
1757                 consumed_down = 1000;
1758
1759         ret = usb4_usb3_port_write_allocated_bandwidth(port, consumed_up,
1760                                                        consumed_down);
1761         if (ret)
1762                 goto err_request;
1763
1764         *upstream_bw = consumed_up;
1765         *downstream_bw = consumed_down;
1766
1767 err_request:
1768         usb4_usb3_port_clear_cm_request(port);
1769         return ret;
1770 }