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