591bc8b48cd21c1a71fffe8ef4699ac6c107cbb9
[platform/kernel/u-boot.git] / drivers / pci / pci-aardvark.c
1 /*
2  * ***************************************************************************
3  * Copyright (C) 2015 Marvell International Ltd.
4  * ***************************************************************************
5  * This program is free software: you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the Free
7  * Software Foundation, either version 2 of the License, or any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  * ***************************************************************************
17  */
18 /* pcie_advk.c
19  *
20  * Ported from Linux driver - driver/pci/host/pci-aardvark.c
21  *
22  * Author: Victor Gu <xigu@marvell.com>
23  *         Hezi Shahmoon <hezi.shahmoon@marvell.com>
24  *
25  */
26
27 #include <common.h>
28 #include <dm.h>
29 #include <pci.h>
30 #include <asm/io.h>
31 #include <asm-generic/gpio.h>
32 #include <dm/device_compat.h>
33 #include <linux/bitops.h>
34 #include <linux/delay.h>
35 #include <linux/ioport.h>
36
37 /* PCIe core registers */
38 #define PCIE_CORE_CMD_STATUS_REG                                0x4
39 #define     PCIE_CORE_CMD_IO_ACCESS_EN                          BIT(0)
40 #define     PCIE_CORE_CMD_MEM_ACCESS_EN                         BIT(1)
41 #define     PCIE_CORE_CMD_MEM_IO_REQ_EN                         BIT(2)
42 #define PCIE_CORE_DEV_REV_REG                                   0x8
43 #define PCIE_CORE_EXP_ROM_BAR_REG                               0x30
44 #define PCIE_CORE_PCIEXP_CAP_OFF                                0xc0
45 #define PCIE_CORE_DEV_CTRL_STATS_REG                            0xc8
46 #define     PCIE_CORE_DEV_CTRL_STATS_RELAX_ORDER_DISABLE        (0 << 4)
47 #define     PCIE_CORE_DEV_CTRL_STATS_SNOOP_DISABLE              (0 << 11)
48 #define     PCIE_CORE_DEV_CTRL_STATS_MAX_PAYLOAD_SIZE           0x2
49 #define     PCIE_CORE_DEV_CTRL_STATS_MAX_PAYLOAD_SIZE_SHIFT     5
50 #define     PCIE_CORE_DEV_CTRL_STATS_MAX_RD_REQ_SIZE            0x2
51 #define     PCIE_CORE_DEV_CTRL_STATS_MAX_RD_REQ_SIZE_SHIFT      12
52 #define PCIE_CORE_LINK_CTRL_STAT_REG                            0xd0
53 #define     PCIE_CORE_LINK_TRAINING                             BIT(5)
54 #define PCIE_CORE_ERR_CAPCTL_REG                                0x118
55 #define     PCIE_CORE_ERR_CAPCTL_ECRC_CHK_TX                    BIT(5)
56 #define     PCIE_CORE_ERR_CAPCTL_ECRC_CHK_TX_EN                 BIT(6)
57 #define     PCIE_CORE_ERR_CAPCTL_ECRC_CHECK                     BIT(7)
58 #define     PCIE_CORE_ERR_CAPCTL_ECRC_CHECK_RCV                 BIT(8)
59
60 /* PIO registers base address and register offsets */
61 #define PIO_BASE_ADDR                           0x4000
62 #define PIO_CTRL                                (PIO_BASE_ADDR + 0x0)
63 #define   PIO_CTRL_TYPE_MASK                    GENMASK(3, 0)
64 #define   PIO_CTRL_ADDR_WIN_DISABLE             BIT(24)
65 #define PIO_STAT                                (PIO_BASE_ADDR + 0x4)
66 #define   PIO_COMPLETION_STATUS_SHIFT           7
67 #define   PIO_COMPLETION_STATUS_MASK            GENMASK(9, 7)
68 #define   PIO_COMPLETION_STATUS_OK              0
69 #define   PIO_COMPLETION_STATUS_UR              1
70 #define   PIO_COMPLETION_STATUS_CRS             2
71 #define   PIO_COMPLETION_STATUS_CA              4
72 #define   PIO_NON_POSTED_REQ                    BIT(10)
73 #define   PIO_ERR_STATUS                        BIT(11)
74 #define PIO_ADDR_LS                             (PIO_BASE_ADDR + 0x8)
75 #define PIO_ADDR_MS                             (PIO_BASE_ADDR + 0xc)
76 #define PIO_WR_DATA                             (PIO_BASE_ADDR + 0x10)
77 #define PIO_WR_DATA_STRB                        (PIO_BASE_ADDR + 0x14)
78 #define PIO_RD_DATA                             (PIO_BASE_ADDR + 0x18)
79 #define PIO_START                               (PIO_BASE_ADDR + 0x1c)
80 #define PIO_ISR                                 (PIO_BASE_ADDR + 0x20)
81
82 /* Aardvark Control registers */
83 #define CONTROL_BASE_ADDR                       0x4800
84 #define PCIE_CORE_CTRL0_REG                     (CONTROL_BASE_ADDR + 0x0)
85 #define     PCIE_GEN_SEL_MSK                    0x3
86 #define     PCIE_GEN_SEL_SHIFT                  0x0
87 #define     SPEED_GEN_1                         0
88 #define     SPEED_GEN_2                         1
89 #define     SPEED_GEN_3                         2
90 #define     IS_RC_MSK                           1
91 #define     IS_RC_SHIFT                         2
92 #define     LANE_CNT_MSK                        0x18
93 #define     LANE_CNT_SHIFT                      0x3
94 #define     LANE_COUNT_1                        (0 << LANE_CNT_SHIFT)
95 #define     LANE_COUNT_2                        (1 << LANE_CNT_SHIFT)
96 #define     LANE_COUNT_4                        (2 << LANE_CNT_SHIFT)
97 #define     LANE_COUNT_8                        (3 << LANE_CNT_SHIFT)
98 #define     LINK_TRAINING_EN                    BIT(6)
99 #define PCIE_CORE_CTRL2_REG                     (CONTROL_BASE_ADDR + 0x8)
100 #define     PCIE_CORE_CTRL2_RESERVED            0x7
101 #define     PCIE_CORE_CTRL2_TD_ENABLE           BIT(4)
102 #define     PCIE_CORE_CTRL2_STRICT_ORDER_ENABLE BIT(5)
103 #define     PCIE_CORE_CTRL2_ADDRWIN_MAP_ENABLE  BIT(6)
104
105 /* PCIe window configuration */
106 #define OB_WIN_BASE_ADDR                        0x4c00
107 #define OB_WIN_BLOCK_SIZE                       0x20
108 #define OB_WIN_COUNT                            8
109 #define OB_WIN_REG_ADDR(win, offset)            (OB_WIN_BASE_ADDR + \
110                                                  OB_WIN_BLOCK_SIZE * (win) + \
111                                                  (offset))
112 #define OB_WIN_MATCH_LS(win)                    OB_WIN_REG_ADDR(win, 0x00)
113 #define     OB_WIN_ENABLE                       BIT(0)
114 #define OB_WIN_MATCH_MS(win)                    OB_WIN_REG_ADDR(win, 0x04)
115 #define OB_WIN_REMAP_LS(win)                    OB_WIN_REG_ADDR(win, 0x08)
116 #define OB_WIN_REMAP_MS(win)                    OB_WIN_REG_ADDR(win, 0x0c)
117 #define OB_WIN_MASK_LS(win)                     OB_WIN_REG_ADDR(win, 0x10)
118 #define OB_WIN_MASK_MS(win)                     OB_WIN_REG_ADDR(win, 0x14)
119 #define OB_WIN_ACTIONS(win)                     OB_WIN_REG_ADDR(win, 0x18)
120 #define OB_WIN_DEFAULT_ACTIONS                  (OB_WIN_ACTIONS(OB_WIN_COUNT-1) + 0x4)
121 #define     OB_WIN_FUNC_NUM_MASK                GENMASK(31, 24)
122 #define     OB_WIN_FUNC_NUM_SHIFT               24
123 #define     OB_WIN_FUNC_NUM_ENABLE              BIT(23)
124 #define     OB_WIN_BUS_NUM_BITS_MASK            GENMASK(22, 20)
125 #define     OB_WIN_BUS_NUM_BITS_SHIFT           20
126 #define     OB_WIN_MSG_CODE_ENABLE              BIT(22)
127 #define     OB_WIN_MSG_CODE_MASK                GENMASK(21, 14)
128 #define     OB_WIN_MSG_CODE_SHIFT               14
129 #define     OB_WIN_MSG_PAYLOAD_LEN              BIT(12)
130 #define     OB_WIN_ATTR_ENABLE                  BIT(11)
131 #define     OB_WIN_ATTR_TC_MASK                 GENMASK(10, 8)
132 #define     OB_WIN_ATTR_TC_SHIFT                8
133 #define     OB_WIN_ATTR_RELAXED                 BIT(7)
134 #define     OB_WIN_ATTR_NOSNOOP                 BIT(6)
135 #define     OB_WIN_ATTR_POISON                  BIT(5)
136 #define     OB_WIN_ATTR_IDO                     BIT(4)
137 #define     OB_WIN_TYPE_MASK                    GENMASK(3, 0)
138 #define     OB_WIN_TYPE_SHIFT                   0
139 #define     OB_WIN_TYPE_MEM                     0x0
140 #define     OB_WIN_TYPE_IO                      0x4
141 #define     OB_WIN_TYPE_CONFIG_TYPE0            0x8
142 #define     OB_WIN_TYPE_CONFIG_TYPE1            0x9
143 #define     OB_WIN_TYPE_MSG                     0xc
144
145 /* LMI registers base address and register offsets */
146 #define LMI_BASE_ADDR                           0x6000
147 #define CFG_REG                                 (LMI_BASE_ADDR + 0x0)
148 #define     LTSSM_SHIFT                         24
149 #define     LTSSM_MASK                          0x3f
150 #define     LTSSM_L0                            0x10
151 #define     LTSSM_DISABLED                      0x20
152 #define VENDOR_ID_REG                           (LMI_BASE_ADDR + 0x44)
153
154 /* PCIe core controller registers */
155 #define CTRL_CORE_BASE_ADDR                     0x18000
156 #define CTRL_CONFIG_REG                         (CTRL_CORE_BASE_ADDR + 0x0)
157 #define     CTRL_MODE_SHIFT                     0x0
158 #define     CTRL_MODE_MASK                      0x1
159 #define     PCIE_CORE_MODE_DIRECT               0x0
160 #define     PCIE_CORE_MODE_COMMAND              0x1
161
162 /* Transaction types */
163 #define PCIE_CONFIG_RD_TYPE0                    0x8
164 #define PCIE_CONFIG_RD_TYPE1                    0x9
165 #define PCIE_CONFIG_WR_TYPE0                    0xa
166 #define PCIE_CONFIG_WR_TYPE1                    0xb
167
168 /* PCI_BDF shifts 8bit, so we need extra 4bit shift */
169 #define PCIE_BDF(b, d, f)                       (PCI_BDF(b, d, f) << 4)
170 #define PCIE_CONF_BUS(bus)                      (((bus) & 0xff) << 20)
171 #define PCIE_CONF_DEV(dev)                      (((dev) & 0x1f) << 15)
172 #define PCIE_CONF_FUNC(fun)                     (((fun) & 0x7)  << 12)
173 #define PCIE_CONF_REG(reg)                      ((reg) & 0xffc)
174 #define PCIE_CONF_ADDR(bus, devfn, where)       \
175         (PCIE_CONF_BUS(bus) | PCIE_CONF_DEV(PCI_SLOT(devfn))    | \
176          PCIE_CONF_FUNC(PCI_FUNC(devfn)) | PCIE_CONF_REG(where))
177
178 /* PCIe Retries & Timeout definitions */
179 #define PIO_MAX_RETRIES                         1500
180 #define PIO_WAIT_TIMEOUT                        1000
181 #define LINK_MAX_RETRIES                        10
182 #define LINK_WAIT_TIMEOUT                       100000
183
184 #define CFG_RD_CRS_VAL                  0xFFFF0001
185
186 /**
187  * struct pcie_advk - Advk PCIe controller state
188  *
189  * @reg_base:    The base address of the register space.
190  * @first_busno: This driver supports multiple PCIe controllers.
191  *               first_busno stores the bus number of the PCIe root-port
192  *               number which may vary depending on the PCIe setup
193  *               (PEX switches etc).
194  * @sec_busno:   sec_busno stores the bus number for the device behind
195  *               the PCIe root-port
196  * @device:      The pointer to PCI uclass device.
197  */
198 struct pcie_advk {
199         void           *base;
200         int            first_busno;
201         int            sec_busno;
202         struct udevice *dev;
203         struct gpio_desc reset_gpio;
204         u32            cfgcache[0x34 - 0x10];
205         bool           cfgcrssve;
206 };
207
208 static inline void advk_writel(struct pcie_advk *pcie, uint val, uint reg)
209 {
210         writel(val, pcie->base + reg);
211 }
212
213 static inline uint advk_readl(struct pcie_advk *pcie, uint reg)
214 {
215         return readl(pcie->base + reg);
216 }
217
218 /**
219  * pcie_advk_addr_valid() - Check for valid bus address
220  *
221  * @pcie: Pointer to the PCI bus
222  * @busno: Bus number of PCI device
223  * @dev: Device number of PCI device
224  * @func: Function number of PCI device
225  * @bdf: The PCI device to access
226  *
227  * Return: true on valid, false on invalid
228  */
229 static bool pcie_advk_addr_valid(struct pcie_advk *pcie,
230                                  int busno, u8 dev, u8 func)
231 {
232         /* On the primary (local) bus there is only one PCI Bridge */
233         if (busno == pcie->first_busno && (dev != 0 || func != 0))
234                 return false;
235
236         /*
237          * In PCI-E only a single device (0) can exist on the secondary bus.
238          * Beyond the secondary bus, there might be a Switch and anything is
239          * possible.
240          */
241         if (busno == pcie->sec_busno && dev != 0)
242                 return false;
243
244         return true;
245 }
246
247 /**
248  * pcie_advk_wait_pio() - Wait for PIO access to be accomplished
249  *
250  * @pcie: The PCI device to access
251  *
252  * Wait up to 1.5 seconds for PIO access to be accomplished.
253  *
254  * Return positive - retry count if PIO access is accomplished.
255  * Return negative - error if PIO access is timed out.
256  */
257 static int pcie_advk_wait_pio(struct pcie_advk *pcie)
258 {
259         uint start, isr;
260         uint count;
261
262         for (count = 1; count <= PIO_MAX_RETRIES; count++) {
263                 start = advk_readl(pcie, PIO_START);
264                 isr = advk_readl(pcie, PIO_ISR);
265                 if (!start && isr)
266                         return count;
267                 /*
268                  * Do not check the PIO state too frequently,
269                  * 100us delay is appropriate.
270                  */
271                 udelay(PIO_WAIT_TIMEOUT);
272         }
273
274         dev_err(pcie->dev, "PIO read/write transfer time out\n");
275         return -ETIMEDOUT;
276 }
277
278 /**
279  * pcie_advk_check_pio_status() - Validate PIO status and get the read result
280  *
281  * @pcie: Pointer to the PCI bus
282  * @allow_crs: Only for read requests, if CRS response is allowed
283  * @read_val: Pointer to the read result
284  *
285  * Return: 0 on success
286  */
287 static int pcie_advk_check_pio_status(struct pcie_advk *pcie,
288                                       bool allow_crs,
289                                       uint *read_val)
290 {
291         int ret;
292         uint reg;
293         unsigned int status;
294         char *strcomp_status, *str_posted;
295
296         reg = advk_readl(pcie, PIO_STAT);
297         status = (reg & PIO_COMPLETION_STATUS_MASK) >>
298                 PIO_COMPLETION_STATUS_SHIFT;
299
300         switch (status) {
301         case PIO_COMPLETION_STATUS_OK:
302                 if (reg & PIO_ERR_STATUS) {
303                         strcomp_status = "COMP_ERR";
304                         ret = -EFAULT;
305                         break;
306                 }
307                 /* Get the read result */
308                 if (read_val)
309                         *read_val = advk_readl(pcie, PIO_RD_DATA);
310                 /* No error */
311                 strcomp_status = NULL;
312                 ret = 0;
313                 break;
314         case PIO_COMPLETION_STATUS_UR:
315                 strcomp_status = "UR";
316                 ret = -EOPNOTSUPP;
317                 break;
318         case PIO_COMPLETION_STATUS_CRS:
319                 if (allow_crs && read_val) {
320                         /* For reading, CRS is not an error status. */
321                         *read_val = CFG_RD_CRS_VAL;
322                         strcomp_status = NULL;
323                         ret = 0;
324                 } else {
325                         strcomp_status = "CRS";
326                         ret = -EAGAIN;
327                 }
328                 break;
329         case PIO_COMPLETION_STATUS_CA:
330                 strcomp_status = "CA";
331                 ret = -ECANCELED;
332                 break;
333         default:
334                 strcomp_status = "Unknown";
335                 ret = -EINVAL;
336                 break;
337         }
338
339         if (!strcomp_status)
340                 return ret;
341
342         if (reg & PIO_NON_POSTED_REQ)
343                 str_posted = "Non-posted";
344         else
345                 str_posted = "Posted";
346
347         dev_dbg(pcie->dev, "%s PIO Response Status: %s, %#x @ %#x\n",
348                 str_posted, strcomp_status, reg,
349                 advk_readl(pcie, PIO_ADDR_LS));
350
351         return ret;
352 }
353
354 /**
355  * pcie_advk_read_config() - Read from configuration space
356  *
357  * @bus: Pointer to the PCI bus
358  * @bdf: Identifies the PCIe device to access
359  * @offset: The offset into the device's configuration space
360  * @valuep: A pointer at which to store the read value
361  * @size: Indicates the size of access to perform
362  *
363  * Read a value of size @size from offset @offset within the configuration
364  * space of the device identified by the bus, device & function numbers in @bdf
365  * on the PCI bus @bus.
366  *
367  * Return: 0 on success
368  */
369 static int pcie_advk_read_config(const struct udevice *bus, pci_dev_t bdf,
370                                  uint offset, ulong *valuep,
371                                  enum pci_size_t size)
372 {
373         struct pcie_advk *pcie = dev_get_priv(bus);
374         int busno = PCI_BUS(bdf) - dev_seq(bus);
375         int retry_count;
376         bool allow_crs;
377         ulong data;
378         uint reg;
379         int ret;
380
381         dev_dbg(pcie->dev, "PCIE CFG read:  (b,d,f)=(%2d,%2d,%2d) ",
382                 PCI_BUS(bdf), PCI_DEV(bdf), PCI_FUNC(bdf));
383
384         if (!pcie_advk_addr_valid(pcie, busno, PCI_DEV(bdf), PCI_FUNC(bdf))) {
385                 dev_dbg(pcie->dev, "- out of range\n");
386                 *valuep = pci_get_ff(size);
387                 return 0;
388         }
389
390         /*
391          * The configuration space of the PCI Bridge on primary (local) bus is
392          * not accessible via PIO transfers like all other PCIe devices. PCI
393          * Bridge config registers are available directly in Aardvark memory
394          * space starting at offset zero. Moreover PCI Bridge registers in the
395          * range 0x10 - 0x34 are not available and register 0x38 (Expansion ROM
396          * Base Address) is at offset 0x30.
397          * We therefore read configuration space content of the primary PCI
398          * Bridge from our virtual cache.
399          */
400         if (busno == pcie->first_busno) {
401                 if (offset >= 0x10 && offset < 0x34)
402                         data = pcie->cfgcache[(offset - 0x10) / 4];
403                 else if ((offset & ~3) == PCI_ROM_ADDRESS1)
404                         data = advk_readl(pcie, PCIE_CORE_EXP_ROM_BAR_REG);
405                 else
406                         data = advk_readl(pcie, offset & ~3);
407
408                 if ((offset & ~3) == (PCI_HEADER_TYPE & ~3)) {
409                         /*
410                          * Change Header Type of PCI Bridge device to Type 1
411                          * (0x01, used by PCI Bridges) because hardwired value
412                          * is Type 0 (0x00, used by Endpoint devices).
413                          */
414                         data &= ~0x007f0000;
415                         data |= PCI_HEADER_TYPE_BRIDGE << 16;
416                 }
417
418                 if ((offset & ~3) == PCIE_CORE_PCIEXP_CAP_OFF + PCI_EXP_RTCTL) {
419                         /* CRSSVE bit is stored only in cache */
420                         if (pcie->cfgcrssve)
421                                 data |= PCI_EXP_RTCTL_CRSSVE;
422                 }
423
424                 if ((offset & ~3) == PCIE_CORE_PCIEXP_CAP_OFF +
425                                      (PCI_EXP_RTCAP & ~3)) {
426                         /* CRS is emulated below, so set CRSVIS capability */
427                         data |= PCI_EXP_RTCAP_CRSVIS << 16;
428                 }
429
430                 *valuep = pci_conv_32_to_size(data, offset, size);
431
432                 return 0;
433         }
434
435         /*
436          * Returning fabricated CRS value (0xFFFF0001) by PCIe Root Complex to
437          * OS is allowed only for 4-byte PCI_VENDOR_ID config read request and
438          * only when CRSSVE bit in Root Port PCIe device is enabled. In all
439          * other error PCIe Root Complex must return all-ones.
440          *
441          * U-Boot currently does not support handling of CRS return value for
442          * PCI_VENDOR_ID config read request and also does not set CRSSVE bit.
443          * So it means that pcie->cfgcrssve is false. But the code is prepared
444          * for returning CRS, so that if U-Boot does support CRS in the future,
445          * it will work for Aardvark.
446          */
447         allow_crs = pcie->cfgcrssve;
448
449         if (advk_readl(pcie, PIO_START)) {
450                 dev_err(pcie->dev,
451                         "Previous PIO read/write transfer is still running\n");
452                 if (allow_crs) {
453                         *valuep = CFG_RD_CRS_VAL;
454                         return 0;
455                 }
456                 *valuep = pci_get_ff(size);
457                 return -EAGAIN;
458         }
459
460         /* Program the control register */
461         reg = advk_readl(pcie, PIO_CTRL);
462         reg &= ~PIO_CTRL_TYPE_MASK;
463         if (busno == pcie->sec_busno)
464                 reg |= PCIE_CONFIG_RD_TYPE0;
465         else
466                 reg |= PCIE_CONFIG_RD_TYPE1;
467         advk_writel(pcie, reg, PIO_CTRL);
468
469         /* Program the address registers */
470         reg = PCIE_BDF(busno, PCI_DEV(bdf), PCI_FUNC(bdf)) | PCIE_CONF_REG(offset);
471         advk_writel(pcie, reg, PIO_ADDR_LS);
472         advk_writel(pcie, 0, PIO_ADDR_MS);
473
474         retry_count = 0;
475
476 retry:
477         /* Start the transfer */
478         advk_writel(pcie, 1, PIO_ISR);
479         advk_writel(pcie, 1, PIO_START);
480
481         ret = pcie_advk_wait_pio(pcie);
482         if (ret < 0) {
483                 if (allow_crs) {
484                         *valuep = CFG_RD_CRS_VAL;
485                         return 0;
486                 }
487                 *valuep = pci_get_ff(size);
488                 return ret;
489         }
490
491         retry_count += ret;
492
493         /* Check PIO status and get the read result */
494         ret = pcie_advk_check_pio_status(pcie, allow_crs, &reg);
495         if (ret == -EAGAIN && retry_count < PIO_MAX_RETRIES)
496                 goto retry;
497         if (ret) {
498                 *valuep = pci_get_ff(size);
499                 return ret;
500         }
501
502         dev_dbg(pcie->dev, "(addr,size,val)=(0x%04x, %d, 0x%08x)\n",
503                 offset, size, reg);
504         *valuep = pci_conv_32_to_size(reg, offset, size);
505
506         return 0;
507 }
508
509 /**
510  * pcie_calc_datastrobe() - Calculate data strobe
511  *
512  * @offset: The offset into the device's configuration space
513  * @size: Indicates the size of access to perform
514  *
515  * Calculate data strobe according to offset and size
516  *
517  */
518 static uint pcie_calc_datastrobe(uint offset, enum pci_size_t size)
519 {
520         uint bytes, data_strobe;
521
522         switch (size) {
523         case PCI_SIZE_8:
524                 bytes = 1;
525                 break;
526         case PCI_SIZE_16:
527                 bytes = 2;
528                 break;
529         default:
530                 bytes = 4;
531         }
532
533         data_strobe = GENMASK(bytes - 1, 0) << (offset & 0x3);
534
535         return data_strobe;
536 }
537
538 /**
539  * pcie_advk_write_config() - Write to configuration space
540  *
541  * @bus: Pointer to the PCI bus
542  * @bdf: Identifies the PCIe device to access
543  * @offset: The offset into the device's configuration space
544  * @value: The value to write
545  * @size: Indicates the size of access to perform
546  *
547  * Write the value @value of size @size from offset @offset within the
548  * configuration space of the device identified by the bus, device & function
549  * numbers in @bdf on the PCI bus @bus.
550  *
551  * Return: 0 on success
552  */
553 static int pcie_advk_write_config(struct udevice *bus, pci_dev_t bdf,
554                                   uint offset, ulong value,
555                                   enum pci_size_t size)
556 {
557         struct pcie_advk *pcie = dev_get_priv(bus);
558         int busno = PCI_BUS(bdf) - dev_seq(bus);
559         int retry_count;
560         ulong data;
561         uint reg;
562         int ret;
563
564         dev_dbg(pcie->dev, "PCIE CFG write: (b,d,f)=(%2d,%2d,%2d) ",
565                 PCI_BUS(bdf), PCI_DEV(bdf), PCI_FUNC(bdf));
566         dev_dbg(pcie->dev, "(addr,size,val)=(0x%04x, %d, 0x%08lx)\n",
567                 offset, size, value);
568
569         if (!pcie_advk_addr_valid(pcie, busno, PCI_DEV(bdf), PCI_FUNC(bdf))) {
570                 dev_dbg(pcie->dev, "- out of range\n");
571                 return 0;
572         }
573
574         /*
575          * As explained in pcie_advk_read_config(), for the configuration
576          * space of the primary PCI Bridge, we write the content into virtual
577          * cache.
578          */
579         if (busno == pcie->first_busno) {
580                 if (offset >= 0x10 && offset < 0x34) {
581                         data = pcie->cfgcache[(offset - 0x10) / 4];
582                         data = pci_conv_size_to_32(data, value, offset, size);
583                         pcie->cfgcache[(offset - 0x10) / 4] = data;
584                 } else if ((offset & ~3) == PCI_ROM_ADDRESS1) {
585                         data = advk_readl(pcie, PCIE_CORE_EXP_ROM_BAR_REG);
586                         data = pci_conv_size_to_32(data, value, offset, size);
587                         advk_writel(pcie, data, PCIE_CORE_EXP_ROM_BAR_REG);
588                 } else {
589                         data = advk_readl(pcie, offset & ~3);
590                         data = pci_conv_size_to_32(data, value, offset, size);
591                         advk_writel(pcie, data, offset & ~3);
592                 }
593
594                 if (offset == PCI_PRIMARY_BUS)
595                         pcie->first_busno = data & 0xff;
596
597                 if (offset == PCI_SECONDARY_BUS ||
598                     (offset == PCI_PRIMARY_BUS && size != PCI_SIZE_8))
599                         pcie->sec_busno = (data >> 8) & 0xff;
600
601                 if ((offset & ~3) == PCIE_CORE_PCIEXP_CAP_OFF + PCI_EXP_RTCTL)
602                         pcie->cfgcrssve = data & PCI_EXP_RTCTL_CRSSVE;
603
604                 return 0;
605         }
606
607         if (advk_readl(pcie, PIO_START)) {
608                 dev_err(pcie->dev,
609                         "Previous PIO read/write transfer is still running\n");
610                 return -EAGAIN;
611         }
612
613         /* Program the control register */
614         reg = advk_readl(pcie, PIO_CTRL);
615         reg &= ~PIO_CTRL_TYPE_MASK;
616         if (busno == pcie->sec_busno)
617                 reg |= PCIE_CONFIG_WR_TYPE0;
618         else
619                 reg |= PCIE_CONFIG_WR_TYPE1;
620         advk_writel(pcie, reg, PIO_CTRL);
621
622         /* Program the address registers */
623         reg = PCIE_BDF(busno, PCI_DEV(bdf), PCI_FUNC(bdf)) | PCIE_CONF_REG(offset);
624         advk_writel(pcie, reg, PIO_ADDR_LS);
625         advk_writel(pcie, 0, PIO_ADDR_MS);
626         dev_dbg(pcie->dev, "\tPIO req. - addr = 0x%08x\n", reg);
627
628         /* Program the data register */
629         reg = pci_conv_size_to_32(0, value, offset, size);
630         advk_writel(pcie, reg, PIO_WR_DATA);
631         dev_dbg(pcie->dev, "\tPIO req. - val  = 0x%08x\n", reg);
632
633         /* Program the data strobe */
634         reg = pcie_calc_datastrobe(offset, size);
635         advk_writel(pcie, reg, PIO_WR_DATA_STRB);
636         dev_dbg(pcie->dev, "\tPIO req. - strb = 0x%02x\n", reg);
637
638         retry_count = 0;
639
640 retry:
641         /* Start the transfer */
642         advk_writel(pcie, 1, PIO_ISR);
643         advk_writel(pcie, 1, PIO_START);
644
645         ret = pcie_advk_wait_pio(pcie);
646         if (ret < 0)
647                 return ret;
648
649         retry_count += ret;
650
651         /* Check PIO status */
652         ret = pcie_advk_check_pio_status(pcie, false, NULL);
653         if (ret == -EAGAIN && retry_count < PIO_MAX_RETRIES)
654                 goto retry;
655         return ret;
656 }
657
658 /**
659  * pcie_advk_link_up() - Check if PCIe link is up or not
660  *
661  * @pcie: The PCI device to access
662  *
663  * Return 1 (true) on link up.
664  * Return 0 (false) on link down.
665  */
666 static int pcie_advk_link_up(struct pcie_advk *pcie)
667 {
668         u32 val, ltssm_state;
669
670         val = advk_readl(pcie, CFG_REG);
671         ltssm_state = (val >> LTSSM_SHIFT) & LTSSM_MASK;
672         return ltssm_state >= LTSSM_L0 && ltssm_state < LTSSM_DISABLED;
673 }
674
675 /**
676  * pcie_advk_wait_for_link() - Wait for link training to be accomplished
677  *
678  * @pcie: The PCI device to access
679  *
680  * Wait up to 1 second for link training to be accomplished.
681  *
682  * Return 1 (true) if link training ends up with link up success.
683  * Return 0 (false) if link training ends up with link up failure.
684  */
685 static int pcie_advk_wait_for_link(struct pcie_advk *pcie)
686 {
687         int retries;
688
689         /* check if the link is up or not */
690         for (retries = 0; retries < LINK_MAX_RETRIES; retries++) {
691                 if (pcie_advk_link_up(pcie)) {
692                         printf("PCIe: Link up\n");
693                         return 0;
694                 }
695
696                 udelay(LINK_WAIT_TIMEOUT);
697         }
698
699         printf("PCIe: Link down\n");
700
701         return -ETIMEDOUT;
702 }
703
704 /*
705  * Set PCIe address window register which could be used for memory
706  * mapping.
707  */
708 static void pcie_advk_set_ob_win(struct pcie_advk *pcie, u8 win_num,
709                                  phys_addr_t match, phys_addr_t remap,
710                                  phys_addr_t mask, u32 actions)
711 {
712         advk_writel(pcie, OB_WIN_ENABLE |
713                           lower_32_bits(match), OB_WIN_MATCH_LS(win_num));
714         advk_writel(pcie, upper_32_bits(match), OB_WIN_MATCH_MS(win_num));
715         advk_writel(pcie, lower_32_bits(remap), OB_WIN_REMAP_LS(win_num));
716         advk_writel(pcie, upper_32_bits(remap), OB_WIN_REMAP_MS(win_num));
717         advk_writel(pcie, lower_32_bits(mask), OB_WIN_MASK_LS(win_num));
718         advk_writel(pcie, upper_32_bits(mask), OB_WIN_MASK_MS(win_num));
719         advk_writel(pcie, actions, OB_WIN_ACTIONS(win_num));
720 }
721
722 static void pcie_advk_disable_ob_win(struct pcie_advk *pcie, u8 win_num)
723 {
724         advk_writel(pcie, 0, OB_WIN_MATCH_LS(win_num));
725         advk_writel(pcie, 0, OB_WIN_MATCH_MS(win_num));
726         advk_writel(pcie, 0, OB_WIN_REMAP_LS(win_num));
727         advk_writel(pcie, 0, OB_WIN_REMAP_MS(win_num));
728         advk_writel(pcie, 0, OB_WIN_MASK_LS(win_num));
729         advk_writel(pcie, 0, OB_WIN_MASK_MS(win_num));
730         advk_writel(pcie, 0, OB_WIN_ACTIONS(win_num));
731 }
732
733 static void pcie_advk_set_ob_region(struct pcie_advk *pcie, int *wins,
734                                     struct pci_region *region, u32 actions)
735 {
736         phys_addr_t phys_start = region->phys_start;
737         pci_addr_t bus_start = region->bus_start;
738         pci_size_t size = region->size;
739         phys_addr_t win_mask;
740         u64 win_size;
741
742         if (*wins == -1)
743                 return;
744
745         /*
746          * The n-th PCIe window is configured by tuple (match, remap, mask)
747          * and an access to address A uses this window if A matches the
748          * match with given mask.
749          * So every PCIe window size must be a power of two and every start
750          * address must be aligned to window size. Minimal size is 64 KiB
751          * because lower 16 bits of mask must be zero. Remapped address
752          * may have set only bits from the mask.
753          */
754         while (*wins < OB_WIN_COUNT && size > 0) {
755                 /* Calculate the largest aligned window size */
756                 win_size = (1ULL << (fls64(size) - 1)) |
757                            (phys_start ? (1ULL << __ffs64(phys_start)) : 0);
758                 win_size = 1ULL << __ffs64(win_size);
759                 win_mask = ~(win_size - 1);
760                 if (win_size < 0x10000 || (bus_start & ~win_mask))
761                         break;
762
763                 dev_dbg(pcie->dev,
764                         "Configuring PCIe window %d: [0x%llx-0x%llx] as 0x%x\n",
765                         *wins, (u64)phys_start, (u64)phys_start + win_size,
766                         actions);
767                 pcie_advk_set_ob_win(pcie, *wins, phys_start, bus_start,
768                                      win_mask, actions);
769
770                 phys_start += win_size;
771                 bus_start += win_size;
772                 size -= win_size;
773                 (*wins)++;
774         }
775
776         if (size > 0) {
777                 *wins = -1;
778                 dev_err(pcie->dev,
779                         "Invalid PCIe region [0x%llx-0x%llx]\n",
780                         (u64)region->phys_start,
781                         (u64)region->phys_start + region->size);
782         }
783 }
784
785 /**
786  * pcie_advk_setup_hw() - PCIe initailzation
787  *
788  * @pcie: The PCI device to access
789  *
790  * Return: 0 on success
791  */
792 static int pcie_advk_setup_hw(struct pcie_advk *pcie)
793 {
794         struct pci_region *io, *mem, *pref;
795         int i, wins;
796         u32 reg;
797
798         /* Set to Direct mode */
799         reg = advk_readl(pcie, CTRL_CONFIG_REG);
800         reg &= ~(CTRL_MODE_MASK << CTRL_MODE_SHIFT);
801         reg |= ((PCIE_CORE_MODE_DIRECT & CTRL_MODE_MASK) << CTRL_MODE_SHIFT);
802         advk_writel(pcie, reg, CTRL_CONFIG_REG);
803
804         /* Set PCI global control register to RC mode */
805         reg = advk_readl(pcie, PCIE_CORE_CTRL0_REG);
806         reg |= (IS_RC_MSK << IS_RC_SHIFT);
807         advk_writel(pcie, reg, PCIE_CORE_CTRL0_REG);
808
809         /*
810          * Replace incorrect PCI vendor id value 0x1b4b by correct value 0x11ab.
811          * VENDOR_ID_REG contains vendor id in low 16 bits and subsystem vendor
812          * id in high 16 bits. Updating this register changes readback value of
813          * read-only vendor id bits in PCIE_CORE_DEV_ID_REG register. Workaround
814          * for erratum 4.1: "The value of device and vendor ID is incorrect".
815          */
816         advk_writel(pcie, 0x11ab11ab, VENDOR_ID_REG);
817
818         /*
819          * Change Class Code of PCI Bridge device to PCI Bridge (0x600400),
820          * because default value is Mass Storage Controller (0x010400), causing
821          * U-Boot to fail to recognize it as P2P Bridge.
822          *
823          * Note that this Aardvark PCI Bridge does not have a compliant Type 1
824          * Configuration Space and it even cannot be accessed via Aardvark's
825          * PCI config space access method. Something like config space is
826          * available in internal Aardvark registers starting at offset 0x0
827          * and is reported as Type 0. In range 0x10 - 0x34 it has totally
828          * different registers. So our driver reports Header Type as Type 1 and
829          * for the above mentioned range redirects access to the virtual
830          * cfgcache[] buffer, which avoids changing internal Aardvark registers.
831          */
832         reg = advk_readl(pcie, PCIE_CORE_DEV_REV_REG);
833         reg &= ~0xffffff00;
834         reg |= (PCI_CLASS_BRIDGE_PCI << 8) << 8;
835         advk_writel(pcie, reg, PCIE_CORE_DEV_REV_REG);
836
837         /* Set Advanced Error Capabilities and Control PF0 register */
838         reg = PCIE_CORE_ERR_CAPCTL_ECRC_CHK_TX |
839                 PCIE_CORE_ERR_CAPCTL_ECRC_CHK_TX_EN |
840                 PCIE_CORE_ERR_CAPCTL_ECRC_CHECK |
841                 PCIE_CORE_ERR_CAPCTL_ECRC_CHECK_RCV;
842         advk_writel(pcie, reg, PCIE_CORE_ERR_CAPCTL_REG);
843
844         /* Set PCIe Device Control and Status 1 PF0 register */
845         reg = PCIE_CORE_DEV_CTRL_STATS_RELAX_ORDER_DISABLE |
846                 (PCIE_CORE_DEV_CTRL_STATS_MAX_PAYLOAD_SIZE <<
847                  PCIE_CORE_DEV_CTRL_STATS_MAX_PAYLOAD_SIZE_SHIFT) |
848                 (PCIE_CORE_DEV_CTRL_STATS_MAX_RD_REQ_SIZE <<
849                  PCIE_CORE_DEV_CTRL_STATS_MAX_RD_REQ_SIZE_SHIFT) |
850                 PCIE_CORE_DEV_CTRL_STATS_SNOOP_DISABLE;
851         advk_writel(pcie, reg, PCIE_CORE_DEV_CTRL_STATS_REG);
852
853         /* Program PCIe Control 2 to disable strict ordering */
854         reg = PCIE_CORE_CTRL2_RESERVED |
855                 PCIE_CORE_CTRL2_TD_ENABLE;
856         advk_writel(pcie, reg, PCIE_CORE_CTRL2_REG);
857
858         /* Set GEN2 */
859         reg = advk_readl(pcie, PCIE_CORE_CTRL0_REG);
860         reg &= ~PCIE_GEN_SEL_MSK;
861         reg |= SPEED_GEN_2;
862         advk_writel(pcie, reg, PCIE_CORE_CTRL0_REG);
863
864         /* Set lane X1 */
865         reg = advk_readl(pcie, PCIE_CORE_CTRL0_REG);
866         reg &= ~LANE_CNT_MSK;
867         reg |= LANE_COUNT_1;
868         advk_writel(pcie, reg, PCIE_CORE_CTRL0_REG);
869
870         /* Enable link training */
871         reg = advk_readl(pcie, PCIE_CORE_CTRL0_REG);
872         reg |= LINK_TRAINING_EN;
873         advk_writel(pcie, reg, PCIE_CORE_CTRL0_REG);
874
875         /*
876          * Enable AXI address window location generation:
877          * When it is enabled, the default outbound window
878          * configurations (Default User Field: 0xD0074CFC)
879          * are used to transparent address translation for
880          * the outbound transactions. Thus, PCIe address
881          * windows are not required for transparent memory
882          * access when default outbound window configuration
883          * is set for memory access.
884          */
885         reg = advk_readl(pcie, PCIE_CORE_CTRL2_REG);
886         reg |= PCIE_CORE_CTRL2_ADDRWIN_MAP_ENABLE;
887         advk_writel(pcie, reg, PCIE_CORE_CTRL2_REG);
888
889         /*
890          * Bypass the address window mapping for PIO:
891          * Since PIO access already contains all required
892          * info over AXI interface by PIO registers, the
893          * address window is not required.
894          */
895         reg = advk_readl(pcie, PIO_CTRL);
896         reg |= PIO_CTRL_ADDR_WIN_DISABLE;
897         advk_writel(pcie, reg, PIO_CTRL);
898
899         /*
900          * Set memory access in Default User Field so it
901          * is not required to configure PCIe address for
902          * transparent memory access.
903          */
904         advk_writel(pcie, OB_WIN_TYPE_MEM, OB_WIN_DEFAULT_ACTIONS);
905
906         /*
907          * Configure PCIe address windows for non-memory or
908          * non-transparent access as by default PCIe uses
909          * transparent memory access.
910          */
911         wins = 0;
912         pci_get_regions(pcie->dev, &io, &mem, &pref);
913         if (io)
914                 pcie_advk_set_ob_region(pcie, &wins, io, OB_WIN_TYPE_IO);
915         if (mem && mem->phys_start != mem->bus_start)
916                 pcie_advk_set_ob_region(pcie, &wins, mem, OB_WIN_TYPE_MEM);
917         if (pref && pref->phys_start != pref->bus_start)
918                 pcie_advk_set_ob_region(pcie, &wins, pref, OB_WIN_TYPE_MEM);
919
920         /* Disable remaining PCIe outbound windows */
921         for (i = ((wins >= 0) ? wins : 0); i < OB_WIN_COUNT; i++)
922                 pcie_advk_disable_ob_win(pcie, i);
923
924         if (wins == -1)
925                 return -EINVAL;
926
927         /* Wait for PCIe link up */
928         if (pcie_advk_wait_for_link(pcie))
929                 return -ENXIO;
930
931         return 0;
932 }
933
934 /**
935  * pcie_advk_probe() - Probe the PCIe bus for active link
936  *
937  * @dev: A pointer to the device being operated on
938  *
939  * Probe for an active link on the PCIe bus and configure the controller
940  * to enable this port.
941  *
942  * Return: 0 on success, else -ENODEV
943  */
944 static int pcie_advk_probe(struct udevice *dev)
945 {
946         struct pcie_advk *pcie = dev_get_priv(dev);
947
948         gpio_request_by_name(dev, "reset-gpios", 0, &pcie->reset_gpio,
949                              GPIOD_IS_OUT);
950         /*
951          * Issue reset to add-in card through the dedicated GPIO.
952          * Some boards are connecting the card reset pin to common system
953          * reset wire and others are using separate GPIO port.
954          * In the last case we have to release a reset of the addon card
955          * using this GPIO.
956          *
957          * FIX-ME:
958          *     The PCIe RESET signal is not supposed to be released along
959          *     with the SOC RESET signal. It should be lowered as early as
960          *     possible before PCIe PHY initialization. Moreover, the PCIe
961          *     clock should be gated as well.
962          */
963         if (dm_gpio_is_valid(&pcie->reset_gpio)) {
964                 dev_dbg(dev, "Toggle PCIE Reset GPIO ...\n");
965                 dm_gpio_set_value(&pcie->reset_gpio, 1);
966                 mdelay(200);
967                 dm_gpio_set_value(&pcie->reset_gpio, 0);
968         } else {
969                 dev_warn(dev, "PCIE Reset on GPIO support is missing\n");
970         }
971
972         pcie->dev = pci_get_controller(dev);
973
974         /* PCI Bridge support 32-bit I/O and 64-bit prefetch mem addressing */
975         pcie->cfgcache[(PCI_IO_BASE - 0x10) / 4] =
976                 PCI_IO_RANGE_TYPE_32 | (PCI_IO_RANGE_TYPE_32 << 8);
977         pcie->cfgcache[(PCI_PREF_MEMORY_BASE - 0x10) / 4] =
978                 PCI_PREF_RANGE_TYPE_64 | (PCI_PREF_RANGE_TYPE_64 << 16);
979
980         return pcie_advk_setup_hw(pcie);
981 }
982
983 static int pcie_advk_remove(struct udevice *dev)
984 {
985         struct pcie_advk *pcie = dev_get_priv(dev);
986         u32 reg;
987         int i;
988
989         for (i = 0; i < OB_WIN_COUNT; i++)
990                 pcie_advk_disable_ob_win(pcie, i);
991
992         reg = advk_readl(pcie, PCIE_CORE_CMD_STATUS_REG);
993         reg &= ~(PCIE_CORE_CMD_MEM_ACCESS_EN |
994                  PCIE_CORE_CMD_IO_ACCESS_EN |
995                  PCIE_CORE_CMD_MEM_IO_REQ_EN);
996         advk_writel(pcie, reg, PCIE_CORE_CMD_STATUS_REG);
997
998         reg = advk_readl(pcie, PCIE_CORE_CTRL0_REG);
999         reg &= ~LINK_TRAINING_EN;
1000         advk_writel(pcie, reg, PCIE_CORE_CTRL0_REG);
1001
1002         return 0;
1003 }
1004
1005 /**
1006  * pcie_advk_of_to_plat() - Translate from DT to device state
1007  *
1008  * @dev: A pointer to the device being operated on
1009  *
1010  * Translate relevant data from the device tree pertaining to device @dev into
1011  * state that the driver will later make use of. This state is stored in the
1012  * device's private data structure.
1013  *
1014  * Return: 0 on success, else -EINVAL
1015  */
1016 static int pcie_advk_of_to_plat(struct udevice *dev)
1017 {
1018         struct pcie_advk *pcie = dev_get_priv(dev);
1019
1020         /* Get the register base address */
1021         pcie->base = (void *)dev_read_addr_index(dev, 0);
1022         if ((fdt_addr_t)pcie->base == FDT_ADDR_T_NONE)
1023                 return -EINVAL;
1024
1025         return 0;
1026 }
1027
1028 static const struct dm_pci_ops pcie_advk_ops = {
1029         .read_config    = pcie_advk_read_config,
1030         .write_config   = pcie_advk_write_config,
1031 };
1032
1033 static const struct udevice_id pcie_advk_ids[] = {
1034         { .compatible = "marvell,armada-3700-pcie" },
1035         { }
1036 };
1037
1038 U_BOOT_DRIVER(pcie_advk) = {
1039         .name                   = "pcie_advk",
1040         .id                     = UCLASS_PCI,
1041         .of_match               = pcie_advk_ids,
1042         .ops                    = &pcie_advk_ops,
1043         .of_to_plat     = pcie_advk_of_to_plat,
1044         .probe                  = pcie_advk_probe,
1045         .remove                 = pcie_advk_remove,
1046         .flags                  = DM_FLAG_OS_PREPARE,
1047         .priv_auto      = sizeof(struct pcie_advk),
1048 };