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 <fdtdec.h>
10 #include <linux/libfdt.h>
11 #include <pci.h>
12 #include <dm/lists.h>
13 
14 struct sandbox_pci_emul_priv {
15 	int dev_count;
16 };
17 
18 int sandbox_pci_get_emul(struct udevice *bus, pci_dev_t find_devfn,
19 			 struct udevice **containerp, struct udevice **emulp)
20 {
21 	struct udevice *dev;
22 	int ret;
23 
24 	*containerp = NULL;
25 	ret = pci_bus_find_devfn(bus, PCI_MASK_BUS(find_devfn), &dev);
26 	if (ret) {
27 		debug("%s: Could not find emulator for dev %x\n", __func__,
28 		      find_devfn);
29 		return ret;
30 	}
31 	*containerp = dev;
32 
33 	if (device_get_uclass_id(dev) == UCLASS_PCI_GENERIC) {
34 		ret = device_find_first_child(dev, emulp);
35 		if (ret)
36 			return ret;
37 	} else {
38 		*emulp = dev;
39 	}
40 
41 	return *emulp ? 0 : -ENODEV;
42 }
43 
44 static int sandbox_pci_emul_post_probe(struct udevice *dev)
45 {
46 	struct sandbox_pci_emul_priv *priv = dev->uclass->priv;
47 
48 	priv->dev_count++;
49 	sandbox_set_enable_pci_map(true);
50 
51 	return 0;
52 }
53 
54 static int sandbox_pci_emul_pre_remove(struct udevice *dev)
55 {
56 	struct sandbox_pci_emul_priv *priv = dev->uclass->priv;
57 
58 	priv->dev_count--;
59 	sandbox_set_enable_pci_map(priv->dev_count > 0);
60 
61 	return 0;
62 }
63 
64 UCLASS_DRIVER(pci_emul) = {
65 	.id		= UCLASS_PCI_EMUL,
66 	.name		= "pci_emul",
67 	.post_probe	= sandbox_pci_emul_post_probe,
68 	.pre_remove	= sandbox_pci_emul_pre_remove,
69 	.priv_auto_alloc_size	= sizeof(struct sandbox_pci_emul_priv),
70 };
71