Merge tag 'u-boot-amlogic-20210112' of https://gitlab.denx.de/u-boot/custodians/u...
[platform/kernel/u-boot.git] / drivers / pci / pci-uclass.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Copyright (c) 2014 Google, Inc
4  * Written by Simon Glass <sjg@chromium.org>
5  */
6
7 #include <common.h>
8 #include <dm.h>
9 #include <errno.h>
10 #include <init.h>
11 #include <log.h>
12 #include <malloc.h>
13 #include <pci.h>
14 #include <asm/io.h>
15 #include <dm/device-internal.h>
16 #include <dm/lists.h>
17 #include <dm/uclass-internal.h>
18 #if defined(CONFIG_X86) && defined(CONFIG_HAVE_FSP)
19 #include <asm/fsp/fsp_support.h>
20 #endif
21 #include <linux/delay.h>
22 #include "pci_internal.h"
23
24 DECLARE_GLOBAL_DATA_PTR;
25
26 int pci_get_bus(int busnum, struct udevice **busp)
27 {
28         int ret;
29
30         ret = uclass_get_device_by_seq(UCLASS_PCI, busnum, busp);
31
32         /* Since buses may not be numbered yet try a little harder with bus 0 */
33         if (ret == -ENODEV) {
34                 ret = uclass_first_device_err(UCLASS_PCI, busp);
35                 if (ret)
36                         return ret;
37                 ret = uclass_get_device_by_seq(UCLASS_PCI, busnum, busp);
38         }
39
40         return ret;
41 }
42
43 struct udevice *pci_get_controller(struct udevice *dev)
44 {
45         while (device_is_on_pci_bus(dev))
46                 dev = dev->parent;
47
48         return dev;
49 }
50
51 pci_dev_t dm_pci_get_bdf(const struct udevice *dev)
52 {
53         struct pci_child_plat *pplat = dev_get_parent_plat(dev);
54         struct udevice *bus = dev->parent;
55
56         /*
57          * This error indicates that @dev is a device on an unprobed PCI bus.
58          * The bus likely has bus=seq == -1, so the PCI_ADD_BUS() macro below
59          * will produce a bad BDF>
60          *
61          * A common cause of this problem is that this function is called in the
62          * of_to_plat() method of @dev. Accessing the PCI bus in that
63          * method is not allowed, since it has not yet been probed. To fix this,
64          * move that access to the probe() method of @dev instead.
65          */
66         if (!device_active(bus))
67                 log_err("PCI: Device '%s' on unprobed bus '%s'\n", dev->name,
68                         bus->name);
69         return PCI_ADD_BUS(dev_seq(bus), pplat->devfn);
70 }
71
72 /**
73  * pci_get_bus_max() - returns the bus number of the last active bus
74  *
75  * @return last bus number, or -1 if no active buses
76  */
77 static int pci_get_bus_max(void)
78 {
79         struct udevice *bus;
80         struct uclass *uc;
81         int ret = -1;
82
83         ret = uclass_get(UCLASS_PCI, &uc);
84         uclass_foreach_dev(bus, uc) {
85                 if (dev_seq(bus) > ret)
86                         ret = dev_seq(bus);
87         }
88
89         debug("%s: ret=%d\n", __func__, ret);
90
91         return ret;
92 }
93
94 int pci_last_busno(void)
95 {
96         return pci_get_bus_max();
97 }
98
99 int pci_get_ff(enum pci_size_t size)
100 {
101         switch (size) {
102         case PCI_SIZE_8:
103                 return 0xff;
104         case PCI_SIZE_16:
105                 return 0xffff;
106         default:
107                 return 0xffffffff;
108         }
109 }
110
111 static void pci_dev_find_ofnode(struct udevice *bus, phys_addr_t bdf,
112                                 ofnode *rnode)
113 {
114         struct fdt_pci_addr addr;
115         ofnode node;
116         int ret;
117
118         dev_for_each_subnode(node, bus) {
119                 ret = ofnode_read_pci_addr(node, FDT_PCI_SPACE_CONFIG, "reg",
120                                            &addr);
121                 if (ret)
122                         continue;
123
124                 if (PCI_MASK_BUS(addr.phys_hi) != PCI_MASK_BUS(bdf))
125                         continue;
126
127                 *rnode = node;
128                 break;
129         }
130 };
131
132 int pci_bus_find_devfn(const struct udevice *bus, pci_dev_t find_devfn,
133                        struct udevice **devp)
134 {
135         struct udevice *dev;
136
137         for (device_find_first_child(bus, &dev);
138              dev;
139              device_find_next_child(&dev)) {
140                 struct pci_child_plat *pplat;
141
142                 pplat = dev_get_parent_plat(dev);
143                 if (pplat && pplat->devfn == find_devfn) {
144                         *devp = dev;
145                         return 0;
146                 }
147         }
148
149         return -ENODEV;
150 }
151
152 int dm_pci_bus_find_bdf(pci_dev_t bdf, struct udevice **devp)
153 {
154         struct udevice *bus;
155         int ret;
156
157         ret = pci_get_bus(PCI_BUS(bdf), &bus);
158         if (ret)
159                 return ret;
160         return pci_bus_find_devfn(bus, PCI_MASK_BUS(bdf), devp);
161 }
162
163 static int pci_device_matches_ids(struct udevice *dev,
164                                   struct pci_device_id *ids)
165 {
166         struct pci_child_plat *pplat;
167         int i;
168
169         pplat = dev_get_parent_plat(dev);
170         if (!pplat)
171                 return -EINVAL;
172         for (i = 0; ids[i].vendor != 0; i++) {
173                 if (pplat->vendor == ids[i].vendor &&
174                     pplat->device == ids[i].device)
175                         return i;
176         }
177
178         return -EINVAL;
179 }
180
181 int pci_bus_find_devices(struct udevice *bus, struct pci_device_id *ids,
182                          int *indexp, struct udevice **devp)
183 {
184         struct udevice *dev;
185
186         /* Scan all devices on this bus */
187         for (device_find_first_child(bus, &dev);
188              dev;
189              device_find_next_child(&dev)) {
190                 if (pci_device_matches_ids(dev, ids) >= 0) {
191                         if ((*indexp)-- <= 0) {
192                                 *devp = dev;
193                                 return 0;
194                         }
195                 }
196         }
197
198         return -ENODEV;
199 }
200
201 int pci_find_device_id(struct pci_device_id *ids, int index,
202                        struct udevice **devp)
203 {
204         struct udevice *bus;
205
206         /* Scan all known buses */
207         for (uclass_first_device(UCLASS_PCI, &bus);
208              bus;
209              uclass_next_device(&bus)) {
210                 if (!pci_bus_find_devices(bus, ids, &index, devp))
211                         return 0;
212         }
213         *devp = NULL;
214
215         return -ENODEV;
216 }
217
218 static int dm_pci_bus_find_device(struct udevice *bus, unsigned int vendor,
219                                   unsigned int device, int *indexp,
220                                   struct udevice **devp)
221 {
222         struct pci_child_plat *pplat;
223         struct udevice *dev;
224
225         for (device_find_first_child(bus, &dev);
226              dev;
227              device_find_next_child(&dev)) {
228                 pplat = dev_get_parent_plat(dev);
229                 if (pplat->vendor == vendor && pplat->device == device) {
230                         if (!(*indexp)--) {
231                                 *devp = dev;
232                                 return 0;
233                         }
234                 }
235         }
236
237         return -ENODEV;
238 }
239
240 int dm_pci_find_device(unsigned int vendor, unsigned int device, int index,
241                        struct udevice **devp)
242 {
243         struct udevice *bus;
244
245         /* Scan all known buses */
246         for (uclass_first_device(UCLASS_PCI, &bus);
247              bus;
248              uclass_next_device(&bus)) {
249                 if (!dm_pci_bus_find_device(bus, vendor, device, &index, devp))
250                         return device_probe(*devp);
251         }
252         *devp = NULL;
253
254         return -ENODEV;
255 }
256
257 int dm_pci_find_class(uint find_class, int index, struct udevice **devp)
258 {
259         struct udevice *dev;
260
261         /* Scan all known buses */
262         for (pci_find_first_device(&dev);
263              dev;
264              pci_find_next_device(&dev)) {
265                 struct pci_child_plat *pplat = dev_get_parent_plat(dev);
266
267                 if (pplat->class == find_class && !index--) {
268                         *devp = dev;
269                         return device_probe(*devp);
270                 }
271         }
272         *devp = NULL;
273
274         return -ENODEV;
275 }
276
277 int pci_bus_write_config(struct udevice *bus, pci_dev_t bdf, int offset,
278                          unsigned long value, enum pci_size_t size)
279 {
280         struct dm_pci_ops *ops;
281
282         ops = pci_get_ops(bus);
283         if (!ops->write_config)
284                 return -ENOSYS;
285         return ops->write_config(bus, bdf, offset, value, size);
286 }
287
288 int pci_bus_clrset_config32(struct udevice *bus, pci_dev_t bdf, int offset,
289                             u32 clr, u32 set)
290 {
291         ulong val;
292         int ret;
293
294         ret = pci_bus_read_config(bus, bdf, offset, &val, PCI_SIZE_32);
295         if (ret)
296                 return ret;
297         val &= ~clr;
298         val |= set;
299
300         return pci_bus_write_config(bus, bdf, offset, val, PCI_SIZE_32);
301 }
302
303 int pci_write_config(pci_dev_t bdf, int offset, unsigned long value,
304                      enum pci_size_t size)
305 {
306         struct udevice *bus;
307         int ret;
308
309         ret = pci_get_bus(PCI_BUS(bdf), &bus);
310         if (ret)
311                 return ret;
312
313         return pci_bus_write_config(bus, bdf, offset, value, size);
314 }
315
316 int dm_pci_write_config(struct udevice *dev, int offset, unsigned long value,
317                         enum pci_size_t size)
318 {
319         struct udevice *bus;
320
321         for (bus = dev; device_is_on_pci_bus(bus);)
322                 bus = bus->parent;
323         return pci_bus_write_config(bus, dm_pci_get_bdf(dev), offset, value,
324                                     size);
325 }
326
327 int pci_write_config32(pci_dev_t bdf, int offset, u32 value)
328 {
329         return pci_write_config(bdf, offset, value, PCI_SIZE_32);
330 }
331
332 int pci_write_config16(pci_dev_t bdf, int offset, u16 value)
333 {
334         return pci_write_config(bdf, offset, value, PCI_SIZE_16);
335 }
336
337 int pci_write_config8(pci_dev_t bdf, int offset, u8 value)
338 {
339         return pci_write_config(bdf, offset, value, PCI_SIZE_8);
340 }
341
342 int dm_pci_write_config8(struct udevice *dev, int offset, u8 value)
343 {
344         return dm_pci_write_config(dev, offset, value, PCI_SIZE_8);
345 }
346
347 int dm_pci_write_config16(struct udevice *dev, int offset, u16 value)
348 {
349         return dm_pci_write_config(dev, offset, value, PCI_SIZE_16);
350 }
351
352 int dm_pci_write_config32(struct udevice *dev, int offset, u32 value)
353 {
354         return dm_pci_write_config(dev, offset, value, PCI_SIZE_32);
355 }
356
357 int pci_bus_read_config(const struct udevice *bus, pci_dev_t bdf, int offset,
358                         unsigned long *valuep, enum pci_size_t size)
359 {
360         struct dm_pci_ops *ops;
361
362         ops = pci_get_ops(bus);
363         if (!ops->read_config)
364                 return -ENOSYS;
365         return ops->read_config(bus, bdf, offset, valuep, size);
366 }
367
368 int pci_read_config(pci_dev_t bdf, int offset, unsigned long *valuep,
369                     enum pci_size_t size)
370 {
371         struct udevice *bus;
372         int ret;
373
374         ret = pci_get_bus(PCI_BUS(bdf), &bus);
375         if (ret)
376                 return ret;
377
378         return pci_bus_read_config(bus, bdf, offset, valuep, size);
379 }
380
381 int dm_pci_read_config(const struct udevice *dev, int offset,
382                        unsigned long *valuep, enum pci_size_t size)
383 {
384         const struct udevice *bus;
385
386         for (bus = dev; device_is_on_pci_bus(bus);)
387                 bus = bus->parent;
388         return pci_bus_read_config(bus, dm_pci_get_bdf(dev), offset, valuep,
389                                    size);
390 }
391
392 int pci_read_config32(pci_dev_t bdf, int offset, u32 *valuep)
393 {
394         unsigned long value;
395         int ret;
396
397         ret = pci_read_config(bdf, offset, &value, PCI_SIZE_32);
398         if (ret)
399                 return ret;
400         *valuep = value;
401
402         return 0;
403 }
404
405 int pci_read_config16(pci_dev_t bdf, int offset, u16 *valuep)
406 {
407         unsigned long value;
408         int ret;
409
410         ret = pci_read_config(bdf, offset, &value, PCI_SIZE_16);
411         if (ret)
412                 return ret;
413         *valuep = value;
414
415         return 0;
416 }
417
418 int pci_read_config8(pci_dev_t bdf, int offset, u8 *valuep)
419 {
420         unsigned long value;
421         int ret;
422
423         ret = pci_read_config(bdf, offset, &value, PCI_SIZE_8);
424         if (ret)
425                 return ret;
426         *valuep = value;
427
428         return 0;
429 }
430
431 int dm_pci_read_config8(const struct udevice *dev, int offset, u8 *valuep)
432 {
433         unsigned long value;
434         int ret;
435
436         ret = dm_pci_read_config(dev, offset, &value, PCI_SIZE_8);
437         if (ret)
438                 return ret;
439         *valuep = value;
440
441         return 0;
442 }
443
444 int dm_pci_read_config16(const struct udevice *dev, int offset, u16 *valuep)
445 {
446         unsigned long value;
447         int ret;
448
449         ret = dm_pci_read_config(dev, offset, &value, PCI_SIZE_16);
450         if (ret)
451                 return ret;
452         *valuep = value;
453
454         return 0;
455 }
456
457 int dm_pci_read_config32(const struct udevice *dev, int offset, u32 *valuep)
458 {
459         unsigned long value;
460         int ret;
461
462         ret = dm_pci_read_config(dev, offset, &value, PCI_SIZE_32);
463         if (ret)
464                 return ret;
465         *valuep = value;
466
467         return 0;
468 }
469
470 int dm_pci_clrset_config8(struct udevice *dev, int offset, u32 clr, u32 set)
471 {
472         u8 val;
473         int ret;
474
475         ret = dm_pci_read_config8(dev, offset, &val);
476         if (ret)
477                 return ret;
478         val &= ~clr;
479         val |= set;
480
481         return dm_pci_write_config8(dev, offset, val);
482 }
483
484 int dm_pci_clrset_config16(struct udevice *dev, int offset, u32 clr, u32 set)
485 {
486         u16 val;
487         int ret;
488
489         ret = dm_pci_read_config16(dev, offset, &val);
490         if (ret)
491                 return ret;
492         val &= ~clr;
493         val |= set;
494
495         return dm_pci_write_config16(dev, offset, val);
496 }
497
498 int dm_pci_clrset_config32(struct udevice *dev, int offset, u32 clr, u32 set)
499 {
500         u32 val;
501         int ret;
502
503         ret = dm_pci_read_config32(dev, offset, &val);
504         if (ret)
505                 return ret;
506         val &= ~clr;
507         val |= set;
508
509         return dm_pci_write_config32(dev, offset, val);
510 }
511
512 static void set_vga_bridge_bits(struct udevice *dev)
513 {
514         struct udevice *parent = dev->parent;
515         u16 bc;
516
517         while (dev_seq(parent) != 0) {
518                 dm_pci_read_config16(parent, PCI_BRIDGE_CONTROL, &bc);
519                 bc |= PCI_BRIDGE_CTL_VGA;
520                 dm_pci_write_config16(parent, PCI_BRIDGE_CONTROL, bc);
521                 parent = parent->parent;
522         }
523 }
524
525 int pci_auto_config_devices(struct udevice *bus)
526 {
527         struct pci_controller *hose = dev_get_uclass_priv(bus);
528         struct pci_child_plat *pplat;
529         unsigned int sub_bus;
530         struct udevice *dev;
531         int ret;
532
533         sub_bus = dev_seq(bus);
534         debug("%s: start\n", __func__);
535         pciauto_config_init(hose);
536         for (ret = device_find_first_child(bus, &dev);
537              !ret && dev;
538              ret = device_find_next_child(&dev)) {
539                 unsigned int max_bus;
540                 int ret;
541
542                 debug("%s: device %s\n", __func__, dev->name);
543                 if (dev_has_ofnode(dev) &&
544                     dev_read_bool(dev, "pci,no-autoconfig"))
545                         continue;
546                 ret = dm_pciauto_config_device(dev);
547                 if (ret < 0)
548                         return log_msg_ret("auto", ret);
549                 max_bus = ret;
550                 sub_bus = max(sub_bus, max_bus);
551
552                 pplat = dev_get_parent_plat(dev);
553                 if (pplat->class == (PCI_CLASS_DISPLAY_VGA << 8))
554                         set_vga_bridge_bits(dev);
555         }
556         debug("%s: done\n", __func__);
557
558         return log_msg_ret("sub", sub_bus);
559 }
560
561 int pci_generic_mmap_write_config(
562         const struct udevice *bus,
563         int (*addr_f)(const struct udevice *bus, pci_dev_t bdf, uint offset,
564                       void **addrp),
565         pci_dev_t bdf,
566         uint offset,
567         ulong value,
568         enum pci_size_t size)
569 {
570         void *address;
571
572         if (addr_f(bus, bdf, offset, &address) < 0)
573                 return 0;
574
575         switch (size) {
576         case PCI_SIZE_8:
577                 writeb(value, address);
578                 return 0;
579         case PCI_SIZE_16:
580                 writew(value, address);
581                 return 0;
582         case PCI_SIZE_32:
583                 writel(value, address);
584                 return 0;
585         default:
586                 return -EINVAL;
587         }
588 }
589
590 int pci_generic_mmap_read_config(
591         const struct udevice *bus,
592         int (*addr_f)(const struct udevice *bus, pci_dev_t bdf, uint offset,
593                       void **addrp),
594         pci_dev_t bdf,
595         uint offset,
596         ulong *valuep,
597         enum pci_size_t size)
598 {
599         void *address;
600
601         if (addr_f(bus, bdf, offset, &address) < 0) {
602                 *valuep = pci_get_ff(size);
603                 return 0;
604         }
605
606         switch (size) {
607         case PCI_SIZE_8:
608                 *valuep = readb(address);
609                 return 0;
610         case PCI_SIZE_16:
611                 *valuep = readw(address);
612                 return 0;
613         case PCI_SIZE_32:
614                 *valuep = readl(address);
615                 return 0;
616         default:
617                 return -EINVAL;
618         }
619 }
620
621 int dm_pci_hose_probe_bus(struct udevice *bus)
622 {
623         int sub_bus;
624         int ret;
625         int ea_pos;
626         u8 reg;
627
628         debug("%s\n", __func__);
629
630         ea_pos = dm_pci_find_capability(bus, PCI_CAP_ID_EA);
631         if (ea_pos) {
632                 dm_pci_read_config8(bus, ea_pos + sizeof(u32) + sizeof(u8),
633                                     &reg);
634                 sub_bus = reg;
635         } else {
636                 sub_bus = pci_get_bus_max() + 1;
637         }
638         debug("%s: bus = %d/%s\n", __func__, sub_bus, bus->name);
639         dm_pciauto_prescan_setup_bridge(bus, sub_bus);
640
641         ret = device_probe(bus);
642         if (ret) {
643                 debug("%s: Cannot probe bus %s: %d\n", __func__, bus->name,
644                       ret);
645                 return log_msg_ret("probe", ret);
646         }
647
648         dm_pciauto_postscan_setup_bridge(bus, sub_bus);
649
650         return sub_bus;
651 }
652
653 /**
654  * pci_match_one_device - Tell if a PCI device structure has a matching
655  *                        PCI device id structure
656  * @id: single PCI device id structure to match
657  * @find: the PCI device id structure to match against
658  *
659  * Returns true if the finding pci_device_id structure matched or false if
660  * there is no match.
661  */
662 static bool pci_match_one_id(const struct pci_device_id *id,
663                              const struct pci_device_id *find)
664 {
665         if ((id->vendor == PCI_ANY_ID || id->vendor == find->vendor) &&
666             (id->device == PCI_ANY_ID || id->device == find->device) &&
667             (id->subvendor == PCI_ANY_ID || id->subvendor == find->subvendor) &&
668             (id->subdevice == PCI_ANY_ID || id->subdevice == find->subdevice) &&
669             !((id->class ^ find->class) & id->class_mask))
670                 return true;
671
672         return false;
673 }
674
675 /**
676  * pci_find_and_bind_driver() - Find and bind the right PCI driver
677  *
678  * This only looks at certain fields in the descriptor.
679  *
680  * @parent:     Parent bus
681  * @find_id:    Specification of the driver to find
682  * @bdf:        Bus/device/function addreess - see PCI_BDF()
683  * @devp:       Returns a pointer to the device created
684  * @return 0 if OK, -EPERM if the device is not needed before relocation and
685  *         therefore was not created, other -ve value on error
686  */
687 static int pci_find_and_bind_driver(struct udevice *parent,
688                                     struct pci_device_id *find_id,
689                                     pci_dev_t bdf, struct udevice **devp)
690 {
691         struct pci_driver_entry *start, *entry;
692         ofnode node = ofnode_null();
693         const char *drv;
694         int n_ents;
695         int ret;
696         char name[30], *str;
697         bool bridge;
698
699         *devp = NULL;
700
701         debug("%s: Searching for driver: vendor=%x, device=%x\n", __func__,
702               find_id->vendor, find_id->device);
703
704         /* Determine optional OF node */
705         if (ofnode_valid(dev_ofnode(parent)))
706                 pci_dev_find_ofnode(parent, bdf, &node);
707
708         if (ofnode_valid(node) && !ofnode_is_available(node)) {
709                 debug("%s: Ignoring disabled device\n", __func__);
710                 return log_msg_ret("dis", -EPERM);
711         }
712
713         start = ll_entry_start(struct pci_driver_entry, pci_driver_entry);
714         n_ents = ll_entry_count(struct pci_driver_entry, pci_driver_entry);
715         for (entry = start; entry != start + n_ents; entry++) {
716                 const struct pci_device_id *id;
717                 struct udevice *dev;
718                 const struct driver *drv;
719
720                 for (id = entry->match;
721                      id->vendor || id->subvendor || id->class_mask;
722                      id++) {
723                         if (!pci_match_one_id(id, find_id))
724                                 continue;
725
726                         drv = entry->driver;
727
728                         /*
729                          * In the pre-relocation phase, we only bind devices
730                          * whose driver has the DM_FLAG_PRE_RELOC set, to save
731                          * precious memory space as on some platforms as that
732                          * space is pretty limited (ie: using Cache As RAM).
733                          */
734                         if (!(gd->flags & GD_FLG_RELOC) &&
735                             !(drv->flags & DM_FLAG_PRE_RELOC))
736                                 return log_msg_ret("pre", -EPERM);
737
738                         /*
739                          * We could pass the descriptor to the driver as
740                          * plat (instead of NULL) and allow its bind()
741                          * method to return -ENOENT if it doesn't support this
742                          * device. That way we could continue the search to
743                          * find another driver. For now this doesn't seem
744                          * necesssary, so just bind the first match.
745                          */
746                         ret = device_bind(parent, drv, drv->name, NULL, node,
747                                           &dev);
748                         if (ret)
749                                 goto error;
750                         debug("%s: Match found: %s\n", __func__, drv->name);
751                         dev->driver_data = id->driver_data;
752                         *devp = dev;
753                         return 0;
754                 }
755         }
756
757         bridge = (find_id->class >> 8) == PCI_CLASS_BRIDGE_PCI;
758         /*
759          * In the pre-relocation phase, we only bind bridge devices to save
760          * precious memory space as on some platforms as that space is pretty
761          * limited (ie: using Cache As RAM).
762          */
763         if (!(gd->flags & GD_FLG_RELOC) && !bridge)
764                 return log_msg_ret("notbr", -EPERM);
765
766         /* Bind a generic driver so that the device can be used */
767         sprintf(name, "pci_%x:%x.%x", dev_seq(parent), PCI_DEV(bdf),
768                 PCI_FUNC(bdf));
769         str = strdup(name);
770         if (!str)
771                 return -ENOMEM;
772         drv = bridge ? "pci_bridge_drv" : "pci_generic_drv";
773
774         ret = device_bind_driver_to_node(parent, drv, str, node, devp);
775         if (ret) {
776                 debug("%s: Failed to bind generic driver: %d\n", __func__, ret);
777                 free(str);
778                 return ret;
779         }
780         debug("%s: No match found: bound generic driver instead\n", __func__);
781
782         return 0;
783
784 error:
785         debug("%s: No match found: error %d\n", __func__, ret);
786         return ret;
787 }
788
789 int pci_bind_bus_devices(struct udevice *bus)
790 {
791         ulong vendor, device;
792         ulong header_type;
793         pci_dev_t bdf, end;
794         bool found_multi;
795         int ari_off;
796         int ret;
797
798         found_multi = false;
799         end = PCI_BDF(dev_seq(bus), PCI_MAX_PCI_DEVICES - 1,
800                       PCI_MAX_PCI_FUNCTIONS - 1);
801         for (bdf = PCI_BDF(dev_seq(bus), 0, 0); bdf <= end;
802              bdf += PCI_BDF(0, 0, 1)) {
803                 struct pci_child_plat *pplat;
804                 struct udevice *dev;
805                 ulong class;
806
807                 if (!PCI_FUNC(bdf))
808                         found_multi = false;
809                 if (PCI_FUNC(bdf) && !found_multi)
810                         continue;
811
812                 /* Check only the first access, we don't expect problems */
813                 ret = pci_bus_read_config(bus, bdf, PCI_VENDOR_ID, &vendor,
814                                           PCI_SIZE_16);
815                 if (ret)
816                         goto error;
817
818                 if (vendor == 0xffff || vendor == 0x0000)
819                         continue;
820
821                 pci_bus_read_config(bus, bdf, PCI_HEADER_TYPE,
822                                     &header_type, PCI_SIZE_8);
823
824                 if (!PCI_FUNC(bdf))
825                         found_multi = header_type & 0x80;
826
827                 debug("%s: bus %d/%s: found device %x, function %d", __func__,
828                       dev_seq(bus), bus->name, PCI_DEV(bdf), PCI_FUNC(bdf));
829                 pci_bus_read_config(bus, bdf, PCI_DEVICE_ID, &device,
830                                     PCI_SIZE_16);
831                 pci_bus_read_config(bus, bdf, PCI_CLASS_REVISION, &class,
832                                     PCI_SIZE_32);
833                 class >>= 8;
834
835                 /* Find this device in the device tree */
836                 ret = pci_bus_find_devfn(bus, PCI_MASK_BUS(bdf), &dev);
837                 debug(": find ret=%d\n", ret);
838
839                 /* If nothing in the device tree, bind a device */
840                 if (ret == -ENODEV) {
841                         struct pci_device_id find_id;
842                         ulong val;
843
844                         memset(&find_id, '\0', sizeof(find_id));
845                         find_id.vendor = vendor;
846                         find_id.device = device;
847                         find_id.class = class;
848                         if ((header_type & 0x7f) == PCI_HEADER_TYPE_NORMAL) {
849                                 pci_bus_read_config(bus, bdf,
850                                                     PCI_SUBSYSTEM_VENDOR_ID,
851                                                     &val, PCI_SIZE_32);
852                                 find_id.subvendor = val & 0xffff;
853                                 find_id.subdevice = val >> 16;
854                         }
855                         ret = pci_find_and_bind_driver(bus, &find_id, bdf,
856                                                        &dev);
857                 }
858                 if (ret == -EPERM)
859                         continue;
860                 else if (ret)
861                         return ret;
862
863                 /* Update the platform data */
864                 pplat = dev_get_parent_plat(dev);
865                 pplat->devfn = PCI_MASK_BUS(bdf);
866                 pplat->vendor = vendor;
867                 pplat->device = device;
868                 pplat->class = class;
869
870                 if (IS_ENABLED(CONFIG_PCI_ARID)) {
871                         ari_off = dm_pci_find_ext_capability(dev,
872                                                              PCI_EXT_CAP_ID_ARI);
873                         if (ari_off) {
874                                 u16 ari_cap;
875
876                                 /*
877                                  * Read Next Function number in ARI Cap
878                                  * Register
879                                  */
880                                 dm_pci_read_config16(dev, ari_off + 4,
881                                                      &ari_cap);
882                                 /*
883                                  * Update next scan on this function number,
884                                  * subtract 1 in BDF to satisfy loop increment.
885                                  */
886                                 if (ari_cap & 0xff00) {
887                                         bdf = PCI_BDF(PCI_BUS(bdf),
888                                                       PCI_DEV(ari_cap),
889                                                       PCI_FUNC(ari_cap));
890                                         bdf = bdf - 0x100;
891                                 }
892                         }
893                 }
894         }
895
896         return 0;
897 error:
898         printf("Cannot read bus configuration: %d\n", ret);
899
900         return ret;
901 }
902
903 static void decode_regions(struct pci_controller *hose, ofnode parent_node,
904                            ofnode node)
905 {
906         int pci_addr_cells, addr_cells, size_cells;
907         int cells_per_record;
908         struct bd_info *bd;
909         const u32 *prop;
910         int max_regions;
911         int len;
912         int i;
913
914         prop = ofnode_get_property(node, "ranges", &len);
915         if (!prop) {
916                 debug("%s: Cannot decode regions\n", __func__);
917                 return;
918         }
919
920         pci_addr_cells = ofnode_read_simple_addr_cells(node);
921         addr_cells = ofnode_read_simple_addr_cells(parent_node);
922         size_cells = ofnode_read_simple_size_cells(node);
923
924         /* PCI addresses are always 3-cells */
925         len /= sizeof(u32);
926         cells_per_record = pci_addr_cells + addr_cells + size_cells;
927         hose->region_count = 0;
928         debug("%s: len=%d, cells_per_record=%d\n", __func__, len,
929               cells_per_record);
930
931         /* Dynamically allocate the regions array */
932         max_regions = len / cells_per_record + CONFIG_NR_DRAM_BANKS;
933         hose->regions = (struct pci_region *)
934                 calloc(1, max_regions * sizeof(struct pci_region));
935
936         for (i = 0; i < max_regions; i++, len -= cells_per_record) {
937                 u64 pci_addr, addr, size;
938                 int space_code;
939                 u32 flags;
940                 int type;
941                 int pos;
942
943                 if (len < cells_per_record)
944                         break;
945                 flags = fdt32_to_cpu(prop[0]);
946                 space_code = (flags >> 24) & 3;
947                 pci_addr = fdtdec_get_number(prop + 1, 2);
948                 prop += pci_addr_cells;
949                 addr = fdtdec_get_number(prop, addr_cells);
950                 prop += addr_cells;
951                 size = fdtdec_get_number(prop, size_cells);
952                 prop += size_cells;
953                 debug("%s: region %d, pci_addr=%llx, addr=%llx, size=%llx, space_code=%d\n",
954                       __func__, hose->region_count, pci_addr, addr, size, space_code);
955                 if (space_code & 2) {
956                         type = flags & (1U << 30) ? PCI_REGION_PREFETCH :
957                                         PCI_REGION_MEM;
958                 } else if (space_code & 1) {
959                         type = PCI_REGION_IO;
960                 } else {
961                         continue;
962                 }
963
964                 if (!IS_ENABLED(CONFIG_SYS_PCI_64BIT) &&
965                     type == PCI_REGION_MEM && upper_32_bits(pci_addr)) {
966                         debug(" - beyond the 32-bit boundary, ignoring\n");
967                         continue;
968                 }
969
970                 pos = -1;
971                 if (!IS_ENABLED(CONFIG_PCI_REGION_MULTI_ENTRY)) {
972                         for (i = 0; i < hose->region_count; i++) {
973                                 if (hose->regions[i].flags == type)
974                                         pos = i;
975                         }
976                 }
977
978                 if (pos == -1)
979                         pos = hose->region_count++;
980                 debug(" - type=%d, pos=%d\n", type, pos);
981                 pci_set_region(hose->regions + pos, pci_addr, addr, size, type);
982         }
983
984         /* Add a region for our local memory */
985         bd = gd->bd;
986         if (!bd)
987                 return;
988
989         for (i = 0; i < CONFIG_NR_DRAM_BANKS; ++i) {
990                 if (bd->bi_dram[i].size) {
991                         pci_set_region(hose->regions + hose->region_count++,
992                                        bd->bi_dram[i].start,
993                                        bd->bi_dram[i].start,
994                                        bd->bi_dram[i].size,
995                                        PCI_REGION_MEM | PCI_REGION_SYS_MEMORY);
996                 }
997         }
998
999         return;
1000 }
1001
1002 static int pci_uclass_pre_probe(struct udevice *bus)
1003 {
1004         struct pci_controller *hose;
1005         struct uclass *uc;
1006         int ret;
1007
1008         debug("%s, bus=%d/%s, parent=%s\n", __func__, dev_seq(bus), bus->name,
1009               bus->parent->name);
1010         hose = dev_get_uclass_priv(bus);
1011
1012         /*
1013          * Set the sequence number, if device_bind() doesn't. We want control
1014          * of this so that numbers are allocated as devices are probed. That
1015          * ensures that sub-bus numbered is correct (sub-buses must get numbers
1016          * higher than their parents)
1017          */
1018         if (dev_seq(bus) == -1) {
1019                 ret = uclass_get(UCLASS_PCI, &uc);
1020                 if (ret)
1021                         return ret;
1022                 bus->seq_ = uclass_find_next_free_seq(uc);
1023         }
1024
1025         /* For bridges, use the top-level PCI controller */
1026         if (!device_is_on_pci_bus(bus)) {
1027                 hose->ctlr = bus;
1028                 decode_regions(hose, dev_ofnode(bus->parent), dev_ofnode(bus));
1029         } else {
1030                 struct pci_controller *parent_hose;
1031
1032                 parent_hose = dev_get_uclass_priv(bus->parent);
1033                 hose->ctlr = parent_hose->bus;
1034         }
1035
1036         hose->bus = bus;
1037         hose->first_busno = dev_seq(bus);
1038         hose->last_busno = dev_seq(bus);
1039         if (dev_has_ofnode(bus)) {
1040                 hose->skip_auto_config_until_reloc =
1041                         dev_read_bool(bus,
1042                                       "u-boot,skip-auto-config-until-reloc");
1043         }
1044
1045         return 0;
1046 }
1047
1048 static int pci_uclass_post_probe(struct udevice *bus)
1049 {
1050         struct pci_controller *hose = dev_get_uclass_priv(bus);
1051         int ret;
1052
1053         debug("%s: probing bus %d\n", __func__, dev_seq(bus));
1054         ret = pci_bind_bus_devices(bus);
1055         if (ret)
1056                 return log_msg_ret("bind", ret);
1057
1058         if (CONFIG_IS_ENABLED(PCI_PNP) && ll_boot_init() &&
1059             (!hose->skip_auto_config_until_reloc ||
1060              (gd->flags & GD_FLG_RELOC))) {
1061                 ret = pci_auto_config_devices(bus);
1062                 if (ret < 0)
1063                         return log_msg_ret("cfg", ret);
1064         }
1065
1066 #if defined(CONFIG_X86) && defined(CONFIG_HAVE_FSP)
1067         /*
1068          * Per Intel FSP specification, we should call FSP notify API to
1069          * inform FSP that PCI enumeration has been done so that FSP will
1070          * do any necessary initialization as required by the chipset's
1071          * BIOS Writer's Guide (BWG).
1072          *
1073          * Unfortunately we have to put this call here as with driver model,
1074          * the enumeration is all done on a lazy basis as needed, so until
1075          * something is touched on PCI it won't happen.
1076          *
1077          * Note we only call this 1) after U-Boot is relocated, and 2)
1078          * root bus has finished probing.
1079          */
1080         if ((gd->flags & GD_FLG_RELOC) && dev_seq(bus) == 0 && ll_boot_init()) {
1081                 ret = fsp_init_phase_pci();
1082                 if (ret)
1083                         return log_msg_ret("fsp", ret);
1084         }
1085 #endif
1086
1087         return 0;
1088 }
1089
1090 static int pci_uclass_child_post_bind(struct udevice *dev)
1091 {
1092         struct pci_child_plat *pplat;
1093
1094         if (!dev_has_ofnode(dev))
1095                 return 0;
1096
1097         pplat = dev_get_parent_plat(dev);
1098
1099         /* Extract vendor id and device id if available */
1100         ofnode_read_pci_vendev(dev_ofnode(dev), &pplat->vendor, &pplat->device);
1101
1102         /* Extract the devfn from fdt_pci_addr */
1103         pplat->devfn = pci_get_devfn(dev);
1104
1105         return 0;
1106 }
1107
1108 static int pci_bridge_read_config(const struct udevice *bus, pci_dev_t bdf,
1109                                   uint offset, ulong *valuep,
1110                                   enum pci_size_t size)
1111 {
1112         struct pci_controller *hose = dev_get_uclass_priv(bus);
1113
1114         return pci_bus_read_config(hose->ctlr, bdf, offset, valuep, size);
1115 }
1116
1117 static int pci_bridge_write_config(struct udevice *bus, pci_dev_t bdf,
1118                                    uint offset, ulong value,
1119                                    enum pci_size_t size)
1120 {
1121         struct pci_controller *hose = dev_get_uclass_priv(bus);
1122
1123         return pci_bus_write_config(hose->ctlr, bdf, offset, value, size);
1124 }
1125
1126 static int skip_to_next_device(struct udevice *bus, struct udevice **devp)
1127 {
1128         struct udevice *dev;
1129         int ret = 0;
1130
1131         /*
1132          * Scan through all the PCI controllers. On x86 there will only be one
1133          * but that is not necessarily true on other hardware.
1134          */
1135         do {
1136                 device_find_first_child(bus, &dev);
1137                 if (dev) {
1138                         *devp = dev;
1139                         return 0;
1140                 }
1141                 ret = uclass_next_device(&bus);
1142                 if (ret)
1143                         return ret;
1144         } while (bus);
1145
1146         return 0;
1147 }
1148
1149 int pci_find_next_device(struct udevice **devp)
1150 {
1151         struct udevice *child = *devp;
1152         struct udevice *bus = child->parent;
1153         int ret;
1154
1155         /* First try all the siblings */
1156         *devp = NULL;
1157         while (child) {
1158                 device_find_next_child(&child);
1159                 if (child) {
1160                         *devp = child;
1161                         return 0;
1162                 }
1163         }
1164
1165         /* We ran out of siblings. Try the next bus */
1166         ret = uclass_next_device(&bus);
1167         if (ret)
1168                 return ret;
1169
1170         return bus ? skip_to_next_device(bus, devp) : 0;
1171 }
1172
1173 int pci_find_first_device(struct udevice **devp)
1174 {
1175         struct udevice *bus;
1176         int ret;
1177
1178         *devp = NULL;
1179         ret = uclass_first_device(UCLASS_PCI, &bus);
1180         if (ret)
1181                 return ret;
1182
1183         return skip_to_next_device(bus, devp);
1184 }
1185
1186 ulong pci_conv_32_to_size(ulong value, uint offset, enum pci_size_t size)
1187 {
1188         switch (size) {
1189         case PCI_SIZE_8:
1190                 return (value >> ((offset & 3) * 8)) & 0xff;
1191         case PCI_SIZE_16:
1192                 return (value >> ((offset & 2) * 8)) & 0xffff;
1193         default:
1194                 return value;
1195         }
1196 }
1197
1198 ulong pci_conv_size_to_32(ulong old, ulong value, uint offset,
1199                           enum pci_size_t size)
1200 {
1201         uint off_mask;
1202         uint val_mask, shift;
1203         ulong ldata, mask;
1204
1205         switch (size) {
1206         case PCI_SIZE_8:
1207                 off_mask = 3;
1208                 val_mask = 0xff;
1209                 break;
1210         case PCI_SIZE_16:
1211                 off_mask = 2;
1212                 val_mask = 0xffff;
1213                 break;
1214         default:
1215                 return value;
1216         }
1217         shift = (offset & off_mask) * 8;
1218         ldata = (value & val_mask) << shift;
1219         mask = val_mask << shift;
1220         value = (old & ~mask) | ldata;
1221
1222         return value;
1223 }
1224
1225 int pci_get_dma_regions(struct udevice *dev, struct pci_region *memp, int index)
1226 {
1227         int pci_addr_cells, addr_cells, size_cells;
1228         int cells_per_record;
1229         const u32 *prop;
1230         int len;
1231         int i = 0;
1232
1233         prop = ofnode_get_property(dev_ofnode(dev), "dma-ranges", &len);
1234         if (!prop) {
1235                 log_err("PCI: Device '%s': Cannot decode dma-ranges\n",
1236                         dev->name);
1237                 return -EINVAL;
1238         }
1239
1240         pci_addr_cells = ofnode_read_simple_addr_cells(dev_ofnode(dev));
1241         addr_cells = ofnode_read_simple_addr_cells(dev_ofnode(dev->parent));
1242         size_cells = ofnode_read_simple_size_cells(dev_ofnode(dev));
1243
1244         /* PCI addresses are always 3-cells */
1245         len /= sizeof(u32);
1246         cells_per_record = pci_addr_cells + addr_cells + size_cells;
1247         debug("%s: len=%d, cells_per_record=%d\n", __func__, len,
1248               cells_per_record);
1249
1250         while (len) {
1251                 memp->bus_start = fdtdec_get_number(prop + 1, 2);
1252                 prop += pci_addr_cells;
1253                 memp->phys_start = fdtdec_get_number(prop, addr_cells);
1254                 prop += addr_cells;
1255                 memp->size = fdtdec_get_number(prop, size_cells);
1256                 prop += size_cells;
1257
1258                 if (i == index)
1259                         return 0;
1260                 i++;
1261                 len -= cells_per_record;
1262         }
1263
1264         return -EINVAL;
1265 }
1266
1267 int pci_get_regions(struct udevice *dev, struct pci_region **iop,
1268                     struct pci_region **memp, struct pci_region **prefp)
1269 {
1270         struct udevice *bus = pci_get_controller(dev);
1271         struct pci_controller *hose = dev_get_uclass_priv(bus);
1272         int i;
1273
1274         *iop = NULL;
1275         *memp = NULL;
1276         *prefp = NULL;
1277         for (i = 0; i < hose->region_count; i++) {
1278                 switch (hose->regions[i].flags) {
1279                 case PCI_REGION_IO:
1280                         if (!*iop || (*iop)->size < hose->regions[i].size)
1281                                 *iop = hose->regions + i;
1282                         break;
1283                 case PCI_REGION_MEM:
1284                         if (!*memp || (*memp)->size < hose->regions[i].size)
1285                                 *memp = hose->regions + i;
1286                         break;
1287                 case (PCI_REGION_MEM | PCI_REGION_PREFETCH):
1288                         if (!*prefp || (*prefp)->size < hose->regions[i].size)
1289                                 *prefp = hose->regions + i;
1290                         break;
1291                 }
1292         }
1293
1294         return (*iop != NULL) + (*memp != NULL) + (*prefp != NULL);
1295 }
1296
1297 u32 dm_pci_read_bar32(const struct udevice *dev, int barnum)
1298 {
1299         u32 addr;
1300         int bar;
1301
1302         bar = PCI_BASE_ADDRESS_0 + barnum * 4;
1303         dm_pci_read_config32(dev, bar, &addr);
1304
1305         /*
1306          * If we get an invalid address, return this so that comparisons with
1307          * FDT_ADDR_T_NONE work correctly
1308          */
1309         if (addr == 0xffffffff)
1310                 return addr;
1311         else if (addr & PCI_BASE_ADDRESS_SPACE_IO)
1312                 return addr & PCI_BASE_ADDRESS_IO_MASK;
1313         else
1314                 return addr & PCI_BASE_ADDRESS_MEM_MASK;
1315 }
1316
1317 void dm_pci_write_bar32(struct udevice *dev, int barnum, u32 addr)
1318 {
1319         int bar;
1320
1321         bar = PCI_BASE_ADDRESS_0 + barnum * 4;
1322         dm_pci_write_config32(dev, bar, addr);
1323 }
1324
1325 static int _dm_pci_bus_to_phys(struct udevice *ctlr,
1326                                pci_addr_t bus_addr, unsigned long flags,
1327                                unsigned long skip_mask, phys_addr_t *pa)
1328 {
1329         struct pci_controller *hose = dev_get_uclass_priv(ctlr);
1330         struct pci_region *res;
1331         int i;
1332
1333         if (hose->region_count == 0) {
1334                 *pa = bus_addr;
1335                 return 0;
1336         }
1337
1338         for (i = 0; i < hose->region_count; i++) {
1339                 res = &hose->regions[i];
1340
1341                 if (((res->flags ^ flags) & PCI_REGION_TYPE) != 0)
1342                         continue;
1343
1344                 if (res->flags & skip_mask)
1345                         continue;
1346
1347                 if (bus_addr >= res->bus_start &&
1348                     (bus_addr - res->bus_start) < res->size) {
1349                         *pa = (bus_addr - res->bus_start + res->phys_start);
1350                         return 0;
1351                 }
1352         }
1353
1354         return 1;
1355 }
1356
1357 phys_addr_t dm_pci_bus_to_phys(struct udevice *dev, pci_addr_t bus_addr,
1358                                unsigned long flags)
1359 {
1360         phys_addr_t phys_addr = 0;
1361         struct udevice *ctlr;
1362         int ret;
1363
1364         /* The root controller has the region information */
1365         ctlr = pci_get_controller(dev);
1366
1367         /*
1368          * if PCI_REGION_MEM is set we do a two pass search with preference
1369          * on matches that don't have PCI_REGION_SYS_MEMORY set
1370          */
1371         if ((flags & PCI_REGION_TYPE) == PCI_REGION_MEM) {
1372                 ret = _dm_pci_bus_to_phys(ctlr, bus_addr,
1373                                           flags, PCI_REGION_SYS_MEMORY,
1374                                           &phys_addr);
1375                 if (!ret)
1376                         return phys_addr;
1377         }
1378
1379         ret = _dm_pci_bus_to_phys(ctlr, bus_addr, flags, 0, &phys_addr);
1380
1381         if (ret)
1382                 puts("pci_hose_bus_to_phys: invalid physical address\n");
1383
1384         return phys_addr;
1385 }
1386
1387 int _dm_pci_phys_to_bus(struct udevice *dev, phys_addr_t phys_addr,
1388                         unsigned long flags, unsigned long skip_mask,
1389                         pci_addr_t *ba)
1390 {
1391         struct pci_region *res;
1392         struct udevice *ctlr;
1393         pci_addr_t bus_addr;
1394         int i;
1395         struct pci_controller *hose;
1396
1397         /* The root controller has the region information */
1398         ctlr = pci_get_controller(dev);
1399         hose = dev_get_uclass_priv(ctlr);
1400
1401         if (hose->region_count == 0) {
1402                 *ba = phys_addr;
1403                 return 0;
1404         }
1405
1406         for (i = 0; i < hose->region_count; i++) {
1407                 res = &hose->regions[i];
1408
1409                 if (((res->flags ^ flags) & PCI_REGION_TYPE) != 0)
1410                         continue;
1411
1412                 if (res->flags & skip_mask)
1413                         continue;
1414
1415                 bus_addr = phys_addr - res->phys_start + res->bus_start;
1416
1417                 if (bus_addr >= res->bus_start &&
1418                     (bus_addr - res->bus_start) < res->size) {
1419                         *ba = bus_addr;
1420                         return 0;
1421                 }
1422         }
1423
1424         return 1;
1425 }
1426
1427 pci_addr_t dm_pci_phys_to_bus(struct udevice *dev, phys_addr_t phys_addr,
1428                               unsigned long flags)
1429 {
1430         pci_addr_t bus_addr = 0;
1431         int ret;
1432
1433         /*
1434          * if PCI_REGION_MEM is set we do a two pass search with preference
1435          * on matches that don't have PCI_REGION_SYS_MEMORY set
1436          */
1437         if ((flags & PCI_REGION_TYPE) == PCI_REGION_MEM) {
1438                 ret = _dm_pci_phys_to_bus(dev, phys_addr, flags,
1439                                           PCI_REGION_SYS_MEMORY, &bus_addr);
1440                 if (!ret)
1441                         return bus_addr;
1442         }
1443
1444         ret = _dm_pci_phys_to_bus(dev, phys_addr, flags, 0, &bus_addr);
1445
1446         if (ret)
1447                 puts("pci_hose_phys_to_bus: invalid physical address\n");
1448
1449         return bus_addr;
1450 }
1451
1452 static phys_addr_t dm_pci_map_ea_virt(struct udevice *dev, int ea_off,
1453                                       struct pci_child_plat *pdata)
1454 {
1455         phys_addr_t addr = 0;
1456
1457         /*
1458          * In the case of a Virtual Function device using BAR
1459          * base and size, add offset for VFn BAR(1, 2, 3...n)
1460          */
1461         if (pdata->is_virtfn) {
1462                 size_t sz;
1463                 u32 ea_entry;
1464
1465                 /* MaxOffset, 1st DW */
1466                 dm_pci_read_config32(dev, ea_off + 8, &ea_entry);
1467                 sz = ea_entry & PCI_EA_FIELD_MASK;
1468                 /* Fill up lower 2 bits */
1469                 sz |= (~PCI_EA_FIELD_MASK);
1470
1471                 if (ea_entry & PCI_EA_IS_64) {
1472                         /* MaxOffset 2nd DW */
1473                         dm_pci_read_config32(dev, ea_off + 16, &ea_entry);
1474                         sz |= ((u64)ea_entry) << 32;
1475                 }
1476
1477                 addr = (pdata->virtid - 1) * (sz + 1);
1478         }
1479
1480         return addr;
1481 }
1482
1483 static void *dm_pci_map_ea_bar(struct udevice *dev, int bar, int flags,
1484                                int ea_off, struct pci_child_plat *pdata)
1485 {
1486         int ea_cnt, i, entry_size;
1487         int bar_id = (bar - PCI_BASE_ADDRESS_0) >> 2;
1488         u32 ea_entry;
1489         phys_addr_t addr;
1490
1491         if (IS_ENABLED(CONFIG_PCI_SRIOV)) {
1492                 /*
1493                  * In the case of a Virtual Function device, device is
1494                  * Physical function, so pdata will point to required VF
1495                  * specific data.
1496                  */
1497                 if (pdata->is_virtfn)
1498                         bar_id += PCI_EA_BEI_VF_BAR0;
1499         }
1500
1501         /* EA capability structure header */
1502         dm_pci_read_config32(dev, ea_off, &ea_entry);
1503         ea_cnt = (ea_entry >> 16) & PCI_EA_NUM_ENT_MASK;
1504         ea_off += PCI_EA_FIRST_ENT;
1505
1506         for (i = 0; i < ea_cnt; i++, ea_off += entry_size) {
1507                 /* Entry header */
1508                 dm_pci_read_config32(dev, ea_off, &ea_entry);
1509                 entry_size = ((ea_entry & PCI_EA_ES) + 1) << 2;
1510
1511                 if (((ea_entry & PCI_EA_BEI) >> 4) != bar_id)
1512                         continue;
1513
1514                 /* Base address, 1st DW */
1515                 dm_pci_read_config32(dev, ea_off + 4, &ea_entry);
1516                 addr = ea_entry & PCI_EA_FIELD_MASK;
1517                 if (ea_entry & PCI_EA_IS_64) {
1518                         /* Base address, 2nd DW, skip over 4B MaxOffset */
1519                         dm_pci_read_config32(dev, ea_off + 12, &ea_entry);
1520                         addr |= ((u64)ea_entry) << 32;
1521                 }
1522
1523                 if (IS_ENABLED(CONFIG_PCI_SRIOV))
1524                         addr += dm_pci_map_ea_virt(dev, ea_off, pdata);
1525
1526                 /* size ignored for now */
1527                 return map_physmem(addr, 0, flags);
1528         }
1529
1530         return 0;
1531 }
1532
1533 void *dm_pci_map_bar(struct udevice *dev, int bar, int flags)
1534 {
1535         struct pci_child_plat *pdata = dev_get_parent_plat(dev);
1536         struct udevice *udev = dev;
1537         pci_addr_t pci_bus_addr;
1538         u32 bar_response;
1539         int ea_off;
1540
1541         if (IS_ENABLED(CONFIG_PCI_SRIOV)) {
1542                 /*
1543                  * In case of Virtual Function devices, use PF udevice
1544                  * as EA capability is defined in Physical Function
1545                  */
1546                 if (pdata->is_virtfn)
1547                         udev = pdata->pfdev;
1548         }
1549
1550         /*
1551          * if the function supports Enhanced Allocation use that instead of
1552          * BARs
1553          * Incase of virtual functions, pdata will help read VF BEI
1554          * and EA entry size.
1555          */
1556         ea_off = dm_pci_find_capability(udev, PCI_CAP_ID_EA);
1557         if (ea_off)
1558                 return dm_pci_map_ea_bar(udev, bar, flags, ea_off, pdata);
1559
1560         /* read BAR address */
1561         dm_pci_read_config32(udev, bar, &bar_response);
1562         pci_bus_addr = (pci_addr_t)(bar_response & ~0xf);
1563
1564         /*
1565          * Pass "0" as the length argument to pci_bus_to_virt.  The arg
1566          * isn't actually used on any platform because U-Boot assumes a static
1567          * linear mapping.  In the future, this could read the BAR size
1568          * and pass that as the size if needed.
1569          */
1570         return dm_pci_bus_to_virt(udev, pci_bus_addr, flags, 0, MAP_NOCACHE);
1571 }
1572
1573 static int _dm_pci_find_next_capability(struct udevice *dev, u8 pos, int cap)
1574 {
1575         int ttl = PCI_FIND_CAP_TTL;
1576         u8 id;
1577         u16 ent;
1578
1579         dm_pci_read_config8(dev, pos, &pos);
1580
1581         while (ttl--) {
1582                 if (pos < PCI_STD_HEADER_SIZEOF)
1583                         break;
1584                 pos &= ~3;
1585                 dm_pci_read_config16(dev, pos, &ent);
1586
1587                 id = ent & 0xff;
1588                 if (id == 0xff)
1589                         break;
1590                 if (id == cap)
1591                         return pos;
1592                 pos = (ent >> 8);
1593         }
1594
1595         return 0;
1596 }
1597
1598 int dm_pci_find_next_capability(struct udevice *dev, u8 start, int cap)
1599 {
1600         return _dm_pci_find_next_capability(dev, start + PCI_CAP_LIST_NEXT,
1601                                             cap);
1602 }
1603
1604 int dm_pci_find_capability(struct udevice *dev, int cap)
1605 {
1606         u16 status;
1607         u8 header_type;
1608         u8 pos;
1609
1610         dm_pci_read_config16(dev, PCI_STATUS, &status);
1611         if (!(status & PCI_STATUS_CAP_LIST))
1612                 return 0;
1613
1614         dm_pci_read_config8(dev, PCI_HEADER_TYPE, &header_type);
1615         if ((header_type & 0x7f) == PCI_HEADER_TYPE_CARDBUS)
1616                 pos = PCI_CB_CAPABILITY_LIST;
1617         else
1618                 pos = PCI_CAPABILITY_LIST;
1619
1620         return _dm_pci_find_next_capability(dev, pos, cap);
1621 }
1622
1623 int dm_pci_find_next_ext_capability(struct udevice *dev, int start, int cap)
1624 {
1625         u32 header;
1626         int ttl;
1627         int pos = PCI_CFG_SPACE_SIZE;
1628
1629         /* minimum 8 bytes per capability */
1630         ttl = (PCI_CFG_SPACE_EXP_SIZE - PCI_CFG_SPACE_SIZE) / 8;
1631
1632         if (start)
1633                 pos = start;
1634
1635         dm_pci_read_config32(dev, pos, &header);
1636         /*
1637          * If we have no capabilities, this is indicated by cap ID,
1638          * cap version and next pointer all being 0.
1639          */
1640         if (header == 0)
1641                 return 0;
1642
1643         while (ttl--) {
1644                 if (PCI_EXT_CAP_ID(header) == cap)
1645                         return pos;
1646
1647                 pos = PCI_EXT_CAP_NEXT(header);
1648                 if (pos < PCI_CFG_SPACE_SIZE)
1649                         break;
1650
1651                 dm_pci_read_config32(dev, pos, &header);
1652         }
1653
1654         return 0;
1655 }
1656
1657 int dm_pci_find_ext_capability(struct udevice *dev, int cap)
1658 {
1659         return dm_pci_find_next_ext_capability(dev, 0, cap);
1660 }
1661
1662 int dm_pci_flr(struct udevice *dev)
1663 {
1664         int pcie_off;
1665         u32 cap;
1666
1667         /* look for PCI Express Capability */
1668         pcie_off = dm_pci_find_capability(dev, PCI_CAP_ID_EXP);
1669         if (!pcie_off)
1670                 return -ENOENT;
1671
1672         /* check FLR capability */
1673         dm_pci_read_config32(dev, pcie_off + PCI_EXP_DEVCAP, &cap);
1674         if (!(cap & PCI_EXP_DEVCAP_FLR))
1675                 return -ENOENT;
1676
1677         dm_pci_clrset_config16(dev, pcie_off + PCI_EXP_DEVCTL, 0,
1678                                PCI_EXP_DEVCTL_BCR_FLR);
1679
1680         /* wait 100ms, per PCI spec */
1681         mdelay(100);
1682
1683         return 0;
1684 }
1685
1686 #if defined(CONFIG_PCI_SRIOV)
1687 int pci_sriov_init(struct udevice *pdev, int vf_en)
1688 {
1689         u16 vendor, device;
1690         struct udevice *bus;
1691         struct udevice *dev;
1692         pci_dev_t bdf;
1693         u16 ctrl;
1694         u16 num_vfs;
1695         u16 total_vf;
1696         u16 vf_offset;
1697         u16 vf_stride;
1698         int vf, ret;
1699         int pos;
1700
1701         pos = dm_pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_SRIOV);
1702         if (!pos) {
1703                 debug("Error: SRIOV capability not found\n");
1704                 return -ENOENT;
1705         }
1706
1707         dm_pci_read_config16(pdev, pos + PCI_SRIOV_CTRL, &ctrl);
1708
1709         dm_pci_read_config16(pdev, pos + PCI_SRIOV_TOTAL_VF, &total_vf);
1710         if (vf_en > total_vf)
1711                 vf_en = total_vf;
1712         dm_pci_write_config16(pdev, pos + PCI_SRIOV_NUM_VF, vf_en);
1713
1714         ctrl |= PCI_SRIOV_CTRL_VFE | PCI_SRIOV_CTRL_MSE;
1715         dm_pci_write_config16(pdev, pos + PCI_SRIOV_CTRL, ctrl);
1716
1717         dm_pci_read_config16(pdev, pos + PCI_SRIOV_NUM_VF, &num_vfs);
1718         if (num_vfs > vf_en)
1719                 num_vfs = vf_en;
1720
1721         dm_pci_read_config16(pdev, pos + PCI_SRIOV_VF_OFFSET, &vf_offset);
1722         dm_pci_read_config16(pdev, pos + PCI_SRIOV_VF_STRIDE, &vf_stride);
1723
1724         dm_pci_read_config16(pdev, PCI_VENDOR_ID, &vendor);
1725         dm_pci_read_config16(pdev, pos + PCI_SRIOV_VF_DID, &device);
1726
1727         bdf = dm_pci_get_bdf(pdev);
1728
1729         pci_get_bus(PCI_BUS(bdf), &bus);
1730
1731         if (!bus)
1732                 return -ENODEV;
1733
1734         bdf += PCI_BDF(0, 0, vf_offset);
1735
1736         for (vf = 0; vf < num_vfs; vf++) {
1737                 struct pci_child_plat *pplat;
1738                 ulong class;
1739
1740                 pci_bus_read_config(bus, bdf, PCI_CLASS_DEVICE,
1741                                     &class, PCI_SIZE_16);
1742
1743                 debug("%s: bus %d/%s: found VF %x:%x\n", __func__,
1744                       dev_seq(bus), bus->name, PCI_DEV(bdf), PCI_FUNC(bdf));
1745
1746                 /* Find this device in the device tree */
1747                 ret = pci_bus_find_devfn(bus, PCI_MASK_BUS(bdf), &dev);
1748
1749                 if (ret == -ENODEV) {
1750                         struct pci_device_id find_id;
1751
1752                         memset(&find_id, '\0', sizeof(find_id));
1753                         find_id.vendor = vendor;
1754                         find_id.device = device;
1755                         find_id.class = class;
1756
1757                         ret = pci_find_and_bind_driver(bus, &find_id,
1758                                                        bdf, &dev);
1759
1760                         if (ret)
1761                                 return ret;
1762                 }
1763
1764                 /* Update the platform data */
1765                 pplat = dev_get_parent_plat(dev);
1766                 pplat->devfn = PCI_MASK_BUS(bdf);
1767                 pplat->vendor = vendor;
1768                 pplat->device = device;
1769                 pplat->class = class;
1770                 pplat->is_virtfn = true;
1771                 pplat->pfdev = pdev;
1772                 pplat->virtid = vf * vf_stride + vf_offset;
1773
1774                 debug("%s: bus %d/%s: found VF %x:%x %x:%x class %lx id %x\n",
1775                       __func__, dev_seq(dev), dev->name, PCI_DEV(bdf),
1776                       PCI_FUNC(bdf), vendor, device, class, pplat->virtid);
1777                 bdf += PCI_BDF(0, 0, vf_stride);
1778         }
1779
1780         return 0;
1781 }
1782
1783 int pci_sriov_get_totalvfs(struct udevice *pdev)
1784 {
1785         u16 total_vf;
1786         int pos;
1787
1788         pos = dm_pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_SRIOV);
1789         if (!pos) {
1790                 debug("Error: SRIOV capability not found\n");
1791                 return -ENOENT;
1792         }
1793
1794         dm_pci_read_config16(pdev, pos + PCI_SRIOV_TOTAL_VF, &total_vf);
1795
1796         return total_vf;
1797 }
1798 #endif /* SRIOV */
1799
1800 UCLASS_DRIVER(pci) = {
1801         .id             = UCLASS_PCI,
1802         .name           = "pci",
1803         .flags          = DM_UC_FLAG_SEQ_ALIAS | DM_UC_FLAG_NO_AUTO_SEQ,
1804         .post_bind      = dm_scan_fdt_dev,
1805         .pre_probe      = pci_uclass_pre_probe,
1806         .post_probe     = pci_uclass_post_probe,
1807         .child_post_bind = pci_uclass_child_post_bind,
1808         .per_device_auto        = sizeof(struct pci_controller),
1809         .per_child_plat_auto    = sizeof(struct pci_child_plat),
1810 };
1811
1812 static const struct dm_pci_ops pci_bridge_ops = {
1813         .read_config    = pci_bridge_read_config,
1814         .write_config   = pci_bridge_write_config,
1815 };
1816
1817 static const struct udevice_id pci_bridge_ids[] = {
1818         { .compatible = "pci-bridge" },
1819         { }
1820 };
1821
1822 U_BOOT_DRIVER(pci_bridge_drv) = {
1823         .name           = "pci_bridge_drv",
1824         .id             = UCLASS_PCI,
1825         .of_match       = pci_bridge_ids,
1826         .ops            = &pci_bridge_ops,
1827 };
1828
1829 UCLASS_DRIVER(pci_generic) = {
1830         .id             = UCLASS_PCI_GENERIC,
1831         .name           = "pci_generic",
1832 };
1833
1834 static const struct udevice_id pci_generic_ids[] = {
1835         { .compatible = "pci-generic" },
1836         { }
1837 };
1838
1839 U_BOOT_DRIVER(pci_generic_drv) = {
1840         .name           = "pci_generic_drv",
1841         .id             = UCLASS_PCI_GENERIC,
1842         .of_match       = pci_generic_ids,
1843 };
1844
1845 void pci_init(void)
1846 {
1847         struct udevice *bus;
1848
1849         /*
1850          * Enumerate all known controller devices. Enumeration has the side-
1851          * effect of probing them, so PCIe devices will be enumerated too.
1852          */
1853         for (uclass_first_device_check(UCLASS_PCI, &bus);
1854              bus;
1855              uclass_next_device_check(&bus)) {
1856                 ;
1857         }
1858 }