GNU Linux-libre 4.14.330-gnu1
[releases.git] / drivers / pci / host / pci-aardvark.c
1 /*
2  * Driver for the Aardvark PCIe controller, used on Marvell Armada
3  * 3700.
4  *
5  * Copyright (C) 2016 Marvell
6  *
7  * Author: Hezi Shahmoon <hezi.shahmoon@marvell.com>
8  *
9  * This file is licensed under the terms of the GNU General Public
10  * License version 2.  This program is licensed "as is" without any
11  * warranty of any kind, whether express or implied.
12  */
13
14 #include <linux/delay.h>
15 #include <linux/gpio/consumer.h>
16 #include <linux/interrupt.h>
17 #include <linux/irq.h>
18 #include <linux/irqdomain.h>
19 #include <linux/kernel.h>
20 #include <linux/pci.h>
21 #include <linux/init.h>
22 #include <linux/platform_device.h>
23 #include <linux/of_address.h>
24 #include <linux/of_gpio.h>
25 #include <linux/of_pci.h>
26
27 /* PCIe core registers */
28 #define PCIE_CORE_CMD_STATUS_REG                                0x4
29 #define     PCIE_CORE_CMD_IO_ACCESS_EN                          BIT(0)
30 #define     PCIE_CORE_CMD_MEM_ACCESS_EN                         BIT(1)
31 #define     PCIE_CORE_CMD_MEM_IO_REQ_EN                         BIT(2)
32 #define PCIE_CORE_PCIEXP_CAP                                    0xc0
33 #define PCIE_CORE_ERR_CAPCTL_REG                                0x118
34 #define     PCIE_CORE_ERR_CAPCTL_ECRC_CHK_TX                    BIT(5)
35 #define     PCIE_CORE_ERR_CAPCTL_ECRC_CHK_TX_EN                 BIT(6)
36 #define     PCIE_CORE_ERR_CAPCTL_ECRC_CHCK                      BIT(7)
37 #define     PCIE_CORE_ERR_CAPCTL_ECRC_CHCK_RCV                  BIT(8)
38
39 /* PIO registers base address and register offsets */
40 #define PIO_BASE_ADDR                           0x4000
41 #define PIO_CTRL                                (PIO_BASE_ADDR + 0x0)
42 #define   PIO_CTRL_TYPE_MASK                    GENMASK(3, 0)
43 #define   PIO_CTRL_ADDR_WIN_DISABLE             BIT(24)
44 #define PIO_STAT                                (PIO_BASE_ADDR + 0x4)
45 #define   PIO_COMPLETION_STATUS_SHIFT           7
46 #define   PIO_COMPLETION_STATUS_MASK            GENMASK(9, 7)
47 #define   PIO_COMPLETION_STATUS_OK              0
48 #define   PIO_COMPLETION_STATUS_UR              1
49 #define   PIO_COMPLETION_STATUS_CRS             2
50 #define   PIO_COMPLETION_STATUS_CA              4
51 #define   PIO_NON_POSTED_REQ                    BIT(10)
52 #define   PIO_ERR_STATUS                        BIT(11)
53 #define PIO_ADDR_LS                             (PIO_BASE_ADDR + 0x8)
54 #define PIO_ADDR_MS                             (PIO_BASE_ADDR + 0xc)
55 #define PIO_WR_DATA                             (PIO_BASE_ADDR + 0x10)
56 #define PIO_WR_DATA_STRB                        (PIO_BASE_ADDR + 0x14)
57 #define PIO_RD_DATA                             (PIO_BASE_ADDR + 0x18)
58 #define PIO_START                               (PIO_BASE_ADDR + 0x1c)
59 #define PIO_ISR                                 (PIO_BASE_ADDR + 0x20)
60 #define PIO_ISRM                                (PIO_BASE_ADDR + 0x24)
61
62 /* Aardvark Control registers */
63 #define CONTROL_BASE_ADDR                       0x4800
64 #define PCIE_CORE_CTRL0_REG                     (CONTROL_BASE_ADDR + 0x0)
65 #define     PCIE_GEN_SEL_MSK                    0x3
66 #define     PCIE_GEN_SEL_SHIFT                  0x0
67 #define     SPEED_GEN_1                         0
68 #define     SPEED_GEN_2                         1
69 #define     SPEED_GEN_3                         2
70 #define     IS_RC_MSK                           1
71 #define     IS_RC_SHIFT                         2
72 #define     LANE_CNT_MSK                        0x18
73 #define     LANE_CNT_SHIFT                      0x3
74 #define     LANE_COUNT_1                        (0 << LANE_CNT_SHIFT)
75 #define     LANE_COUNT_2                        (1 << LANE_CNT_SHIFT)
76 #define     LANE_COUNT_4                        (2 << LANE_CNT_SHIFT)
77 #define     LANE_COUNT_8                        (3 << LANE_CNT_SHIFT)
78 #define     LINK_TRAINING_EN                    BIT(6)
79 #define     LEGACY_INTA                         BIT(28)
80 #define     LEGACY_INTB                         BIT(29)
81 #define     LEGACY_INTC                         BIT(30)
82 #define     LEGACY_INTD                         BIT(31)
83 #define PCIE_CORE_CTRL1_REG                     (CONTROL_BASE_ADDR + 0x4)
84 #define     HOT_RESET_GEN                       BIT(0)
85 #define PCIE_CORE_CTRL2_REG                     (CONTROL_BASE_ADDR + 0x8)
86 #define     PCIE_CORE_CTRL2_RESERVED            0x7
87 #define     PCIE_CORE_CTRL2_TD_ENABLE           BIT(4)
88 #define     PCIE_CORE_CTRL2_STRICT_ORDER_ENABLE BIT(5)
89 #define     PCIE_CORE_CTRL2_OB_WIN_ENABLE       BIT(6)
90 #define     PCIE_CORE_CTRL2_MSI_ENABLE          BIT(10)
91 #define PCIE_ISR0_REG                           (CONTROL_BASE_ADDR + 0x40)
92 #define PCIE_ISR0_MASK_REG                      (CONTROL_BASE_ADDR + 0x44)
93 #define     PCIE_ISR0_MSI_INT_PENDING           BIT(24)
94 #define     PCIE_ISR0_INTX_ASSERT(val)          BIT(16 + (val))
95 #define     PCIE_ISR0_INTX_DEASSERT(val)        BIT(20 + (val))
96 #define     PCIE_ISR0_ALL_MASK                  GENMASK(31, 0)
97 #define PCIE_ISR1_REG                           (CONTROL_BASE_ADDR + 0x48)
98 #define PCIE_ISR1_MASK_REG                      (CONTROL_BASE_ADDR + 0x4C)
99 #define     PCIE_ISR1_POWER_STATE_CHANGE        BIT(4)
100 #define     PCIE_ISR1_FLUSH                     BIT(5)
101 #define     PCIE_ISR1_INTX_ASSERT(val)          BIT(8 + (val))
102 #define     PCIE_ISR1_ALL_MASK                  GENMASK(31, 0)
103 #define PCIE_MSI_ADDR_LOW_REG                   (CONTROL_BASE_ADDR + 0x50)
104 #define PCIE_MSI_ADDR_HIGH_REG                  (CONTROL_BASE_ADDR + 0x54)
105 #define PCIE_MSI_STATUS_REG                     (CONTROL_BASE_ADDR + 0x58)
106 #define PCIE_MSI_MASK_REG                       (CONTROL_BASE_ADDR + 0x5C)
107 #define     PCIE_MSI_ALL_MASK                   GENMASK(31, 0)
108 #define PCIE_MSI_PAYLOAD_REG                    (CONTROL_BASE_ADDR + 0x9C)
109 #define     PCIE_MSI_DATA_MASK                  GENMASK(15, 0)
110
111 /* PCIe window configuration */
112 #define OB_WIN_BASE_ADDR                        0x4c00
113 #define OB_WIN_BLOCK_SIZE                       0x20
114 #define OB_WIN_COUNT                            8
115 #define OB_WIN_REG_ADDR(win, offset)            (OB_WIN_BASE_ADDR + \
116                                                  OB_WIN_BLOCK_SIZE * (win) + \
117                                                  (offset))
118 #define OB_WIN_MATCH_LS(win)                    OB_WIN_REG_ADDR(win, 0x00)
119 #define     OB_WIN_ENABLE                       BIT(0)
120 #define OB_WIN_MATCH_MS(win)                    OB_WIN_REG_ADDR(win, 0x04)
121 #define OB_WIN_REMAP_LS(win)                    OB_WIN_REG_ADDR(win, 0x08)
122 #define OB_WIN_REMAP_MS(win)                    OB_WIN_REG_ADDR(win, 0x0c)
123 #define OB_WIN_MASK_LS(win)                     OB_WIN_REG_ADDR(win, 0x10)
124 #define OB_WIN_MASK_MS(win)                     OB_WIN_REG_ADDR(win, 0x14)
125 #define OB_WIN_ACTIONS(win)                     OB_WIN_REG_ADDR(win, 0x18)
126 #define OB_WIN_DEFAULT_ACTIONS                  (OB_WIN_ACTIONS(OB_WIN_COUNT-1) + 0x4)
127 #define     OB_WIN_FUNC_NUM_MASK                GENMASK(31, 24)
128 #define     OB_WIN_FUNC_NUM_SHIFT               24
129 #define     OB_WIN_FUNC_NUM_ENABLE              BIT(23)
130 #define     OB_WIN_BUS_NUM_BITS_MASK            GENMASK(22, 20)
131 #define     OB_WIN_BUS_NUM_BITS_SHIFT           20
132 #define     OB_WIN_MSG_CODE_ENABLE              BIT(22)
133 #define     OB_WIN_MSG_CODE_MASK                GENMASK(21, 14)
134 #define     OB_WIN_MSG_CODE_SHIFT               14
135 #define     OB_WIN_MSG_PAYLOAD_LEN              BIT(12)
136 #define     OB_WIN_ATTR_ENABLE                  BIT(11)
137 #define     OB_WIN_ATTR_TC_MASK                 GENMASK(10, 8)
138 #define     OB_WIN_ATTR_TC_SHIFT                8
139 #define     OB_WIN_ATTR_RELAXED                 BIT(7)
140 #define     OB_WIN_ATTR_NOSNOOP                 BIT(6)
141 #define     OB_WIN_ATTR_POISON                  BIT(5)
142 #define     OB_WIN_ATTR_IDO                     BIT(4)
143 #define     OB_WIN_TYPE_MASK                    GENMASK(3, 0)
144 #define     OB_WIN_TYPE_SHIFT                   0
145 #define     OB_WIN_TYPE_MEM                     0x0
146 #define     OB_WIN_TYPE_IO                      0x4
147 #define     OB_WIN_TYPE_CONFIG_TYPE0            0x8
148 #define     OB_WIN_TYPE_CONFIG_TYPE1            0x9
149 #define     OB_WIN_TYPE_MSG                     0xc
150
151 /* LMI registers base address and register offsets */
152 #define LMI_BASE_ADDR                           0x6000
153 #define CFG_REG                                 (LMI_BASE_ADDR + 0x0)
154 #define     LTSSM_SHIFT                         24
155 #define     LTSSM_MASK                          0x3f
156 #define     RC_BAR_CONFIG                       0x300
157
158 /* LTSSM values in CFG_REG */
159 enum {
160         LTSSM_DETECT_QUIET                      = 0x0,
161         LTSSM_DETECT_ACTIVE                     = 0x1,
162         LTSSM_POLLING_ACTIVE                    = 0x2,
163         LTSSM_POLLING_COMPLIANCE                = 0x3,
164         LTSSM_POLLING_CONFIGURATION             = 0x4,
165         LTSSM_CONFIG_LINKWIDTH_START            = 0x5,
166         LTSSM_CONFIG_LINKWIDTH_ACCEPT           = 0x6,
167         LTSSM_CONFIG_LANENUM_ACCEPT             = 0x7,
168         LTSSM_CONFIG_LANENUM_WAIT               = 0x8,
169         LTSSM_CONFIG_COMPLETE                   = 0x9,
170         LTSSM_CONFIG_IDLE                       = 0xa,
171         LTSSM_RECOVERY_RCVR_LOCK                = 0xb,
172         LTSSM_RECOVERY_SPEED                    = 0xc,
173         LTSSM_RECOVERY_RCVR_CFG                 = 0xd,
174         LTSSM_RECOVERY_IDLE                     = 0xe,
175         LTSSM_L0                                = 0x10,
176         LTSSM_RX_L0S_ENTRY                      = 0x11,
177         LTSSM_RX_L0S_IDLE                       = 0x12,
178         LTSSM_RX_L0S_FTS                        = 0x13,
179         LTSSM_TX_L0S_ENTRY                      = 0x14,
180         LTSSM_TX_L0S_IDLE                       = 0x15,
181         LTSSM_TX_L0S_FTS                        = 0x16,
182         LTSSM_L1_ENTRY                          = 0x17,
183         LTSSM_L1_IDLE                           = 0x18,
184         LTSSM_L2_IDLE                           = 0x19,
185         LTSSM_L2_TRANSMIT_WAKE                  = 0x1a,
186         LTSSM_DISABLED                          = 0x20,
187         LTSSM_LOOPBACK_ENTRY_MASTER             = 0x21,
188         LTSSM_LOOPBACK_ACTIVE_MASTER            = 0x22,
189         LTSSM_LOOPBACK_EXIT_MASTER              = 0x23,
190         LTSSM_LOOPBACK_ENTRY_SLAVE              = 0x24,
191         LTSSM_LOOPBACK_ACTIVE_SLAVE             = 0x25,
192         LTSSM_LOOPBACK_EXIT_SLAVE               = 0x26,
193         LTSSM_HOT_RESET                         = 0x27,
194         LTSSM_RECOVERY_EQUALIZATION_PHASE0      = 0x28,
195         LTSSM_RECOVERY_EQUALIZATION_PHASE1      = 0x29,
196         LTSSM_RECOVERY_EQUALIZATION_PHASE2      = 0x2a,
197         LTSSM_RECOVERY_EQUALIZATION_PHASE3      = 0x2b,
198 };
199
200 /* PCIe core controller registers */
201 #define CTRL_CORE_BASE_ADDR                     0x18000
202 #define CTRL_CONFIG_REG                         (CTRL_CORE_BASE_ADDR + 0x0)
203 #define     CTRL_MODE_SHIFT                     0x0
204 #define     CTRL_MODE_MASK                      0x1
205 #define     PCIE_CORE_MODE_DIRECT               0x0
206 #define     PCIE_CORE_MODE_COMMAND              0x1
207
208 /* PCIe Central Interrupts Registers */
209 #define CENTRAL_INT_BASE_ADDR                   0x1b000
210 #define HOST_CTRL_INT_STATUS_REG                (CENTRAL_INT_BASE_ADDR + 0x0)
211 #define HOST_CTRL_INT_MASK_REG                  (CENTRAL_INT_BASE_ADDR + 0x4)
212 #define     PCIE_IRQ_CMDQ_INT                   BIT(0)
213 #define     PCIE_IRQ_MSI_STATUS_INT             BIT(1)
214 #define     PCIE_IRQ_CMD_SENT_DONE              BIT(3)
215 #define     PCIE_IRQ_DMA_INT                    BIT(4)
216 #define     PCIE_IRQ_IB_DXFERDONE               BIT(5)
217 #define     PCIE_IRQ_OB_DXFERDONE               BIT(6)
218 #define     PCIE_IRQ_OB_RXFERDONE               BIT(7)
219 #define     PCIE_IRQ_COMPQ_INT                  BIT(12)
220 #define     PCIE_IRQ_DIR_RD_DDR_DET             BIT(13)
221 #define     PCIE_IRQ_DIR_WR_DDR_DET             BIT(14)
222 #define     PCIE_IRQ_CORE_INT                   BIT(16)
223 #define     PCIE_IRQ_CORE_INT_PIO               BIT(17)
224 #define     PCIE_IRQ_DPMU_INT                   BIT(18)
225 #define     PCIE_IRQ_PCIE_MIS_INT               BIT(19)
226 #define     PCIE_IRQ_MSI_INT1_DET               BIT(20)
227 #define     PCIE_IRQ_MSI_INT2_DET               BIT(21)
228 #define     PCIE_IRQ_RC_DBELL_DET               BIT(22)
229 #define     PCIE_IRQ_EP_STATUS                  BIT(23)
230 #define     PCIE_IRQ_ALL_MASK                   GENMASK(31, 0)
231 #define     PCIE_IRQ_ENABLE_INTS_MASK           PCIE_IRQ_CORE_INT
232
233 /* Transaction types */
234 #define PCIE_CONFIG_RD_TYPE0                    0x8
235 #define PCIE_CONFIG_RD_TYPE1                    0x9
236 #define PCIE_CONFIG_WR_TYPE0                    0xa
237 #define PCIE_CONFIG_WR_TYPE1                    0xb
238
239 #define PCIE_CONF_BUS(bus)                      (((bus) & 0xff) << 20)
240 #define PCIE_CONF_DEV(dev)                      (((dev) & 0x1f) << 15)
241 #define PCIE_CONF_FUNC(fun)                     (((fun) & 0x7)  << 12)
242 #define PCIE_CONF_REG(reg)                      ((reg) & 0xffc)
243 #define PCIE_CONF_ADDR(bus, devfn, where)       \
244         (PCIE_CONF_BUS(bus) | PCIE_CONF_DEV(PCI_SLOT(devfn))    | \
245          PCIE_CONF_FUNC(PCI_FUNC(devfn)) | PCIE_CONF_REG(where))
246
247 #define PIO_RETRY_CNT                   750000 /* 1.5 s */
248 #define PIO_RETRY_DELAY                 2 /* 2 us*/
249
250 #define LINK_WAIT_MAX_RETRIES           10
251 #define LINK_WAIT_USLEEP_MIN            90000
252 #define LINK_WAIT_USLEEP_MAX            100000
253
254 #define MSI_IRQ_NUM                     32
255
256 struct advk_pcie {
257         struct platform_device *pdev;
258         void __iomem *base;
259         struct list_head resources;
260         struct {
261                 phys_addr_t match;
262                 phys_addr_t remap;
263                 phys_addr_t mask;
264                 u32 actions;
265         } wins[OB_WIN_COUNT];
266         u8 wins_count;
267         struct irq_domain *irq_domain;
268         struct irq_chip irq_chip;
269         raw_spinlock_t irq_lock;
270         struct irq_domain *msi_domain;
271         struct irq_domain *msi_inner_domain;
272         struct irq_chip msi_bottom_irq_chip;
273         struct irq_chip msi_irq_chip;
274         struct msi_domain_info msi_domain_info;
275         DECLARE_BITMAP(msi_used, MSI_IRQ_NUM);
276         struct mutex msi_used_lock;
277         u16 msi_msg;
278         int root_bus_nr;
279         int link_gen;
280         struct gpio_desc *reset_gpio;
281 };
282
283 static inline void advk_writel(struct advk_pcie *pcie, u32 val, u64 reg)
284 {
285         writel(val, pcie->base + reg);
286 }
287
288 static inline u32 advk_readl(struct advk_pcie *pcie, u64 reg)
289 {
290         return readl(pcie->base + reg);
291 }
292
293 static u8 advk_pcie_ltssm_state(struct advk_pcie *pcie)
294 {
295         u32 val;
296         u8 ltssm_state;
297
298         val = advk_readl(pcie, CFG_REG);
299         ltssm_state = (val >> LTSSM_SHIFT) & LTSSM_MASK;
300         return ltssm_state;
301 }
302
303 static inline bool advk_pcie_link_up(struct advk_pcie *pcie)
304 {
305         /* check if LTSSM is in normal operation - some L* state */
306         u8 ltssm_state = advk_pcie_ltssm_state(pcie);
307         return ltssm_state >= LTSSM_L0 && ltssm_state < LTSSM_DISABLED;
308 }
309
310 static inline bool advk_pcie_link_training(struct advk_pcie *pcie)
311 {
312         /*
313           * According to PCIe Base specification 3.0, Table 4-14: Link
314           * Status Mapped to the LTSSM is Link Training mapped to LTSSM
315           * Configuration and Recovery states.
316           */
317         u8 ltssm_state = advk_pcie_ltssm_state(pcie);
318         return ((ltssm_state >= LTSSM_CONFIG_LINKWIDTH_START &&
319                   ltssm_state < LTSSM_L0) ||
320                 (ltssm_state >= LTSSM_RECOVERY_EQUALIZATION_PHASE0 &&
321                   ltssm_state <= LTSSM_RECOVERY_EQUALIZATION_PHASE3));
322 }
323
324 static int advk_pcie_wait_for_link(struct advk_pcie *pcie)
325 {
326         int retries;
327
328         /* check if the link is up or not */
329         for (retries = 0; retries < LINK_WAIT_MAX_RETRIES; retries++) {
330                 if (advk_pcie_link_up(pcie))
331                         return 0;
332
333                 usleep_range(LINK_WAIT_USLEEP_MIN, LINK_WAIT_USLEEP_MAX);
334         }
335
336         return -ETIMEDOUT;
337 }
338
339 static void advk_pcie_issue_perst(struct advk_pcie *pcie)
340 {
341         if (!pcie->reset_gpio)
342                 return;
343
344         /* 10ms delay is needed for some cards */
345         dev_info(&pcie->pdev->dev, "issuing PERST via reset GPIO for 10ms\n");
346         gpiod_set_value_cansleep(pcie->reset_gpio, 1);
347         usleep_range(10000, 11000);
348         gpiod_set_value_cansleep(pcie->reset_gpio, 0);
349 }
350
351 static void advk_pcie_train_link(struct advk_pcie *pcie)
352 {
353         struct device *dev = &pcie->pdev->dev;
354         u32 reg;
355         int ret;
356
357         /*
358          * Setup PCIe rev / gen compliance based on device tree property
359          * 'max-link-speed' which also forces maximal link speed.
360          */
361         reg = advk_readl(pcie, PCIE_CORE_CTRL0_REG);
362         reg &= ~PCIE_GEN_SEL_MSK;
363         if (pcie->link_gen == 3)
364                 reg |= SPEED_GEN_3;
365         else if (pcie->link_gen == 2)
366                 reg |= SPEED_GEN_2;
367         else
368                 reg |= SPEED_GEN_1;
369         advk_writel(pcie, reg, PCIE_CORE_CTRL0_REG);
370
371         /*
372          * Set maximal link speed value also into PCIe Link Control 2 register.
373          * Armada 3700 Functional Specification says that default value is based
374          * on SPEED_GEN but tests showed that default value is always 8.0 GT/s.
375          */
376         reg = advk_readl(pcie, PCIE_CORE_PCIEXP_CAP + PCI_EXP_LNKCTL2);
377         reg &= ~PCI_EXP_LNKCTL2_TLS;
378         if (pcie->link_gen == 3)
379                 reg |= PCI_EXP_LNKCTL2_TLS_8_0GT;
380         else if (pcie->link_gen == 2)
381                 reg |= PCI_EXP_LNKCTL2_TLS_5_0GT;
382         else
383                 reg |= PCI_EXP_LNKCTL2_TLS_2_5GT;
384         advk_writel(pcie, reg, PCIE_CORE_PCIEXP_CAP + PCI_EXP_LNKCTL2);
385
386         /* Enable link training after selecting PCIe generation */
387         reg = advk_readl(pcie, PCIE_CORE_CTRL0_REG);
388         reg |= LINK_TRAINING_EN;
389         advk_writel(pcie, reg, PCIE_CORE_CTRL0_REG);
390
391         /*
392          * Reset PCIe card via PERST# signal. Some cards are not detected
393          * during link training when they are in some non-initial state.
394          */
395         advk_pcie_issue_perst(pcie);
396
397         /*
398          * PERST# signal could have been asserted by pinctrl subsystem before
399          * probe() callback has been called or issued explicitly by reset gpio
400          * function advk_pcie_issue_perst(), making the endpoint going into
401          * fundamental reset. As required by PCI Express spec (PCI Express
402          * Base Specification, REV. 4.0 PCI Express, February 19 2014, 6.6.1
403          * Conventional Reset) a delay for at least 100ms after such a reset
404          * before sending a Configuration Request to the device is needed.
405          * So wait until PCIe link is up. Function advk_pcie_wait_for_link()
406          * waits for link at least 900ms.
407          */
408         ret = advk_pcie_wait_for_link(pcie);
409         if (ret < 0)
410                 dev_err(dev, "link never came up\n");
411         else
412                 dev_info(dev, "link up\n");
413 }
414
415 /*
416  * Set PCIe address window register which could be used for memory
417  * mapping.
418  */
419 static void advk_pcie_set_ob_win(struct advk_pcie *pcie, u8 win_num,
420                                  phys_addr_t match, phys_addr_t remap,
421                                  phys_addr_t mask, u32 actions)
422 {
423         advk_writel(pcie, OB_WIN_ENABLE |
424                           lower_32_bits(match), OB_WIN_MATCH_LS(win_num));
425         advk_writel(pcie, upper_32_bits(match), OB_WIN_MATCH_MS(win_num));
426         advk_writel(pcie, lower_32_bits(remap), OB_WIN_REMAP_LS(win_num));
427         advk_writel(pcie, upper_32_bits(remap), OB_WIN_REMAP_MS(win_num));
428         advk_writel(pcie, lower_32_bits(mask), OB_WIN_MASK_LS(win_num));
429         advk_writel(pcie, upper_32_bits(mask), OB_WIN_MASK_MS(win_num));
430         advk_writel(pcie, actions, OB_WIN_ACTIONS(win_num));
431 }
432
433 static void advk_pcie_disable_ob_win(struct advk_pcie *pcie, u8 win_num)
434 {
435         advk_writel(pcie, 0, OB_WIN_MATCH_LS(win_num));
436         advk_writel(pcie, 0, OB_WIN_MATCH_MS(win_num));
437         advk_writel(pcie, 0, OB_WIN_REMAP_LS(win_num));
438         advk_writel(pcie, 0, OB_WIN_REMAP_MS(win_num));
439         advk_writel(pcie, 0, OB_WIN_MASK_LS(win_num));
440         advk_writel(pcie, 0, OB_WIN_MASK_MS(win_num));
441         advk_writel(pcie, 0, OB_WIN_ACTIONS(win_num));
442 }
443
444 static void advk_pcie_setup_hw(struct advk_pcie *pcie)
445 {
446         u32 reg;
447         int i;
448
449         /* Set to Direct mode */
450         reg = advk_readl(pcie, CTRL_CONFIG_REG);
451         reg &= ~(CTRL_MODE_MASK << CTRL_MODE_SHIFT);
452         reg |= ((PCIE_CORE_MODE_DIRECT & CTRL_MODE_MASK) << CTRL_MODE_SHIFT);
453         advk_writel(pcie, reg, CTRL_CONFIG_REG);
454
455         /* Set PCI global control register to RC mode */
456         reg = advk_readl(pcie, PCIE_CORE_CTRL0_REG);
457         reg |= (IS_RC_MSK << IS_RC_SHIFT);
458         advk_writel(pcie, reg, PCIE_CORE_CTRL0_REG);
459
460         /* Set Advanced Error Capabilities and Control PF0 register */
461         reg = PCIE_CORE_ERR_CAPCTL_ECRC_CHK_TX |
462                 PCIE_CORE_ERR_CAPCTL_ECRC_CHK_TX_EN |
463                 PCIE_CORE_ERR_CAPCTL_ECRC_CHCK |
464                 PCIE_CORE_ERR_CAPCTL_ECRC_CHCK_RCV;
465         advk_writel(pcie, reg, PCIE_CORE_ERR_CAPCTL_REG);
466
467         /* Set PCIe Device Control register */
468         reg = advk_readl(pcie, PCIE_CORE_PCIEXP_CAP + PCI_EXP_DEVCTL);
469         reg &= ~PCI_EXP_DEVCTL_RELAX_EN;
470         reg &= ~PCI_EXP_DEVCTL_NOSNOOP_EN;
471         reg &= ~PCI_EXP_DEVCTL_PAYLOAD;
472         reg &= ~PCI_EXP_DEVCTL_READRQ;
473         reg |= PCI_EXP_DEVCTL_PAYLOAD_512B;
474         reg |= PCI_EXP_DEVCTL_READRQ_512B;
475         advk_writel(pcie, reg, PCIE_CORE_PCIEXP_CAP + PCI_EXP_DEVCTL);
476
477         /* Program PCIe Control 2 to disable strict ordering */
478         reg = PCIE_CORE_CTRL2_RESERVED |
479                 PCIE_CORE_CTRL2_TD_ENABLE;
480         advk_writel(pcie, reg, PCIE_CORE_CTRL2_REG);
481
482         /* Set lane X1 */
483         reg = advk_readl(pcie, PCIE_CORE_CTRL0_REG);
484         reg &= ~LANE_CNT_MSK;
485         reg |= LANE_COUNT_1;
486         advk_writel(pcie, reg, PCIE_CORE_CTRL0_REG);
487
488         /* Enable MSI */
489         reg = advk_readl(pcie, PCIE_CORE_CTRL2_REG);
490         reg |= PCIE_CORE_CTRL2_MSI_ENABLE;
491         advk_writel(pcie, reg, PCIE_CORE_CTRL2_REG);
492
493         /* Clear all interrupts */
494         advk_writel(pcie, PCIE_MSI_ALL_MASK, PCIE_MSI_STATUS_REG);
495         advk_writel(pcie, PCIE_ISR0_ALL_MASK, PCIE_ISR0_REG);
496         advk_writel(pcie, PCIE_ISR1_ALL_MASK, PCIE_ISR1_REG);
497         advk_writel(pcie, PCIE_IRQ_ALL_MASK, HOST_CTRL_INT_STATUS_REG);
498
499         /* Disable All ISR0/1 Sources */
500         reg = PCIE_ISR0_ALL_MASK;
501         reg &= ~PCIE_ISR0_MSI_INT_PENDING;
502         advk_writel(pcie, reg, PCIE_ISR0_MASK_REG);
503
504         advk_writel(pcie, PCIE_ISR1_ALL_MASK, PCIE_ISR1_MASK_REG);
505
506         /* Unmask all MSI's */
507         advk_writel(pcie, ~(u32)PCIE_MSI_ALL_MASK, PCIE_MSI_MASK_REG);
508
509         /* Enable summary interrupt for GIC SPI source */
510         reg = PCIE_IRQ_ALL_MASK & (~PCIE_IRQ_ENABLE_INTS_MASK);
511         advk_writel(pcie, reg, HOST_CTRL_INT_MASK_REG);
512
513         /*
514          * Enable AXI address window location generation:
515          * When it is enabled, the default outbound window
516          * configurations (Default User Field: 0xD0074CFC)
517          * are used to transparent address translation for
518          * the outbound transactions. Thus, PCIe address
519          * windows are not required for transparent memory
520          * access when default outbound window configuration
521          * is set for memory access.
522          */
523         reg = advk_readl(pcie, PCIE_CORE_CTRL2_REG);
524         reg |= PCIE_CORE_CTRL2_OB_WIN_ENABLE;
525         advk_writel(pcie, reg, PCIE_CORE_CTRL2_REG);
526
527         /*
528          * Set memory access in Default User Field so it
529          * is not required to configure PCIe address for
530          * transparent memory access.
531          */
532         advk_writel(pcie, OB_WIN_TYPE_MEM, OB_WIN_DEFAULT_ACTIONS);
533
534         /*
535          * Bypass the address window mapping for PIO:
536          * Since PIO access already contains all required
537          * info over AXI interface by PIO registers, the
538          * address window is not required.
539          */
540         reg = advk_readl(pcie, PIO_CTRL);
541         reg |= PIO_CTRL_ADDR_WIN_DISABLE;
542         advk_writel(pcie, reg, PIO_CTRL);
543
544         /*
545          * Configure PCIe address windows for non-memory or
546          * non-transparent access as by default PCIe uses
547          * transparent memory access.
548          */
549         for (i = 0; i < pcie->wins_count; i++)
550                 advk_pcie_set_ob_win(pcie, i,
551                                      pcie->wins[i].match, pcie->wins[i].remap,
552                                      pcie->wins[i].mask, pcie->wins[i].actions);
553
554         /* Disable remaining PCIe outbound windows */
555         for (i = pcie->wins_count; i < OB_WIN_COUNT; i++)
556                 advk_pcie_disable_ob_win(pcie, i);
557
558         advk_pcie_train_link(pcie);
559
560         reg = advk_readl(pcie, PCIE_CORE_CMD_STATUS_REG);
561         reg |= PCIE_CORE_CMD_MEM_ACCESS_EN |
562                 PCIE_CORE_CMD_IO_ACCESS_EN |
563                 PCIE_CORE_CMD_MEM_IO_REQ_EN;
564         advk_writel(pcie, reg, PCIE_CORE_CMD_STATUS_REG);
565 }
566
567 static int advk_pcie_check_pio_status(struct advk_pcie *pcie, u32 *val)
568 {
569         struct device *dev = &pcie->pdev->dev;
570         u32 reg;
571         unsigned int status;
572         char *strcomp_status, *str_posted;
573
574         reg = advk_readl(pcie, PIO_STAT);
575         status = (reg & PIO_COMPLETION_STATUS_MASK) >>
576                 PIO_COMPLETION_STATUS_SHIFT;
577
578         /*
579          * According to HW spec, the PIO status check sequence as below:
580          * 1) even if COMPLETION_STATUS(bit9:7) indicates successful,
581          *    it still needs to check Error Status(bit11), only when this bit
582          *    indicates no error happen, the operation is successful.
583          * 2) value Unsupported Request(1) of COMPLETION_STATUS(bit9:7) only
584          *    means a PIO write error, and for PIO read it is successful with
585          *    a read value of 0xFFFFFFFF.
586          * 3) value Completion Retry Status(CRS) of COMPLETION_STATUS(bit9:7)
587          *    only means a PIO write error, and for PIO read it is successful
588          *    with a read value of 0xFFFF0001.
589          * 4) value Completer Abort (CA) of COMPLETION_STATUS(bit9:7) means
590          *    error for both PIO read and PIO write operation.
591          * 5) other errors are indicated as 'unknown'.
592          */
593         switch (status) {
594         case PIO_COMPLETION_STATUS_OK:
595                 if (reg & PIO_ERR_STATUS) {
596                         strcomp_status = "COMP_ERR";
597                         break;
598                 }
599                 /* Get the read result */
600                 if (val)
601                         *val = advk_readl(pcie, PIO_RD_DATA);
602                 /* No error */
603                 strcomp_status = NULL;
604                 break;
605         case PIO_COMPLETION_STATUS_UR:
606                 strcomp_status = "UR";
607                 break;
608         case PIO_COMPLETION_STATUS_CRS:
609                 /* PCIe r4.0, sec 2.3.2, says:
610                  * If CRS Software Visibility is not enabled, the Root Complex
611                  * must re-issue the Configuration Request as a new Request.
612                  * A Root Complex implementation may choose to limit the number
613                  * of Configuration Request/CRS Completion Status loops before
614                  * determining that something is wrong with the target of the
615                  * Request and taking appropriate action, e.g., complete the
616                  * Request to the host as a failed transaction.
617                  *
618                  * To simplify implementation do not re-issue the Configuration
619                  * Request and complete the Request as a failed transaction.
620                  */
621                 strcomp_status = "CRS";
622                 break;
623         case PIO_COMPLETION_STATUS_CA:
624                 strcomp_status = "CA";
625                 break;
626         default:
627                 strcomp_status = "Unknown";
628                 break;
629         }
630
631         if (!strcomp_status)
632                 return 0;
633
634         if (reg & PIO_NON_POSTED_REQ)
635                 str_posted = "Non-posted";
636         else
637                 str_posted = "Posted";
638
639         dev_dbg(dev, "%s PIO Response Status: %s, %#x @ %#x\n",
640                 str_posted, strcomp_status, reg, advk_readl(pcie, PIO_ADDR_LS));
641
642         return -EFAULT;
643 }
644
645 static int advk_pcie_wait_pio(struct advk_pcie *pcie)
646 {
647         struct device *dev = &pcie->pdev->dev;
648         int i;
649
650         for (i = 0; i < PIO_RETRY_CNT; i++) {
651                 u32 start, isr;
652
653                 start = advk_readl(pcie, PIO_START);
654                 isr = advk_readl(pcie, PIO_ISR);
655                 if (!start && isr)
656                         return 0;
657                 udelay(PIO_RETRY_DELAY);
658         }
659
660         dev_err(dev, "PIO read/write transfer time out\n");
661         return -ETIMEDOUT;
662 }
663
664 static bool advk_pcie_pio_is_running(struct advk_pcie *pcie)
665 {
666         struct device *dev = &pcie->pdev->dev;
667
668         /*
669          * Trying to start a new PIO transfer when previous has not completed
670          * cause External Abort on CPU which results in kernel panic:
671          *
672          *     SError Interrupt on CPU0, code 0xbf000002 -- SError
673          *     Kernel panic - not syncing: Asynchronous SError Interrupt
674          *
675          * Functions advk_pcie_rd_conf() and advk_pcie_wr_conf() are protected
676          * by raw_spin_lock_irqsave() at pci_lock_config() level to prevent
677          * concurrent calls at the same time. But because PIO transfer may take
678          * about 1.5s when link is down or card is disconnected, it means that
679          * advk_pcie_wait_pio() does not always have to wait for completion.
680          *
681          * Some versions of ARM Trusted Firmware handles this External Abort at
682          * EL3 level and mask it to prevent kernel panic. Relevant TF-A commit:
683          * https://git.trustedfirmware.org/TF-A/trusted-firmware-a.git/commit/?id=3c7dcdac5c50
684          */
685         if (advk_readl(pcie, PIO_START)) {
686                 dev_err(dev, "Previous PIO read/write transfer is still running\n");
687                 return true;
688         }
689
690         return false;
691 }
692
693 static bool advk_pcie_valid_device(struct advk_pcie *pcie, struct pci_bus *bus,
694                                   int devfn)
695 {
696         if ((bus->number == pcie->root_bus_nr) && PCI_SLOT(devfn) != 0)
697                 return false;
698
699         /*
700          * If the link goes down after we check for link-up, nothing bad
701          * happens but the config access times out.
702          */
703         if (bus->number != pcie->root_bus_nr && !advk_pcie_link_up(pcie))
704                 return false;
705
706         return true;
707 }
708
709 static int advk_pcie_rd_conf(struct pci_bus *bus, u32 devfn,
710                              int where, int size, u32 *val)
711 {
712         struct advk_pcie *pcie = bus->sysdata;
713         u32 reg;
714         int ret;
715
716         if (!advk_pcie_valid_device(pcie, bus, devfn)) {
717                 *val = 0xffffffff;
718                 return PCIBIOS_DEVICE_NOT_FOUND;
719         }
720
721         if (advk_pcie_pio_is_running(pcie)) {
722                 *val = 0xffffffff;
723                 return PCIBIOS_SET_FAILED;
724         }
725
726         /* Program the control register */
727         reg = advk_readl(pcie, PIO_CTRL);
728         reg &= ~PIO_CTRL_TYPE_MASK;
729         if (bus->number ==  pcie->root_bus_nr)
730                 reg |= PCIE_CONFIG_RD_TYPE0;
731         else
732                 reg |= PCIE_CONFIG_RD_TYPE1;
733         advk_writel(pcie, reg, PIO_CTRL);
734
735         /* Program the address registers */
736         reg = PCIE_CONF_ADDR(bus->number, devfn, where);
737         advk_writel(pcie, reg, PIO_ADDR_LS);
738         advk_writel(pcie, 0, PIO_ADDR_MS);
739
740         /* Program the data strobe */
741         advk_writel(pcie, 0xf, PIO_WR_DATA_STRB);
742
743         /* Clear PIO DONE ISR and start the transfer */
744         advk_writel(pcie, 1, PIO_ISR);
745         advk_writel(pcie, 1, PIO_START);
746
747         ret = advk_pcie_wait_pio(pcie);
748         if (ret < 0) {
749                 *val = 0xffffffff;
750                 return PCIBIOS_SET_FAILED;
751         }
752
753         /* Check PIO status and get the read result */
754         ret = advk_pcie_check_pio_status(pcie, val);
755         if (ret < 0) {
756                 *val = 0xffffffff;
757                 return PCIBIOS_SET_FAILED;
758         }
759
760         if (size == 1)
761                 *val = (*val >> (8 * (where & 3))) & 0xff;
762         else if (size == 2)
763                 *val = (*val >> (8 * (where & 3))) & 0xffff;
764
765         return PCIBIOS_SUCCESSFUL;
766 }
767
768 static int advk_pcie_wr_conf(struct pci_bus *bus, u32 devfn,
769                                 int where, int size, u32 val)
770 {
771         struct advk_pcie *pcie = bus->sysdata;
772         u32 reg;
773         u32 data_strobe = 0x0;
774         int offset;
775         int ret;
776
777         if (!advk_pcie_valid_device(pcie, bus, devfn))
778                 return PCIBIOS_DEVICE_NOT_FOUND;
779
780         if (where % size)
781                 return PCIBIOS_SET_FAILED;
782
783         if (advk_pcie_pio_is_running(pcie))
784                 return PCIBIOS_SET_FAILED;
785
786         /* Program the control register */
787         reg = advk_readl(pcie, PIO_CTRL);
788         reg &= ~PIO_CTRL_TYPE_MASK;
789         if (bus->number == pcie->root_bus_nr)
790                 reg |= PCIE_CONFIG_WR_TYPE0;
791         else
792                 reg |= PCIE_CONFIG_WR_TYPE1;
793         advk_writel(pcie, reg, PIO_CTRL);
794
795         /* Program the address registers */
796         reg = PCIE_CONF_ADDR(bus->number, devfn, where);
797         advk_writel(pcie, reg, PIO_ADDR_LS);
798         advk_writel(pcie, 0, PIO_ADDR_MS);
799
800         /* Calculate the write strobe */
801         offset      = where & 0x3;
802         reg         = val << (8 * offset);
803         data_strobe = GENMASK(size - 1, 0) << offset;
804
805         /* Program the data register */
806         advk_writel(pcie, reg, PIO_WR_DATA);
807
808         /* Program the data strobe */
809         advk_writel(pcie, data_strobe, PIO_WR_DATA_STRB);
810
811         /* Clear PIO DONE ISR and start the transfer */
812         advk_writel(pcie, 1, PIO_ISR);
813         advk_writel(pcie, 1, PIO_START);
814
815         ret = advk_pcie_wait_pio(pcie);
816         if (ret < 0)
817                 return PCIBIOS_SET_FAILED;
818
819         ret = advk_pcie_check_pio_status(pcie, NULL);
820         if (ret < 0)
821                 return PCIBIOS_SET_FAILED;
822
823         return PCIBIOS_SUCCESSFUL;
824 }
825
826 static struct pci_ops advk_pcie_ops = {
827         .read = advk_pcie_rd_conf,
828         .write = advk_pcie_wr_conf,
829 };
830
831 static void advk_msi_irq_compose_msi_msg(struct irq_data *data,
832                                          struct msi_msg *msg)
833 {
834         struct advk_pcie *pcie = irq_data_get_irq_chip_data(data);
835         phys_addr_t msi_msg = virt_to_phys(&pcie->msi_msg);
836
837         msg->address_lo = lower_32_bits(msi_msg);
838         msg->address_hi = upper_32_bits(msi_msg);
839         msg->data = data->hwirq;
840 }
841
842 static int advk_msi_set_affinity(struct irq_data *irq_data,
843                                  const struct cpumask *mask, bool force)
844 {
845         return -EINVAL;
846 }
847
848 static int advk_msi_irq_domain_alloc(struct irq_domain *domain,
849                                      unsigned int virq,
850                                      unsigned int nr_irqs, void *args)
851 {
852         struct advk_pcie *pcie = domain->host_data;
853         int hwirq, i;
854
855         mutex_lock(&pcie->msi_used_lock);
856         hwirq = bitmap_find_free_region(pcie->msi_used, MSI_IRQ_NUM,
857                                         order_base_2(nr_irqs));
858         mutex_unlock(&pcie->msi_used_lock);
859         if (hwirq < 0)
860                 return -ENOSPC;
861
862         for (i = 0; i < nr_irqs; i++)
863                 irq_domain_set_info(domain, virq + i, hwirq + i,
864                                     &pcie->msi_bottom_irq_chip,
865                                     domain->host_data, handle_simple_irq,
866                                     NULL, NULL);
867
868         return 0;
869 }
870
871 static void advk_msi_irq_domain_free(struct irq_domain *domain,
872                                      unsigned int virq, unsigned int nr_irqs)
873 {
874         struct irq_data *d = irq_domain_get_irq_data(domain, virq);
875         struct advk_pcie *pcie = domain->host_data;
876
877         mutex_lock(&pcie->msi_used_lock);
878         bitmap_release_region(pcie->msi_used, d->hwirq, order_base_2(nr_irqs));
879         mutex_unlock(&pcie->msi_used_lock);
880 }
881
882 static const struct irq_domain_ops advk_msi_domain_ops = {
883         .alloc = advk_msi_irq_domain_alloc,
884         .free = advk_msi_irq_domain_free,
885 };
886
887 static void advk_pcie_irq_mask(struct irq_data *d)
888 {
889         struct advk_pcie *pcie = d->domain->host_data;
890         irq_hw_number_t hwirq = irqd_to_hwirq(d);
891         unsigned long flags;
892         u32 mask;
893
894         raw_spin_lock_irqsave(&pcie->irq_lock, flags);
895         mask = advk_readl(pcie, PCIE_ISR1_MASK_REG);
896         mask |= PCIE_ISR1_INTX_ASSERT(hwirq);
897         advk_writel(pcie, mask, PCIE_ISR1_MASK_REG);
898         raw_spin_unlock_irqrestore(&pcie->irq_lock, flags);
899 }
900
901 static void advk_pcie_irq_unmask(struct irq_data *d)
902 {
903         struct advk_pcie *pcie = d->domain->host_data;
904         irq_hw_number_t hwirq = irqd_to_hwirq(d);
905         unsigned long flags;
906         u32 mask;
907
908         raw_spin_lock_irqsave(&pcie->irq_lock, flags);
909         mask = advk_readl(pcie, PCIE_ISR1_MASK_REG);
910         mask &= ~PCIE_ISR1_INTX_ASSERT(hwirq);
911         advk_writel(pcie, mask, PCIE_ISR1_MASK_REG);
912         raw_spin_unlock_irqrestore(&pcie->irq_lock, flags);
913 }
914
915 static int advk_pcie_irq_map(struct irq_domain *h,
916                              unsigned int virq, irq_hw_number_t hwirq)
917 {
918         struct advk_pcie *pcie = h->host_data;
919
920         advk_pcie_irq_mask(irq_get_irq_data(virq));
921         irq_set_status_flags(virq, IRQ_LEVEL);
922         irq_set_chip_and_handler(virq, &pcie->irq_chip,
923                                  handle_level_irq);
924         irq_set_chip_data(virq, pcie);
925
926         return 0;
927 }
928
929 static const struct irq_domain_ops advk_pcie_irq_domain_ops = {
930         .map = advk_pcie_irq_map,
931         .xlate = irq_domain_xlate_onecell,
932 };
933
934 static int advk_pcie_init_msi_irq_domain(struct advk_pcie *pcie)
935 {
936         struct device *dev = &pcie->pdev->dev;
937         struct device_node *node = dev->of_node;
938         struct irq_chip *bottom_ic, *msi_ic;
939         struct msi_domain_info *msi_di;
940         phys_addr_t msi_msg_phys;
941
942         mutex_init(&pcie->msi_used_lock);
943
944         bottom_ic = &pcie->msi_bottom_irq_chip;
945
946         bottom_ic->name = "MSI";
947         bottom_ic->irq_compose_msi_msg = advk_msi_irq_compose_msi_msg;
948         bottom_ic->irq_set_affinity = advk_msi_set_affinity;
949
950         msi_ic = &pcie->msi_irq_chip;
951         msi_ic->name = "advk-MSI";
952
953         msi_di = &pcie->msi_domain_info;
954         msi_di->flags = MSI_FLAG_USE_DEF_DOM_OPS | MSI_FLAG_USE_DEF_CHIP_OPS |
955                 MSI_FLAG_MULTI_PCI_MSI;
956         msi_di->chip = msi_ic;
957
958         msi_msg_phys = virt_to_phys(&pcie->msi_msg);
959
960         advk_writel(pcie, lower_32_bits(msi_msg_phys),
961                     PCIE_MSI_ADDR_LOW_REG);
962         advk_writel(pcie, upper_32_bits(msi_msg_phys),
963                     PCIE_MSI_ADDR_HIGH_REG);
964
965         pcie->msi_inner_domain =
966                 irq_domain_add_linear(NULL, MSI_IRQ_NUM,
967                                       &advk_msi_domain_ops, pcie);
968         if (!pcie->msi_inner_domain)
969                 return -ENOMEM;
970
971         pcie->msi_domain =
972                 pci_msi_create_irq_domain(of_node_to_fwnode(node),
973                                           msi_di, pcie->msi_inner_domain);
974         if (!pcie->msi_domain) {
975                 irq_domain_remove(pcie->msi_inner_domain);
976                 return -ENOMEM;
977         }
978
979         return 0;
980 }
981
982 static void advk_pcie_remove_msi_irq_domain(struct advk_pcie *pcie)
983 {
984         irq_domain_remove(pcie->msi_domain);
985         irq_domain_remove(pcie->msi_inner_domain);
986 }
987
988 static int advk_pcie_init_irq_domain(struct advk_pcie *pcie)
989 {
990         struct device *dev = &pcie->pdev->dev;
991         struct device_node *node = dev->of_node;
992         struct device_node *pcie_intc_node;
993         struct irq_chip *irq_chip;
994         int ret = 0;
995
996         raw_spin_lock_init(&pcie->irq_lock);
997
998         pcie_intc_node =  of_get_next_child(node, NULL);
999         if (!pcie_intc_node) {
1000                 dev_err(dev, "No PCIe Intc node found\n");
1001                 return -ENODEV;
1002         }
1003
1004         irq_chip = &pcie->irq_chip;
1005
1006         irq_chip->name = devm_kasprintf(dev, GFP_KERNEL, "%s-irq",
1007                                         dev_name(dev));
1008         if (!irq_chip->name) {
1009                 ret = -ENOMEM;
1010                 goto out_put_node;
1011         }
1012
1013         irq_chip->irq_mask = advk_pcie_irq_mask;
1014         irq_chip->irq_mask_ack = advk_pcie_irq_mask;
1015         irq_chip->irq_unmask = advk_pcie_irq_unmask;
1016
1017         pcie->irq_domain =
1018                 irq_domain_add_linear(pcie_intc_node, PCI_NUM_INTX,
1019                                       &advk_pcie_irq_domain_ops, pcie);
1020         if (!pcie->irq_domain) {
1021                 dev_err(dev, "Failed to get a INTx IRQ domain\n");
1022                 ret = -ENOMEM;
1023                 goto out_put_node;
1024         }
1025
1026 out_put_node:
1027         of_node_put(pcie_intc_node);
1028         return ret;
1029 }
1030
1031 static void advk_pcie_remove_irq_domain(struct advk_pcie *pcie)
1032 {
1033         irq_domain_remove(pcie->irq_domain);
1034 }
1035
1036 static void advk_pcie_handle_msi(struct advk_pcie *pcie)
1037 {
1038         u32 msi_val, msi_mask, msi_status, msi_idx;
1039         int virq;
1040
1041         msi_mask = advk_readl(pcie, PCIE_MSI_MASK_REG);
1042         msi_val = advk_readl(pcie, PCIE_MSI_STATUS_REG);
1043         msi_status = msi_val & ((~msi_mask) & PCIE_MSI_ALL_MASK);
1044
1045         for (msi_idx = 0; msi_idx < MSI_IRQ_NUM; msi_idx++) {
1046                 if (!(BIT(msi_idx) & msi_status))
1047                         continue;
1048
1049                 advk_writel(pcie, BIT(msi_idx), PCIE_MSI_STATUS_REG);
1050                 virq = irq_find_mapping(pcie->msi_inner_domain, msi_idx);
1051                 generic_handle_irq(virq);
1052         }
1053
1054         advk_writel(pcie, PCIE_ISR0_MSI_INT_PENDING,
1055                     PCIE_ISR0_REG);
1056 }
1057
1058 static void advk_pcie_handle_int(struct advk_pcie *pcie)
1059 {
1060         u32 isr0_val, isr0_mask, isr0_status;
1061         u32 isr1_val, isr1_mask, isr1_status;
1062         int i, virq;
1063
1064         isr0_val = advk_readl(pcie, PCIE_ISR0_REG);
1065         isr0_mask = advk_readl(pcie, PCIE_ISR0_MASK_REG);
1066         isr0_status = isr0_val & ((~isr0_mask) & PCIE_ISR0_ALL_MASK);
1067
1068         isr1_val = advk_readl(pcie, PCIE_ISR1_REG);
1069         isr1_mask = advk_readl(pcie, PCIE_ISR1_MASK_REG);
1070         isr1_status = isr1_val & ((~isr1_mask) & PCIE_ISR1_ALL_MASK);
1071
1072         /* Process MSI interrupts */
1073         if (isr0_status & PCIE_ISR0_MSI_INT_PENDING)
1074                 advk_pcie_handle_msi(pcie);
1075
1076         /* Process legacy interrupts */
1077         for (i = 0; i < PCI_NUM_INTX; i++) {
1078                 if (!(isr1_status & PCIE_ISR1_INTX_ASSERT(i)))
1079                         continue;
1080
1081                 advk_writel(pcie, PCIE_ISR1_INTX_ASSERT(i),
1082                             PCIE_ISR1_REG);
1083
1084                 virq = irq_find_mapping(pcie->irq_domain, i);
1085                 generic_handle_irq(virq);
1086         }
1087 }
1088
1089 static irqreturn_t advk_pcie_irq_handler(int irq, void *arg)
1090 {
1091         struct advk_pcie *pcie = arg;
1092         u32 status;
1093
1094         status = advk_readl(pcie, HOST_CTRL_INT_STATUS_REG);
1095         if (!(status & PCIE_IRQ_CORE_INT))
1096                 return IRQ_NONE;
1097
1098         advk_pcie_handle_int(pcie);
1099
1100         /* Clear interrupt */
1101         advk_writel(pcie, PCIE_IRQ_CORE_INT, HOST_CTRL_INT_STATUS_REG);
1102
1103         return IRQ_HANDLED;
1104 }
1105
1106 static int advk_pcie_parse_request_of_pci_ranges(struct advk_pcie *pcie)
1107 {
1108         int err, res_valid = 0;
1109         struct device *dev = &pcie->pdev->dev;
1110         struct device_node *np = dev->of_node;
1111         struct resource_entry *win, *tmp;
1112         resource_size_t iobase;
1113
1114         INIT_LIST_HEAD(&pcie->resources);
1115
1116         err = of_pci_get_host_bridge_resources(np, 0, 0xff, &pcie->resources,
1117                                                &iobase);
1118         if (err)
1119                 return err;
1120
1121         err = devm_request_pci_bus_resources(dev, &pcie->resources);
1122         if (err)
1123                 goto out_release_res;
1124
1125         resource_list_for_each_entry_safe(win, tmp, &pcie->resources) {
1126                 struct resource *res = win->res;
1127
1128                 switch (resource_type(res)) {
1129                 case IORESOURCE_IO:
1130                         err = devm_pci_remap_iospace(dev, res, iobase);
1131                         if (err) {
1132                                 dev_warn(dev, "error %d: failed to map resource %pR\n",
1133                                          err, res);
1134                                 resource_list_destroy_entry(win);
1135                         }
1136                         break;
1137                 case IORESOURCE_MEM:
1138                         res_valid |= !(res->flags & IORESOURCE_PREFETCH);
1139                         break;
1140                 case IORESOURCE_BUS:
1141                         pcie->root_bus_nr = res->start;
1142                         break;
1143                 }
1144         }
1145
1146         if (!res_valid) {
1147                 dev_err(dev, "non-prefetchable memory resource required\n");
1148                 err = -EINVAL;
1149                 goto out_release_res;
1150         }
1151
1152         return 0;
1153
1154 out_release_res:
1155         pci_free_resource_list(&pcie->resources);
1156         return err;
1157 }
1158
1159 static int advk_pcie_probe(struct platform_device *pdev)
1160 {
1161         struct device *dev = &pdev->dev;
1162         struct advk_pcie *pcie;
1163         struct resource *res;
1164         struct pci_bus *bus, *child;
1165         struct pci_host_bridge *bridge;
1166         struct resource_entry *entry;
1167         int ret, irq;
1168
1169         bridge = devm_pci_alloc_host_bridge(dev, sizeof(struct advk_pcie));
1170         if (!bridge)
1171                 return -ENOMEM;
1172
1173         pcie = pci_host_bridge_priv(bridge);
1174         pcie->pdev = pdev;
1175
1176         res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
1177         pcie->base = devm_ioremap_resource(dev, res);
1178         if (IS_ERR(pcie->base))
1179                 return PTR_ERR(pcie->base);
1180
1181         irq = platform_get_irq(pdev, 0);
1182         ret = devm_request_irq(dev, irq, advk_pcie_irq_handler,
1183                                IRQF_SHARED | IRQF_NO_THREAD, "advk-pcie",
1184                                pcie);
1185         if (ret) {
1186                 dev_err(dev, "Failed to register interrupt\n");
1187                 return ret;
1188         }
1189
1190         ret = advk_pcie_parse_request_of_pci_ranges(pcie);
1191         if (ret) {
1192                 dev_err(dev, "Failed to parse resources\n");
1193                 return ret;
1194         }
1195
1196         resource_list_for_each_entry(entry, &pcie->resources) {
1197                 resource_size_t start = entry->res->start;
1198                 resource_size_t size = resource_size(entry->res);
1199                 unsigned long type = resource_type(entry->res);
1200                 u64 win_size;
1201
1202                 /*
1203                  * Aardvark hardware allows to configure also PCIe window
1204                  * for config type 0 and type 1 mapping, but driver uses
1205                  * only PIO for issuing configuration transfers which does
1206                  * not use PCIe window configuration.
1207                  */
1208                 if (type != IORESOURCE_MEM && type != IORESOURCE_MEM_64 &&
1209                     type != IORESOURCE_IO)
1210                         continue;
1211
1212                 /*
1213                  * Skip transparent memory resources. Default outbound access
1214                  * configuration is set to transparent memory access so it
1215                  * does not need window configuration.
1216                  */
1217                 if ((type == IORESOURCE_MEM || type == IORESOURCE_MEM_64) &&
1218                     entry->offset == 0)
1219                         continue;
1220
1221                 /*
1222                  * The n-th PCIe window is configured by tuple (match, remap, mask)
1223                  * and an access to address A uses this window if A matches the
1224                  * match with given mask.
1225                  * So every PCIe window size must be a power of two and every start
1226                  * address must be aligned to window size. Minimal size is 64 KiB
1227                  * because lower 16 bits of mask must be zero. Remapped address
1228                  * may have set only bits from the mask.
1229                  */
1230                 while (pcie->wins_count < OB_WIN_COUNT && size > 0) {
1231                         /* Calculate the largest aligned window size */
1232                         win_size = (1ULL << (fls64(size)-1)) |
1233                                    (start ? (1ULL << __ffs64(start)) : 0);
1234                         win_size = 1ULL << __ffs64(win_size);
1235                         if (win_size < 0x10000)
1236                                 break;
1237
1238                         dev_dbg(dev,
1239                                 "Configuring PCIe window %d: [0x%llx-0x%llx] as %lu\n",
1240                                 pcie->wins_count, (unsigned long long)start,
1241                                 (unsigned long long)start + win_size, type);
1242
1243                         if (type == IORESOURCE_IO) {
1244                                 pcie->wins[pcie->wins_count].actions = OB_WIN_TYPE_IO;
1245                                 pcie->wins[pcie->wins_count].match = pci_pio_to_address(start);
1246                         } else {
1247                                 pcie->wins[pcie->wins_count].actions = OB_WIN_TYPE_MEM;
1248                                 pcie->wins[pcie->wins_count].match = start;
1249                         }
1250                         pcie->wins[pcie->wins_count].remap = start - entry->offset;
1251                         pcie->wins[pcie->wins_count].mask = ~(win_size - 1);
1252
1253                         if (pcie->wins[pcie->wins_count].remap & (win_size - 1))
1254                                 break;
1255
1256                         start += win_size;
1257                         size -= win_size;
1258                         pcie->wins_count++;
1259                 }
1260
1261                 if (size > 0) {
1262                         dev_err(&pcie->pdev->dev,
1263                                 "Invalid PCIe region [0x%llx-0x%llx]\n",
1264                                 (unsigned long long)entry->res->start,
1265                                 (unsigned long long)entry->res->end + 1);
1266                         return -EINVAL;
1267                 }
1268         }
1269
1270         pcie->reset_gpio = devm_fwnode_get_index_gpiod_from_child(dev, "reset",
1271                                                                   0,
1272                                                                   dev_fwnode(dev),
1273                                                                   GPIOD_OUT_LOW,
1274                                                                   "pcie1-reset");
1275         ret = PTR_ERR_OR_ZERO(pcie->reset_gpio);
1276         if (ret) {
1277                 if (ret == -ENOENT) {
1278                         pcie->reset_gpio = NULL;
1279                 } else {
1280                         if (ret != -EPROBE_DEFER)
1281                                 dev_err(dev, "Failed to get reset-gpio: %i\n",
1282                                         ret);
1283                         return ret;
1284                 }
1285         }
1286
1287         ret = of_pci_get_max_link_speed(dev->of_node);
1288         if (ret <= 0 || ret > 3)
1289                 pcie->link_gen = 3;
1290         else
1291                 pcie->link_gen = ret;
1292
1293         advk_pcie_setup_hw(pcie);
1294
1295         ret = advk_pcie_init_irq_domain(pcie);
1296         if (ret) {
1297                 dev_err(dev, "Failed to initialize irq\n");
1298                 return ret;
1299         }
1300
1301         ret = advk_pcie_init_msi_irq_domain(pcie);
1302         if (ret) {
1303                 dev_err(dev, "Failed to initialize irq\n");
1304                 advk_pcie_remove_irq_domain(pcie);
1305                 return ret;
1306         }
1307
1308         list_splice_init(&pcie->resources, &bridge->windows);
1309         bridge->dev.parent = dev;
1310         bridge->sysdata = pcie;
1311         bridge->busnr = 0;
1312         bridge->ops = &advk_pcie_ops;
1313         bridge->map_irq = of_irq_parse_and_map_pci;
1314         bridge->swizzle_irq = pci_common_swizzle;
1315
1316         ret = pci_scan_root_bus_bridge(bridge);
1317         if (ret < 0) {
1318                 advk_pcie_remove_msi_irq_domain(pcie);
1319                 advk_pcie_remove_irq_domain(pcie);
1320                 return ret;
1321         }
1322
1323         bus = bridge->bus;
1324
1325         pci_bus_size_bridges(bus);
1326         pci_bus_assign_resources(bus);
1327
1328         list_for_each_entry(child, &bus->children, node)
1329                 pcie_bus_configure_settings(child);
1330
1331         pci_bus_add_devices(bus);
1332         return 0;
1333 }
1334
1335 static const struct of_device_id advk_pcie_of_match_table[] = {
1336         { .compatible = "marvell,armada-3700-pcie", },
1337         {},
1338 };
1339
1340 static struct platform_driver advk_pcie_driver = {
1341         .driver = {
1342                 .name = "advk-pcie",
1343                 .of_match_table = advk_pcie_of_match_table,
1344                 /* Driver unloading/unbinding currently not supported */
1345                 .suppress_bind_attrs = true,
1346         },
1347         .probe = advk_pcie_probe,
1348 };
1349 builtin_platform_driver(advk_pcie_driver);