xref: /freebsd/sys/compat/linuxkpi/common/src/linux_pci.c (revision 5180fce1cf7ec7430ccf2adb88358602e5ccee1e)
1 /*-
2  * Copyright (c) 2015-2016 Mellanox Technologies, Ltd.
3  * All rights reserved.
4  * Copyright (c) 2020-2026 The FreeBSD Foundation
5  *
6  * Portions of this software were developed by Björn Zeeb
7  * under sponsorship from the FreeBSD Foundation.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice unmodified, this list of conditions, and the following
14  *    disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30 
31 /*
32  * This file contains multiple parts:
33  * (1) PCI
34  * (2) DMA
35  * (3) Backlight
36  * (4) Native bus attachment glue.
37  */
38 
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/bus.h>
42 #include <sys/malloc.h>
43 #include <sys/kernel.h>
44 #include <sys/sysctl.h>
45 #include <sys/lock.h>
46 #include <sys/mutex.h>
47 #include <sys/fcntl.h>
48 #include <sys/file.h>
49 #include <sys/filio.h>
50 #include <sys/pciio.h>
51 #include <sys/pctrie.h>
52 #include <sys/rman.h>
53 #include <sys/rwlock.h>
54 #include <sys/stdarg.h>
55 
56 #include <vm/vm.h>
57 #include <vm/pmap.h>
58 
59 #include <machine/bus.h>
60 #include <machine/resource.h>
61 
62 #include <dev/pci/pcivar.h>
63 #include <dev/pci/pci_private.h>
64 #include <dev/pci/pci_iov.h>
65 #include <dev/backlight/backlight.h>
66 
67 #include <linux/kernel.h>
68 #include <linux/kobject.h>
69 #include <linux/device.h>
70 #include <linux/slab.h>
71 #include <linux/module.h>
72 #include <linux/cdev.h>
73 #include <linux/file.h>
74 #include <linux/sysfs.h>
75 #include <linux/mm.h>
76 #include <linux/io.h>
77 #include <linux/vmalloc.h>
78 #define	WANT_NATIVE_PCI_GET_SLOT
79 #include <linux/pci.h>
80 #include <linux/compat.h>
81 
82 #include <linux/backlight.h>
83 
84 #include "backlight_if.h"
85 #include "pcib_if.h"
86 
87 /* -------------------------------------------------------------------------- */
88 /*
89  * For PCI:
90  * we have two ways to create a pci_dev (pdev):
91  * (1) coming from the device_attach DEVMETHOD, and
92  * (2) from manual creation via lkpinew_pci_dev(), in which case
93  *     we have no driver (pdev->pdrv).
94  *
95  * Only devices from (1) end up on our LinuxKPI global lkpi_pci_devices list.
96  */
97 
98 /* Undef the linux function macro defined in linux/pci.h */
99 #undef pci_get_class
100 
101 static void lkpi_pcim_iomap_table_release(struct device *, void *);
102 
103 extern int linuxkpi_debug;
104 SYSCTL_DECL(_compat_linuxkpi);
105 
106 static device_method_t pci_methods[];
107 
108 static struct list_head lkpi_pci_drivers;
109 static struct list_head lkpi_pci_devices;
110 static spinlock_t lkpi_pci_lock;
111 
112 #define	LKPI_PCI_LOCK_INIT()		spin_lock_init(&lkpi_pci_lock)
113 #define	LKPI_PCI_LOCK_DESTROY()		spin_lock_destroy(&lkpi_pci_lock)
114 #define	LKPI_PCI_LOCK()			spin_lock(&lkpi_pci_lock)
115 #define	LKPI_PCI_UNLOCK()		spin_unlock(&lkpi_pci_lock)
116 
117 const char *pci_power_names[] = {
118 	"UNKNOWN", "D0", "D1", "D2", "D3hot", "D3cold"
119 };
120 
121 /* We need some meta-struct to keep track of these for devres. */
122 struct pci_devres {
123 	bool		enable_io;
124 	/* PCIR_MAX_BAR_0 + 1 = 6 => BIT(0..5). */
125 	uint8_t		region_mask;
126 	struct resource	*region_table[PCIR_MAX_BAR_0 + 1]; /* Not needed. */
127 };
128 struct pcim_iomap_devres {
129 	void		*mmio_table[PCIR_MAX_BAR_0 + 1];
130 	struct resource	*res_table[PCIR_MAX_BAR_0 + 1];
131 };
132 
133 struct linux_dma_priv {
134 	uint64_t	dma_mask;
135 	bus_dma_tag_t	dmat;
136 	uint64_t	dma_coherent_mask;
137 	bus_dma_tag_t	dmat_coherent;
138 	struct mtx	lock;
139 	struct pctrie	ptree;
140 };
141 #define	DMA_PRIV_LOCK(priv) mtx_lock(&(priv)->lock)
142 #define	DMA_PRIV_UNLOCK(priv) mtx_unlock(&(priv)->lock)
143 
144 static struct resource_list_entry *
145 lkpi_pci_reserve_bar(struct pci_dev *pdev, struct resource_list *rl,
146     int type, int rid)
147 {
148 	device_t dev;
149 	struct resource *res;
150 
151 	KASSERT(type == SYS_RES_IOPORT || type == SYS_RES_MEMORY,
152 	    ("trying to reserve non-BAR type %d", type));
153 
154 	dev = pdev->pdrv != NULL && pdev->pdrv->isdrm ?
155 	    device_get_parent(pdev->dev.bsddev) : pdev->dev.bsddev;
156 	res = pci_reserve_map(device_get_parent(dev), dev, type, rid, 0, ~0,
157 	    1, 1, 0);
158 	if (res == NULL)
159 		return (NULL);
160 	return (resource_list_find(rl, type, rid));
161 }
162 
163 static struct resource_list_entry *
164 lkpi_pci_get_rle(struct pci_dev *pdev, int type, int rid, bool reserve_bar)
165 {
166 	struct pci_devinfo *dinfo;
167 	struct resource_list *rl;
168 	struct resource_list_entry *rle;
169 
170 	dinfo = device_get_ivars(pdev->dev.bsddev);
171 	rl = &dinfo->resources;
172 	rle = resource_list_find(rl, type, rid);
173 	/* Reserve resources for this BAR if needed. */
174 	if (rle == NULL && reserve_bar)
175 		rle = lkpi_pci_reserve_bar(pdev, rl, type, rid);
176 	return (rle);
177 }
178 
179 static int
180 linux_pdev_dma_uninit(struct pci_dev *pdev)
181 {
182 	struct linux_dma_priv *priv;
183 
184 	priv = pdev->dev.dma_priv;
185 	if (priv == NULL)
186 		return (0);
187 	if (priv->dmat)
188 		bus_dma_tag_destroy(priv->dmat);
189 	if (priv->dmat_coherent)
190 		bus_dma_tag_destroy(priv->dmat_coherent);
191 	mtx_destroy(&priv->lock);
192 	pdev->dev.dma_priv = NULL;
193 	free(priv, M_DEVBUF);
194 	return (0);
195 }
196 
197 static int
198 linux_pdev_dma_init(struct pci_dev *pdev)
199 {
200 	struct linux_dma_priv *priv;
201 	int error;
202 
203 	priv = malloc(sizeof(*priv), M_DEVBUF, M_WAITOK | M_ZERO);
204 
205 	mtx_init(&priv->lock, "lkpi-priv-dma", NULL, MTX_DEF);
206 	pctrie_init(&priv->ptree);
207 
208 	pdev->dev.dma_priv = priv;
209 
210 	/* Create a default DMA tags. */
211 	error = linux_dma_tag_init(&pdev->dev, DMA_BIT_MASK(64));
212 	if (error != 0)
213 		goto err;
214 	/* Coherent is lower 32bit only by default in Linux. */
215 	error = linux_dma_tag_init_coherent(&pdev->dev, DMA_BIT_MASK(32));
216 	if (error != 0)
217 		goto err;
218 
219 	return (error);
220 
221 err:
222 	linux_pdev_dma_uninit(pdev);
223 	return (error);
224 }
225 
226 int
227 linux_dma_tag_init(struct device *dev, u64 dma_mask)
228 {
229 	struct linux_dma_priv *priv;
230 	int error;
231 
232 	priv = dev->dma_priv;
233 
234 	if (priv->dmat) {
235 		if (priv->dma_mask == dma_mask)
236 			return (0);
237 
238 		bus_dma_tag_destroy(priv->dmat);
239 	}
240 
241 	priv->dma_mask = dma_mask;
242 
243 	error = bus_dma_tag_create(bus_get_dma_tag(dev->bsddev),
244 	    1, 0,			/* alignment, boundary */
245 	    dma_mask,			/* lowaddr */
246 	    BUS_SPACE_MAXADDR,		/* highaddr */
247 	    NULL, NULL,			/* filtfunc, filtfuncarg */
248 	    BUS_SPACE_MAXSIZE,		/* maxsize */
249 	    1,				/* nsegments */
250 	    BUS_SPACE_MAXSIZE,		/* maxsegsz */
251 	    0,				/* flags */
252 	    NULL, NULL,			/* lockfunc, lockfuncarg */
253 	    &priv->dmat);
254 	return (-error);
255 }
256 
257 int
258 linux_dma_tag_init_coherent(struct device *dev, u64 dma_mask)
259 {
260 	struct linux_dma_priv *priv;
261 	int error;
262 
263 	priv = dev->dma_priv;
264 
265 	if (priv->dmat_coherent) {
266 		if (priv->dma_coherent_mask == dma_mask)
267 			return (0);
268 
269 		bus_dma_tag_destroy(priv->dmat_coherent);
270 	}
271 
272 	priv->dma_coherent_mask = dma_mask;
273 
274 	error = bus_dma_tag_create(bus_get_dma_tag(dev->bsddev),
275 	    1, 0,			/* alignment, boundary */
276 	    dma_mask,			/* lowaddr */
277 	    BUS_SPACE_MAXADDR,		/* highaddr */
278 	    NULL, NULL,			/* filtfunc, filtfuncarg */
279 	    BUS_SPACE_MAXSIZE,		/* maxsize */
280 	    1,				/* nsegments */
281 	    BUS_SPACE_MAXSIZE,		/* maxsegsz */
282 	    0,				/* flags */
283 	    NULL, NULL,			/* lockfunc, lockfuncarg */
284 	    &priv->dmat_coherent);
285 	return (-error);
286 }
287 
288 static struct pci_driver *
289 linux_pci_find(device_t dev, const struct pci_device_id **idp)
290 {
291 	const struct pci_device_id *id;
292 	struct pci_driver *pdrv;
293 	uint16_t vendor;
294 	uint16_t device;
295 	uint16_t subvendor;
296 	uint16_t subdevice;
297 
298 	vendor = pci_get_vendor(dev);
299 	device = pci_get_device(dev);
300 	subvendor = pci_get_subvendor(dev);
301 	subdevice = pci_get_subdevice(dev);
302 
303 	LKPI_PCI_LOCK();
304 	list_for_each_entry(pdrv, &lkpi_pci_drivers, node) {
305 		for (id = pdrv->id_table; id->vendor != 0; id++) {
306 			if (vendor == id->vendor &&
307 			    (PCI_ANY_ID == id->device || device == id->device) &&
308 			    (PCI_ANY_ID == id->subvendor || subvendor == id->subvendor) &&
309 			    (PCI_ANY_ID == id->subdevice || subdevice == id->subdevice)) {
310 				*idp = id;
311 				LKPI_PCI_UNLOCK();
312 				return (pdrv);
313 			}
314 		}
315 	}
316 	LKPI_PCI_UNLOCK();
317 	return (NULL);
318 }
319 
320 struct pci_dev *
321 lkpi_pci_get_device(uint32_t vendor, uint32_t device, struct pci_dev *odev)
322 {
323 	struct pci_dev *pdev, *found, *odev0;
324 
325 	odev0 = odev;
326 	found = NULL;
327 	LKPI_PCI_LOCK();
328 	list_for_each_entry(pdev, &lkpi_pci_devices, links) {
329 		/* Walk until we find odev. */
330 		if (odev != NULL) {
331 			if (pdev == odev)
332 				odev = NULL;
333 			continue;
334 		}
335 
336 		if ((pdev->vendor == vendor || vendor == PCI_ANY_ID) &&
337 		    (pdev->device == device || device == PCI_ANY_ID)) {
338 			found = pdev;
339 			break;
340 		}
341 	}
342 	pci_dev_get(found);
343 	LKPI_PCI_UNLOCK();
344 	pci_dev_put(odev0);
345 
346 	return (found);
347 }
348 
349 /*
350  * Shared helper function releasing the bus resources which can be built
351  * independent of the way we allocate/initialization the pdev
352  * [pci_upstream_bridge(), pcie_find_root_port()].
353  */
354 static void
355 lkpi_pci_dev_release_common_bus(struct pci_dev *pdev)
356 {
357 	/* Clear the hierarchy recursively to root. */
358 	if (pdev->bus->self != pdev) {
359 		pci_dev_put(pdev->bus->self);
360 		pdev->bus->self = NULL;
361 	}
362 
363 	if (pdev->root != NULL) {
364 		pci_dev_put(pdev->root);
365 		pdev->root = NULL;
366 	}
367 }
368 
369 /* Release helper function to free resources acquired by lkpi_pci_dev_init_common(). */
370 static void
371 lkpi_pci_dev_release_common(struct device *dev)
372 {
373 	struct pci_dev *pdev;
374 
375 	pdev = to_pci_dev(dev);
376 
377 	if (!list_empty_careful(&pdev->dev.irqents)) {
378 		dev_warn(&pdev->dev, "%s: driver did not clean up; "
379 		    "leaking IRQs\n", __func__);
380 		/*
381 		 * XXX add private function to interrupt.h/linux_interrupt.c
382 		 * to walk the list and call free_irq on each if we have to.
383 		 */
384 	}
385 
386 	spin_lock_destroy(&dev->devres_lock);
387 	spin_lock_destroy(&pdev->pcie_cap_lock);
388 
389 	if (!TAILQ_EMPTY(&pdev->mmio)) {
390 		dev_warn(&pdev->dev, "%s: driver did not clean up; "
391 		    "leaking mmio resources\n", __func__);
392 		/* XXX we have two functions to walk and release in here. */
393 	}
394 
395 	if (pdev->msi_desc != NULL) {
396 		for (int i = pci_msi_count(pdev->dev.bsddev) - 1; i >= 0; i--)
397 			free(pdev->msi_desc[i], M_DEVBUF);
398 		free(pdev->msi_desc, M_DEVBUF);
399 	}
400 
401 	free(pdev->bus, M_DEVBUF);
402 	kfree(pdev->path_name);
403 }
404 
405 /*
406  * This is the .release function for the bus attachments
407  * [linux_pci_attach_device()], called when the kobj reference drops to 0.
408  * Note well: there should be no direct calls of this.
409  */
410 static void
411 lkpi_pci_dev_release(struct device *dev)
412 {
413 	struct pci_dev *pdev;
414 
415 	/*
416 	 * Before anything else, we have to free all the dynamic
417 	 * resource which are on the devres list.
418 	 * Otherwise we risk that supporting infrastructure
419 	 * is gone and we panic 'randomly'.
420 	 */
421 	lkpi_devres_release_free_list(dev);
422 
423 	/*
424 	 * Now undo linux_pci_attach_device() in reverse-ish
425 	 * order.
426 	 */
427 	pdev = to_pci_dev(dev);
428 
429 	/*
430 	 * pdrv->remove happens before pci_put_dev() in
431 	 * linux_pci_detach_device(), which means the driver should have
432 	 * cleaned up before we get here; see irqents and mmio below.
433 	 */
434 
435 	/* Clear the hierarchy recursively to root. */
436 	lkpi_pci_dev_release_common_bus(pdev);
437 
438 	LKPI_PCI_LOCK();
439 	list_del(&pdev->links);
440 	LKPI_PCI_UNLOCK();
441 
442 	linux_pdev_dma_uninit(pdev);
443 
444 	/* irq? */
445 
446 	/* Undo lkpi_pci_dev_init_common(). */
447 	/* devres is gone already; went at the very top. */
448 	lkpi_pci_dev_release_common(dev);
449 
450 	/*
451 	 * Lastly, apply an internal hack in order to signal
452 	 * that this was run (device reference fully dropped).
453 	 * See comment in linux_pci_detach_device().
454 	 */
455 	pdev->dev.release = NULL;
456 }
457 
458 /*
459  * This is the .release function for lkpinew_pci_dev(), called when the kobj
460  * reference drops to 0.
461  * Note well: there should be no direct calls of this.
462  */
463 static void
464 lkpinew_pci_dev_release(struct device *dev)
465 {
466 	struct pci_dev *pdev;
467 
468 	pdev = to_pci_dev(dev);
469 
470 	/* The root/bus structure could be built up w/o us having asked for it. */
471 	lkpi_pci_dev_release_common_bus(pdev);
472 	/* Cleanup the lkpi_pci_dev_init_common() resources. */
473 	lkpi_pci_dev_release_common(dev);
474 
475 	free(pdev, M_DEVBUF);
476 }
477 
478 /*
479  * Helper function to iniatlize most of the pdev, dev, .. parts.
480  * This is share by both pdev creation code paths (bus or function call).
481  */
482 static int
483 lkpi_pci_dev_init_common(device_t dev, struct pci_dev *pdev)
484 {
485 	struct pci_devinfo *dinfo;
486 	int error;
487 
488 	error = kobject_init_and_add(&pdev->dev.kobj, &linux_dev_ktype,
489 	    &linux_root_device.kobj, device_get_nameunit(dev));
490 	if (error != 0) {
491 		printf("%s:%d: kobject_init_and_add returned %d\n",
492 		    __func__, __LINE__, error);
493 		return (error);
494 	}
495 
496 	pdev->devfn = PCI_DEVFN(pci_get_slot(dev), pci_get_function(dev));
497 	pdev->vendor = pci_get_vendor(dev);
498 	pdev->device = pci_get_device(dev);
499 	pdev->subsystem_vendor = pci_get_subvendor(dev);
500 	pdev->subsystem_device = pci_get_subdevice(dev);
501 	pdev->class = pci_get_class(dev);
502 	pdev->revision = pci_get_revid(dev);
503 	pdev->path_name = kasprintf(GFP_KERNEL, "%04d:%02d:%02d.%d",
504 	    pci_get_domain(dev), pci_get_bus(dev), pci_get_slot(dev),
505 	    pci_get_function(dev));
506 
507 	pdev->bus = malloc(sizeof(*pdev->bus), M_DEVBUF, M_WAITOK | M_ZERO);
508 	pdev->bus->number = pci_get_bus(dev);
509 	pdev->bus->domain = pci_get_domain(dev);
510 
511 	/* Check if we have reached the root to satisfy pci_is_root_bus() */
512 	dinfo = device_get_ivars(dev);
513 	if (dinfo->cfg.pcie.pcie_location != 0 &&
514 	    dinfo->cfg.pcie.pcie_type == PCIEM_TYPE_ROOT_PORT) {
515 		pdev->bus->self = NULL;
516 	} else {
517 		/*
518 		 * This should be the upstream bridge; pci_upstream_bridge()
519 		 * handles that case on demand as otherwise we'll shadow the
520 		 * entire PCI hierarchy.
521 		 */
522 		pdev->bus->self = pdev;
523 	}
524 	pdev->dev.bsddev = dev;
525 	pdev->dev.parent = &linux_root_device;
526 
527 	if (pci_msi_count(dev) > 0)
528 		pdev->msi_desc = malloc(pci_msi_count(dev) *
529 		    sizeof(*pdev->msi_desc), M_DEVBUF, M_WAITOK | M_ZERO);
530 
531 	TAILQ_INIT(&pdev->mmio);
532 	spin_lock_init(&pdev->pcie_cap_lock);
533 	spin_lock_init(&pdev->dev.devres_lock);
534 	INIT_LIST_HEAD(&pdev->dev.devres_head);
535 	INIT_LIST_HEAD(&pdev->dev.irqents);
536 	INIT_LIST_HEAD(&pdev->links);
537 
538 	return (0);
539 }
540 
541 /*
542  * LinuxKPI PCI dev (pdev) creation by function call.
543  */
544 struct pci_dev *
545 lkpinew_pci_dev(device_t dev)
546 {
547 	struct pci_dev *pdev;
548 	int error;
549 
550 	pdev = malloc(sizeof(*pdev), M_DEVBUF, M_WAITOK|M_ZERO);
551 	error = lkpi_pci_dev_init_common(dev, pdev);
552 	if (error != 0) {
553 		free(pdev, M_DEVBUF);
554 		return (NULL);
555 	}
556 	pdev->dev.release = lkpinew_pci_dev_release;
557 
558 	return (pdev);
559 }
560 
561 struct pci_dev *
562 lkpi_pci_get_class(unsigned int class, struct pci_dev *from)
563 {
564 	device_t dev;
565 	device_t devfrom = NULL;
566 	struct pci_dev *pdev;
567 
568 	if (from != NULL)
569 		devfrom = from->dev.bsddev;
570 
571 	dev = pci_find_class_from(class >> 16, (class >> 8) & 0xFF, devfrom);
572 	if (dev == NULL)
573 		return (NULL);
574 
575 	pdev = lkpinew_pci_dev(dev);
576 	return (pdev);
577 }
578 
579 struct pci_dev *
580 lkpi_pci_get_base_class(unsigned int baseclass, struct pci_dev *from)
581 {
582 	device_t dev;
583 	device_t devfrom = NULL;
584 	struct pci_dev *pdev;
585 
586 	if (from != NULL)
587 		devfrom = from->dev.bsddev;
588 
589 	dev = pci_find_base_class_from(baseclass, devfrom);
590 	if (dev == NULL)
591 		return (NULL);
592 
593 	pdev = lkpinew_pci_dev(dev);
594 	return (pdev);
595 }
596 
597 struct pci_dev *
598 lkpi_pci_get_domain_bus_and_slot(int domain, unsigned int bus,
599     unsigned int devfn)
600 {
601 	device_t dev;
602 	struct pci_dev *pdev;
603 
604 	dev = pci_find_dbsf(domain, bus, PCI_SLOT(devfn), PCI_FUNC(devfn));
605 	if (dev == NULL)
606 		return (NULL);
607 
608 	pdev = lkpinew_pci_dev(dev);
609 	return (pdev);
610 }
611 
612 struct pci_dev *
613 lkpi_pci_get_slot(struct pci_bus *pbus, unsigned int devfn)
614 {
615 	device_t dev;
616 	struct pci_dev *pdev;
617 
618 	dev = pci_find_bsf(pbus->number, PCI_SLOT(devfn), PCI_FUNC(devfn));
619 	if (dev == NULL)
620 		return (NULL);
621 
622 	pdev = lkpinew_pci_dev(dev);
623 	return (pdev);
624 }
625 
626 
627 /*
628  * LinuxKPI PCI dev (pdev) initialization/free from the BUS functions.
629  */
630 /* Note well: this function is public and used by, e.g. nvidia-drm. */
631 int
632 linux_pci_attach_device(device_t dev, struct pci_driver *pdrv,
633     const struct pci_device_id *id, struct pci_dev *pdev)
634 {
635 	struct resource_list_entry *rle;
636 	device_t parent;
637 	struct pci_dev *pbus, *ppbus;
638 	uintptr_t rid;
639 	int error;
640 	bool isdrm;
641 
642 	linux_set_current(curthread);
643 
644 	parent = device_get_parent(dev);
645 	isdrm = pdrv != NULL && pdrv->isdrm;
646 
647 	if (isdrm) {
648 		struct pci_devinfo *dinfo;
649 
650 		dinfo = device_get_ivars(parent);
651 		device_set_ivars(dev, dinfo);
652 	}
653 
654 	error = lkpi_pci_dev_init_common(dev, pdev);
655 	if (error != 0)
656 		return (error);
657 	pdev->dev.release = lkpi_pci_dev_release;
658 
659 	if (isdrm)
660 		PCI_GET_ID(device_get_parent(parent), parent, PCI_ID_RID, &rid);
661 	else
662 		PCI_GET_ID(parent, dev, PCI_ID_RID, &rid);
663 	pdev->devfn = rid;
664 	pdev->pdrv = pdrv;
665 	rle = lkpi_pci_get_rle(pdev, SYS_RES_IRQ, 0, false);
666 	if (rle != NULL)
667 		pdev->dev.irq = rle->start;
668 	else
669 		pdev->dev.irq = LINUX_IRQ_INVALID;
670 	pdev->irq = pdev->dev.irq;
671 	error = linux_pdev_dma_init(pdev);
672 	if (error)
673 		goto out_err;
674 
675 	LKPI_PCI_LOCK();
676 	list_add(&pdev->links, &lkpi_pci_devices);
677 	LKPI_PCI_UNLOCK();
678 
679 	/*
680 	 * Create the hierarchy now as we cannot on demand later.
681 	 * Take special care of DRM as there is a non-PCI device in the chain.
682 	 */
683 	pbus = pdev;
684 	if (isdrm) {
685 		pbus = lkpinew_pci_dev(parent);
686 		if (pbus == NULL) {
687 			error = ENXIO;
688 			goto out_err;
689 		}
690 	}
691 	pcie_find_root_port(pbus);
692 	if (isdrm)
693 		pdev->root = pbus->root;
694 	ppbus = pci_upstream_bridge(pbus);
695 	while (ppbus != NULL && ppbus != pbus) {
696 		pbus = ppbus;
697 		ppbus = pci_upstream_bridge(pbus);
698 	}
699 
700 	if (pdrv != NULL) {
701 		error = pdrv->probe(pdev, id);
702 		if (error)
703 			goto out_err;
704 	}
705 	return (0);
706 
707 out_err:
708 	put_device(&pdev->dev);
709 	return (-error);
710 }
711 
712 /* Note well: this function is public and used by, e.g. nvidia-drm. */
713 int
714 linux_pci_detach_device(struct pci_dev *pdev)
715 {
716 
717 	linux_set_current(curthread);
718 
719 	/*
720 	 * We cannot do much here as almost everything will have
721 	 * to happen as the last reference to the LinuxKPI device
722 	 * goes away.  That will call the release function,
723 	 * which lkpi_pci_dev_init_common() set.  That is were most
724 	 * of the cleanup will happen.  But before that give
725 	 * the driver a chance to cleanup.
726 	 * The big problem is that the Linux KPI does not
727 	 * report back if it was the last kref (well kref
728 	 * does report back but then kobj, dev, pdev do not).
729 	 * So we have little way of knowing if the release
730 	 * happened or not.  We have to play tricks for that
731 	 * and we can given the softc (pdev) is still valid
732 	 * until we return from here.
733 	 */
734 
735 	if (pdev->pdrv != NULL)
736 		pdev->pdrv->remove(pdev);
737 
738 	pci_dev_put(pdev);
739 
740 	/*
741 	 * We (ab)use the release function as a guard to
742 	 * know if we made it there and the device is gone.
743 	 */
744 	if (pdev->dev.release != lkpi_pci_dev_release)
745 		return (0);
746 
747 	/*
748 	 * Detach failed.
749 	 * We need to re-acquire the ref and wait for
750 	 * the other refs to be gone... In theory this
751 	 * should never happen, so log it!
752 	 * XXX I wish there was a KPI to query the ref.
753 	 *
754 	 * If we do not error and wait, we will have a
755 	 * LinuxKPI device dangling active with pointers
756 	 * but the FreeBSD device_t will be 'gone'.
757 	 */
758 	device_printf(pdev->dev.bsddev, "%s failed due to %u other pending "
759 	    "references on the LinuxKPI device.\n", __func__,
760 	    kref_read(&pdev->dev.kobj.kref));
761 	pci_dev_get(pdev);
762 
763 	return (EBUSY);
764 }
765 
766 /*
767  * Devres resource functions.
768  */
769 static int
770 lkpi_pci_disable_dev(struct device *dev)
771 {
772 
773 	(void) pci_disable_io(dev->bsddev, SYS_RES_MEMORY);
774 	(void) pci_disable_io(dev->bsddev, SYS_RES_IOPORT);
775 	return (0);
776 }
777 
778 static struct pci_devres *
779 lkpi_pci_devres_get_alloc(struct pci_dev *pdev)
780 {
781 	struct pci_devres *dr;
782 
783 	dr = lkpi_devres_find(&pdev->dev, lkpi_pci_devres_release, NULL, NULL);
784 	if (dr == NULL) {
785 		dr = lkpi_devres_alloc(lkpi_pci_devres_release, sizeof(*dr),
786 		    GFP_KERNEL | __GFP_ZERO);
787 		if (dr != NULL)
788 			lkpi_devres_add(&pdev->dev, dr);
789 	}
790 
791 	return (dr);
792 }
793 
794 static struct pci_devres *
795 lkpi_pci_devres_find(struct pci_dev *pdev)
796 {
797 	if (!pdev->managed)
798 		return (NULL);
799 
800 	return (lkpi_pci_devres_get_alloc(pdev));
801 }
802 
803 void
804 lkpi_pci_devres_release(struct device *dev, void *p)
805 {
806 	struct pci_devres *dr;
807 	struct pci_dev *pdev;
808 	int bar;
809 
810 	pdev = to_pci_dev(dev);
811 	dr = p;
812 
813 	if (pdev->msix_enabled)
814 		lkpi_pci_disable_msix(pdev);
815         if (pdev->msi_enabled)
816 		lkpi_pci_disable_msi(pdev);
817 
818 	if (dr->enable_io && lkpi_pci_disable_dev(dev) == 0)
819 		dr->enable_io = false;
820 
821 	if (dr->region_mask == 0)
822 		return;
823 	for (bar = PCIR_MAX_BAR_0; bar >= 0; bar--) {
824 
825 		if ((dr->region_mask & (1 << bar)) == 0)
826 			continue;
827 		pci_release_region(pdev, bar);
828 	}
829 }
830 
831 int
832 linuxkpi_pcim_enable_device(struct pci_dev *pdev)
833 {
834 	struct pci_devres *dr;
835 	int error;
836 
837 	/* Here we cannot run through the pdev->managed check. */
838 	dr = lkpi_pci_devres_get_alloc(pdev);
839 	if (dr == NULL)
840 		return (-ENOMEM);
841 
842 	/* If resources were enabled before do not do it again. */
843 	if (dr->enable_io)
844 		return (0);
845 
846 	error = pci_enable_device(pdev);
847 	if (error == 0)
848 		dr->enable_io = true;
849 
850 	/* This device is not managed. */
851 	pdev->managed = true;
852 
853 	return (error);
854 }
855 
856 static struct pcim_iomap_devres *
857 lkpi_pcim_iomap_devres_find(struct pci_dev *pdev)
858 {
859 	struct pcim_iomap_devres *dr;
860 
861 	dr = lkpi_devres_find(&pdev->dev, lkpi_pcim_iomap_table_release,
862 	    NULL, NULL);
863 	if (dr == NULL) {
864 		dr = lkpi_devres_alloc(lkpi_pcim_iomap_table_release,
865 		    sizeof(*dr), GFP_KERNEL | __GFP_ZERO);
866 		if (dr != NULL)
867 			lkpi_devres_add(&pdev->dev, dr);
868 	}
869 
870 	if (dr == NULL)
871 		device_printf(pdev->dev.bsddev, "%s: NULL\n", __func__);
872 
873 	return (dr);
874 }
875 
876 void __iomem **
877 linuxkpi_pcim_iomap_table(struct pci_dev *pdev)
878 {
879 	struct pcim_iomap_devres *dr;
880 
881 	dr = lkpi_pcim_iomap_devres_find(pdev);
882 	if (dr == NULL)
883 		return (NULL);
884 
885 	/*
886 	 * If the driver has manually set a flag to be able to request the
887 	 * resource to use bus_read/write_<n>, return the shadow table.
888 	 */
889 	if (pdev->want_iomap_res)
890 		return ((void **)dr->res_table);
891 
892 	/* This is the Linux default. */
893 	return (dr->mmio_table);
894 }
895 
896 static bool
897 lkpi_pci_bar_id_valid(int bar)
898 {
899 	if (bar < 0 || bar > PCIR_MAX_BAR_0)
900 		return (false);
901 
902 	return (true);
903 }
904 
905 static struct resource *
906 _lkpi_pci_iomap(struct pci_dev *pdev, int bar, unsigned long maxlen __unused)
907 {
908 	struct pci_mmio_region *mmio, *p;
909 	int type;
910 
911 	if (!lkpi_pci_bar_id_valid(bar))
912 		return (NULL);
913 
914 	type = pci_resource_type(pdev, bar);
915 	if (type < 0) {
916 		device_printf(pdev->dev.bsddev, "%s: bar %d type %d\n",
917 		     __func__, bar, type);
918 		return (NULL);
919 	}
920 
921 	/*
922 	 * Check for duplicate mappings.
923 	 * This can happen if a driver calls pci_request_region() first.
924 	 */
925 	TAILQ_FOREACH_SAFE(mmio, &pdev->mmio, next, p) {
926 		if (mmio->type == type && mmio->rid == PCIR_BAR(bar)) {
927 			return (mmio->res);
928 		}
929 	}
930 
931 	mmio = malloc(sizeof(*mmio), M_DEVBUF, M_WAITOK | M_ZERO);
932 	mmio->rid = PCIR_BAR(bar);
933 	mmio->type = type;
934 	mmio->res = bus_alloc_resource_any(pdev->dev.bsddev, mmio->type,
935 	    &mmio->rid, RF_ACTIVE|RF_SHAREABLE);
936 	if (mmio->res == NULL) {
937 		device_printf(pdev->dev.bsddev, "%s: failed to alloc "
938 		    "bar %d type %d rid %d\n",
939 		    __func__, bar, type, PCIR_BAR(bar));
940 		free(mmio, M_DEVBUF);
941 		return (NULL);
942 	}
943 	TAILQ_INSERT_TAIL(&pdev->mmio, mmio, next);
944 
945 	return (mmio->res);
946 }
947 
948 void *
949 linuxkpi_pci_iomap_range(struct pci_dev *pdev, int bar,
950     unsigned long off, unsigned long maxlen)
951 {
952 	struct resource *res;
953 
954 	if (!lkpi_pci_bar_id_valid(bar))
955 		return (NULL);
956 
957 	res = _lkpi_pci_iomap(pdev, bar, maxlen);
958 	if (res == NULL)
959 		return (NULL);
960 	/* This is a FreeBSD extension so we can use bus_*(). */
961 	if (pdev->want_iomap_res)
962 		return (res);
963 	MPASS(off < rman_get_size(res));
964 	return ((void *)(rman_get_bushandle(res) + off));
965 }
966 
967 void *
968 linuxkpi_pci_iomap(struct pci_dev *pdev, int bar, unsigned long maxlen)
969 {
970 	if (!lkpi_pci_bar_id_valid(bar))
971 		return (NULL);
972 
973 	return (linuxkpi_pci_iomap_range(pdev, bar, 0, maxlen));
974 }
975 
976 static void
977 lkpi_set_pcim_iomap_devres(struct pcim_iomap_devres *dr, int bar,
978     void *res)
979 {
980 	dr->mmio_table[bar] = (void *)rman_get_bushandle(res);
981 	dr->res_table[bar] = res;
982 }
983 
984 void *
985 linuxkpi_pcim_iomap(struct pci_dev *pdev, int bar, unsigned long maxlen)
986 {
987 	struct pcim_iomap_devres *dr;
988 	void *res;
989 
990 	if (!lkpi_pci_bar_id_valid(bar))
991 		return (NULL);
992 
993 	dr = lkpi_pcim_iomap_devres_find(pdev);
994 	if (dr == NULL)
995 		return (NULL);
996 
997 	if (dr->res_table[bar] != NULL)
998 		return (dr->res_table[bar]);
999 
1000 	res = linuxkpi_pci_iomap(pdev, bar, maxlen);
1001 	if (res == NULL) {
1002 		/*
1003 		 * Do not free the devres in case there were
1004 		 * other valid mappings before already.
1005 		 */
1006 		return (NULL);
1007 	}
1008 	lkpi_set_pcim_iomap_devres(dr, bar, res);
1009 
1010 	return (res);
1011 }
1012 
1013 void
1014 linuxkpi_pci_iounmap(struct pci_dev *pdev, void *res)
1015 {
1016 	struct pci_mmio_region *mmio, *p;
1017 	bus_space_handle_t bh = (bus_space_handle_t)res;
1018 
1019 	TAILQ_FOREACH_SAFE(mmio, &pdev->mmio, next, p) {
1020 		if (pdev->want_iomap_res) {
1021 			if (res != mmio->res)
1022 				continue;
1023 		} else {
1024 			if (bh <  rman_get_bushandle(mmio->res) ||
1025 			    bh >= rman_get_bushandle(mmio->res) +
1026 				  rman_get_size(mmio->res))
1027 				continue;
1028 		}
1029 		bus_release_resource(pdev->dev.bsddev,
1030 		    mmio->type, mmio->rid, mmio->res);
1031 		TAILQ_REMOVE(&pdev->mmio, mmio, next);
1032 		free(mmio, M_DEVBUF);
1033 		return;
1034 	}
1035 }
1036 
1037 int
1038 linuxkpi_pcim_iomap_regions(struct pci_dev *pdev, uint32_t mask, const char *name)
1039 {
1040 	struct pcim_iomap_devres *dr;
1041 	void *res;
1042 	uint32_t mappings;
1043 	int bar;
1044 
1045 	dr = lkpi_pcim_iomap_devres_find(pdev);
1046 	if (dr == NULL)
1047 		return (-ENOMEM);
1048 
1049 	/* Now iomap all the requested (by "mask") ones. */
1050 	for (bar = mappings = 0; mappings != mask; bar++) {
1051 		if ((mask & (1 << bar)) == 0)
1052 			continue;
1053 
1054 		/* Request double is not allowed. */
1055 		if (dr->mmio_table[bar] != NULL) {
1056 			device_printf(pdev->dev.bsddev, "%s: bar %d %p\n",
1057 			    __func__, bar, dr->mmio_table[bar]);
1058 			goto err;
1059 		}
1060 
1061 		res = _lkpi_pci_iomap(pdev, bar, 0);
1062 		if (res == NULL)
1063 			goto err;
1064 		lkpi_set_pcim_iomap_devres(dr, bar, res);
1065 
1066 		mappings |= (1 << bar);
1067 	}
1068 
1069 	return (0);
1070 err:
1071 	for (bar = PCIR_MAX_BAR_0; bar >= 0; bar--) {
1072 		if ((mappings & (1 << bar)) != 0) {
1073 			res = dr->mmio_table[bar];
1074 			if (res == NULL)
1075 				continue;
1076 			pci_iounmap(pdev, res);
1077 		}
1078 	}
1079 
1080 	return (-EINVAL);
1081 }
1082 
1083 static void
1084 lkpi_pcim_iomap_table_release(struct device *dev, void *p)
1085 {
1086 	struct pcim_iomap_devres *dr;
1087 	struct pci_dev *pdev;
1088 	int bar;
1089 
1090 	dr = p;
1091 	pdev = to_pci_dev(dev);
1092 	for (bar = PCIR_MAX_BAR_0; bar >= 0; bar--) {
1093 
1094 		if (dr->mmio_table[bar] == NULL)
1095 			continue;
1096 
1097 		pci_iounmap(pdev, dr->mmio_table[bar]);
1098 	}
1099 }
1100 
1101 /*
1102  * Resource functions.
1103  */
1104 static struct resource_list_entry *
1105 lkpi_pci_get_bar(struct pci_dev *pdev, int bar, bool reserve)
1106 {
1107 	int type;
1108 
1109 	type = pci_resource_type(pdev, bar);
1110 	if (type < 0)
1111 		return (NULL);
1112 	bar = PCIR_BAR(bar);
1113 	return (lkpi_pci_get_rle(pdev, type, bar, reserve));
1114 }
1115 
1116 struct device *
1117 lkpi_pci_find_irq_dev(unsigned int irq)
1118 {
1119 	struct pci_dev *pdev;
1120 	struct device *found;
1121 
1122 	found = NULL;
1123 	LKPI_PCI_LOCK();
1124 	list_for_each_entry(pdev, &lkpi_pci_devices, links) {
1125 		if (irq == pdev->dev.irq ||
1126 		    (irq >= pdev->dev.irq_start && irq < pdev->dev.irq_end)) {
1127 			found = &pdev->dev;
1128 			break;
1129 		}
1130 	}
1131 	LKPI_PCI_UNLOCK();
1132 	return (found);
1133 }
1134 
1135 unsigned long
1136 pci_resource_start(struct pci_dev *pdev, int bar)
1137 {
1138 	struct resource_list_entry *rle;
1139 	rman_res_t newstart;
1140 	device_t dev;
1141 	int error;
1142 
1143 	if ((rle = lkpi_pci_get_bar(pdev, bar, true)) == NULL)
1144 		return (0);
1145 	dev = pdev->pdrv != NULL && pdev->pdrv->isdrm ?
1146 	    device_get_parent(pdev->dev.bsddev) : pdev->dev.bsddev;
1147 	error = bus_translate_resource(dev, rle->type, rle->start, &newstart);
1148 	if (error != 0) {
1149 		device_printf(pdev->dev.bsddev,
1150 		    "translate of %#jx failed: %d\n",
1151 		    (uintmax_t)rle->start, error);
1152 		return (0);
1153 	}
1154 	return (newstart);
1155 }
1156 
1157 unsigned long
1158 pci_resource_len(struct pci_dev *pdev, int bar)
1159 {
1160 	struct resource_list_entry *rle;
1161 
1162 	if ((rle = lkpi_pci_get_bar(pdev, bar, true)) == NULL)
1163 		return (0);
1164 	return (rle->count);
1165 }
1166 
1167 static int
1168 lkpi_pci_request_region(struct pci_dev *pdev, int bar, const char *res_name,
1169     bool managed)
1170 {
1171 	struct resource *res;
1172 	struct pci_devres *dr;
1173 	struct pci_mmio_region *mmio;
1174 	int rid;
1175 	int type;
1176 
1177 	if (!lkpi_pci_bar_id_valid(bar))
1178 		return (-EINVAL);
1179 
1180 	type = pci_resource_type(pdev, bar);
1181 	if (type < 0)
1182 		return (0);
1183 
1184 	rid = PCIR_BAR(bar);
1185 	res = bus_alloc_resource_any(pdev->dev.bsddev, type, &rid,
1186 	    RF_ACTIVE|RF_SHAREABLE);
1187 	if (res == NULL) {
1188 		device_printf(pdev->dev.bsddev, "%s: failed to alloc "
1189 		    "bar %d type %d rid %d\n",
1190 		    __func__, bar, type, PCIR_BAR(bar));
1191 		return (-EBUSY);
1192 	}
1193 
1194 	/*
1195 	 * It seems there is an implicit devres tracking on these if the device
1196 	 * is managed (lkpi_pci_devres_find() case); otherwise the resources are
1197 	 * not automatically freed on FreeBSD/LinuxKPI though they should be/are
1198 	 * expected to be by Linux drivers.
1199 	 * Otherwise if we are called from a pcim-function with the managed
1200 	 * argument set, we need to track devres independent of pdev->managed.
1201 	 */
1202 	if (managed)
1203 		dr = lkpi_pci_devres_get_alloc(pdev);
1204 	else
1205 		dr = lkpi_pci_devres_find(pdev);
1206 	if (dr != NULL) {
1207 		dr->region_mask |= (1 << bar);
1208 		dr->region_table[bar] = res;
1209 	}
1210 
1211 	/* Even if the device is not managed we need to track it for iomap. */
1212 	mmio = malloc(sizeof(*mmio), M_DEVBUF, M_WAITOK | M_ZERO);
1213 	mmio->rid = PCIR_BAR(bar);
1214 	mmio->type = type;
1215 	mmio->res = res;
1216 	TAILQ_INSERT_TAIL(&pdev->mmio, mmio, next);
1217 
1218 	return (0);
1219 }
1220 
1221 int
1222 linuxkpi_pci_request_region(struct pci_dev *pdev, int bar, const char *res_name)
1223 {
1224 	return (lkpi_pci_request_region(pdev, bar, res_name, false));
1225 }
1226 
1227 int
1228 linuxkpi_pci_request_regions(struct pci_dev *pdev, const char *res_name)
1229 {
1230 	int error;
1231 	int i;
1232 
1233 	for (i = 0; i <= PCIR_MAX_BAR_0; i++) {
1234 		error = pci_request_region(pdev, i, res_name);
1235 		if (error && error != -EBUSY) {
1236 			pci_release_regions(pdev);
1237 			return (error);
1238 		}
1239 	}
1240 	return (0);
1241 }
1242 
1243 int
1244 linuxkpi_pcim_request_all_regions(struct pci_dev *pdev, const char *res_name)
1245 {
1246 	int bar, error;
1247 
1248 	for (bar = 0; bar <= PCIR_MAX_BAR_0; bar++) {
1249 		error = lkpi_pci_request_region(pdev, bar, res_name, true);
1250 		if (error != 0 && error != -EBUSY) {
1251 			device_printf(pdev->dev.bsddev, "%s: bar %d res_name '%s': "
1252 			    "lkpi_pci_request_region returned %d\n", __func__,
1253 			    bar, res_name, error);
1254 			pci_release_regions(pdev);
1255 			return (error);
1256 		}
1257 	}
1258 	return (0);
1259 }
1260 
1261 void
1262 linuxkpi_pci_release_region(struct pci_dev *pdev, int bar)
1263 {
1264 	struct resource_list_entry *rle;
1265 	struct pci_devres *dr;
1266 	struct pci_mmio_region *mmio, *p;
1267 
1268 	if ((rle = lkpi_pci_get_bar(pdev, bar, false)) == NULL)
1269 		return;
1270 
1271 	/*
1272 	 * As we implicitly track the requests we also need to clear them on
1273 	 * release.  Do clear before resource release.
1274 	 */
1275 	dr = lkpi_pci_devres_find(pdev);
1276 	if (dr != NULL) {
1277 		KASSERT(dr->region_table[bar] == rle->res, ("%s: pdev %p bar %d"
1278 		    " region_table res %p != rel->res %p\n", __func__, pdev,
1279 		    bar, dr->region_table[bar], rle->res));
1280 		dr->region_table[bar] = NULL;
1281 		dr->region_mask &= ~(1 << bar);
1282 	}
1283 
1284 	TAILQ_FOREACH_SAFE(mmio, &pdev->mmio, next, p) {
1285 		if (rle->res != (void *)rman_get_bushandle(mmio->res))
1286 			continue;
1287 		TAILQ_REMOVE(&pdev->mmio, mmio, next);
1288 		free(mmio, M_DEVBUF);
1289 	}
1290 
1291 	bus_release_resource(pdev->dev.bsddev, rle->type, rle->rid, rle->res);
1292 }
1293 
1294 void
1295 linuxkpi_pci_release_regions(struct pci_dev *pdev)
1296 {
1297 	int i;
1298 
1299 	for (i = 0; i <= PCIR_MAX_BAR_0; i++)
1300 		pci_release_region(pdev, i);
1301 }
1302 
1303 /*
1304  * MSI(-X) functions.
1305  */
1306 int
1307 linuxkpi_pci_enable_msix(struct pci_dev *pdev, struct msix_entry *entries,
1308     int nreq)
1309 {
1310 	struct resource_list_entry *rle;
1311 	int error;
1312 	int avail;
1313 	int i;
1314 
1315 	avail = pci_msix_count(pdev->dev.bsddev);
1316 	if (avail < nreq) {
1317 		if (avail == 0)
1318 			return -EINVAL;
1319 		return avail;
1320 	}
1321 	avail = nreq;
1322 	if ((error = -pci_alloc_msix(pdev->dev.bsddev, &avail)) != 0)
1323 		return error;
1324 	/*
1325 	* Handle case where "pci_alloc_msix()" may allocate less
1326 	* interrupts than available and return with no error:
1327 	*/
1328 	if (avail < nreq) {
1329 		pci_release_msi(pdev->dev.bsddev);
1330 		return avail;
1331 	}
1332 	rle = lkpi_pci_get_rle(pdev, SYS_RES_IRQ, 1, false);
1333 	pdev->dev.irq_start = rle->start;
1334 	pdev->dev.irq_end = rle->start + avail;
1335 	for (i = 0; i < nreq; i++)
1336 		entries[i].vector = pdev->dev.irq_start + i;
1337 	pdev->msix_enabled = true;
1338 	return (0);
1339 }
1340 
1341 int
1342 _lkpi_pci_enable_msi_range(struct pci_dev *pdev, int minvec, int maxvec)
1343 {
1344 	struct resource_list_entry *rle;
1345 	int error;
1346 	int nvec;
1347 
1348 	if (maxvec < minvec)
1349 		return (-EINVAL);
1350 
1351 	nvec = pci_msi_count(pdev->dev.bsddev);
1352 	if (nvec < 1 || nvec < minvec)
1353 		return (-ENOSPC);
1354 
1355 	nvec = min(nvec, maxvec);
1356 	if ((error = -pci_alloc_msi(pdev->dev.bsddev, &nvec)) != 0)
1357 		return error;
1358 
1359 	/* Native PCI might only ever ask for 32 vectors. */
1360 	if (nvec < minvec) {
1361 		pci_release_msi(pdev->dev.bsddev);
1362 		return (-ENOSPC);
1363 	}
1364 
1365 	rle = lkpi_pci_get_rle(pdev, SYS_RES_IRQ, 1, false);
1366 	pdev->dev.irq_start = rle->start;
1367 	pdev->dev.irq_end = rle->start + nvec;
1368 	pdev->irq = rle->start;
1369 	pdev->msi_enabled = true;
1370 	return (0);
1371 }
1372 
1373 int
1374 pci_alloc_irq_vectors(struct pci_dev *pdev, int minv, int maxv,
1375     unsigned int flags)
1376 {
1377 	int error;
1378 
1379 	if ((flags & PCI_IRQ_AFFINITY) != 0) {
1380 		pr_debug("%s: TODO PCI_IRQ_AFFINITY\n", __func__);
1381 	}
1382 	if (flags & PCI_IRQ_MSIX) {
1383 		struct msix_entry *entries;
1384 		int i;
1385 
1386 		entries = kcalloc(maxv, sizeof(*entries), GFP_KERNEL);
1387 		if (entries == NULL) {
1388 			error = -ENOMEM;
1389 			goto out;
1390 		}
1391 		for (i = 0; i < maxv; ++i)
1392 			entries[i].entry = i;
1393 		error = pci_enable_msix(pdev, entries, maxv);
1394 out:
1395 		kfree(entries);
1396 		if (error == 0 && pdev->msix_enabled)
1397 			return (pdev->dev.irq_end - pdev->dev.irq_start);
1398 	}
1399 	if (flags & PCI_IRQ_MSI) {
1400 		if (pci_msi_count(pdev->dev.bsddev) < minv)
1401 			return (-ENOSPC);
1402 		error = _lkpi_pci_enable_msi_range(pdev, minv, maxv);
1403 		if (error == 0 && pdev->msi_enabled)
1404 			return (pdev->dev.irq_end - pdev->dev.irq_start);
1405 	}
1406 	if (flags & PCI_IRQ_INTX) {
1407 		if (pdev->irq)
1408 			return (1);
1409 	}
1410 
1411 	return (-EINVAL);
1412 }
1413 
1414 struct msi_desc *
1415 lkpi_pci_msi_desc_alloc(unsigned int irq)
1416 {
1417 	struct device *dev;
1418 	struct pci_dev *pdev;
1419 	struct msi_desc *desc;
1420 	struct pci_devinfo *dinfo;
1421 	struct pcicfg_msi *msi;
1422 	int vec;
1423 
1424 	dev = lkpi_pci_find_irq_dev(irq);
1425 	if (dev == NULL)
1426 		return (NULL);
1427 
1428 	pdev = to_pci_dev(dev);
1429 
1430 	if (pdev->msi_desc == NULL)
1431 		return (NULL);
1432 
1433 	if (irq < pdev->dev.irq_start || irq >= pdev->dev.irq_end)
1434 		return (NULL);
1435 
1436 	vec = pdev->dev.irq_start - irq;
1437 
1438 	if (pdev->msi_desc[vec] != NULL)
1439 		return (pdev->msi_desc[vec]);
1440 
1441 	dinfo = device_get_ivars(dev->bsddev);
1442 	msi = &dinfo->cfg.msi;
1443 
1444 	desc = malloc(sizeof(*desc), M_DEVBUF, M_WAITOK | M_ZERO);
1445 
1446 	desc->pci.msi_attrib.is_64 =
1447 	   (msi->msi_ctrl & PCIM_MSICTRL_64BIT) ? true : false;
1448 	desc->msg.data = msi->msi_data;
1449 
1450 	pdev->msi_desc[vec] = desc;
1451 
1452 	return (desc);
1453 }
1454 
1455 bool
1456 pci_device_is_present(struct pci_dev *pdev)
1457 {
1458 	device_t dev;
1459 
1460 	dev = pdev->dev.bsddev;
1461 
1462 	return (bus_child_present(dev));
1463 }
1464 
1465 void *
1466 linuxkpi_pci_map_rom(struct pci_dev *pdev, size_t *size)
1467 {
1468 	device_t dev;
1469 
1470 	dev = pdev->dev.bsddev;
1471 
1472 	if (pci_get_class(dev) != PCIC_DISPLAY &&
1473 	    (pci_get_class(dev) != PCIC_OLD ||
1474 	     pci_get_subclass(dev) != PCIS_OLD_VGA)) {
1475 		pr_debug("%s: TODO\n", __func__);
1476 		return (NULL);
1477 	}
1478 
1479 	return (vga_pci_map_bios(device_get_parent(dev), size));
1480 }
1481 
1482 void
1483 linuxkpi_pci_unmap_rom(struct pci_dev *pdev, void *rom)
1484 {
1485 	device_t dev;
1486 
1487 	dev = pdev->dev.bsddev;
1488 
1489 	vga_pci_unmap_bios(device_get_parent(dev), rom);
1490 }
1491 
1492 /*
1493  * device_* bus functions for PCI.
1494  */
1495 static int
1496 lkpi_pci_probe(device_t dev)
1497 {
1498 	const struct pci_device_id *id;
1499 	struct pci_driver *pdrv;
1500 
1501 	if ((pdrv = linux_pci_find(dev, &id)) == NULL)
1502 		return (ENXIO);
1503 	if (device_get_driver(dev) != &pdrv->bsddriver)
1504 		return (ENXIO);
1505 	device_set_desc(dev, pdrv->name);
1506 
1507 	/* Assume BSS initialized (should never return BUS_PROBE_SPECIFIC). */
1508 	if (pdrv->bsd_probe_return == 0)
1509 		return (BUS_PROBE_DEFAULT);
1510 	else
1511 		return (pdrv->bsd_probe_return);
1512 }
1513 
1514 static int
1515 lkpi_pci_attach(device_t dev)
1516 {
1517 	const struct pci_device_id *id;
1518 	struct pci_driver *pdrv;
1519 	struct pci_dev *pdev;
1520 
1521 	pdrv = linux_pci_find(dev, &id);
1522 	pdev = device_get_softc(dev);
1523 
1524 	MPASS(pdrv != NULL);
1525 	MPASS(pdev != NULL);
1526 
1527 	return (linux_pci_attach_device(dev, pdrv, id, pdev));
1528 }
1529 
1530 static int
1531 lkpi_pci_detach(device_t dev)
1532 {
1533 	struct pci_dev *pdev;
1534 	int error;
1535 
1536 	pdev = device_get_softc(dev);
1537 	MPASS(pdev != NULL);
1538 
1539 	error = linux_pci_detach_device(pdev);
1540 	if (error == 0)
1541 		device_set_desc(dev, NULL);
1542 
1543 	return (error);
1544 }
1545 
1546 static int
1547 lkpi_pci_suspend(device_t dev)
1548 {
1549 	const struct dev_pm_ops *pmops;
1550 	struct pm_message pm = { };
1551 	struct pci_dev *pdev;
1552 	int error;
1553 
1554 	error = 0;
1555 	linux_set_current(curthread);
1556 	pdev = device_get_softc(dev);
1557 	pmops = pdev->pdrv->driver.pm;
1558 
1559 	if (pdev->pdrv->suspend != NULL)
1560 		error = -pdev->pdrv->suspend(pdev, pm);
1561 	else if (pmops != NULL && pmops->suspend != NULL) {
1562 		error = -pmops->suspend(&pdev->dev);
1563 		if (error == 0 && pmops->suspend_late != NULL)
1564 			error = -pmops->suspend_late(&pdev->dev);
1565 		if (error == 0 && pmops->suspend_noirq != NULL)
1566 			error = -pmops->suspend_noirq(&pdev->dev);
1567 	}
1568 	return (error);
1569 }
1570 
1571 static int
1572 lkpi_pci_resume(device_t dev)
1573 {
1574 	const struct dev_pm_ops *pmops;
1575 	struct pci_dev *pdev;
1576 	int error;
1577 
1578 	error = 0;
1579 	linux_set_current(curthread);
1580 	pdev = device_get_softc(dev);
1581 	pmops = pdev->pdrv->driver.pm;
1582 
1583 	if (pdev->pdrv->resume != NULL)
1584 		error = -pdev->pdrv->resume(pdev);
1585 	else if (pmops != NULL && pmops->resume != NULL) {
1586 		if (pmops->resume_early != NULL)
1587 			error = -pmops->resume_early(&pdev->dev);
1588 		if (error == 0 && pmops->resume != NULL)
1589 			error = -pmops->resume(&pdev->dev);
1590 	}
1591 	return (error);
1592 }
1593 
1594 static int
1595 lkpi_pci_shutdown(device_t dev)
1596 {
1597 	struct pci_dev *pdev;
1598 
1599 	linux_set_current(curthread);
1600 	pdev = device_get_softc(dev);
1601 	if (pdev->pdrv->shutdown != NULL)
1602 		pdev->pdrv->shutdown(pdev);
1603 	return (0);
1604 }
1605 
1606 /*
1607  * PCI IOV bus functions.
1608  */
1609 static int
1610 lkpi_pci_iov_init(device_t dev, uint16_t num_vfs, const nvlist_t *pf_config)
1611 {
1612 	struct pci_dev *pdev;
1613 	int error;
1614 
1615 	linux_set_current(curthread);
1616 	pdev = device_get_softc(dev);
1617 	if (pdev->pdrv->bsd_iov_init != NULL)
1618 		error = pdev->pdrv->bsd_iov_init(dev, num_vfs, pf_config);
1619 	else
1620 		error = EINVAL;
1621 	return (error);
1622 }
1623 
1624 static void
1625 lkpi_pci_iov_uninit(device_t dev)
1626 {
1627 	struct pci_dev *pdev;
1628 
1629 	linux_set_current(curthread);
1630 	pdev = device_get_softc(dev);
1631 	if (pdev->pdrv->bsd_iov_uninit != NULL)
1632 		pdev->pdrv->bsd_iov_uninit(dev);
1633 }
1634 
1635 static int
1636 lkpi_pci_iov_add_vf(device_t dev, uint16_t vfnum, const nvlist_t *vf_config)
1637 {
1638 	struct pci_dev *pdev;
1639 	int error;
1640 
1641 	linux_set_current(curthread);
1642 	pdev = device_get_softc(dev);
1643 	if (pdev->pdrv->bsd_iov_add_vf != NULL)
1644 		error = pdev->pdrv->bsd_iov_add_vf(dev, vfnum, vf_config);
1645 	else
1646 		error = EINVAL;
1647 	return (error);
1648 }
1649 
1650 /*
1651  * LinuxKPI driver (un)registration.
1652  */
1653 static int
1654 lkpi_pci_register_driver(struct pci_driver *pdrv, devclass_t dc)
1655 {
1656 	int error;
1657 
1658 	linux_set_current(curthread);
1659 	LKPI_PCI_LOCK();
1660 	list_add(&pdrv->node, &lkpi_pci_drivers);
1661 	LKPI_PCI_UNLOCK();
1662 	if (pdrv->bsddriver.name == NULL)
1663 		pdrv->bsddriver.name = pdrv->name;
1664 	pdrv->bsddriver.methods = pci_methods;
1665 	pdrv->bsddriver.size = sizeof(struct pci_dev);
1666 
1667 	bus_topo_lock();
1668 	error = devclass_add_driver(dc, &pdrv->bsddriver,
1669 	    BUS_PASS_DEFAULT, &pdrv->bsdclass);
1670 	bus_topo_unlock();
1671 	return (-error);
1672 }
1673 
1674 int
1675 linux_pci_register_driver(struct pci_driver *pdrv)
1676 {
1677 	devclass_t dc;
1678 
1679 	pdrv->isdrm = strcmp(pdrv->name, "drmn") == 0;
1680 	dc = pdrv->isdrm ? devclass_create("vgapci") : devclass_find("pci");
1681 	if (dc == NULL)
1682 		return (-ENXIO);
1683 	return (lkpi_pci_register_driver(pdrv, dc));
1684 }
1685 
1686 int
1687 linux_pci_register_drm_driver(struct pci_driver *pdrv)
1688 {
1689 	devclass_t dc;
1690 
1691 	dc = devclass_create("vgapci");
1692 	if (dc == NULL)
1693 		return (-ENXIO);
1694 	pdrv->isdrm = true;
1695 	pdrv->name = "drmn";
1696 	return (lkpi_pci_register_driver(pdrv, dc));
1697 }
1698 
1699 void
1700 linux_pci_unregister_driver(struct pci_driver *pdrv)
1701 {
1702 	devclass_t bus;
1703 
1704 	bus = devclass_find(pdrv->isdrm ? "vgapci" : "pci");
1705 
1706 	LKPI_PCI_LOCK();
1707 	list_del(&pdrv->node);
1708 	LKPI_PCI_UNLOCK();
1709 	bus_topo_lock();
1710 	if (bus != NULL)
1711 		devclass_delete_driver(bus, &pdrv->bsddriver);
1712 	bus_topo_unlock();
1713 }
1714 
1715 void
1716 linux_pci_unregister_drm_driver(struct pci_driver *pdrv)
1717 {
1718 	devclass_t bus;
1719 
1720 	bus = devclass_find("vgapci");
1721 
1722 	LKPI_PCI_LOCK();
1723 	list_del(&pdrv->node);
1724 	LKPI_PCI_UNLOCK();
1725 	bus_topo_lock();
1726 	if (bus != NULL)
1727 		devclass_delete_driver(bus, &pdrv->bsddriver);
1728 	bus_topo_unlock();
1729 }
1730 
1731 /*
1732  * PCI SYSINIT.
1733  */
1734 static void
1735 lkpi_pci_init(void *arg __unused)
1736 {
1737 	INIT_LIST_HEAD(&lkpi_pci_drivers);
1738 	INIT_LIST_HEAD(&lkpi_pci_devices);
1739 	LKPI_PCI_LOCK_INIT();
1740 }
1741 SYSINIT(lkpi_pci_init, SI_SUB_DRIVERS, SI_ORDER_SECOND, lkpi_pci_init, NULL);
1742 
1743 static void
1744 lkpi_pci_uninit(void *arg __unused)
1745 {
1746 	LKPI_PCI_LOCK_DESTROY();
1747 }
1748 SYSUNINIT(lkpi_pci_uninit, SI_SUB_DRIVERS, SI_ORDER_SECOND, lkpi_pci_uninit, NULL);
1749 
1750 /* -------------------------------------------------------------------------- */
1751 /* DMA */
1752 
1753 static counter_u64_t lkpi_pci_nseg1_fail;
1754 SYSCTL_COUNTER_U64(_compat_linuxkpi, OID_AUTO, lkpi_pci_nseg1_fail, CTLFLAG_RD,
1755     &lkpi_pci_nseg1_fail, "Count of busdma mapping failures of single-segment");
1756 
1757 CTASSERT(sizeof(dma_addr_t) <= sizeof(uint64_t));
1758 
1759 struct lkpi_dma_obj {
1760 	void		*vaddr;
1761 	uint64_t	dma_addr;
1762 	bus_dmamap_t	dmamap;
1763 	bus_dma_tag_t	dmat;
1764 };
1765 
1766 static uma_zone_t lkpi_dma_trie_zone;
1767 static uma_zone_t lkpi_dma_obj_zone;
1768 
1769 static void
1770 lkpi_dma_init(void *arg)
1771 {
1772 
1773 	lkpi_dma_trie_zone = uma_zcreate("lkpi_dma_pctrie",
1774 	    pctrie_node_size(), NULL, NULL, pctrie_zone_init, NULL,
1775 	    UMA_ALIGN_PTR, 0);
1776 	lkpi_dma_obj_zone = uma_zcreate("lkpi_dma_object",
1777 	    sizeof(struct lkpi_dma_obj), NULL, NULL, NULL, NULL,
1778 	    UMA_ALIGN_PTR, 0);
1779 	lkpi_pci_nseg1_fail = counter_u64_alloc(M_WAITOK);
1780 }
1781 SYSINIT(lkpi_dma, SI_SUB_DRIVERS, SI_ORDER_THIRD, lkpi_dma_init, NULL);
1782 
1783 static void
1784 lkpi_dma_uninit(void *arg)
1785 {
1786 
1787 	counter_u64_free(lkpi_pci_nseg1_fail);
1788 	uma_zdestroy(lkpi_dma_obj_zone);
1789 	uma_zdestroy(lkpi_dma_trie_zone);
1790 }
1791 SYSUNINIT(lkpi_dma, SI_SUB_DRIVERS, SI_ORDER_THIRD, lkpi_dma_uninit, NULL);
1792 
1793 static void *
1794 linux_dma_trie_alloc(struct pctrie *ptree)
1795 {
1796 
1797 	return (uma_zalloc(lkpi_dma_trie_zone, M_NOWAIT));
1798 }
1799 
1800 static void
1801 linux_dma_trie_free(struct pctrie *ptree, void *node)
1802 {
1803 
1804 	uma_zfree(lkpi_dma_trie_zone, node);
1805 }
1806 
1807 PCTRIE_DEFINE(LINUX_DMA, lkpi_dma_obj, dma_addr, linux_dma_trie_alloc,
1808     linux_dma_trie_free);
1809 
1810 #if defined(__i386__) || defined(__amd64__) || defined(__aarch64__)
1811 static dma_addr_t
1812 linux_dma_map_phys_common(struct device *dev, vm_paddr_t phys, size_t len,
1813     bus_dma_tag_t dmat)
1814 {
1815 	struct linux_dma_priv *priv;
1816 	struct lkpi_dma_obj *obj;
1817 	int error, nseg;
1818 	bus_dma_segment_t seg;
1819 
1820 	priv = dev->dma_priv;
1821 
1822 	/*
1823 	 * If the resultant mapping will be entirely 1:1 with the
1824 	 * physical address, short-circuit the remainder of the
1825 	 * bus_dma API.  This avoids tracking collisions in the pctrie
1826 	 * with the additional benefit of reducing overhead.
1827 	 */
1828 	if (bus_dma_id_mapped(dmat, phys, len))
1829 		return (phys);
1830 
1831 	obj = uma_zalloc(lkpi_dma_obj_zone, M_NOWAIT);
1832 	if (obj == NULL) {
1833 		return (0);
1834 	}
1835 	obj->dmat = dmat;
1836 
1837 	DMA_PRIV_LOCK(priv);
1838 	if (bus_dmamap_create(obj->dmat, 0, &obj->dmamap) != 0) {
1839 		DMA_PRIV_UNLOCK(priv);
1840 		uma_zfree(lkpi_dma_obj_zone, obj);
1841 		return (0);
1842 	}
1843 
1844 	nseg = -1;
1845 	error = _bus_dmamap_load_phys(obj->dmat, obj->dmamap, phys, len,
1846 	    BUS_DMA_NOWAIT, &seg, &nseg);
1847 	if (error != 0) {
1848 		bus_dmamap_destroy(obj->dmat, obj->dmamap);
1849 		DMA_PRIV_UNLOCK(priv);
1850 		uma_zfree(lkpi_dma_obj_zone, obj);
1851 		counter_u64_add(lkpi_pci_nseg1_fail, 1);
1852 		if (linuxkpi_debug) {
1853 			device_printf(dev->bsddev, "%s: _bus_dmamap_load_phys "
1854 			    "error %d, phys %#018jx len %zu\n", __func__,
1855 			    error, (uintmax_t)phys, len);
1856 			dump_stack();
1857 		}
1858 		return (0);
1859 	}
1860 
1861 	KASSERT(++nseg == 1, ("More than one segment (nseg=%d)", nseg));
1862 	obj->dma_addr = seg.ds_addr;
1863 
1864 	error = LINUX_DMA_PCTRIE_INSERT(&priv->ptree, obj);
1865 	if (error != 0) {
1866 		bus_dmamap_unload(obj->dmat, obj->dmamap);
1867 		bus_dmamap_destroy(obj->dmat, obj->dmamap);
1868 		DMA_PRIV_UNLOCK(priv);
1869 		uma_zfree(lkpi_dma_obj_zone, obj);
1870 		return (0);
1871 	}
1872 	DMA_PRIV_UNLOCK(priv);
1873 	return (obj->dma_addr);
1874 }
1875 #else
1876 static dma_addr_t
1877 linux_dma_map_phys_common(struct device *dev __unused, vm_paddr_t phys,
1878     size_t len __unused, bus_dma_tag_t dmat __unused)
1879 {
1880 	return (phys);
1881 }
1882 #endif
1883 
1884 dma_addr_t
1885 lkpi_dma_map_phys(struct device *dev, vm_paddr_t phys, size_t len,
1886     enum dma_data_direction direction, unsigned long attrs)
1887 {
1888 	struct linux_dma_priv *priv;
1889 	dma_addr_t dma;
1890 
1891 	priv = dev->dma_priv;
1892 	dma = linux_dma_map_phys_common(dev, phys, len, priv->dmat);
1893 	if (dma_mapping_error(dev, dma))
1894 		return (dma);
1895 
1896 	if ((attrs & DMA_ATTR_SKIP_CPU_SYNC) == 0)
1897 		dma_sync_single_for_device(dev, dma, len, direction);
1898 
1899 	return (dma);
1900 }
1901 
1902 /* For backward compat only so we can MFC this. Remove before 15. */
1903 dma_addr_t
1904 linux_dma_map_phys(struct device *dev, vm_paddr_t phys, size_t len)
1905 {
1906 	return (lkpi_dma_map_phys(dev, phys, len, DMA_NONE, 0));
1907 }
1908 
1909 #if defined(__i386__) || defined(__amd64__) || defined(__aarch64__)
1910 void
1911 lkpi_dma_unmap(struct device *dev, dma_addr_t dma_addr, size_t len,
1912     enum dma_data_direction direction, unsigned long attrs)
1913 {
1914 	struct linux_dma_priv *priv;
1915 	struct lkpi_dma_obj *obj;
1916 
1917 	priv = dev->dma_priv;
1918 
1919 	if (pctrie_is_empty(&priv->ptree))
1920 		return;
1921 
1922 	DMA_PRIV_LOCK(priv);
1923 	obj = LINUX_DMA_PCTRIE_LOOKUP(&priv->ptree, dma_addr);
1924 	if (obj == NULL) {
1925 		DMA_PRIV_UNLOCK(priv);
1926 		return;
1927 	}
1928 	LINUX_DMA_PCTRIE_REMOVE(&priv->ptree, dma_addr);
1929 
1930 	if ((attrs & DMA_ATTR_SKIP_CPU_SYNC) != 0)
1931 		goto skip_sync;
1932 
1933 	/* dma_sync_single_for_cpu() unrolled to avoid lock recursicn. */
1934 	switch (direction) {
1935 	case DMA_BIDIRECTIONAL:
1936 		bus_dmamap_sync(obj->dmat, obj->dmamap,
1937 		    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
1938 		break;
1939 	case DMA_TO_DEVICE:
1940 		bus_dmamap_sync(obj->dmat, obj->dmamap, BUS_DMASYNC_POSTWRITE);
1941 		break;
1942 	case DMA_FROM_DEVICE:
1943 		bus_dmamap_sync(obj->dmat, obj->dmamap, BUS_DMASYNC_POSTREAD);
1944 		break;
1945 	default:
1946 		break;
1947 	}
1948 
1949 skip_sync:
1950 	bus_dmamap_unload(obj->dmat, obj->dmamap);
1951 	bus_dmamap_destroy(obj->dmat, obj->dmamap);
1952 	DMA_PRIV_UNLOCK(priv);
1953 
1954 	uma_zfree(lkpi_dma_obj_zone, obj);
1955 }
1956 #else
1957 void
1958 lkpi_dma_unmap(struct device *dev, dma_addr_t dma_addr, size_t len,
1959     enum dma_data_direction direction, unsigned long attrs)
1960 {
1961 }
1962 #endif
1963 
1964 /* For backward compat only so we can MFC this. Remove before 15. */
1965 void
1966 linux_dma_unmap(struct device *dev, dma_addr_t dma_addr, size_t len)
1967 {
1968 	lkpi_dma_unmap(dev, dma_addr, len, DMA_NONE, 0);
1969 }
1970 
1971 void *
1972 linux_dma_alloc_coherent(struct device *dev, size_t size,
1973     dma_addr_t *dma_handle, gfp_t flag)
1974 {
1975 	struct linux_dma_priv *priv;
1976 	vm_paddr_t high;
1977 	size_t align;
1978 	void *mem;
1979 
1980 	if (dev == NULL || dev->dma_priv == NULL) {
1981 		*dma_handle = 0;
1982 		return (NULL);
1983 	}
1984 	priv = dev->dma_priv;
1985 	if (priv->dma_coherent_mask)
1986 		high = priv->dma_coherent_mask;
1987 	else
1988 		/* Coherent is lower 32bit only by default in Linux. */
1989 		high = BUS_SPACE_MAXADDR_32BIT;
1990 	align = PAGE_SIZE << get_order(size);
1991 	/* Always zero the allocation. */
1992 	flag |= M_ZERO;
1993 	mem = kmem_alloc_contig(size, flag & GFP_NATIVE_MASK, 0, high,
1994 	    align, 0, VM_MEMATTR_DEFAULT);
1995 	if (mem != NULL) {
1996 		*dma_handle = linux_dma_map_phys_common(dev, vtophys(mem), size,
1997 		    priv->dmat_coherent);
1998 		if (*dma_handle == 0) {
1999 			kmem_free(mem, size);
2000 			mem = NULL;
2001 		}
2002 	} else {
2003 		*dma_handle = 0;
2004 	}
2005 	return (mem);
2006 }
2007 
2008 struct lkpi_devres_dmam_coherent {
2009 	size_t size;
2010 	dma_addr_t handle;
2011 	void *mem;
2012 };
2013 
2014 static void
2015 lkpi_dmam_free_coherent(struct device *dev, void *p)
2016 {
2017 	struct lkpi_devres_dmam_coherent *dr;
2018 
2019 	dr = p;
2020 	dma_free_coherent(dev, dr->size, dr->mem, dr->handle);
2021 }
2022 
2023 static int
2024 lkpi_dmam_coherent_match(struct device *dev, void *dr, void *mp)
2025 {
2026 	struct lkpi_devres_dmam_coherent *a, *b;
2027 
2028 	a = dr;
2029 	b = mp;
2030 
2031 	if (a->mem != b->mem)
2032 		return (0);
2033 	if (a->size != b->size || a->handle != b->handle)
2034 		dev_WARN(dev, "for mem %p: size %zu != %zu || handle %#jx != %#jx\n",
2035 		    a->mem, a->size, b->size,
2036 		    (uintmax_t)a->handle, (uintmax_t)b->handle);
2037 	return (1);
2038 }
2039 
2040 void
2041 linuxkpi_dmam_free_coherent(struct device *dev, size_t size,
2042     void *addr, dma_addr_t dma_handle)
2043 {
2044 	struct lkpi_devres_dmam_coherent match = {
2045 		.size		= size,
2046 		.handle		= dma_handle,
2047 		.mem		= addr
2048 	};
2049 	int error;
2050 
2051 	error = devres_destroy(dev, lkpi_dmam_free_coherent,
2052 	    lkpi_dmam_coherent_match, &match);
2053 	if (error != 0)
2054 		dev_WARN(dev, "devres_destroy returned %d, size %zu addr %p "
2055 		    "dma_handle %#jx\n", error, size, addr, (uintmax_t)dma_handle);
2056 	dma_free_coherent(dev, size, addr, dma_handle);
2057 }
2058 
2059 void *
2060 linuxkpi_dmam_alloc_coherent(struct device *dev, size_t size, dma_addr_t *dma_handle,
2061     gfp_t flag)
2062 {
2063 	struct lkpi_devres_dmam_coherent *dr;
2064 
2065 	dr = lkpi_devres_alloc(lkpi_dmam_free_coherent,
2066 	    sizeof(*dr), GFP_KERNEL | __GFP_ZERO);
2067 
2068 	if (dr == NULL)
2069 		return (NULL);
2070 
2071 	dr->size = size;
2072 	dr->mem = linux_dma_alloc_coherent(dev, size, dma_handle, flag);
2073 	dr->handle = *dma_handle;
2074 	if (dr->mem == NULL) {
2075 		lkpi_devres_free(dr);
2076 		return (NULL);
2077 	}
2078 
2079 	lkpi_devres_add(dev, dr);
2080 	return (dr->mem);
2081 }
2082 
2083 void *
2084 linuxkpi_dma_alloc_noncoherent(struct device *dev, size_t size, dma_addr_t *dma_handle,
2085     enum dma_data_direction direction, gfp_t gfp)
2086 {
2087 	struct linux_dma_priv *priv;
2088 	size_t align;
2089 	void *mem;
2090 
2091 	size = PAGE_ALIGN(size);
2092 	align = PAGE_SIZE << get_order(size);
2093 	mem = kmem_alloc_contig(size, gfp & GFP_NATIVE_MASK, 0, BUS_SPACE_MAXADDR,
2094 	    align, 0, VM_MEMATTR_DEFAULT);
2095 	if (mem == NULL) {
2096 		*dma_handle = 0;
2097 		return (NULL);
2098 	}
2099 
2100 	priv = dev->dma_priv;
2101 	*dma_handle = linux_dma_map_phys_common(dev, vtophys(mem), size, priv->dmat);
2102 	if (*dma_handle == 0) {
2103 		kmem_free(mem, size);
2104 		mem = NULL;
2105 	}
2106 	return (mem);
2107 }
2108 
2109 void
2110 linuxkpi_dma_free_noncoherent(struct device *dev, size_t size, void *vaddr,
2111     dma_addr_t dma_handle, enum dma_data_direction direction)
2112 {
2113 	lkpi_dma_unmap(dev, dma_handle, size, direction, 0);
2114 	kmem_free(vaddr, size);
2115 }
2116 
2117 void *
2118 linuxkpi_dma_alloc_attrs(struct device *dev, size_t size, dma_addr_t *dma_handle,
2119     gfp_t gfp, unsigned long attrs)
2120 {
2121 	return (linuxkpi_dma_alloc_noncoherent(dev, size, dma_handle,
2122 	    DMA_BIDIRECTIONAL, gfp));
2123 }
2124 
2125 void
2126 linuxkpi_dma_free_attrs(struct device *dev, size_t size, void *vaddr,
2127     dma_addr_t dma_handle, unsigned long attrs)
2128 {
2129 	linuxkpi_dma_free_noncoherent(dev, size, vaddr, dma_handle,
2130 	    DMA_BIDIRECTIONAL);
2131 }
2132 
2133 void
2134 linuxkpi_dma_sync(struct device *dev, dma_addr_t dma_addr, size_t size,
2135     bus_dmasync_op_t op)
2136 {
2137 	struct linux_dma_priv *priv;
2138 	struct lkpi_dma_obj *obj;
2139 
2140 	priv = dev->dma_priv;
2141 
2142 	if (pctrie_is_empty(&priv->ptree))
2143 		return;
2144 
2145 	DMA_PRIV_LOCK(priv);
2146 	obj = LINUX_DMA_PCTRIE_LOOKUP(&priv->ptree, dma_addr);
2147 	if (obj == NULL) {
2148 		DMA_PRIV_UNLOCK(priv);
2149 		return;
2150 	}
2151 
2152 	bus_dmamap_sync(obj->dmat, obj->dmamap, op);
2153 	DMA_PRIV_UNLOCK(priv);
2154 }
2155 
2156 void
2157 lkpi_dma_sync_sg(struct device *dev, struct scatterlist *sgl, bus_dmasync_op_t op)
2158 {
2159 	struct linux_dma_priv *priv;
2160 
2161 	priv = dev->dma_priv;
2162 	DMA_PRIV_LOCK(priv);
2163 	bus_dmamap_sync(priv->dmat, sgl->dma_map, op);
2164 	DMA_PRIV_UNLOCK(priv);
2165 }
2166 
2167 int
2168 linux_dma_map_sg_attrs(struct device *dev, struct scatterlist *sgl, int nents,
2169     enum dma_data_direction direction, unsigned long attrs)
2170 {
2171 	struct linux_dma_priv *priv;
2172 	struct scatterlist *sg;
2173 	int i, nseg;
2174 	bus_dma_segment_t seg;
2175 
2176 	priv = dev->dma_priv;
2177 
2178 	DMA_PRIV_LOCK(priv);
2179 
2180 	/* create common DMA map in the first S/G entry */
2181 	if (bus_dmamap_create(priv->dmat, 0, &sgl->dma_map) != 0) {
2182 		DMA_PRIV_UNLOCK(priv);
2183 		return (0);
2184 	}
2185 
2186 	/* load all S/G list entries */
2187 	for_each_sg(sgl, sg, nents, i) {
2188 		nseg = -1;
2189 		if (_bus_dmamap_load_phys(priv->dmat, sgl->dma_map,
2190 		    sg_phys(sg), sg->length, BUS_DMA_NOWAIT,
2191 		    &seg, &nseg) != 0) {
2192 			bus_dmamap_unload(priv->dmat, sgl->dma_map);
2193 			bus_dmamap_destroy(priv->dmat, sgl->dma_map);
2194 			DMA_PRIV_UNLOCK(priv);
2195 			return (0);
2196 		}
2197 		KASSERT(nseg == 0,
2198 		    ("More than one segment (nseg=%d)", nseg + 1));
2199 
2200 		sg_dma_address(sg) = seg.ds_addr;
2201 		sg->dma_length = sg->length;
2202 	}
2203 
2204 	if ((attrs & DMA_ATTR_SKIP_CPU_SYNC) != 0)
2205 		goto skip_sync;
2206 
2207 	switch (direction) {
2208 	case DMA_BIDIRECTIONAL:
2209 		bus_dmamap_sync(priv->dmat, sgl->dma_map,
2210 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
2211 		break;
2212 	case DMA_TO_DEVICE:
2213 		bus_dmamap_sync(priv->dmat, sgl->dma_map, BUS_DMASYNC_PREWRITE);
2214 		break;
2215 	case DMA_FROM_DEVICE:
2216 		bus_dmamap_sync(priv->dmat, sgl->dma_map, BUS_DMASYNC_PREREAD);
2217 		break;
2218 	default:
2219 		break;
2220 	}
2221 skip_sync:
2222 
2223 	DMA_PRIV_UNLOCK(priv);
2224 
2225 	return (nents);
2226 }
2227 
2228 void
2229 linux_dma_unmap_sg_attrs(struct device *dev, struct scatterlist *sgl,
2230     int nents __unused, enum dma_data_direction direction,
2231     unsigned long attrs)
2232 {
2233 	struct linux_dma_priv *priv;
2234 
2235 	priv = dev->dma_priv;
2236 
2237 	DMA_PRIV_LOCK(priv);
2238 
2239 	if ((attrs & DMA_ATTR_SKIP_CPU_SYNC) != 0)
2240 		goto skip_sync;
2241 
2242 	switch (direction) {
2243 	case DMA_BIDIRECTIONAL:
2244 		bus_dmamap_sync(priv->dmat, sgl->dma_map,
2245 		    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
2246 		break;
2247 	case DMA_TO_DEVICE:
2248 		bus_dmamap_sync(priv->dmat, sgl->dma_map, BUS_DMASYNC_POSTWRITE);
2249 		break;
2250 	case DMA_FROM_DEVICE:
2251 		bus_dmamap_sync(priv->dmat, sgl->dma_map, BUS_DMASYNC_POSTREAD);
2252 		break;
2253 	default:
2254 		break;
2255 	}
2256 skip_sync:
2257 
2258 	bus_dmamap_unload(priv->dmat, sgl->dma_map);
2259 	bus_dmamap_destroy(priv->dmat, sgl->dma_map);
2260 	DMA_PRIV_UNLOCK(priv);
2261 }
2262 
2263 struct dma_pool {
2264 	struct device  *pool_device;
2265 	uma_zone_t	pool_zone;
2266 	struct mtx	pool_lock;
2267 	bus_dma_tag_t	pool_dmat;
2268 	size_t		pool_entry_size;
2269 	struct pctrie	pool_ptree;
2270 };
2271 
2272 #define	DMA_POOL_LOCK(pool) mtx_lock(&(pool)->pool_lock)
2273 #define	DMA_POOL_UNLOCK(pool) mtx_unlock(&(pool)->pool_lock)
2274 
2275 static inline int
2276 dma_pool_obj_ctor(void *mem, int size, void *arg, int flags)
2277 {
2278 	struct lkpi_dma_obj *obj = mem;
2279 	struct dma_pool *pool = arg;
2280 	int error, nseg;
2281 	bus_dma_segment_t seg;
2282 
2283 	nseg = -1;
2284 	DMA_POOL_LOCK(pool);
2285 	error = _bus_dmamap_load_phys(pool->pool_dmat, obj->dmamap,
2286 	    vtophys(obj->vaddr), pool->pool_entry_size, BUS_DMA_NOWAIT,
2287 	    &seg, &nseg);
2288 	DMA_POOL_UNLOCK(pool);
2289 	if (error != 0) {
2290 		return (error);
2291 	}
2292 	KASSERT(++nseg == 1, ("More than one segment (nseg=%d)", nseg));
2293 	obj->dma_addr = seg.ds_addr;
2294 
2295 	return (0);
2296 }
2297 
2298 static void
2299 dma_pool_obj_dtor(void *mem, int size, void *arg)
2300 {
2301 	struct lkpi_dma_obj *obj = mem;
2302 	struct dma_pool *pool = arg;
2303 
2304 	DMA_POOL_LOCK(pool);
2305 	bus_dmamap_unload(pool->pool_dmat, obj->dmamap);
2306 	DMA_POOL_UNLOCK(pool);
2307 }
2308 
2309 static int
2310 dma_pool_obj_import(void *arg, void **store, int count, int domain __unused,
2311     int flags)
2312 {
2313 	struct dma_pool *pool = arg;
2314 	struct lkpi_dma_obj *obj;
2315 	int error, i;
2316 
2317 	for (i = 0; i < count; i++) {
2318 		obj = uma_zalloc(lkpi_dma_obj_zone, flags);
2319 		if (obj == NULL)
2320 			break;
2321 
2322 		error = bus_dmamem_alloc(pool->pool_dmat, &obj->vaddr,
2323 		    BUS_DMA_NOWAIT, &obj->dmamap);
2324 		if (error!= 0) {
2325 			uma_zfree(lkpi_dma_obj_zone, obj);
2326 			break;
2327 		}
2328 
2329 		store[i] = obj;
2330 	}
2331 
2332 	return (i);
2333 }
2334 
2335 static void
2336 dma_pool_obj_release(void *arg, void **store, int count)
2337 {
2338 	struct dma_pool *pool = arg;
2339 	struct lkpi_dma_obj *obj;
2340 	int i;
2341 
2342 	for (i = 0; i < count; i++) {
2343 		obj = store[i];
2344 		bus_dmamem_free(pool->pool_dmat, obj->vaddr, obj->dmamap);
2345 		uma_zfree(lkpi_dma_obj_zone, obj);
2346 	}
2347 }
2348 
2349 struct dma_pool *
2350 linux_dma_pool_create(char *name, struct device *dev, size_t size,
2351     size_t align, size_t boundary)
2352 {
2353 	struct linux_dma_priv *priv;
2354 	struct dma_pool *pool;
2355 
2356 	priv = dev->dma_priv;
2357 
2358 	pool = kzalloc(sizeof(*pool), GFP_KERNEL);
2359 	pool->pool_device = dev;
2360 	pool->pool_entry_size = size;
2361 
2362 	if (bus_dma_tag_create(bus_get_dma_tag(dev->bsddev),
2363 	    align, boundary,		/* alignment, boundary */
2364 	    priv->dma_mask,		/* lowaddr */
2365 	    BUS_SPACE_MAXADDR,		/* highaddr */
2366 	    NULL, NULL,			/* filtfunc, filtfuncarg */
2367 	    size,			/* maxsize */
2368 	    1,				/* nsegments */
2369 	    size,			/* maxsegsz */
2370 	    0,				/* flags */
2371 	    NULL, NULL,			/* lockfunc, lockfuncarg */
2372 	    &pool->pool_dmat)) {
2373 		kfree(pool);
2374 		return (NULL);
2375 	}
2376 
2377 	pool->pool_zone = uma_zcache_create(name, -1, dma_pool_obj_ctor,
2378 	    dma_pool_obj_dtor, NULL, NULL, dma_pool_obj_import,
2379 	    dma_pool_obj_release, pool, 0);
2380 
2381 	mtx_init(&pool->pool_lock, "lkpi-dma-pool", NULL, MTX_DEF);
2382 	pctrie_init(&pool->pool_ptree);
2383 
2384 	return (pool);
2385 }
2386 
2387 void
2388 linux_dma_pool_destroy(struct dma_pool *pool)
2389 {
2390 
2391 	uma_zdestroy(pool->pool_zone);
2392 	bus_dma_tag_destroy(pool->pool_dmat);
2393 	mtx_destroy(&pool->pool_lock);
2394 	kfree(pool);
2395 }
2396 
2397 void
2398 lkpi_dmam_pool_destroy(struct device *dev, void *p)
2399 {
2400 	struct dma_pool *pool;
2401 
2402 	pool = *(struct dma_pool **)p;
2403 	LINUX_DMA_PCTRIE_RECLAIM(&pool->pool_ptree);
2404 	linux_dma_pool_destroy(pool);
2405 }
2406 
2407 void *
2408 linux_dma_pool_alloc(struct dma_pool *pool, gfp_t mem_flags,
2409     dma_addr_t *handle)
2410 {
2411 	struct lkpi_dma_obj *obj;
2412 
2413 	obj = uma_zalloc_arg(pool->pool_zone, pool, mem_flags & GFP_NATIVE_MASK);
2414 	if (obj == NULL)
2415 		return (NULL);
2416 
2417 	DMA_POOL_LOCK(pool);
2418 	if (LINUX_DMA_PCTRIE_INSERT(&pool->pool_ptree, obj) != 0) {
2419 		DMA_POOL_UNLOCK(pool);
2420 		uma_zfree_arg(pool->pool_zone, obj, pool);
2421 		return (NULL);
2422 	}
2423 	DMA_POOL_UNLOCK(pool);
2424 
2425 	*handle = obj->dma_addr;
2426 	return (obj->vaddr);
2427 }
2428 
2429 void
2430 linux_dma_pool_free(struct dma_pool *pool, void *vaddr, dma_addr_t dma_addr)
2431 {
2432 	struct lkpi_dma_obj *obj;
2433 
2434 	DMA_POOL_LOCK(pool);
2435 	obj = LINUX_DMA_PCTRIE_LOOKUP(&pool->pool_ptree, dma_addr);
2436 	if (obj == NULL) {
2437 		DMA_POOL_UNLOCK(pool);
2438 		return;
2439 	}
2440 	LINUX_DMA_PCTRIE_REMOVE(&pool->pool_ptree, dma_addr);
2441 	DMA_POOL_UNLOCK(pool);
2442 
2443 	uma_zfree_arg(pool->pool_zone, obj, pool);
2444 }
2445 
2446 /* -------------------------------------------------------------------------- */
2447 /* Backlight. */
2448 
2449 static int
2450 lkpi_backlight_get_status(device_t dev, struct backlight_props *props)
2451 {
2452 	struct pci_dev *pdev;
2453 
2454 	linux_set_current(curthread);
2455 	pdev = device_get_softc(dev);
2456 
2457 	props->brightness = pdev->dev.bd->props.brightness;
2458 	props->brightness = props->brightness * 100 / pdev->dev.bd->props.max_brightness;
2459 	props->nlevels = 0;
2460 
2461 	return (0);
2462 }
2463 
2464 static int
2465 lkpi_backlight_get_info(device_t dev, struct backlight_info *info)
2466 {
2467 	struct pci_dev *pdev;
2468 
2469 	linux_set_current(curthread);
2470 	pdev = device_get_softc(dev);
2471 
2472 	info->type = BACKLIGHT_TYPE_PANEL;
2473 	strlcpy(info->name, pdev->dev.bd->name, BACKLIGHTMAXNAMELENGTH);
2474 	return (0);
2475 }
2476 
2477 static int
2478 lkpi_backlight_update_status(device_t dev, struct backlight_props *props)
2479 {
2480 	struct pci_dev *pdev;
2481 
2482 	linux_set_current(curthread);
2483 	pdev = device_get_softc(dev);
2484 
2485 	pdev->dev.bd->props.brightness = pdev->dev.bd->props.max_brightness *
2486 		props->brightness / 100;
2487 	pdev->dev.bd->props.power = props->brightness == 0 ?
2488 		4/* FB_BLANK_POWERDOWN */ : 0/* FB_BLANK_UNBLANK */;
2489 	return (pdev->dev.bd->ops->update_status(pdev->dev.bd));
2490 }
2491 
2492 struct backlight_device *
2493 linux_backlight_device_register(const char *name, struct device *dev,
2494     void *data, const struct backlight_ops *ops, struct backlight_properties *props)
2495 {
2496 
2497 	dev->bd = malloc(sizeof(*dev->bd), M_DEVBUF, M_WAITOK | M_ZERO);
2498 	dev->bd->ops = ops;
2499 	dev->bd->props.type = props->type;
2500 	dev->bd->props.max_brightness = props->max_brightness;
2501 	dev->bd->props.brightness = props->brightness;
2502 	dev->bd->props.power = props->power;
2503 	dev->bd->data = data;
2504 	dev->bd->dev = dev;
2505 	dev->bd->name = strdup(name, M_DEVBUF);
2506 
2507 	dev->backlight_dev = backlight_register(name, dev->bsddev);
2508 
2509 	return (dev->bd);
2510 }
2511 
2512 void
2513 linux_backlight_device_unregister(struct backlight_device *bd)
2514 {
2515 
2516 	backlight_destroy(bd->dev->backlight_dev);
2517 	free(bd->name, M_DEVBUF);
2518 	free(bd, M_DEVBUF);
2519 }
2520 
2521 /* -------------------------------------------------------------------------- */
2522 /* Native bus attachment glue. */
2523 
2524 static device_method_t pci_methods[] = {
2525 	DEVMETHOD(device_probe,			lkpi_pci_probe),
2526 	DEVMETHOD(device_attach,		lkpi_pci_attach),
2527 	DEVMETHOD(device_detach,		lkpi_pci_detach),
2528 	DEVMETHOD(device_suspend,		lkpi_pci_suspend),
2529 	DEVMETHOD(device_resume,		lkpi_pci_resume),
2530 	DEVMETHOD(device_shutdown,		lkpi_pci_shutdown),
2531 
2532 	DEVMETHOD(pci_iov_init,			lkpi_pci_iov_init),
2533 	DEVMETHOD(pci_iov_uninit,		lkpi_pci_iov_uninit),
2534 	DEVMETHOD(pci_iov_add_vf,		lkpi_pci_iov_add_vf),
2535 
2536 	/* Bus interface. */
2537 	DEVMETHOD(bus_add_child,		bus_generic_add_child),
2538 
2539 	/* backlight interface */
2540 	DEVMETHOD(backlight_update_status,	lkpi_backlight_update_status),
2541 	DEVMETHOD(backlight_get_status,		lkpi_backlight_get_status),
2542 	DEVMETHOD(backlight_get_info,		lkpi_backlight_get_info),
2543 	DEVMETHOD_END
2544 };
2545