pci.c revision 128075
1/*
2 * Copyright (c) 1997, Stefan Esser <se@freebsd.org>
3 * Copyright (c) 2000, Michael Smith <msmith@freebsd.org>
4 * Copyright (c) 2000, BSDi
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice unmodified, this list of conditions, and the following
12 *    disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 *
28 * $FreeBSD: head/sys/dev/pci/pci.c 128075 2004-04-09 20:41:18Z imp $
29 *
30 */
31
32#include "opt_bus.h"
33
34#include <sys/param.h>
35#include <sys/systm.h>
36#include <sys/malloc.h>
37#include <sys/module.h>
38#include <sys/linker.h>
39#include <sys/fcntl.h>
40#include <sys/conf.h>
41#include <sys/kernel.h>
42#include <sys/queue.h>
43#include <sys/sysctl.h>
44#include <sys/types.h>
45
46#include <vm/vm.h>
47#include <vm/pmap.h>
48#include <vm/vm_extern.h>
49
50#include <sys/bus.h>
51#include <machine/bus.h>
52#include <sys/rman.h>
53#include <machine/resource.h>
54
55#include <sys/pciio.h>
56#include <dev/pci/pcireg.h>
57#include <dev/pci/pcivar.h>
58#include <dev/pci/pci_private.h>
59
60#include "pcib_if.h"
61#include "pci_if.h"
62
63static uint32_t		pci_mapbase(unsigned mapreg);
64static int		pci_maptype(unsigned mapreg);
65static int		pci_mapsize(unsigned testval);
66static int		pci_maprange(unsigned mapreg);
67static void		pci_fixancient(pcicfgregs *cfg);
68
69static int		pci_porten(device_t pcib, int b, int s, int f);
70static int		pci_memen(device_t pcib, int b, int s, int f);
71static int		pci_add_map(device_t pcib, device_t bus, device_t dev,
72			    int b, int s, int f, int reg,
73			    struct resource_list *rl);
74static void		pci_add_resources(device_t pcib, device_t bus,
75			    device_t dev);
76static int		pci_probe(device_t dev);
77static int		pci_attach(device_t dev);
78static void		pci_load_vendor_data(void);
79static int		pci_describe_parse_line(char **ptr, int *vendor,
80			    int *device, char **desc);
81static char		*pci_describe_device(device_t dev);
82static int		pci_modevent(module_t mod, int what, void *arg);
83static void		pci_hdrtypedata(device_t pcib, int b, int s, int f,
84			    pcicfgregs *cfg);
85static void		pci_read_extcap(device_t pcib, pcicfgregs *cfg);
86static void		pci_cfg_restore(device_t, struct pci_devinfo *);
87static void		pci_cfg_save(device_t, struct pci_devinfo *, int);
88
89static device_method_t pci_methods[] = {
90	/* Device interface */
91	DEVMETHOD(device_probe,		pci_probe),
92	DEVMETHOD(device_attach,	pci_attach),
93	DEVMETHOD(device_shutdown,	bus_generic_shutdown),
94	DEVMETHOD(device_suspend,	pci_suspend),
95	DEVMETHOD(device_resume,	pci_resume),
96
97	/* Bus interface */
98	DEVMETHOD(bus_print_child,	pci_print_child),
99	DEVMETHOD(bus_probe_nomatch,	pci_probe_nomatch),
100	DEVMETHOD(bus_read_ivar,	pci_read_ivar),
101	DEVMETHOD(bus_write_ivar,	pci_write_ivar),
102	DEVMETHOD(bus_driver_added,	pci_driver_added),
103	DEVMETHOD(bus_setup_intr,	bus_generic_setup_intr),
104	DEVMETHOD(bus_teardown_intr,	bus_generic_teardown_intr),
105
106	DEVMETHOD(bus_get_resource_list,pci_get_resource_list),
107	DEVMETHOD(bus_set_resource,	bus_generic_rl_set_resource),
108	DEVMETHOD(bus_get_resource,	bus_generic_rl_get_resource),
109	DEVMETHOD(bus_delete_resource,	pci_delete_resource),
110	DEVMETHOD(bus_alloc_resource,	pci_alloc_resource),
111	DEVMETHOD(bus_release_resource,	bus_generic_rl_release_resource),
112	DEVMETHOD(bus_activate_resource, bus_generic_activate_resource),
113	DEVMETHOD(bus_deactivate_resource, bus_generic_deactivate_resource),
114	DEVMETHOD(bus_child_pnpinfo_str, pci_child_pnpinfo_str_method),
115	DEVMETHOD(bus_child_location_str, pci_child_location_str_method),
116
117	/* PCI interface */
118	DEVMETHOD(pci_read_config,	pci_read_config_method),
119	DEVMETHOD(pci_write_config,	pci_write_config_method),
120	DEVMETHOD(pci_enable_busmaster,	pci_enable_busmaster_method),
121	DEVMETHOD(pci_disable_busmaster, pci_disable_busmaster_method),
122	DEVMETHOD(pci_enable_io,	pci_enable_io_method),
123	DEVMETHOD(pci_disable_io,	pci_disable_io_method),
124	DEVMETHOD(pci_get_powerstate,	pci_get_powerstate_method),
125	DEVMETHOD(pci_set_powerstate,	pci_set_powerstate_method),
126	DEVMETHOD(pci_assign_interrupt,	pci_assign_interrupt_method),
127
128	{ 0, 0 }
129};
130
131DEFINE_CLASS_0(pci, pci_driver, pci_methods, 0);
132
133devclass_t	pci_devclass;
134DRIVER_MODULE(pci, pcib, pci_driver, pci_devclass, pci_modevent, 0);
135MODULE_VERSION(pci, 1);
136
137static char	*pci_vendordata;
138static size_t	pci_vendordata_size;
139
140
141struct pci_quirk {
142	uint32_t devid;	/* Vendor/device of the card */
143	int	type;
144#define PCI_QUIRK_MAP_REG	1 /* PCI map register in weird place */
145	int	arg1;
146	int	arg2;
147};
148
149struct pci_quirk pci_quirks[] = {
150	/* The Intel 82371AB and 82443MX has a map register at offset 0x90. */
151	{ 0x71138086, PCI_QUIRK_MAP_REG,	0x90,	 0 },
152	{ 0x719b8086, PCI_QUIRK_MAP_REG,	0x90,	 0 },
153	/* As does the Serverworks OSB4 (the SMBus mapping register) */
154	{ 0x02001166, PCI_QUIRK_MAP_REG,	0x90,	 0 },
155
156	{ 0 }
157};
158
159/* map register information */
160#define PCI_MAPMEM	0x01	/* memory map */
161#define PCI_MAPMEMP	0x02	/* prefetchable memory map */
162#define PCI_MAPPORT	0x04	/* port map */
163
164struct devlist pci_devq;
165uint32_t pci_generation;
166uint32_t pci_numdevs = 0;
167
168/* sysctl vars */
169SYSCTL_NODE(_hw, OID_AUTO, pci, CTLFLAG_RD, 0, "PCI bus tuning parameters");
170
171static int pci_enable_io_modes = 1;
172TUNABLE_INT("hw.pci.enable_io_modes", (int *)&pci_enable_io_modes);
173SYSCTL_INT(_hw_pci, OID_AUTO, enable_io_modes, CTLFLAG_RW,
174    &pci_enable_io_modes, 1,
175    "Enable I/O and memory bits in the config register.  Some BIOSes do not\n\
176enable these bits correctly.  We'd like to do this all the time, but there\n\
177are some peripherals that this causes problems with.");
178
179/* Find a device_t by bus/slot/function */
180
181device_t
182pci_find_bsf(uint8_t bus, uint8_t slot, uint8_t func)
183{
184	struct pci_devinfo *dinfo;
185
186	STAILQ_FOREACH(dinfo, &pci_devq, pci_links) {
187		if ((dinfo->cfg.bus == bus) &&
188		    (dinfo->cfg.slot == slot) &&
189		    (dinfo->cfg.func == func)) {
190			return (dinfo->cfg.dev);
191		}
192	}
193
194	return (NULL);
195}
196
197/* Find a device_t by vendor/device ID */
198
199device_t
200pci_find_device(uint16_t vendor, uint16_t device)
201{
202	struct pci_devinfo *dinfo;
203
204	STAILQ_FOREACH(dinfo, &pci_devq, pci_links) {
205		if ((dinfo->cfg.vendor == vendor) &&
206		    (dinfo->cfg.device == device)) {
207			return (dinfo->cfg.dev);
208		}
209	}
210
211	return (NULL);
212}
213
214/* return base address of memory or port map */
215
216static uint32_t
217pci_mapbase(unsigned mapreg)
218{
219	int mask = 0x03;
220	if ((mapreg & 0x01) == 0)
221		mask = 0x0f;
222	return (mapreg & ~mask);
223}
224
225/* return map type of memory or port map */
226
227static int
228pci_maptype(unsigned mapreg)
229{
230	static uint8_t maptype[0x10] = {
231		PCI_MAPMEM,		PCI_MAPPORT,
232		PCI_MAPMEM,		0,
233		PCI_MAPMEM,		PCI_MAPPORT,
234		0,			0,
235		PCI_MAPMEM|PCI_MAPMEMP,	PCI_MAPPORT,
236		PCI_MAPMEM|PCI_MAPMEMP, 0,
237		PCI_MAPMEM|PCI_MAPMEMP,	PCI_MAPPORT,
238		0,			0,
239	};
240
241	return maptype[mapreg & 0x0f];
242}
243
244/* return log2 of map size decoded for memory or port map */
245
246static int
247pci_mapsize(unsigned testval)
248{
249	int ln2size;
250
251	testval = pci_mapbase(testval);
252	ln2size = 0;
253	if (testval != 0) {
254		while ((testval & 1) == 0)
255		{
256			ln2size++;
257			testval >>= 1;
258		}
259	}
260	return (ln2size);
261}
262
263/* return log2 of address range supported by map register */
264
265static int
266pci_maprange(unsigned mapreg)
267{
268	int ln2range = 0;
269	switch (mapreg & 0x07) {
270	case 0x00:
271	case 0x01:
272	case 0x05:
273		ln2range = 32;
274		break;
275	case 0x02:
276		ln2range = 20;
277		break;
278	case 0x04:
279		ln2range = 64;
280		break;
281	}
282	return (ln2range);
283}
284
285/* adjust some values from PCI 1.0 devices to match 2.0 standards ... */
286
287static void
288pci_fixancient(pcicfgregs *cfg)
289{
290	if (cfg->hdrtype != 0)
291		return;
292
293	/* PCI to PCI bridges use header type 1 */
294	if (cfg->baseclass == PCIC_BRIDGE && cfg->subclass == PCIS_BRIDGE_PCI)
295		cfg->hdrtype = 1;
296}
297
298/* extract header type specific config data */
299
300static void
301pci_hdrtypedata(device_t pcib, int b, int s, int f, pcicfgregs *cfg)
302{
303#define REG(n, w)	PCIB_READ_CONFIG(pcib, b, s, f, n, w)
304	switch (cfg->hdrtype) {
305	case 0:
306		cfg->subvendor      = REG(PCIR_SUBVEND_0, 2);
307		cfg->subdevice      = REG(PCIR_SUBDEV_0, 2);
308		cfg->nummaps	    = PCI_MAXMAPS_0;
309		break;
310	case 1:
311		cfg->subvendor      = REG(PCIR_SUBVEND_1, 2);
312		cfg->subdevice      = REG(PCIR_SUBDEV_1, 2);
313		cfg->nummaps	    = PCI_MAXMAPS_1;
314		break;
315	case 2:
316		cfg->subvendor      = REG(PCIR_SUBVEND_2, 2);
317		cfg->subdevice      = REG(PCIR_SUBDEV_2, 2);
318		cfg->nummaps	    = PCI_MAXMAPS_2;
319		break;
320	}
321#undef REG
322}
323
324/* read configuration header into pcicfgregs structure */
325
326struct pci_devinfo *
327pci_read_device(device_t pcib, int b, int s, int f, size_t size)
328{
329#define REG(n, w)	PCIB_READ_CONFIG(pcib, b, s, f, n, w)
330	pcicfgregs *cfg = NULL;
331	struct pci_devinfo *devlist_entry;
332	struct devlist *devlist_head;
333
334	devlist_head = &pci_devq;
335
336	devlist_entry = NULL;
337
338	if (REG(PCIR_DEVVENDOR, 4) != -1) {
339		devlist_entry = malloc(size, M_DEVBUF, M_WAITOK | M_ZERO);
340		if (devlist_entry == NULL)
341			return (NULL);
342
343		cfg = &devlist_entry->cfg;
344
345		cfg->bus		= b;
346		cfg->slot		= s;
347		cfg->func		= f;
348		cfg->vendor		= REG(PCIR_VENDOR, 2);
349		cfg->device		= REG(PCIR_DEVICE, 2);
350		cfg->cmdreg		= REG(PCIR_COMMAND, 2);
351		cfg->statreg		= REG(PCIR_STATUS, 2);
352		cfg->baseclass		= REG(PCIR_CLASS, 1);
353		cfg->subclass		= REG(PCIR_SUBCLASS, 1);
354		cfg->progif		= REG(PCIR_PROGIF, 1);
355		cfg->revid		= REG(PCIR_REVID, 1);
356		cfg->hdrtype		= REG(PCIR_HDRTYPE, 1);
357		cfg->cachelnsz		= REG(PCIR_CACHELNSZ, 1);
358		cfg->lattimer		= REG(PCIR_LATTIMER, 1);
359		cfg->intpin		= REG(PCIR_INTPIN, 1);
360		cfg->intline		= REG(PCIR_INTLINE, 1);
361
362		cfg->mingnt		= REG(PCIR_MINGNT, 1);
363		cfg->maxlat		= REG(PCIR_MAXLAT, 1);
364
365		cfg->mfdev		= (cfg->hdrtype & PCIM_MFDEV) != 0;
366		cfg->hdrtype		&= ~PCIM_MFDEV;
367
368		pci_fixancient(cfg);
369		pci_hdrtypedata(pcib, b, s, f, cfg);
370
371		if (REG(PCIR_STATUS, 2) & PCIM_STATUS_CAPPRESENT)
372			pci_read_extcap(pcib, cfg);
373
374		STAILQ_INSERT_TAIL(devlist_head, devlist_entry, pci_links);
375
376		devlist_entry->conf.pc_sel.pc_bus = cfg->bus;
377		devlist_entry->conf.pc_sel.pc_dev = cfg->slot;
378		devlist_entry->conf.pc_sel.pc_func = cfg->func;
379		devlist_entry->conf.pc_hdr = cfg->hdrtype;
380
381		devlist_entry->conf.pc_subvendor = cfg->subvendor;
382		devlist_entry->conf.pc_subdevice = cfg->subdevice;
383		devlist_entry->conf.pc_vendor = cfg->vendor;
384		devlist_entry->conf.pc_device = cfg->device;
385
386		devlist_entry->conf.pc_class = cfg->baseclass;
387		devlist_entry->conf.pc_subclass = cfg->subclass;
388		devlist_entry->conf.pc_progif = cfg->progif;
389		devlist_entry->conf.pc_revid = cfg->revid;
390
391		pci_numdevs++;
392		pci_generation++;
393	}
394	return (devlist_entry);
395#undef REG
396}
397
398static void
399pci_read_extcap(device_t pcib, pcicfgregs *cfg)
400{
401#define REG(n, w)	PCIB_READ_CONFIG(pcib, cfg->bus, cfg->slot, cfg->func, n, w)
402	int	ptr, nextptr, ptrptr;
403
404	switch (cfg->hdrtype & PCIM_HDRTYPE) {
405	case 0:
406		ptrptr = PCIR_CAP_PTR;
407		break;
408	case 2:
409		ptrptr = 0x14;
410		break;
411	default:
412		return;		/* no extended capabilities support */
413	}
414	nextptr = REG(ptrptr, 1);	/* sanity check? */
415
416	/*
417	 * Read capability entries.
418	 */
419	while (nextptr != 0) {
420		/* Sanity check */
421		if (nextptr > 255) {
422			printf("illegal PCI extended capability offset %d\n",
423			    nextptr);
424			return;
425		}
426		/* Find the next entry */
427		ptr = nextptr;
428		nextptr = REG(ptr + 1, 1);
429
430		/* Process this entry */
431		switch (REG(ptr, 1)) {
432		case PCIY_PMG:		/* PCI power management */
433			if (cfg->pp.pp_cap == 0) {
434				cfg->pp.pp_cap = REG(ptr + PCIR_POWER_CAP, 2);
435				cfg->pp.pp_status = ptr + PCIR_POWER_STATUS;
436				cfg->pp.pp_pmcsr = ptr + PCIR_POWER_PMCSR;
437				if ((nextptr - ptr) > PCIR_POWER_DATA)
438					cfg->pp.pp_data = ptr + PCIR_POWER_DATA;
439			}
440			break;
441		case PCIY_MSI:		/* PCI MSI */
442			cfg->msi.msi_ctrl = REG(ptr + PCIR_MSI_CTRL, 2);
443			if (cfg->msi.msi_ctrl & PCIM_MSICTRL_64BIT)
444				cfg->msi.msi_data = PCIR_MSI_DATA_64BIT;
445			else
446				cfg->msi.msi_data = PCIR_MSI_DATA;
447			cfg->msi.msi_msgnum = 1 << ((cfg->msi.msi_ctrl &
448						     PCIM_MSICTRL_MMC_MASK)>>1);
449		default:
450			break;
451		}
452	}
453#undef REG
454}
455
456/* free pcicfgregs structure and all depending data structures */
457
458int
459pci_freecfg(struct pci_devinfo *dinfo)
460{
461	struct devlist *devlist_head;
462
463	devlist_head = &pci_devq;
464
465	STAILQ_REMOVE(devlist_head, dinfo, pci_devinfo, pci_links);
466	free(dinfo, M_DEVBUF);
467
468	/* increment the generation count */
469	pci_generation++;
470
471	/* we're losing one device */
472	pci_numdevs--;
473	return (0);
474}
475
476/*
477 * PCI power manangement
478 */
479int
480pci_set_powerstate_method(device_t dev, device_t child, int state)
481{
482	struct pci_devinfo *dinfo = device_get_ivars(child);
483	pcicfgregs *cfg = &dinfo->cfg;
484	uint16_t status;
485	int result;
486
487	if (cfg->pp.pp_cap != 0) {
488		status = PCI_READ_CONFIG(dev, child, cfg->pp.pp_status, 2)
489		    & ~PCIM_PSTAT_DMASK;
490		result = 0;
491		switch (state) {
492		case PCI_POWERSTATE_D0:
493			status |= PCIM_PSTAT_D0;
494			break;
495		case PCI_POWERSTATE_D1:
496			if (cfg->pp.pp_cap & PCIM_PCAP_D1SUPP) {
497				status |= PCIM_PSTAT_D1;
498			} else {
499				result = EOPNOTSUPP;
500			}
501			break;
502		case PCI_POWERSTATE_D2:
503			if (cfg->pp.pp_cap & PCIM_PCAP_D2SUPP) {
504				status |= PCIM_PSTAT_D2;
505			} else {
506				result = EOPNOTSUPP;
507			}
508			break;
509		case PCI_POWERSTATE_D3:
510			status |= PCIM_PSTAT_D3;
511			break;
512		default:
513			result = EINVAL;
514		}
515		if (result == 0)
516			PCI_WRITE_CONFIG(dev, child, cfg->pp.pp_status, status,
517					 2);
518	} else {
519		result = ENXIO;
520	}
521	return(result);
522}
523
524int
525pci_get_powerstate_method(device_t dev, device_t child)
526{
527	struct pci_devinfo *dinfo = device_get_ivars(child);
528	pcicfgregs *cfg = &dinfo->cfg;
529	uint16_t status;
530	int result;
531
532	if (cfg->pp.pp_cap != 0) {
533		status = PCI_READ_CONFIG(dev, child, cfg->pp.pp_status, 2);
534		switch (status & PCIM_PSTAT_DMASK) {
535		case PCIM_PSTAT_D0:
536			result = PCI_POWERSTATE_D0;
537			break;
538		case PCIM_PSTAT_D1:
539			result = PCI_POWERSTATE_D1;
540			break;
541		case PCIM_PSTAT_D2:
542			result = PCI_POWERSTATE_D2;
543			break;
544		case PCIM_PSTAT_D3:
545			result = PCI_POWERSTATE_D3;
546			break;
547		default:
548			result = PCI_POWERSTATE_UNKNOWN;
549			break;
550		}
551	} else {
552		/* No support, device is always at D0 */
553		result = PCI_POWERSTATE_D0;
554	}
555	return(result);
556}
557
558/*
559 * Some convenience functions for PCI device drivers.
560 */
561
562static __inline void
563pci_set_command_bit(device_t dev, device_t child, uint16_t bit)
564{
565	uint16_t	command;
566
567	command = PCI_READ_CONFIG(dev, child, PCIR_COMMAND, 2);
568	command |= bit;
569	PCI_WRITE_CONFIG(dev, child, PCIR_COMMAND, command, 2);
570}
571
572static __inline void
573pci_clear_command_bit(device_t dev, device_t child, uint16_t bit)
574{
575	uint16_t	command;
576
577	command = PCI_READ_CONFIG(dev, child, PCIR_COMMAND, 2);
578	command &= ~bit;
579	PCI_WRITE_CONFIG(dev, child, PCIR_COMMAND, command, 2);
580}
581
582int
583pci_enable_busmaster_method(device_t dev, device_t child)
584{
585	pci_set_command_bit(dev, child, PCIM_CMD_BUSMASTEREN);
586	return (0);
587}
588
589int
590pci_disable_busmaster_method(device_t dev, device_t child)
591{
592	pci_clear_command_bit(dev, child, PCIM_CMD_BUSMASTEREN);
593	return (0);
594}
595
596int
597pci_enable_io_method(device_t dev, device_t child, int space)
598{
599	uint16_t command;
600	uint16_t bit;
601	char *error;
602
603	bit = 0;
604	error = NULL;
605
606	switch(space) {
607	case SYS_RES_IOPORT:
608		bit = PCIM_CMD_PORTEN;
609		error = "port";
610		break;
611	case SYS_RES_MEMORY:
612		bit = PCIM_CMD_MEMEN;
613		error = "memory";
614		break;
615	default:
616		return (EINVAL);
617	}
618	pci_set_command_bit(dev, child, bit);
619	/* Some devices seem to need a brief stall here, what do to? */
620	command = PCI_READ_CONFIG(dev, child, PCIR_COMMAND, 2);
621	if (command & bit)
622		return (0);
623	device_printf(child, "failed to enable %s mapping!\n", error);
624	return (ENXIO);
625}
626
627int
628pci_disable_io_method(device_t dev, device_t child, int space)
629{
630	uint16_t command;
631	uint16_t bit;
632	char *error;
633
634	bit = 0;
635	error = NULL;
636
637	switch(space) {
638	case SYS_RES_IOPORT:
639		bit = PCIM_CMD_PORTEN;
640		error = "port";
641		break;
642	case SYS_RES_MEMORY:
643		bit = PCIM_CMD_MEMEN;
644		error = "memory";
645		break;
646	default:
647		return (EINVAL);
648	}
649	pci_clear_command_bit(dev, child, bit);
650	command = PCI_READ_CONFIG(dev, child, PCIR_COMMAND, 2);
651	if (command & bit) {
652		device_printf(child, "failed to disable %s mapping!\n", error);
653		return (ENXIO);
654	}
655	return (0);
656}
657
658/*
659 * New style pci driver.  Parent device is either a pci-host-bridge or a
660 * pci-pci-bridge.  Both kinds are represented by instances of pcib.
661 */
662
663void
664pci_print_verbose(struct pci_devinfo *dinfo)
665{
666	if (bootverbose) {
667		pcicfgregs *cfg = &dinfo->cfg;
668
669		printf("found->\tvendor=0x%04x, dev=0x%04x, revid=0x%02x\n",
670		    cfg->vendor, cfg->device, cfg->revid);
671		printf("\tbus=%d, slot=%d, func=%d\n",
672		    cfg->bus, cfg->slot, cfg->func);
673		printf("\tclass=%02x-%02x-%02x, hdrtype=0x%02x, mfdev=%d\n",
674		    cfg->baseclass, cfg->subclass, cfg->progif, cfg->hdrtype,
675		    cfg->mfdev);
676		printf("\tcmdreg=0x%04x, statreg=0x%04x, cachelnsz=%d (dwords)\n",
677		    cfg->cmdreg, cfg->statreg, cfg->cachelnsz);
678		printf("\tlattimer=0x%02x (%d ns), mingnt=0x%02x (%d ns), maxlat=0x%02x (%d ns)\n",
679		    cfg->lattimer, cfg->lattimer * 30, cfg->mingnt,
680		    cfg->mingnt * 250, cfg->maxlat, cfg->maxlat * 250);
681		if (cfg->intpin > 0)
682			printf("\tintpin=%c, irq=%d\n",
683			    cfg->intpin +'a' -1, cfg->intline);
684		if (cfg->pp.pp_cap) {
685			uint16_t status;
686
687			status = pci_read_config(cfg->dev, cfg->pp.pp_status, 2);
688			printf("\tpowerspec %d  supports D0%s%s D3  current D%d\n",
689			    cfg->pp.pp_cap & PCIM_PCAP_SPEC,
690			    cfg->pp.pp_cap & PCIM_PCAP_D1SUPP ? " D1" : "",
691			    cfg->pp.pp_cap & PCIM_PCAP_D2SUPP ? " D2" : "",
692			    status & PCIM_PSTAT_DMASK);
693		}
694		if (cfg->msi.msi_data) {
695			int ctrl;
696
697			ctrl =  cfg->msi.msi_ctrl;
698			printf("\tMSI supports %d message%s%s%s\n",
699			    cfg->msi.msi_msgnum,
700			    (cfg->msi.msi_msgnum == 1) ? "" : "s",
701			    (ctrl & PCIM_MSICTRL_64BIT) ? ", 64 bit" : "",
702			    (ctrl & PCIM_MSICTRL_VECTOR) ? ", vector masks":"");
703		}
704	}
705}
706
707static int
708pci_porten(device_t pcib, int b, int s, int f)
709{
710	return (PCIB_READ_CONFIG(pcib, b, s, f, PCIR_COMMAND, 2)
711		& PCIM_CMD_PORTEN) != 0;
712}
713
714static int
715pci_memen(device_t pcib, int b, int s, int f)
716{
717	return (PCIB_READ_CONFIG(pcib, b, s, f, PCIR_COMMAND, 2)
718		& PCIM_CMD_MEMEN) != 0;
719}
720
721/*
722 * Add a resource based on a pci map register. Return 1 if the map
723 * register is a 32bit map register or 2 if it is a 64bit register.
724 */
725static int
726pci_add_map(device_t pcib, device_t bus, device_t dev,
727    int b, int s, int f, int reg, struct resource_list *rl)
728{
729	uint32_t map;
730	uint64_t base;
731	uint64_t start, end, count;
732	uint8_t ln2size;
733	uint8_t ln2range;
734	uint32_t testval;
735	uint16_t cmd;
736	int type;
737
738	map = PCIB_READ_CONFIG(pcib, b, s, f, reg, 4);
739	PCIB_WRITE_CONFIG(pcib, b, s, f, reg, 0xffffffff, 4);
740	testval = PCIB_READ_CONFIG(pcib, b, s, f, reg, 4);
741	PCIB_WRITE_CONFIG(pcib, b, s, f, reg, map, 4);
742
743	if (pci_maptype(map) & PCI_MAPMEM)
744		type = SYS_RES_MEMORY;
745	else
746		type = SYS_RES_IOPORT;
747	ln2size = pci_mapsize(testval);
748	ln2range = pci_maprange(testval);
749	base = pci_mapbase(map);
750
751	/*
752	 * For I/O registers, if bottom bit is set, and the next bit up
753	 * isn't clear, we know we have a BAR that doesn't conform to the
754	 * spec, so ignore it.  Also, sanity check the size of the data
755	 * areas to the type of memory involved.
756	 */
757	if ((testval & 0x1) == 0x1 &&
758	    (testval & 0x2) != 0)
759		return (1);
760	if ((type == SYS_RES_MEMORY && ln2size < 5) ||
761	    (type == SYS_RES_IOPORT && ln2size < 3))
762		return (1);
763
764	if (ln2range == 64)
765		/* Read the other half of a 64bit map register */
766		base |= (uint64_t) PCIB_READ_CONFIG(pcib, b, s, f, reg + 4, 4) << 32;
767
768	if (bootverbose) {
769		printf("\tmap[%02x]: type %x, range %2d, base %08x, size %2d",
770		    reg, pci_maptype(map), ln2range,
771		    (unsigned int) base, ln2size);
772		if (type == SYS_RES_IOPORT && !pci_porten(pcib, b, s, f))
773			printf(", port disabled\n");
774		else if (type == SYS_RES_MEMORY && !pci_memen(pcib, b, s, f))
775			printf(", memory disabled\n");
776		else
777			printf(", enabled\n");
778	}
779
780	/*
781	 * This code theoretically does the right thing, but has
782	 * undesirable side effects in some cases where peripherals
783	 * respond oddly to having these bits enabled.  Let the user
784	 * be able to turn them off (since pci_enable_io_modes is 1 by
785	 * default).
786	 */
787	if (pci_enable_io_modes) {
788		/* Turn on resources that have been left off by a lazy BIOS */
789		if (type == SYS_RES_IOPORT && !pci_porten(pcib, b, s, f)) {
790			cmd = PCIB_READ_CONFIG(pcib, b, s, f, PCIR_COMMAND, 2);
791			cmd |= PCIM_CMD_PORTEN;
792			PCIB_WRITE_CONFIG(pcib, b, s, f, PCIR_COMMAND, cmd, 2);
793		}
794		if (type == SYS_RES_MEMORY && !pci_memen(pcib, b, s, f)) {
795			cmd = PCIB_READ_CONFIG(pcib, b, s, f, PCIR_COMMAND, 2);
796			cmd |= PCIM_CMD_MEMEN;
797			PCIB_WRITE_CONFIG(pcib, b, s, f, PCIR_COMMAND, cmd, 2);
798		}
799	} else {
800		if (type == SYS_RES_IOPORT && !pci_porten(pcib, b, s, f))
801			return (1);
802		if (type == SYS_RES_MEMORY && !pci_memen(pcib, b, s, f))
803			return (1);
804	}
805	/*
806	 * If base is 0, then we have problems.  It is best to ignore
807	 * such entires for the moment.  These will be allocated later if
808	 * the driver specifically requests them.
809	 */
810	if (base == 0)
811		return 1;
812	start = base;
813	end = base + (1 << ln2size) - 1;
814	count = 1 << ln2size;
815	resource_list_add(rl, type, reg, start, end, count);
816
817	/*
818	 * Not quite sure what to do on failure of allocating the resource
819	 * since I can postulate several right answers.
820	 */
821	resource_list_alloc(rl, bus, dev, type, &reg, start, end, count, 0);
822	return ((ln2range == 64) ? 2 : 1);
823}
824
825static void
826pci_add_resources(device_t pcib, device_t bus, device_t dev)
827{
828	struct pci_devinfo *dinfo = device_get_ivars(dev);
829	pcicfgregs *cfg = &dinfo->cfg;
830	struct resource_list *rl = &dinfo->resources;
831	struct pci_quirk *q;
832	int b, i, irq, f, s;
833
834	b = cfg->bus;
835	s = cfg->slot;
836	f = cfg->func;
837	for (i = 0; i < cfg->nummaps;)
838		i += pci_add_map(pcib, bus, dev, b, s, f, PCIR_BAR(i), rl);
839
840	for (q = &pci_quirks[0]; q->devid; q++) {
841		if (q->devid == ((cfg->device << 16) | cfg->vendor)
842		    && q->type == PCI_QUIRK_MAP_REG)
843			pci_add_map(pcib, bus, dev, b, s, f, q->arg1, rl);
844	}
845
846	if (cfg->intpin > 0 && PCI_INTERRUPT_VALID(cfg->intline)) {
847#if defined(__ia64__) || defined(__i386__) || defined(__amd64__)
848		/*
849		 * Try to re-route interrupts. Sometimes the BIOS or
850		 * firmware may leave bogus values in these registers.
851		 * If the re-route fails, then just stick with what we
852		 * have.
853		 */
854		irq = PCI_ASSIGN_INTERRUPT(bus, dev);
855		if (PCI_INTERRUPT_VALID(irq)) {
856			pci_write_config(dev, PCIR_INTLINE, irq, 1);
857			cfg->intline = irq;
858		} else
859#endif
860			irq = cfg->intline;
861		resource_list_add(rl, SYS_RES_IRQ, 0, irq, irq, 1);
862	}
863}
864
865void
866pci_add_children(device_t dev, int busno, size_t dinfo_size)
867{
868#define REG(n, w)	PCIB_READ_CONFIG(pcib, busno, s, f, n, w)
869	device_t pcib = device_get_parent(dev);
870	struct pci_devinfo *dinfo;
871	int maxslots;
872	int s, f, pcifunchigh;
873	uint8_t hdrtype;
874
875	KASSERT(dinfo_size >= sizeof(struct pci_devinfo),
876	    ("dinfo_size too small"));
877	maxslots = PCIB_MAXSLOTS(pcib);
878	for (s = 0; s <= maxslots; s++) {
879		pcifunchigh = 0;
880		f = 0;
881		hdrtype = REG(PCIR_HDRTYPE, 1);
882		if ((hdrtype & PCIM_HDRTYPE) > PCI_MAXHDRTYPE)
883			continue;
884		if (hdrtype & PCIM_MFDEV)
885			pcifunchigh = PCI_FUNCMAX;
886		for (f = 0; f <= pcifunchigh; f++) {
887			dinfo = pci_read_device(pcib, busno, s, f, dinfo_size);
888			if (dinfo != NULL) {
889				pci_add_child(dev, dinfo);
890			}
891		}
892	}
893#undef REG
894}
895
896void
897pci_add_child(device_t bus, struct pci_devinfo *dinfo)
898{
899	device_t pcib;
900
901	pcib = device_get_parent(bus);
902	dinfo->cfg.dev = device_add_child(bus, NULL, -1);
903	device_set_ivars(dinfo->cfg.dev, dinfo);
904	pci_cfg_save(dinfo->cfg.dev, dinfo, 0);
905	pci_cfg_restore(dinfo->cfg.dev, dinfo);
906	pci_add_resources(pcib, bus, dinfo->cfg.dev);
907	pci_print_verbose(dinfo);
908}
909
910static int
911pci_probe(device_t dev)
912{
913
914	device_set_desc(dev, "PCI bus");
915
916	/* Allow other subclasses to override this driver. */
917	return (-1000);
918}
919
920static int
921pci_attach(device_t dev)
922{
923	int busno;
924
925	/*
926	 * Since there can be multiple independantly numbered PCI
927	 * busses on some large alpha systems, we can't use the unit
928	 * number to decide what bus we are probing. We ask the parent
929	 * pcib what our bus number is.
930	 */
931	busno = pcib_get_bus(dev);
932	if (bootverbose)
933		device_printf(dev, "physical bus=%d\n", busno);
934
935	pci_add_children(dev, busno, sizeof(struct pci_devinfo));
936
937	return (bus_generic_attach(dev));
938}
939
940int
941pci_suspend(device_t dev)
942{
943	int numdevs;
944	device_t *devlist;
945	device_t child;
946	struct pci_devinfo *dinfo;
947	int i;
948
949	/*
950	 * Save the pci configuration space for each child.  We don't need
951	 * to do this, unless the BIOS suspend code powers down the bus and
952	 * the devices on the bus.
953	 */
954	device_get_children(dev, &devlist, &numdevs);
955	for (i = 0; i < numdevs; i++) {
956		child = devlist[i];
957		dinfo = (struct pci_devinfo *) device_get_ivars(child);
958		pci_cfg_save(child, dinfo, 0);
959	}
960	free(devlist, M_TEMP);
961	return (bus_generic_suspend(dev));
962}
963
964int
965pci_resume(device_t dev)
966{
967	int numdevs;
968	device_t *devlist;
969	device_t child;
970	struct pci_devinfo *dinfo;
971	int i;
972
973	/*
974	 * Restore the pci configuration space for each child.
975	 */
976	device_get_children(dev, &devlist, &numdevs);
977	for (i = 0; i < numdevs; i++) {
978		child = devlist[i];
979		dinfo = (struct pci_devinfo *) device_get_ivars(child);
980		pci_cfg_restore(child, dinfo);
981	}
982	free(devlist, M_TEMP);
983	return (bus_generic_resume(dev));
984}
985
986static void
987pci_load_vendor_data(void)
988{
989	caddr_t vendordata, info;
990
991	if ((vendordata = preload_search_by_type("pci_vendor_data")) != NULL) {
992		info = preload_search_info(vendordata, MODINFO_ADDR);
993		pci_vendordata = *(char **)info;
994		info = preload_search_info(vendordata, MODINFO_SIZE);
995		pci_vendordata_size = *(size_t *)info;
996		/* terminate the database */
997		pci_vendordata[pci_vendordata_size] = '\n';
998	}
999}
1000
1001void
1002pci_driver_added(device_t dev, driver_t *driver)
1003{
1004	int numdevs;
1005	device_t *devlist;
1006	device_t child;
1007	struct pci_devinfo *dinfo;
1008	int i;
1009
1010	device_printf(dev, "driver added\n");
1011	DEVICE_IDENTIFY(driver, dev);
1012	device_get_children(dev, &devlist, &numdevs);
1013	for (i = 0; i < numdevs; i++) {
1014		child = devlist[i];
1015		if (device_get_state(child) != DS_NOTPRESENT)
1016			continue;
1017		dinfo = device_get_ivars(child);
1018		pci_print_verbose(dinfo);
1019/*XXX???*/	/* resource_list_init(&dinfo->cfg.resources); */
1020		printf("pci%d:%d:%d: reprobing on driver added\n",
1021		    dinfo->cfg.bus, dinfo->cfg.slot, dinfo->cfg.func);
1022		pci_cfg_restore(child, dinfo);
1023		if (device_probe_and_attach(child) != 0)
1024			pci_cfg_save(child, dinfo, 1);
1025	}
1026	free(devlist, M_TEMP);
1027}
1028
1029int
1030pci_print_child(device_t dev, device_t child)
1031{
1032	struct pci_devinfo *dinfo;
1033	struct resource_list *rl;
1034	int retval = 0;
1035
1036	dinfo = device_get_ivars(child);
1037	rl = &dinfo->resources;
1038
1039	retval += bus_print_child_header(dev, child);
1040
1041	retval += resource_list_print_type(rl, "port", SYS_RES_IOPORT, "%#lx");
1042	retval += resource_list_print_type(rl, "mem", SYS_RES_MEMORY, "%#lx");
1043	retval += resource_list_print_type(rl, "irq", SYS_RES_IRQ, "%ld");
1044	if (device_get_flags(dev))
1045		retval += printf(" flags %#x", device_get_flags(dev));
1046
1047	retval += printf(" at device %d.%d", pci_get_slot(child),
1048	    pci_get_function(child));
1049
1050	retval += bus_print_child_footer(dev, child);
1051
1052	return (retval);
1053}
1054
1055static struct
1056{
1057	int	class;
1058	int	subclass;
1059	char	*desc;
1060} pci_nomatch_tab[] = {
1061	{PCIC_OLD,		-1,			"old"},
1062	{PCIC_OLD,		PCIS_OLD_NONVGA,	"non-VGA display device"},
1063	{PCIC_OLD,		PCIS_OLD_VGA,		"VGA-compatible display device"},
1064	{PCIC_STORAGE,		-1,			"mass storage"},
1065	{PCIC_STORAGE,		PCIS_STORAGE_SCSI,	"SCSI"},
1066	{PCIC_STORAGE,		PCIS_STORAGE_IDE,	"ATA"},
1067	{PCIC_STORAGE,		PCIS_STORAGE_FLOPPY,	"floppy disk"},
1068	{PCIC_STORAGE,		PCIS_STORAGE_IPI,	"IPI"},
1069	{PCIC_STORAGE,		PCIS_STORAGE_RAID,	"RAID"},
1070	{PCIC_NETWORK,		-1,			"network"},
1071	{PCIC_NETWORK,		PCIS_NETWORK_ETHERNET,	"ethernet"},
1072	{PCIC_NETWORK,		PCIS_NETWORK_TOKENRING,	"token ring"},
1073	{PCIC_NETWORK,		PCIS_NETWORK_FDDI,	"fddi"},
1074	{PCIC_NETWORK,		PCIS_NETWORK_ATM,	"ATM"},
1075	{PCIC_DISPLAY,		-1,			"display"},
1076	{PCIC_DISPLAY,		PCIS_DISPLAY_VGA,	"VGA"},
1077	{PCIC_DISPLAY,		PCIS_DISPLAY_XGA,	"XGA"},
1078	{PCIC_MULTIMEDIA,	-1,			"multimedia"},
1079	{PCIC_MULTIMEDIA,	PCIS_MULTIMEDIA_VIDEO,	"video"},
1080	{PCIC_MULTIMEDIA,	PCIS_MULTIMEDIA_AUDIO,	"audio"},
1081	{PCIC_MEMORY,		-1,			"memory"},
1082	{PCIC_MEMORY,		PCIS_MEMORY_RAM,	"RAM"},
1083	{PCIC_MEMORY,		PCIS_MEMORY_FLASH,	"flash"},
1084	{PCIC_BRIDGE,		-1,			"bridge"},
1085	{PCIC_BRIDGE,		PCIS_BRIDGE_HOST,	"HOST-PCI"},
1086	{PCIC_BRIDGE,		PCIS_BRIDGE_ISA,	"PCI-ISA"},
1087	{PCIC_BRIDGE,		PCIS_BRIDGE_EISA,	"PCI-EISA"},
1088	{PCIC_BRIDGE,		PCIS_BRIDGE_MCA,	"PCI-MCA"},
1089	{PCIC_BRIDGE,		PCIS_BRIDGE_PCI,	"PCI-PCI"},
1090	{PCIC_BRIDGE,		PCIS_BRIDGE_PCMCIA,	"PCI-PCMCIA"},
1091	{PCIC_BRIDGE,		PCIS_BRIDGE_NUBUS,	"PCI-NuBus"},
1092	{PCIC_BRIDGE,		PCIS_BRIDGE_CARDBUS,	"PCI-CardBus"},
1093	{PCIC_BRIDGE,		PCIS_BRIDGE_OTHER,	"PCI-unknown"},
1094	{PCIC_SIMPLECOMM,	-1,			"simple comms"},
1095	{PCIC_SIMPLECOMM,	PCIS_SIMPLECOMM_UART,	"UART"},	/* could detect 16550 */
1096	{PCIC_SIMPLECOMM,	PCIS_SIMPLECOMM_PAR,	"parallel port"},
1097	{PCIC_BASEPERIPH,	-1,			"base peripheral"},
1098	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_PIC,	"interrupt controller"},
1099	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_DMA,	"DMA controller"},
1100	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_TIMER,	"timer"},
1101	{PCIC_BASEPERIPH,	PCIS_BASEPERIPH_RTC,	"realtime clock"},
1102	{PCIC_INPUTDEV,		-1,			"input device"},
1103	{PCIC_INPUTDEV,		PCIS_INPUTDEV_KEYBOARD,	"keyboard"},
1104	{PCIC_INPUTDEV,		PCIS_INPUTDEV_DIGITIZER,"digitizer"},
1105	{PCIC_INPUTDEV,		PCIS_INPUTDEV_MOUSE,	"mouse"},
1106	{PCIC_DOCKING,		-1,			"docking station"},
1107	{PCIC_PROCESSOR,	-1,			"processor"},
1108	{PCIC_SERIALBUS,	-1,			"serial bus"},
1109	{PCIC_SERIALBUS,	PCIS_SERIALBUS_FW,	"FireWire"},
1110	{PCIC_SERIALBUS,	PCIS_SERIALBUS_ACCESS,	"AccessBus"},
1111	{PCIC_SERIALBUS,	PCIS_SERIALBUS_SSA,	"SSA"},
1112	{PCIC_SERIALBUS,	PCIS_SERIALBUS_USB,	"USB"},
1113	{PCIC_SERIALBUS,	PCIS_SERIALBUS_FC,	"Fibre Channel"},
1114	{PCIC_SERIALBUS,	PCIS_SERIALBUS_SMBUS,	"SMBus"},
1115	{0, 0,		NULL}
1116};
1117
1118void
1119pci_probe_nomatch(device_t dev, device_t child)
1120{
1121	int	i;
1122	char	*cp, *scp, *device;
1123
1124	/*
1125	 * Look for a listing for this device in a loaded device database.
1126	 */
1127	if ((device = pci_describe_device(child)) != NULL) {
1128		device_printf(dev, "<%s>", device);
1129		free(device, M_DEVBUF);
1130	} else {
1131		/*
1132		 * Scan the class/subclass descriptions for a general
1133		 * description.
1134		 */
1135		cp = "unknown";
1136		scp = NULL;
1137		for (i = 0; pci_nomatch_tab[i].desc != NULL; i++) {
1138			if (pci_nomatch_tab[i].class == pci_get_class(child)) {
1139				if (pci_nomatch_tab[i].subclass == -1) {
1140					cp = pci_nomatch_tab[i].desc;
1141				} else if (pci_nomatch_tab[i].subclass ==
1142				    pci_get_subclass(child)) {
1143					scp = pci_nomatch_tab[i].desc;
1144				}
1145			}
1146		}
1147		device_printf(dev, "<%s%s%s>",
1148		    cp ? cp : "",
1149		    ((cp != NULL) && (scp != NULL)) ? ", " : "",
1150		    scp ? scp : "");
1151	}
1152	printf(" at device %d.%d (no driver attached)\n",
1153	    pci_get_slot(child), pci_get_function(child));
1154	pci_cfg_save(child, (struct pci_devinfo *) device_get_ivars(child), 1);
1155	return;
1156}
1157
1158/*
1159 * Parse the PCI device database, if loaded, and return a pointer to a
1160 * description of the device.
1161 *
1162 * The database is flat text formatted as follows:
1163 *
1164 * Any line not in a valid format is ignored.
1165 * Lines are terminated with newline '\n' characters.
1166 *
1167 * A VENDOR line consists of the 4 digit (hex) vendor code, a TAB, then
1168 * the vendor name.
1169 *
1170 * A DEVICE line is entered immediately below the corresponding VENDOR ID.
1171 * - devices cannot be listed without a corresponding VENDOR line.
1172 * A DEVICE line consists of a TAB, the 4 digit (hex) device code,
1173 * another TAB, then the device name.
1174 */
1175
1176/*
1177 * Assuming (ptr) points to the beginning of a line in the database,
1178 * return the vendor or device and description of the next entry.
1179 * The value of (vendor) or (device) inappropriate for the entry type
1180 * is set to -1.  Returns nonzero at the end of the database.
1181 *
1182 * Note that this is slightly unrobust in the face of corrupt data;
1183 * we attempt to safeguard against this by spamming the end of the
1184 * database with a newline when we initialise.
1185 */
1186static int
1187pci_describe_parse_line(char **ptr, int *vendor, int *device, char **desc)
1188{
1189	char	*cp = *ptr;
1190	int	left;
1191
1192	*device = -1;
1193	*vendor = -1;
1194	**desc = '\0';
1195	for (;;) {
1196		left = pci_vendordata_size - (cp - pci_vendordata);
1197		if (left <= 0) {
1198			*ptr = cp;
1199			return(1);
1200		}
1201
1202		/* vendor entry? */
1203		if (*cp != '\t' &&
1204		    sscanf(cp, "%x\t%80[^\n]", vendor, *desc) == 2)
1205			break;
1206		/* device entry? */
1207		if (*cp == '\t' &&
1208		    sscanf(cp, "%x\t%80[^\n]", device, *desc) == 2)
1209			break;
1210
1211		/* skip to next line */
1212		while (*cp != '\n' && left > 0) {
1213			cp++;
1214			left--;
1215		}
1216		if (*cp == '\n') {
1217			cp++;
1218			left--;
1219		}
1220	}
1221	/* skip to next line */
1222	while (*cp != '\n' && left > 0) {
1223		cp++;
1224		left--;
1225	}
1226	if (*cp == '\n' && left > 0)
1227		cp++;
1228	*ptr = cp;
1229	return(0);
1230}
1231
1232static char *
1233pci_describe_device(device_t dev)
1234{
1235	int	vendor, device;
1236	char	*desc, *vp, *dp, *line;
1237
1238	desc = vp = dp = NULL;
1239
1240	/*
1241	 * If we have no vendor data, we can't do anything.
1242	 */
1243	if (pci_vendordata == NULL)
1244		goto out;
1245
1246	/*
1247	 * Scan the vendor data looking for this device
1248	 */
1249	line = pci_vendordata;
1250	if ((vp = malloc(80, M_DEVBUF, M_NOWAIT)) == NULL)
1251		goto out;
1252	for (;;) {
1253		if (pci_describe_parse_line(&line, &vendor, &device, &vp))
1254			goto out;
1255		if (vendor == pci_get_vendor(dev))
1256			break;
1257	}
1258	if ((dp = malloc(80, M_DEVBUF, M_NOWAIT)) == NULL)
1259		goto out;
1260	for (;;) {
1261		if (pci_describe_parse_line(&line, &vendor, &device, &dp)) {
1262			*dp = 0;
1263			break;
1264		}
1265		if (vendor != -1) {
1266			*dp = 0;
1267			break;
1268		}
1269		if (device == pci_get_device(dev))
1270			break;
1271	}
1272	if (dp[0] == '\0')
1273		snprintf(dp, 80, "0x%x", pci_get_device(dev));
1274	if ((desc = malloc(strlen(vp) + strlen(dp) + 3, M_DEVBUF, M_NOWAIT)) !=
1275	    NULL)
1276		sprintf(desc, "%s, %s", vp, dp);
1277 out:
1278	if (vp != NULL)
1279		free(vp, M_DEVBUF);
1280	if (dp != NULL)
1281		free(dp, M_DEVBUF);
1282	return(desc);
1283}
1284
1285int
1286pci_read_ivar(device_t dev, device_t child, int which, uintptr_t *result)
1287{
1288	struct pci_devinfo *dinfo;
1289	pcicfgregs *cfg;
1290
1291	dinfo = device_get_ivars(child);
1292	cfg = &dinfo->cfg;
1293
1294	switch (which) {
1295	case PCI_IVAR_ETHADDR:
1296		/*
1297		 * The generic accessor doesn't deal with failure, so
1298		 * we set the return value, then return an error.
1299		 */
1300		*((uint8_t **) result) = NULL;
1301		return (EINVAL);
1302	case PCI_IVAR_SUBVENDOR:
1303		*result = cfg->subvendor;
1304		break;
1305	case PCI_IVAR_SUBDEVICE:
1306		*result = cfg->subdevice;
1307		break;
1308	case PCI_IVAR_VENDOR:
1309		*result = cfg->vendor;
1310		break;
1311	case PCI_IVAR_DEVICE:
1312		*result = cfg->device;
1313		break;
1314	case PCI_IVAR_DEVID:
1315		*result = (cfg->device << 16) | cfg->vendor;
1316		break;
1317	case PCI_IVAR_CLASS:
1318		*result = cfg->baseclass;
1319		break;
1320	case PCI_IVAR_SUBCLASS:
1321		*result = cfg->subclass;
1322		break;
1323	case PCI_IVAR_PROGIF:
1324		*result = cfg->progif;
1325		break;
1326	case PCI_IVAR_REVID:
1327		*result = cfg->revid;
1328		break;
1329	case PCI_IVAR_INTPIN:
1330		*result = cfg->intpin;
1331		break;
1332	case PCI_IVAR_IRQ:
1333		*result = cfg->intline;
1334		break;
1335	case PCI_IVAR_BUS:
1336		*result = cfg->bus;
1337		break;
1338	case PCI_IVAR_SLOT:
1339		*result = cfg->slot;
1340		break;
1341	case PCI_IVAR_FUNCTION:
1342		*result = cfg->func;
1343		break;
1344	default:
1345		return (ENOENT);
1346	}
1347	return (0);
1348}
1349
1350int
1351pci_write_ivar(device_t dev, device_t child, int which, uintptr_t value)
1352{
1353	struct pci_devinfo *dinfo;
1354
1355	dinfo = device_get_ivars(child);
1356
1357	switch (which) {
1358	case PCI_IVAR_INTPIN:
1359		dinfo->cfg.intpin = value;
1360		return (0);
1361	case PCI_IVAR_ETHADDR:
1362	case PCI_IVAR_SUBVENDOR:
1363	case PCI_IVAR_SUBDEVICE:
1364	case PCI_IVAR_VENDOR:
1365	case PCI_IVAR_DEVICE:
1366	case PCI_IVAR_DEVID:
1367	case PCI_IVAR_CLASS:
1368	case PCI_IVAR_SUBCLASS:
1369	case PCI_IVAR_PROGIF:
1370	case PCI_IVAR_REVID:
1371	case PCI_IVAR_IRQ:
1372	case PCI_IVAR_BUS:
1373	case PCI_IVAR_SLOT:
1374	case PCI_IVAR_FUNCTION:
1375		return (EINVAL);	/* disallow for now */
1376
1377	default:
1378		return (ENOENT);
1379	}
1380}
1381
1382
1383#include "opt_ddb.h"
1384#ifdef DDB
1385#include <ddb/ddb.h>
1386#include <sys/cons.h>
1387
1388/*
1389 * List resources based on pci map registers, used for within ddb
1390 */
1391
1392DB_SHOW_COMMAND(pciregs, db_pci_dump)
1393{
1394	struct pci_devinfo *dinfo;
1395	struct devlist *devlist_head;
1396	struct pci_conf *p;
1397	const char *name;
1398	int i, error, none_count, quit;
1399
1400	none_count = 0;
1401	/* get the head of the device queue */
1402	devlist_head = &pci_devq;
1403
1404	/*
1405	 * Go through the list of devices and print out devices
1406	 */
1407	db_setup_paging(db_simple_pager, &quit, DB_LINES_PER_PAGE);
1408	for (error = 0, i = 0, quit = 0,
1409	     dinfo = STAILQ_FIRST(devlist_head);
1410	     (dinfo != NULL) && (error == 0) && (i < pci_numdevs) && !quit;
1411	     dinfo = STAILQ_NEXT(dinfo, pci_links), i++) {
1412
1413		/* Populate pd_name and pd_unit */
1414		name = NULL;
1415		if (dinfo->cfg.dev)
1416			name = device_get_name(dinfo->cfg.dev);
1417
1418		p = &dinfo->conf;
1419		db_printf("%s%d@pci%d:%d:%d:\tclass=0x%06x card=0x%08x "
1420			"chip=0x%08x rev=0x%02x hdr=0x%02x\n",
1421			(name && *name) ? name : "none",
1422			(name && *name) ? (int)device_get_unit(dinfo->cfg.dev) :
1423			none_count++,
1424			p->pc_sel.pc_bus, p->pc_sel.pc_dev,
1425			p->pc_sel.pc_func, (p->pc_class << 16) |
1426			(p->pc_subclass << 8) | p->pc_progif,
1427			(p->pc_subdevice << 16) | p->pc_subvendor,
1428			(p->pc_device << 16) | p->pc_vendor,
1429			p->pc_revid, p->pc_hdr);
1430	}
1431}
1432#endif /* DDB */
1433
1434/*
1435 * XXX I'm not sure the following is good for 64-bit bars.
1436 */
1437static struct resource *
1438pci_alloc_map(device_t dev, device_t child, int type, int *rid,
1439    u_long start, u_long end, u_long count, u_int flags)
1440{
1441	struct pci_devinfo *dinfo = device_get_ivars(child);
1442	struct resource_list *rl = &dinfo->resources;
1443	struct resource_list_entry *rle;
1444	struct resource *res;
1445	uint32_t map, testval;
1446	int mapsize;
1447
1448	/*
1449	 * Weed out the bogons, and figure out how large the BAR/map is.
1450	 */
1451	map = pci_read_config(child, *rid, 4);
1452	if (pci_maptype(map) & PCI_MAPMEM) {
1453		if (type != SYS_RES_MEMORY) {
1454			device_printf(child, "rid %#x says memory, driver wants %d failed.\n", *rid, type);
1455			return (NULL);
1456		}
1457	} else {
1458		if (type != SYS_RES_IOPORT) {
1459			device_printf(child, "rid %#x says ioport, driver wants %d failed.\n", *rid, type);
1460			return (NULL);
1461		}
1462	}
1463	pci_write_config(child, *rid, 0xffffffff, 4);
1464	testval = pci_read_config(child, *rid, 4);
1465
1466	/*
1467	 * Allocate enough resource, and then write back the
1468	 * appropriate bar for that resource (this is the part
1469	 * I'm not sure is good for 64-bit bars).
1470	 */
1471	mapsize = pci_mapsize(testval);
1472	count = 1 << mapsize;
1473	if (RF_ALIGNMENT(flags) < mapsize)
1474	    flags = (flags & ~RF_ALIGNMENT_MASK) | RF_ALIGNMENT_LOG2(mapsize);
1475	res = BUS_ALLOC_RESOURCE(device_get_parent(dev), child, type, rid,
1476	    start, end, count, flags);
1477	if (res == NULL) {
1478		device_printf(child, "%#lx bytes of rid %#x res %d failed.\n",
1479		    count, *rid, type);
1480		pci_write_config(child, *rid, map, 4);
1481		return (NULL);
1482	}
1483	resource_list_add(rl, type, *rid, start, end, count);
1484	rle = resource_list_find(rl, type, *rid);
1485	if (rle == NULL)
1486		panic("pci_alloc_map: unexpedly can't find resource.");
1487	rle->res = res;
1488	device_printf(child, "Lazy allocation of %#lx bytes rid %#x type %d at %#lx\n",
1489	    count, *rid, type, rman_get_start(res));
1490	pci_write_config(child, *rid, rman_get_start(res), 4);
1491	return (res);
1492}
1493
1494
1495struct resource *
1496pci_alloc_resource(device_t dev, device_t child, int type, int *rid,
1497		   u_long start, u_long end, u_long count, u_int flags)
1498{
1499	struct pci_devinfo *dinfo = device_get_ivars(child);
1500	struct resource_list *rl = &dinfo->resources;
1501	struct resource_list_entry *rle;
1502	pcicfgregs *cfg = &dinfo->cfg;
1503
1504	/*
1505	 * Perform lazy resource allocation
1506	 */
1507	if (device_get_parent(child) == dev) {
1508		switch (type) {
1509		case SYS_RES_IRQ:
1510			/*
1511			 * If the child device doesn't have an
1512			 * interrupt routed and is deserving of an
1513			 * interrupt, try to assign it one.
1514			 */
1515			if (!PCI_INTERRUPT_VALID(cfg->intline) &&
1516			    (cfg->intpin != 0)) {
1517				cfg->intline = PCI_ASSIGN_INTERRUPT(dev, child);
1518				if (PCI_INTERRUPT_VALID(cfg->intline)) {
1519					pci_write_config(child, PCIR_INTLINE,
1520					    cfg->intline, 1);
1521					resource_list_add(rl, SYS_RES_IRQ, 0,
1522					    cfg->intline, cfg->intline, 1);
1523				}
1524			}
1525			break;
1526		case SYS_RES_IOPORT:
1527		case SYS_RES_MEMORY:
1528			if (*rid < PCIR_BAR(cfg->nummaps)) {
1529				/*
1530				 * Enable the I/O mode.  We should
1531				 * also be assigning resources too
1532				 * when none are present.  The
1533				 * resource_list_alloc kind of sorta does
1534				 * this...
1535				 */
1536				if (PCI_ENABLE_IO(dev, child, type))
1537					return (NULL);
1538			}
1539			rle = resource_list_find(rl, type, *rid);
1540			if (rle == NULL)
1541				return (pci_alloc_map(dev, child, type, rid,
1542				    start, end, count, flags));
1543			break;
1544		}
1545		/*
1546		 * If we've already allocated the resource, then
1547		 * return it now.  But first we may need to activate
1548		 * it, since we don't allocate the resource as active
1549		 * above.  Normally this would be done down in the
1550		 * nexus, but since we short-circuit that path we have
1551		 * to do its job here.  Not sure if we should free the
1552		 * resource if it fails to activate.
1553		 */
1554		rle = resource_list_find(rl, type, *rid);
1555		if (rle != NULL && rle->res != NULL) {
1556			device_printf(child, "Bus reserved %#lx bytes for rid %#x type %d at %#lx\n", rman_get_size(rle->res), *rid, type, rman_get_start(rle->res));
1557			if ((flags & RF_ACTIVE) &&
1558			    bus_generic_activate_resource(dev, child, type,
1559			    *rid, rle->res) != 0)
1560				return NULL;
1561			return (rle->res);
1562		}
1563	}
1564	return (resource_list_alloc(rl, dev, child, type, rid,
1565	    start, end, count, flags));
1566}
1567
1568void
1569pci_delete_resource(device_t dev, device_t child, int type, int rid)
1570{
1571	struct pci_devinfo *dinfo;
1572	struct resource_list *rl;
1573	struct resource_list_entry *rle;
1574
1575	if (device_get_parent(child) != dev)
1576		return;
1577
1578	dinfo = device_get_ivars(child);
1579	rl = &dinfo->resources;
1580	rle = resource_list_find(rl, type, rid);
1581	if (rle) {
1582		if (rle->res) {
1583			if (rman_get_device(rle->res) != dev ||
1584			    rman_get_flags(rle->res) & RF_ACTIVE) {
1585				device_printf(dev, "delete_resource: "
1586				    "Resource still owned by child, oops. "
1587				    "(type=%d, rid=%d, addr=%lx)\n",
1588				    rle->type, rle->rid,
1589				    rman_get_start(rle->res));
1590				return;
1591			}
1592			bus_release_resource(dev, type, rid, rle->res);
1593		}
1594		resource_list_delete(rl, type, rid);
1595	}
1596	/*
1597	 * Why do we turn off the PCI configuration BAR when we delete a
1598	 * resource? -- imp
1599	 */
1600	pci_write_config(child, rid, 0, 4);
1601	BUS_DELETE_RESOURCE(device_get_parent(dev), child, type, rid);
1602}
1603
1604struct resource_list *
1605pci_get_resource_list (device_t dev, device_t child)
1606{
1607	struct pci_devinfo *dinfo = device_get_ivars(child);
1608
1609	return (&dinfo->resources);
1610}
1611
1612uint32_t
1613pci_read_config_method(device_t dev, device_t child, int reg, int width)
1614{
1615	struct pci_devinfo *dinfo = device_get_ivars(child);
1616	pcicfgregs *cfg = &dinfo->cfg;
1617
1618	return (PCIB_READ_CONFIG(device_get_parent(dev),
1619	    cfg->bus, cfg->slot, cfg->func, reg, width));
1620}
1621
1622void
1623pci_write_config_method(device_t dev, device_t child, int reg,
1624    uint32_t val, int width)
1625{
1626	struct pci_devinfo *dinfo = device_get_ivars(child);
1627	pcicfgregs *cfg = &dinfo->cfg;
1628
1629	PCIB_WRITE_CONFIG(device_get_parent(dev),
1630	    cfg->bus, cfg->slot, cfg->func, reg, val, width);
1631}
1632
1633int
1634pci_child_location_str_method(device_t dev, device_t child, char *buf,
1635    size_t buflen)
1636{
1637	struct pci_devinfo *dinfo;
1638
1639	dinfo = device_get_ivars(child);
1640	snprintf(buf, buflen, "slot=%d function=%d", pci_get_slot(child),
1641	    pci_get_function(child));
1642	return (0);
1643}
1644
1645int
1646pci_child_pnpinfo_str_method(device_t dev, device_t child, char *buf,
1647    size_t buflen)
1648{
1649	struct pci_devinfo *dinfo;
1650	pcicfgregs *cfg;
1651
1652	dinfo = device_get_ivars(child);
1653	cfg = &dinfo->cfg;
1654	snprintf(buf, buflen, "vendor=0x%04x device=0x%04x subvendor=0x%04x "
1655	    "subdevice=0x%04x class=0x%02x%02x%02x", cfg->vendor, cfg->device,
1656	    cfg->subvendor, cfg->subdevice, cfg->baseclass, cfg->subclass,
1657	    cfg->progif);
1658	return (0);
1659}
1660
1661int
1662pci_assign_interrupt_method(device_t dev, device_t child)
1663{
1664	struct pci_devinfo *dinfo = device_get_ivars(child);
1665	pcicfgregs *cfg = &dinfo->cfg;
1666
1667	return (PCIB_ROUTE_INTERRUPT(device_get_parent(dev), child,
1668	    cfg->intpin));
1669}
1670
1671static int
1672pci_modevent(module_t mod, int what, void *arg)
1673{
1674	static dev_t pci_cdev;
1675
1676	switch (what) {
1677	case MOD_LOAD:
1678		STAILQ_INIT(&pci_devq);
1679		pci_generation = 0;
1680		pci_cdev = make_dev(&pcicdev, 0, UID_ROOT, GID_WHEEL, 0644,
1681		    "pci");
1682		pci_load_vendor_data();
1683		break;
1684
1685	case MOD_UNLOAD:
1686		destroy_dev(pci_cdev);
1687		break;
1688	}
1689
1690	return (0);
1691}
1692
1693static void
1694pci_cfg_restore(device_t dev, struct pci_devinfo *dinfo)
1695{
1696	int i;
1697
1698	/*
1699	 * Only do header type 0 devices.  Type 1 devices are bridges, which
1700	 * we know need special treatment.  Type 2 devices are cardbus bridges
1701	 * which also require special treatment.  Other types are unknown, and
1702	 * we err on the side of safety by ignoring them.
1703	 */
1704	if (dinfo->cfg.hdrtype != 0)
1705		return;
1706	if (pci_get_powerstate(dev) != PCI_POWERSTATE_D0) {
1707		printf("pci%d:%d:%d: setting power state D0\n", dinfo->cfg.bus,
1708		    dinfo->cfg.slot, dinfo->cfg.func);
1709		pci_set_powerstate(dev, PCI_POWERSTATE_D0);
1710	}
1711	for (i = 0; i < dinfo->cfg.nummaps; i++)
1712		pci_write_config(dev, PCIR_MAPS + i * 4, dinfo->cfg.bar[i], 4);
1713	pci_write_config(dev, PCIR_BIOS, dinfo->cfg.bios, 4);
1714	pci_write_config(dev, PCIR_COMMAND, dinfo->cfg.cmdreg, 2);
1715	pci_write_config(dev, PCIR_INTLINE, dinfo->cfg.intline, 1);
1716	pci_write_config(dev, PCIR_INTPIN, dinfo->cfg.intpin, 1);
1717	pci_write_config(dev, PCIR_MINGNT, dinfo->cfg.mingnt, 1);
1718	pci_write_config(dev, PCIR_MAXLAT, dinfo->cfg.maxlat, 1);
1719	pci_write_config(dev, PCIR_CACHELNSZ, dinfo->cfg.cachelnsz, 1);
1720	pci_write_config(dev, PCIR_LATTIMER, dinfo->cfg.lattimer, 1);
1721}
1722
1723static void
1724pci_cfg_save(device_t dev, struct pci_devinfo *dinfo, int setstate)
1725{
1726	int i;
1727	uint32_t cls;
1728
1729	/*
1730	 * Only do header type 0 devices.  Type 1 devices are bridges, which
1731	 * we know need special treatment.  Type 2 devices are cardbus bridges
1732	 * which also require special treatment.  Other types are unknown, and
1733	 * we err on the side of safety by ignoring them.  Powering down
1734	 * bridges should not be undertaken lightly.
1735	 */
1736	if (dinfo->cfg.hdrtype != 0)
1737		return;
1738	for (i = 0; i < dinfo->cfg.nummaps; i++)
1739		dinfo->cfg.bar[i] = pci_read_config(dev, PCIR_MAPS + i * 4, 4);
1740	dinfo->cfg.bios = pci_read_config(dev, PCIR_BIOS, 4);
1741
1742	/*
1743	 * Some drivers apparently write to these registers w/o
1744	 * updating our cahced copy.  No harm happens if we update the
1745	 * copy, so do so here so we can restore them.  The COMMAND
1746	 * register is modified by the bus w/o updating the cache.  This
1747	 * should represent the normally writable portion of the 'defined'
1748	 * part of type 0 headers.  In theory we also need to save/restore
1749	 * the PCI capability structures we know about, but apart from power
1750	 * we don't know any that are writable.
1751	 */
1752	dinfo->cfg.cmdreg = pci_read_config(dev, PCIR_COMMAND, 2);
1753	dinfo->cfg.intline = pci_read_config(dev, PCIR_INTLINE, 1);
1754	dinfo->cfg.intpin = pci_read_config(dev, PCIR_INTPIN, 1);
1755	dinfo->cfg.mingnt = pci_read_config(dev, PCIR_MINGNT, 1);
1756	dinfo->cfg.maxlat = pci_read_config(dev, PCIR_MAXLAT, 1);
1757	dinfo->cfg.cachelnsz = pci_read_config(dev, PCIR_CACHELNSZ, 1);
1758	dinfo->cfg.lattimer = pci_read_config(dev, PCIR_LATTIMER, 1);
1759
1760	/*
1761	 * don't set the state for display devices and for memory devices
1762	 * since bad things happen.  we should (a) have drivers that can easily
1763	 * detach and (b) use generic drivers for these devices so that some
1764	 * device actually attaches.  We need to make sure that when we
1765	 * implement (a) we don't power the device down on a reattach.
1766	 *
1767	 * John and Nate also tell me that we should be running the power up
1768	 * and power down hooks when we change power state for those nodes
1769	 * that have ACPI hooks in the tree.
1770	 */
1771	cls = pci_get_class(dev);
1772	if (setstate && cls != PCIC_DISPLAY && cls != PCIC_MEMORY) {
1773		if (pci_get_powerstate(dev) != PCI_POWERSTATE_D3) {
1774			printf("pci%d:%d:%d: setting power state D3\n", dinfo->cfg.bus,
1775			    dinfo->cfg.slot, dinfo->cfg.func);
1776			pci_set_powerstate(dev, PCI_POWERSTATE_D3);
1777		}
1778	}
1779}
1780