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