xref: /titanic_50/usr/src/uts/i86pc/os/lgrpplat.c (revision 75ce41a57ff334bd8fe2cb9ed51eea835892f944)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 /*
28  * LOCALITY GROUP (LGROUP) PLATFORM SUPPORT FOR X86/AMD64 PLATFORMS
29  * ================================================================
30  * Multiprocessor AMD and Intel systems may have Non Uniform Memory Access
31  * (NUMA).  A NUMA machine consists of one or more "nodes" that each consist of
32  * one or more CPUs and some local memory.  The CPUs in each node can access
33  * the memory in the other nodes but at a higher latency than accessing their
34  * local memory.  Typically, a system with only one node has Uniform Memory
35  * Access (UMA), but it may be possible to have a one node system that has
36  * some global memory outside of the node which is higher latency.
37  *
38  * Module Description
39  * ------------------
40  * This module provides a platform interface for determining which CPUs and
41  * which memory (and how much) are in a NUMA node and how far each node is from
42  * each other.  The interface is used by the Virtual Memory (VM) system and the
43  * common lgroup framework.  The VM system uses the plat_*() routines to fill
44  * in its memory node (memnode) array with the physical address range spanned
45  * by each NUMA node to know which memory belongs to which node, so it can
46  * build and manage a physical page free list for each NUMA node and allocate
47  * local memory from each node as needed.  The common lgroup framework uses the
48  * exported lgrp_plat_*() routines to figure out which CPUs and memory belong
49  * to each node (leaf lgroup) and how far each node is from each other, so it
50  * can build the latency (lgroup) topology for the machine in order to optimize
51  * for locality.  Also, an lgroup platform handle instead of lgroups are used
52  * in the interface with this module, so this module shouldn't need to know
53  * anything about lgroups.  Instead, it just needs to know which CPUs, memory,
54  * etc. are in each NUMA node, how far each node is from each other, and to use
55  * a unique lgroup platform handle to refer to each node through the interface.
56  *
57  * Determining NUMA Configuration
58  * ------------------------------
59  * By default, this module will try to determine the NUMA configuration of the
60  * machine by reading the ACPI System Resource Affinity Table (SRAT) and System
61  * Locality Information Table (SLIT).  The SRAT contains info to tell which
62  * CPUs and memory are local to a given proximity domain (NUMA node).  The SLIT
63  * is a matrix that gives the distance between each system locality (which is
64  * a NUMA node and should correspond to proximity domains in the SRAT).  For
65  * more details on the SRAT and SLIT, please refer to an ACPI 3.0 or newer
66  * specification.
67  *
68  * If the SRAT doesn't exist on a system with AMD Opteron processors, we
69  * examine registers in PCI configuration space to determine how many nodes are
70  * in the system and which CPUs and memory are in each node.
71  * do while booting the kernel.
72  *
73  * NOTE: Using these PCI configuration space registers to determine this
74  *       locality info is not guaranteed to work or be compatible across all
75  *	 Opteron processor families.
76  *
77  * If the SLIT does not exist or look right, the kernel will probe to determine
78  * the distance between nodes as long as the NUMA CPU and memory configuration
79  * has been determined (see lgrp_plat_probe() for details).
80  *
81  * Data Structures
82  * ---------------
83  * The main data structures used by this code are the following:
84  *
85  * - lgrp_plat_cpu_node[]		CPU to node ID mapping table indexed by
86  *					CPU ID (only used for SRAT)
87  *
88  * - lgrp_plat_lat_stats.latencies[][]	Table of latencies between same and
89  *					different nodes indexed by node ID
90  *
91  * - lgrp_plat_node_cnt			Number of NUMA nodes in system
92  *
93  * - lgrp_plat_node_domain[]		Node ID to proximity domain ID mapping
94  *					table indexed by node ID (only used
95  *					for SRAT)
96  *
97  * - lgrp_plat_node_memory[]		Table with physical address range for
98  *					each node indexed by node ID
99  *
100  * The code is implemented to make the following always be true:
101  *
102  *	lgroup platform handle == node ID == memnode ID
103  *
104  * Moreover, it allows for the proximity domain ID to be equal to all of the
105  * above as long as the proximity domains IDs are numbered from 0 to <number of
106  * nodes - 1>.  This is done by hashing each proximity domain ID into the range
107  * from 0 to <number of nodes - 1>.  Then proximity ID N will hash into node ID
108  * N and proximity domain ID N will be entered into lgrp_plat_node_domain[N]
109  * and be assigned node ID N.  If the proximity domain IDs aren't numbered
110  * from 0 to <number of nodes - 1>, then hashing the proximity domain IDs into
111  * lgrp_plat_node_domain[] will still work for assigning proximity domain IDs
112  * to node IDs.  However, the proximity domain IDs may not map to the
113  * equivalent node ID since we want to keep the node IDs numbered from 0 to
114  * <number of nodes - 1> to minimize cost of searching and potentially space.
115  *
116  * The code below really tries to do the above.  However, the virtual memory
117  * system expects the memnodes which describe the physical address range for
118  * each NUMA node to be arranged in ascending order by physical address.  (:-(
119  * Otherwise, the kernel will panic in different semi-random places in the VM
120  * system.
121  *
122  * Consequently, this module has to try to sort the nodes in ascending order by
123  * each node's starting physical address to try to meet this "constraint" in
124  * the VM system (see lgrp_plat_node_sort()).  Also, the lowest numbered
125  * proximity domain ID in the system is deteremined and used to make the lowest
126  * numbered proximity domain map to node 0 in hopes that the proximity domains
127  * are sorted in ascending order by physical address already even if their IDs
128  * don't start at 0 (see NODE_DOMAIN_HASH() and lgrp_plat_srat_domains()).
129  * Finally, it is important to note that these workarounds may not be
130  * sufficient if/when memory hotplugging is supported and the VM system may
131  * ultimately need to be fixed to handle this....
132  */
133 
134 
135 #include <sys/archsystm.h>	/* for {in,out}{b,w,l}() */
136 #include <sys/bootconf.h>
137 #include <sys/cmn_err.h>
138 #include <sys/controlregs.h>
139 #include <sys/cpupart.h>
140 #include <sys/cpuvar.h>
141 #include <sys/lgrp.h>
142 #include <sys/machsystm.h>
143 #include <sys/memlist.h>
144 #include <sys/memnode.h>
145 #include <sys/mman.h>
146 #include <sys/pci_cfgspace.h>
147 #include <sys/pci_impl.h>
148 #include <sys/param.h>
149 #include <sys/pghw.h>
150 #include <sys/promif.h>		/* for prom_printf() */
151 #include <sys/sysmacros.h>
152 #include <sys/systm.h>
153 #include <sys/thread.h>
154 #include <sys/types.h>
155 #include <sys/var.h>
156 #include <sys/x86_archext.h>	/* for x86_feature and X86_AMD */
157 #include <vm/hat_i86.h>
158 #include <vm/seg_kmem.h>
159 #include <vm/vm_dep.h>
160 
161 #include "acpi_fw.h"		/* for SRAT and SLIT */
162 
163 
164 #define	MAX_NODES		8
165 #define	NLGRP			(MAX_NODES * (MAX_NODES - 1) + 1)
166 
167 /*
168  * Constants for configuring probing
169  */
170 #define	LGRP_PLAT_PROBE_NROUNDS		64	/* default laps for probing */
171 #define	LGRP_PLAT_PROBE_NSAMPLES	1	/* default samples to take */
172 #define	LGRP_PLAT_PROBE_NREADS		256	/* number of vendor ID reads */
173 
174 /*
175  * Flags for probing
176  */
177 #define	LGRP_PLAT_PROBE_ENABLE		0x1	/* enable probing */
178 #define	LGRP_PLAT_PROBE_PGCPY		0x2	/* probe using page copy */
179 #define	LGRP_PLAT_PROBE_VENDOR		0x4	/* probe vendor ID register */
180 
181 /*
182  * Hash proximity domain ID into node to domain mapping table "mod" number of
183  * nodes to minimize span of entries used and try to have lowest numbered
184  * proximity domain be node 0
185  */
186 #define	NODE_DOMAIN_HASH(domain, node_cnt) \
187 	((lgrp_plat_prox_domain_min == UINT32_MAX) ? (domain) % node_cnt : \
188 	    ((domain) - lgrp_plat_prox_domain_min) % node_cnt)
189 
190 
191 /*
192  * CPU to node ID mapping structure (only used with SRAT)
193  */
194 typedef	struct cpu_node_map {
195 	int		exists;
196 	uint_t		node;
197 	uint32_t	apicid;
198 	uint32_t	prox_domain;
199 } cpu_node_map_t;
200 
201 /*
202  * Latency statistics
203  */
204 typedef struct lgrp_plat_latency_stats {
205 	hrtime_t	latencies[MAX_NODES][MAX_NODES];
206 	hrtime_t	latency_max;
207 	hrtime_t	latency_min;
208 } lgrp_plat_latency_stats_t;
209 
210 /*
211  * Memory configuration for probing
212  */
213 typedef struct lgrp_plat_probe_mem_config {
214 	size_t	probe_memsize;		/* how much memory to probe per node */
215 	caddr_t	probe_va[MAX_NODES];	/* where memory mapped for probing */
216 	pfn_t	probe_pfn[MAX_NODES];	/* physical pages to map for probing */
217 } lgrp_plat_probe_mem_config_t;
218 
219 /*
220  * Statistics kept for probing
221  */
222 typedef struct lgrp_plat_probe_stats {
223 	hrtime_t	flush_cost;
224 	hrtime_t	probe_cost;
225 	hrtime_t	probe_cost_total;
226 	hrtime_t	probe_error_code;
227 	hrtime_t	probe_errors[MAX_NODES][MAX_NODES];
228 	int		probe_suspect[MAX_NODES][MAX_NODES];
229 	hrtime_t	probe_max[MAX_NODES][MAX_NODES];
230 	hrtime_t	probe_min[MAX_NODES][MAX_NODES];
231 } lgrp_plat_probe_stats_t;
232 
233 /*
234  * Node to proximity domain ID mapping structure (only used with SRAT)
235  */
236 typedef	struct node_domain_map {
237 	int		exists;
238 	uint32_t	prox_domain;
239 } node_domain_map_t;
240 
241 /*
242  * Node ID and starting and ending page for physical memory in node
243  */
244 typedef	struct node_phys_addr_map {
245 	pfn_t		start;
246 	pfn_t		end;
247 	int		exists;
248 	uint32_t	prox_domain;
249 } node_phys_addr_map_t;
250 
251 /*
252  * Number of CPUs for which we got APIC IDs
253  */
254 static int				lgrp_plat_apic_ncpus = 0;
255 
256 /*
257  * CPU to node ID mapping table (only used for SRAT)
258  */
259 static cpu_node_map_t			lgrp_plat_cpu_node[NCPU];
260 
261 /*
262  * Latency statistics
263  */
264 lgrp_plat_latency_stats_t		lgrp_plat_lat_stats;
265 
266 /*
267  * Whether memory is interleaved across nodes causing MPO to be disabled
268  */
269 static int				lgrp_plat_mem_intrlv = 0;
270 
271 /*
272  * Node ID to proximity domain ID mapping table (only used for SRAT)
273  */
274 static node_domain_map_t		lgrp_plat_node_domain[MAX_NODES];
275 
276 /*
277  * Physical address range for memory in each node
278  */
279 static node_phys_addr_map_t		lgrp_plat_node_memory[MAX_NODES];
280 
281 /*
282  * Statistics gotten from probing
283  */
284 static lgrp_plat_probe_stats_t		lgrp_plat_probe_stats;
285 
286 /*
287  * Memory configuration for probing
288  */
289 static lgrp_plat_probe_mem_config_t	lgrp_plat_probe_mem_config;
290 
291 /*
292  * Lowest proximity domain ID seen in ACPI SRAT
293  */
294 static uint32_t				lgrp_plat_prox_domain_min = UINT32_MAX;
295 
296 /*
297  * Error code from processing ACPI SRAT
298  */
299 static int				lgrp_plat_srat_error = 0;
300 
301 /*
302  * Error code from processing ACPI SLIT
303  */
304 static int				lgrp_plat_slit_error = 0;
305 
306 /*
307  * Allocate lgroup array statically
308  */
309 static lgrp_t				lgrp_space[NLGRP];
310 static int				nlgrps_alloc;
311 
312 
313 /*
314  * Enable finding and using minimum proximity domain ID when hashing
315  */
316 int			lgrp_plat_domain_min_enable = 1;
317 
318 /*
319  * Number of nodes in system
320  */
321 uint_t			lgrp_plat_node_cnt = 1;
322 
323 /*
324  * Enable sorting nodes in ascending order by starting physical address
325  */
326 int			lgrp_plat_node_sort_enable = 1;
327 
328 /*
329  * Configuration Parameters for Probing
330  * - lgrp_plat_probe_flags	Flags to specify enabling probing, probe
331  *				operation, etc.
332  * - lgrp_plat_probe_nrounds	How many rounds of probing to do
333  * - lgrp_plat_probe_nsamples	Number of samples to take when probing each
334  *				node
335  * - lgrp_plat_probe_nreads	Number of times to read vendor ID from
336  *				Northbridge for each probe
337  */
338 uint_t			lgrp_plat_probe_flags = 0;
339 int			lgrp_plat_probe_nrounds = LGRP_PLAT_PROBE_NROUNDS;
340 int			lgrp_plat_probe_nsamples = LGRP_PLAT_PROBE_NSAMPLES;
341 int			lgrp_plat_probe_nreads = LGRP_PLAT_PROBE_NREADS;
342 
343 /*
344  * Enable use of ACPI System Resource Affinity Table (SRAT) and System
345  * Locality Information Table (SLIT)
346  */
347 int			lgrp_plat_srat_enable = 1;
348 int			lgrp_plat_slit_enable = 1;
349 
350 /*
351  * mnode_xwa: set to non-zero value to initiate workaround if large pages are
352  * found to be crossing memory node boundaries. The workaround will eliminate
353  * a base size page at the end of each memory node boundary to ensure that
354  * a large page with constituent pages that span more than 1 memory node
355  * can never be formed.
356  *
357  */
358 int	mnode_xwa = 1;
359 
360 /*
361  * Static array to hold lgroup statistics
362  */
363 struct lgrp_stats	lgrp_stats[NLGRP];
364 
365 
366 /*
367  * Forward declarations of platform interface routines
368  */
369 void		plat_build_mem_nodes(struct memlist *list);
370 
371 int		plat_lgrphand_to_mem_node(lgrp_handle_t hand);
372 
373 lgrp_handle_t	plat_mem_node_to_lgrphand(int mnode);
374 
375 int		plat_mnode_xcheck(pfn_t pfncnt);
376 
377 int		plat_pfn_to_mem_node(pfn_t pfn);
378 
379 /*
380  * Forward declarations of lgroup platform interface routines
381  */
382 lgrp_t		*lgrp_plat_alloc(lgrp_id_t lgrpid);
383 
384 void		lgrp_plat_config(lgrp_config_flag_t flag, uintptr_t arg);
385 
386 lgrp_handle_t	lgrp_plat_cpu_to_hand(processorid_t id);
387 
388 void		lgrp_plat_init(void);
389 
390 int		lgrp_plat_latency(lgrp_handle_t from, lgrp_handle_t to);
391 
392 void		lgrp_plat_main_init(void);
393 
394 int		lgrp_plat_max_lgrps(void);
395 
396 pgcnt_t		lgrp_plat_mem_size(lgrp_handle_t plathand,
397     lgrp_mem_query_t query);
398 
399 lgrp_handle_t	lgrp_plat_pfn_to_hand(pfn_t pfn);
400 
401 void		lgrp_plat_probe(void);
402 
403 lgrp_handle_t	lgrp_plat_root_hand(void);
404 
405 
406 /*
407  * Forward declarations of local routines
408  */
409 static int	is_opteron(void);
410 
411 static int	lgrp_plat_cpu_node_update(node_domain_map_t *node_domain,
412     int node_cnt, cpu_node_map_t *cpu_node, int nentries, uint32_t apicid,
413     uint32_t domain);
414 
415 static int	lgrp_plat_cpu_to_node(cpu_t *cp, cpu_node_map_t *cpu_node);
416 
417 static int	lgrp_plat_domain_to_node(node_domain_map_t *node_domain,
418     int node_cnt, uint32_t domain);
419 
420 static void	lgrp_plat_latency_adjust(node_phys_addr_map_t *node_memory,
421     lgrp_plat_latency_stats_t *lat_stats,
422     lgrp_plat_probe_stats_t *probe_stats);
423 
424 static int	lgrp_plat_latency_verify(node_phys_addr_map_t *node_memory,
425     lgrp_plat_latency_stats_t *lat_stats);
426 
427 static pgcnt_t	lgrp_plat_mem_size_default(lgrp_handle_t, lgrp_mem_query_t);
428 
429 static int	lgrp_plat_node_domain_update(node_domain_map_t *node_domain,
430     int node_cnt, uint32_t domain);
431 
432 static int	lgrp_plat_node_memory_update(node_domain_map_t *node_domain,
433     int node_cnt, node_phys_addr_map_t *node_memory, uint64_t start,
434     uint64_t end, uint32_t domain);
435 
436 static void	lgrp_plat_node_sort(node_domain_map_t *node_domain,
437     int node_cnt, cpu_node_map_t *cpu_node, int cpu_count,
438     node_phys_addr_map_t *node_memory);
439 
440 static hrtime_t	lgrp_plat_probe_time(int to, cpu_node_map_t *cpu_node,
441     lgrp_plat_probe_mem_config_t *probe_mem_config,
442     lgrp_plat_latency_stats_t *lat_stats,
443     lgrp_plat_probe_stats_t *probe_stats);
444 
445 static int	lgrp_plat_process_cpu_apicids(cpu_node_map_t *cpu_node);
446 
447 static int	lgrp_plat_process_slit(struct slit *tp, uint_t node_cnt,
448     node_phys_addr_map_t *node_memory, lgrp_plat_latency_stats_t *lat_stats);
449 
450 static int	lgrp_plat_process_srat(struct srat *tp,
451     uint32_t *prox_domain_min, node_domain_map_t *node_domain,
452     cpu_node_map_t *cpu_node, int cpu_count,
453     node_phys_addr_map_t *node_memory);
454 
455 static int	lgrp_plat_srat_domains(struct srat *tp,
456     uint32_t *prox_domain_min);
457 
458 static void	lgrp_plat_2level_setup(node_phys_addr_map_t *node_memory,
459     lgrp_plat_latency_stats_t *lat_stats);
460 
461 static void	opt_get_numa_config(uint_t *node_cnt, int *mem_intrlv,
462     node_phys_addr_map_t *node_memory);
463 
464 static hrtime_t	opt_probe_vendor(int dest_node, int nreads);
465 
466 
467 /*
468  * PLATFORM INTERFACE ROUTINES
469  */
470 
471 /*
472  * Configure memory nodes for machines with more than one node (ie NUMA)
473  */
474 void
475 plat_build_mem_nodes(struct memlist *list)
476 {
477 	pfn_t		cur_start;	/* start addr of subrange */
478 	pfn_t		cur_end;	/* end addr of subrange */
479 	pfn_t		start;		/* start addr of whole range */
480 	pfn_t		end;		/* end addr of whole range */
481 	pgcnt_t		endcnt;		/* pages to sacrifice */
482 
483 	/*
484 	 * Boot install lists are arranged <addr, len>, ...
485 	 */
486 	while (list) {
487 		int	node;
488 
489 		start = list->address >> PAGESHIFT;
490 		end = (list->address + list->size - 1) >> PAGESHIFT;
491 
492 		if (start > physmax) {
493 			list = list->next;
494 			continue;
495 		}
496 		if (end > physmax)
497 			end = physmax;
498 
499 		/*
500 		 * When there is only one memnode, just add memory to memnode
501 		 */
502 		if (max_mem_nodes == 1) {
503 			mem_node_add_slice(start, end);
504 			list = list->next;
505 			continue;
506 		}
507 
508 		/*
509 		 * mem_node_add_slice() expects to get a memory range that
510 		 * is within one memnode, so need to split any memory range
511 		 * that spans multiple memnodes into subranges that are each
512 		 * contained within one memnode when feeding them to
513 		 * mem_node_add_slice()
514 		 */
515 		cur_start = start;
516 		do {
517 			node = plat_pfn_to_mem_node(cur_start);
518 
519 			/*
520 			 * Panic if DRAM address map registers or SRAT say
521 			 * memory in node doesn't exist or address from
522 			 * boot installed memory list entry isn't in this node.
523 			 * This shouldn't happen and rest of code can't deal
524 			 * with this if it does.
525 			 */
526 			if (node < 0 || node >= lgrp_plat_node_cnt ||
527 			    !lgrp_plat_node_memory[node].exists ||
528 			    cur_start < lgrp_plat_node_memory[node].start ||
529 			    cur_start > lgrp_plat_node_memory[node].end) {
530 				cmn_err(CE_PANIC, "Don't know which memnode "
531 				    "to add installed memory address 0x%lx\n",
532 				    cur_start);
533 			}
534 
535 			/*
536 			 * End of current subrange should not span memnodes
537 			 */
538 			cur_end = end;
539 			endcnt = 0;
540 			if (lgrp_plat_node_memory[node].exists &&
541 			    cur_end > lgrp_plat_node_memory[node].end) {
542 				cur_end = lgrp_plat_node_memory[node].end;
543 				if (mnode_xwa > 1) {
544 					/*
545 					 * sacrifice the last page in each
546 					 * node to eliminate large pages
547 					 * that span more than 1 memory node.
548 					 */
549 					endcnt = 1;
550 					physinstalled--;
551 				}
552 			}
553 
554 			mem_node_add_slice(cur_start, cur_end - endcnt);
555 
556 			/*
557 			 * Next subrange starts after end of current one
558 			 */
559 			cur_start = cur_end + 1;
560 		} while (cur_end < end);
561 
562 		list = list->next;
563 	}
564 	mem_node_physalign = 0;
565 	mem_node_pfn_shift = 0;
566 }
567 
568 
569 int
570 plat_lgrphand_to_mem_node(lgrp_handle_t hand)
571 {
572 	if (max_mem_nodes == 1)
573 		return (0);
574 
575 	return ((int)hand);
576 }
577 
578 
579 /*
580  * plat_mnode_xcheck: checks the node memory ranges to see if there is a pfncnt
581  * range of pages aligned on pfncnt that crosses an node boundary. Returns 1 if
582  * a crossing is found and returns 0 otherwise.
583  */
584 int
585 plat_mnode_xcheck(pfn_t pfncnt)
586 {
587 	int	node, prevnode = -1, basenode;
588 	pfn_t	ea, sa;
589 
590 	for (node = 0; node < lgrp_plat_node_cnt; node++) {
591 
592 		if (lgrp_plat_node_memory[node].exists == 0)
593 			continue;
594 
595 		if (prevnode == -1) {
596 			prevnode = node;
597 			basenode = node;
598 			continue;
599 		}
600 
601 		/* assume x86 node pfn ranges are in increasing order */
602 		ASSERT(lgrp_plat_node_memory[node].start >
603 		    lgrp_plat_node_memory[prevnode].end);
604 
605 		/*
606 		 * continue if the starting address of node is not contiguous
607 		 * with the previous node.
608 		 */
609 
610 		if (lgrp_plat_node_memory[node].start !=
611 		    (lgrp_plat_node_memory[prevnode].end + 1)) {
612 			basenode = node;
613 			prevnode = node;
614 			continue;
615 		}
616 
617 		/* check if the starting address of node is pfncnt aligned */
618 		if ((lgrp_plat_node_memory[node].start & (pfncnt - 1)) != 0) {
619 
620 			/*
621 			 * at this point, node starts at an unaligned boundary
622 			 * and is contiguous with the previous node(s) to
623 			 * basenode. Check if there is an aligned contiguous
624 			 * range of length pfncnt that crosses this boundary.
625 			 */
626 
627 			sa = P2ALIGN(lgrp_plat_node_memory[prevnode].end,
628 			    pfncnt);
629 			ea = P2ROUNDUP((lgrp_plat_node_memory[node].start),
630 			    pfncnt);
631 
632 			ASSERT((ea - sa) == pfncnt);
633 			if (sa >= lgrp_plat_node_memory[basenode].start &&
634 			    ea <= (lgrp_plat_node_memory[node].end + 1)) {
635 				/*
636 				 * large page found to cross mnode boundary.
637 				 * Return Failure if workaround not enabled.
638 				 */
639 				if (mnode_xwa == 0)
640 					return (1);
641 				mnode_xwa++;
642 			}
643 		}
644 		prevnode = node;
645 	}
646 	return (0);
647 }
648 
649 
650 lgrp_handle_t
651 plat_mem_node_to_lgrphand(int mnode)
652 {
653 	if (max_mem_nodes == 1)
654 		return (LGRP_DEFAULT_HANDLE);
655 
656 	return ((lgrp_handle_t)mnode);
657 }
658 
659 
660 int
661 plat_pfn_to_mem_node(pfn_t pfn)
662 {
663 	int	node;
664 
665 	if (max_mem_nodes == 1)
666 		return (0);
667 
668 	for (node = 0; node < lgrp_plat_node_cnt; node++) {
669 		/*
670 		 * Skip nodes with no memory
671 		 */
672 		if (!lgrp_plat_node_memory[node].exists)
673 			continue;
674 
675 		if (pfn >= lgrp_plat_node_memory[node].start &&
676 		    pfn <= lgrp_plat_node_memory[node].end)
677 			return (node);
678 	}
679 
680 	/*
681 	 * Didn't find memnode where this PFN lives which should never happen
682 	 */
683 	ASSERT(node < lgrp_plat_node_cnt);
684 	return (-1);
685 }
686 
687 
688 /*
689  * LGROUP PLATFORM INTERFACE ROUTINES
690  */
691 
692 /*
693  * Allocate additional space for an lgroup.
694  */
695 /* ARGSUSED */
696 lgrp_t *
697 lgrp_plat_alloc(lgrp_id_t lgrpid)
698 {
699 	lgrp_t *lgrp;
700 
701 	lgrp = &lgrp_space[nlgrps_alloc++];
702 	if (lgrpid >= NLGRP || nlgrps_alloc > NLGRP)
703 		return (NULL);
704 	return (lgrp);
705 }
706 
707 
708 /*
709  * Platform handling for (re)configuration changes
710  */
711 /* ARGSUSED */
712 void
713 lgrp_plat_config(lgrp_config_flag_t flag, uintptr_t arg)
714 {
715 }
716 
717 
718 /*
719  * Return the platform handle for the lgroup containing the given CPU
720  */
721 /* ARGSUSED */
722 lgrp_handle_t
723 lgrp_plat_cpu_to_hand(processorid_t id)
724 {
725 	lgrp_handle_t	hand;
726 
727 	if (lgrp_plat_node_cnt == 1)
728 		return (LGRP_DEFAULT_HANDLE);
729 
730 	hand = (lgrp_handle_t)lgrp_plat_cpu_to_node(cpu[id],
731 	    lgrp_plat_cpu_node);
732 
733 	ASSERT(hand != (lgrp_handle_t)-1);
734 	if (hand == (lgrp_handle_t)-1)
735 		return (LGRP_NULL_HANDLE);
736 
737 	return (hand);
738 }
739 
740 
741 /*
742  * Platform-specific initialization of lgroups
743  */
744 void
745 lgrp_plat_init(void)
746 {
747 #if defined(__xpv)
748 	/*
749 	 * XXPV	For now, the hypervisor treats all memory equally.
750 	 */
751 	lgrp_plat_node_cnt = max_mem_nodes = 1;
752 #else	/* __xpv */
753 	uint_t		probe_op;
754 	u_longlong_t	value;
755 
756 	/*
757 	 * Get boot property for lgroup topology height limit
758 	 */
759 	if (bootprop_getval(BP_LGRP_TOPO_LEVELS, &value) == 0)
760 		(void) lgrp_topo_ht_limit_set((int)value);
761 
762 	/*
763 	 * Get boot property for enabling/disabling SRAT
764 	 */
765 	if (bootprop_getval(BP_LGRP_SRAT_ENABLE, &value) == 0)
766 		lgrp_plat_srat_enable = (int)value;
767 
768 	/*
769 	 * Get boot property for enabling/disabling SLIT
770 	 */
771 	if (bootprop_getval(BP_LGRP_SLIT_ENABLE, &value) == 0)
772 		lgrp_plat_slit_enable = (int)value;
773 
774 	/*
775 	 * Initialize as a UMA machine
776 	 */
777 	if (lgrp_topo_ht_limit() == 1) {
778 		lgrp_plat_node_cnt = max_mem_nodes = 1;
779 		return;
780 	}
781 
782 	/*
783 	 * Read boot property with CPU to APIC ID mapping table/array and fill
784 	 * in CPU to node ID mapping table with APIC ID for each CPU
785 	 */
786 	lgrp_plat_apic_ncpus =
787 	    lgrp_plat_process_cpu_apicids(lgrp_plat_cpu_node);
788 
789 	/*
790 	 * Determine which CPUs and memory are local to each other and number
791 	 * of NUMA nodes by reading ACPI System Resource Affinity Table (SRAT)
792 	 */
793 	if (lgrp_plat_apic_ncpus > 0) {
794 		int	retval;
795 
796 		retval = lgrp_plat_process_srat(srat_ptr,
797 		    &lgrp_plat_prox_domain_min,
798 		    lgrp_plat_node_domain, lgrp_plat_cpu_node,
799 		    lgrp_plat_apic_ncpus, lgrp_plat_node_memory);
800 		if (retval <= 0) {
801 			lgrp_plat_srat_error = retval;
802 			lgrp_plat_node_cnt = 1;
803 		} else {
804 			lgrp_plat_srat_error = 0;
805 			lgrp_plat_node_cnt = retval;
806 		}
807 	}
808 
809 	/*
810 	 * Try to use PCI config space registers on Opteron if there's an error
811 	 * processing CPU to APIC ID mapping or SRAT
812 	 */
813 	if ((lgrp_plat_apic_ncpus <= 0 || lgrp_plat_srat_error != 0) &&
814 	    is_opteron())
815 		opt_get_numa_config(&lgrp_plat_node_cnt, &lgrp_plat_mem_intrlv,
816 		    lgrp_plat_node_memory);
817 
818 	/*
819 	 * Don't bother to setup system for multiple lgroups and only use one
820 	 * memory node when memory is interleaved between any nodes or there is
821 	 * only one NUMA node
822 	 *
823 	 * NOTE: May need to change this for Dynamic Reconfiguration (DR)
824 	 *	 when and if it happens for x86/x64
825 	 */
826 	if (lgrp_plat_mem_intrlv || lgrp_plat_node_cnt == 1) {
827 		lgrp_plat_node_cnt = max_mem_nodes = 1;
828 		(void) lgrp_topo_ht_limit_set(1);
829 		return;
830 	}
831 
832 	/*
833 	 * Leaf lgroups on x86/x64 architectures contain one physical
834 	 * processor chip. Tune lgrp_expand_proc_thresh and
835 	 * lgrp_expand_proc_diff so that lgrp_choose() will spread
836 	 * things out aggressively.
837 	 */
838 	lgrp_expand_proc_thresh = LGRP_LOADAVG_THREAD_MAX / 2;
839 	lgrp_expand_proc_diff = 0;
840 
841 	/*
842 	 * There should be one memnode (physical page free list(s)) for
843 	 * each node
844 	 */
845 	max_mem_nodes = lgrp_plat_node_cnt;
846 
847 	/*
848 	 * Initialize min and max latency before reading SLIT or probing
849 	 */
850 	lgrp_plat_lat_stats.latency_min = -1;
851 	lgrp_plat_lat_stats.latency_max = 0;
852 
853 	/*
854 	 * Determine how far each NUMA node is from each other by
855 	 * reading ACPI System Locality Information Table (SLIT) if it
856 	 * exists
857 	 */
858 	lgrp_plat_slit_error = lgrp_plat_process_slit(slit_ptr,
859 	    lgrp_plat_node_cnt, lgrp_plat_node_memory,
860 	    &lgrp_plat_lat_stats);
861 	if (lgrp_plat_slit_error == 0)
862 		return;
863 
864 	/*
865 	 * Probe to determine latency between NUMA nodes when SLIT
866 	 * doesn't exist or make sense
867 	 */
868 	lgrp_plat_probe_flags |= LGRP_PLAT_PROBE_ENABLE;
869 
870 	/*
871 	 * Specify whether to probe using vendor ID register or page copy
872 	 * if hasn't been specified already or is overspecified
873 	 */
874 	probe_op = lgrp_plat_probe_flags &
875 	    (LGRP_PLAT_PROBE_PGCPY|LGRP_PLAT_PROBE_VENDOR);
876 
877 	if (probe_op == 0 ||
878 	    probe_op == (LGRP_PLAT_PROBE_PGCPY|LGRP_PLAT_PROBE_VENDOR)) {
879 		lgrp_plat_probe_flags &=
880 		    ~(LGRP_PLAT_PROBE_PGCPY|LGRP_PLAT_PROBE_VENDOR);
881 		if (is_opteron())
882 			lgrp_plat_probe_flags |=
883 			    LGRP_PLAT_PROBE_VENDOR;
884 		else
885 			lgrp_plat_probe_flags |= LGRP_PLAT_PROBE_PGCPY;
886 	}
887 
888 	/*
889 	 * Probing errors can mess up the lgroup topology and
890 	 * force us fall back to a 2 level lgroup topology.
891 	 * Here we bound how tall the lgroup topology can grow
892 	 * in hopes of avoiding any anamolies in probing from
893 	 * messing up the lgroup topology by limiting the
894 	 * accuracy of the latency topology.
895 	 *
896 	 * Assume that nodes will at least be configured in a
897 	 * ring, so limit height of lgroup topology to be less
898 	 * than number of nodes on a system with 4 or more
899 	 * nodes
900 	 */
901 	if (lgrp_plat_node_cnt >= 4 && lgrp_topo_ht_limit() ==
902 	    lgrp_topo_ht_limit_default())
903 		(void) lgrp_topo_ht_limit_set(lgrp_plat_node_cnt - 1);
904 #endif	/* __xpv */
905 }
906 
907 
908 /*
909  * Return latency between "from" and "to" lgroups
910  *
911  * This latency number can only be used for relative comparison
912  * between lgroups on the running system, cannot be used across platforms,
913  * and may not reflect the actual latency.  It is platform and implementation
914  * specific, so platform gets to decide its value.  It would be nice if the
915  * number was at least proportional to make comparisons more meaningful though.
916  */
917 /* ARGSUSED */
918 int
919 lgrp_plat_latency(lgrp_handle_t from, lgrp_handle_t to)
920 {
921 	lgrp_handle_t	src, dest;
922 	int		node;
923 
924 	if (max_mem_nodes == 1)
925 		return (0);
926 
927 	/*
928 	 * Return max latency for root lgroup
929 	 */
930 	if (from == LGRP_DEFAULT_HANDLE || to == LGRP_DEFAULT_HANDLE)
931 		return (lgrp_plat_lat_stats.latency_max);
932 
933 	src = from;
934 	dest = to;
935 
936 	/*
937 	 * Return 0 for nodes (lgroup platform handles) out of range
938 	 */
939 	if (src < 0 || src >= MAX_NODES || dest < 0 || dest >= MAX_NODES)
940 		return (0);
941 
942 	/*
943 	 * Probe from current CPU if its lgroup latencies haven't been set yet
944 	 * and we are trying to get latency from current CPU to some node
945 	 */
946 	node = lgrp_plat_cpu_to_node(CPU, lgrp_plat_cpu_node);
947 	ASSERT(node >= 0 && node < lgrp_plat_node_cnt);
948 	if (lgrp_plat_lat_stats.latencies[src][src] == 0 && node == src)
949 		lgrp_plat_probe();
950 
951 	return (lgrp_plat_lat_stats.latencies[src][dest]);
952 }
953 
954 
955 /*
956  * Platform-specific initialization
957  */
958 void
959 lgrp_plat_main_init(void)
960 {
961 	int	curnode;
962 	int	ht_limit;
963 	int	i;
964 
965 	/*
966 	 * Print a notice that MPO is disabled when memory is interleaved
967 	 * across nodes....Would do this when it is discovered, but can't
968 	 * because it happens way too early during boot....
969 	 */
970 	if (lgrp_plat_mem_intrlv)
971 		cmn_err(CE_NOTE,
972 		    "MPO disabled because memory is interleaved\n");
973 
974 	/*
975 	 * Don't bother to do any probing if it is disabled, there is only one
976 	 * node, or the height of the lgroup topology less than or equal to 2
977 	 */
978 	ht_limit = lgrp_topo_ht_limit();
979 	if (!(lgrp_plat_probe_flags & LGRP_PLAT_PROBE_ENABLE) ||
980 	    max_mem_nodes == 1 || ht_limit <= 2) {
981 		/*
982 		 * Setup lgroup latencies for 2 level lgroup topology
983 		 * (ie. local and remote only) if they haven't been set yet
984 		 */
985 		if (ht_limit == 2 && lgrp_plat_lat_stats.latency_min == -1 &&
986 		    lgrp_plat_lat_stats.latency_max == 0)
987 			lgrp_plat_2level_setup(lgrp_plat_node_memory,
988 			    &lgrp_plat_lat_stats);
989 		return;
990 	}
991 
992 	if (lgrp_plat_probe_flags & LGRP_PLAT_PROBE_VENDOR) {
993 		/*
994 		 * Should have been able to probe from CPU 0 when it was added
995 		 * to lgroup hierarchy, but may not have been able to then
996 		 * because it happens so early in boot that gethrtime() hasn't
997 		 * been initialized.  (:-(
998 		 */
999 		curnode = lgrp_plat_cpu_to_node(CPU, lgrp_plat_cpu_node);
1000 		ASSERT(curnode >= 0 && curnode < lgrp_plat_node_cnt);
1001 		if (lgrp_plat_lat_stats.latencies[curnode][curnode] == 0)
1002 			lgrp_plat_probe();
1003 
1004 		return;
1005 	}
1006 
1007 	/*
1008 	 * When probing memory, use one page for every sample to determine
1009 	 * lgroup topology and taking multiple samples
1010 	 */
1011 	if (lgrp_plat_probe_mem_config.probe_memsize == 0)
1012 		lgrp_plat_probe_mem_config.probe_memsize = PAGESIZE *
1013 		    lgrp_plat_probe_nsamples;
1014 
1015 	/*
1016 	 * Map memory in each node needed for probing to determine latency
1017 	 * topology
1018 	 */
1019 	for (i = 0; i < lgrp_plat_node_cnt; i++) {
1020 		int	mnode;
1021 
1022 		/*
1023 		 * Skip this node and leave its probe page NULL
1024 		 * if it doesn't have any memory
1025 		 */
1026 		mnode = plat_lgrphand_to_mem_node((lgrp_handle_t)i);
1027 		if (!mem_node_config[mnode].exists) {
1028 			lgrp_plat_probe_mem_config.probe_va[i] = NULL;
1029 			continue;
1030 		}
1031 
1032 		/*
1033 		 * Allocate one kernel virtual page
1034 		 */
1035 		lgrp_plat_probe_mem_config.probe_va[i] = vmem_alloc(heap_arena,
1036 		    lgrp_plat_probe_mem_config.probe_memsize, VM_NOSLEEP);
1037 		if (lgrp_plat_probe_mem_config.probe_va[i] == NULL) {
1038 			cmn_err(CE_WARN,
1039 			    "lgrp_plat_main_init: couldn't allocate memory");
1040 			return;
1041 		}
1042 
1043 		/*
1044 		 * Get PFN for first page in each node
1045 		 */
1046 		lgrp_plat_probe_mem_config.probe_pfn[i] =
1047 		    mem_node_config[mnode].physbase;
1048 
1049 		/*
1050 		 * Map virtual page to first page in node
1051 		 */
1052 		hat_devload(kas.a_hat, lgrp_plat_probe_mem_config.probe_va[i],
1053 		    lgrp_plat_probe_mem_config.probe_memsize,
1054 		    lgrp_plat_probe_mem_config.probe_pfn[i],
1055 		    PROT_READ | PROT_WRITE | HAT_PLAT_NOCACHE,
1056 		    HAT_LOAD_NOCONSIST);
1057 	}
1058 
1059 	/*
1060 	 * Probe from current CPU
1061 	 */
1062 	lgrp_plat_probe();
1063 }
1064 
1065 
1066 /*
1067  * Return the maximum number of lgrps supported by the platform.
1068  * Before lgrp topology is known it returns an estimate based on the number of
1069  * nodes. Once topology is known it returns the actual maximim number of lgrps
1070  * created. Since x86/x64 doesn't support Dynamic Reconfiguration (DR) and
1071  * dynamic addition of new nodes, this number may not grow during system
1072  * lifetime (yet).
1073  */
1074 int
1075 lgrp_plat_max_lgrps(void)
1076 {
1077 	return (lgrp_topo_initialized ?
1078 	    lgrp_alloc_max + 1 :
1079 	    lgrp_plat_node_cnt * (lgrp_plat_node_cnt - 1) + 1);
1080 }
1081 
1082 
1083 /*
1084  * Return the number of free pages in an lgroup.
1085  *
1086  * For query of LGRP_MEM_SIZE_FREE, return the number of base pagesize
1087  * pages on freelists.  For query of LGRP_MEM_SIZE_AVAIL, return the
1088  * number of allocatable base pagesize pages corresponding to the
1089  * lgroup (e.g. do not include page_t's, BOP_ALLOC()'ed memory, ..)
1090  * For query of LGRP_MEM_SIZE_INSTALL, return the amount of physical
1091  * memory installed, regardless of whether or not it's usable.
1092  */
1093 pgcnt_t
1094 lgrp_plat_mem_size(lgrp_handle_t plathand, lgrp_mem_query_t query)
1095 {
1096 	int	mnode;
1097 	pgcnt_t npgs = (pgcnt_t)0;
1098 	extern struct memlist *phys_avail;
1099 	extern struct memlist *phys_install;
1100 
1101 
1102 	if (plathand == LGRP_DEFAULT_HANDLE)
1103 		return (lgrp_plat_mem_size_default(plathand, query));
1104 
1105 	if (plathand != LGRP_NULL_HANDLE) {
1106 		mnode = plat_lgrphand_to_mem_node(plathand);
1107 		if (mnode >= 0 && mem_node_config[mnode].exists) {
1108 			switch (query) {
1109 			case LGRP_MEM_SIZE_FREE:
1110 				npgs = MNODE_PGCNT(mnode);
1111 				break;
1112 			case LGRP_MEM_SIZE_AVAIL:
1113 				npgs = mem_node_memlist_pages(mnode,
1114 				    phys_avail);
1115 				break;
1116 			case LGRP_MEM_SIZE_INSTALL:
1117 				npgs = mem_node_memlist_pages(mnode,
1118 				    phys_install);
1119 				break;
1120 			default:
1121 				break;
1122 			}
1123 		}
1124 	}
1125 	return (npgs);
1126 }
1127 
1128 
1129 /*
1130  * Return the platform handle of the lgroup that contains the physical memory
1131  * corresponding to the given page frame number
1132  */
1133 /* ARGSUSED */
1134 lgrp_handle_t
1135 lgrp_plat_pfn_to_hand(pfn_t pfn)
1136 {
1137 	int	mnode;
1138 
1139 	if (max_mem_nodes == 1)
1140 		return (LGRP_DEFAULT_HANDLE);
1141 
1142 	if (pfn > physmax)
1143 		return (LGRP_NULL_HANDLE);
1144 
1145 	mnode = plat_pfn_to_mem_node(pfn);
1146 	if (mnode < 0)
1147 		return (LGRP_NULL_HANDLE);
1148 
1149 	return (MEM_NODE_2_LGRPHAND(mnode));
1150 }
1151 
1152 
1153 /*
1154  * Probe memory in each node from current CPU to determine latency topology
1155  *
1156  * The probing code will probe the vendor ID register on the Northbridge of
1157  * Opteron processors and probe memory for other processors by default.
1158  *
1159  * Since probing is inherently error prone, the code takes laps across all the
1160  * nodes probing from each node to each of the other nodes some number of
1161  * times.  Furthermore, each node is probed some number of times before moving
1162  * onto the next one during each lap.  The minimum latency gotten between nodes
1163  * is kept as the latency between the nodes.
1164  *
1165  * After all that,  the probe times are adjusted by normalizing values that are
1166  * close to each other and local latencies are made the same.  Lastly, the
1167  * latencies are verified to make sure that certain conditions are met (eg.
1168  * local < remote, latency(a, b) == latency(b, a), etc.).
1169  *
1170  * If any of the conditions aren't met, the code will export a NUMA
1171  * configuration with the local CPUs and memory given by the SRAT or PCI config
1172  * space registers and one remote memory latency since it can't tell exactly
1173  * how far each node is from each other.
1174  */
1175 void
1176 lgrp_plat_probe(void)
1177 {
1178 	int				from;
1179 	int				i;
1180 	lgrp_plat_latency_stats_t	*lat_stats;
1181 	hrtime_t			probe_time;
1182 	int				to;
1183 
1184 	if (!(lgrp_plat_probe_flags & LGRP_PLAT_PROBE_ENABLE) ||
1185 	    max_mem_nodes == 1 || lgrp_topo_ht_limit() <= 2)
1186 		return;
1187 
1188 	/*
1189 	 * Determine ID of node containing current CPU
1190 	 */
1191 	from = lgrp_plat_cpu_to_node(CPU, lgrp_plat_cpu_node);
1192 	ASSERT(from >= 0 && from < lgrp_plat_node_cnt);
1193 	if (srat_ptr && lgrp_plat_srat_enable && !lgrp_plat_srat_error)
1194 		ASSERT(lgrp_plat_node_domain[from].exists);
1195 
1196 	/*
1197 	 * Don't need to probe if got times already
1198 	 */
1199 	lat_stats = &lgrp_plat_lat_stats;
1200 	if (lat_stats->latencies[from][from] != 0)
1201 		return;
1202 
1203 	/*
1204 	 * Read vendor ID in Northbridge or read and write page(s)
1205 	 * in each node from current CPU and remember how long it takes,
1206 	 * so we can build latency topology of machine later.
1207 	 * This should approximate the memory latency between each node.
1208 	 */
1209 	for (i = 0; i < lgrp_plat_probe_nrounds; i++) {
1210 		for (to = 0; to < lgrp_plat_node_cnt; to++) {
1211 			/*
1212 			 * Get probe time and bail out if can't get it yet
1213 			 */
1214 			probe_time = lgrp_plat_probe_time(to,
1215 			    lgrp_plat_cpu_node, &lgrp_plat_probe_mem_config,
1216 			    &lgrp_plat_lat_stats, &lgrp_plat_probe_stats);
1217 			if (probe_time == 0)
1218 				return;
1219 
1220 			/*
1221 			 * Keep lowest probe time as latency between nodes
1222 			 */
1223 			if (lat_stats->latencies[from][to] == 0 ||
1224 			    probe_time < lat_stats->latencies[from][to])
1225 				lat_stats->latencies[from][to] = probe_time;
1226 
1227 			/*
1228 			 * Update overall minimum and maximum probe times
1229 			 * across all nodes
1230 			 */
1231 			if (probe_time < lat_stats->latency_min ||
1232 			    lat_stats->latency_min == -1)
1233 				lat_stats->latency_min = probe_time;
1234 			if (probe_time > lat_stats->latency_max)
1235 				lat_stats->latency_max = probe_time;
1236 		}
1237 	}
1238 
1239 	/*
1240 	 * - Fix up latencies such that local latencies are same,
1241 	 *   latency(i, j) == latency(j, i), etc. (if possible)
1242 	 *
1243 	 * - Verify that latencies look ok
1244 	 *
1245 	 * - Fallback to just optimizing for local and remote if
1246 	 *   latencies didn't look right
1247 	 */
1248 	lgrp_plat_latency_adjust(lgrp_plat_node_memory, &lgrp_plat_lat_stats,
1249 	    &lgrp_plat_probe_stats);
1250 	lgrp_plat_probe_stats.probe_error_code =
1251 	    lgrp_plat_latency_verify(lgrp_plat_node_memory,
1252 	    &lgrp_plat_lat_stats);
1253 	if (lgrp_plat_probe_stats.probe_error_code)
1254 		lgrp_plat_2level_setup(lgrp_plat_node_memory,
1255 		    &lgrp_plat_lat_stats);
1256 }
1257 
1258 
1259 /*
1260  * Return platform handle for root lgroup
1261  */
1262 lgrp_handle_t
1263 lgrp_plat_root_hand(void)
1264 {
1265 	return (LGRP_DEFAULT_HANDLE);
1266 }
1267 
1268 
1269 /*
1270  * INTERNAL ROUTINES
1271  */
1272 
1273 
1274 /*
1275  * Update CPU to node mapping for given CPU and proximity domain (and returns
1276  * negative numbers for errors and positive ones for success)
1277  */
1278 static int
1279 lgrp_plat_cpu_node_update(node_domain_map_t *node_domain, int node_cnt,
1280     cpu_node_map_t *cpu_node, int nentries, uint32_t apicid, uint32_t domain)
1281 {
1282 	uint_t	i;
1283 	int	node;
1284 
1285 	/*
1286 	 * Get node number for proximity domain
1287 	 */
1288 	node = lgrp_plat_domain_to_node(node_domain, node_cnt, domain);
1289 	if (node == -1) {
1290 		node = lgrp_plat_node_domain_update(node_domain, node_cnt,
1291 		    domain);
1292 		if (node == -1)
1293 			return (-1);
1294 	}
1295 
1296 	/*
1297 	 * Search for entry with given APIC ID and fill in its node and
1298 	 * proximity domain IDs (if they haven't been set already)
1299 	 */
1300 	for (i = 0; i < nentries; i++) {
1301 		/*
1302 		 * Skip nonexistent entries and ones without matching APIC ID
1303 		 */
1304 		if (!cpu_node[i].exists || cpu_node[i].apicid != apicid)
1305 			continue;
1306 
1307 		/*
1308 		 * Just return if entry completely and correctly filled in
1309 		 * already
1310 		 */
1311 		if (cpu_node[i].prox_domain == domain &&
1312 		    cpu_node[i].node == node)
1313 			return (1);
1314 
1315 		/*
1316 		 * Fill in node and proximity domain IDs
1317 		 */
1318 		cpu_node[i].prox_domain = domain;
1319 		cpu_node[i].node = node;
1320 
1321 		return (0);
1322 	}
1323 
1324 	/*
1325 	 * Return error when entry for APIC ID wasn't found in table
1326 	 */
1327 	return (-2);
1328 }
1329 
1330 
1331 /*
1332  * Get node ID for given CPU
1333  */
1334 static int
1335 lgrp_plat_cpu_to_node(cpu_t *cp, cpu_node_map_t *cpu_node)
1336 {
1337 	processorid_t	cpuid;
1338 
1339 	if (cp == NULL)
1340 		return (-1);
1341 
1342 	cpuid = cp->cpu_id;
1343 	if (cpuid < 0 || cpuid >= max_ncpus)
1344 		return (-1);
1345 
1346 	/*
1347 	 * SRAT doesn't exist, isn't enabled, or there was an error processing
1348 	 * it, so return chip ID for Opteron and -1 otherwise.
1349 	 */
1350 	if (srat_ptr == NULL || !lgrp_plat_srat_enable ||
1351 	    lgrp_plat_srat_error) {
1352 		if (is_opteron())
1353 			return (pg_plat_hw_instance_id(cp, PGHW_CHIP));
1354 		return (-1);
1355 	}
1356 
1357 	/*
1358 	 * Return -1 when CPU to node ID mapping entry doesn't exist for given
1359 	 * CPU
1360 	 */
1361 	if (!cpu_node[cpuid].exists)
1362 		return (-1);
1363 
1364 	return (cpu_node[cpuid].node);
1365 }
1366 
1367 
1368 /*
1369  * Return node number for given proximity domain/system locality
1370  */
1371 static int
1372 lgrp_plat_domain_to_node(node_domain_map_t *node_domain, int node_cnt,
1373     uint32_t domain)
1374 {
1375 	uint_t	node;
1376 	uint_t	start;
1377 
1378 	/*
1379 	 * Hash proximity domain ID into node to domain mapping table (array),
1380 	 * search for entry with matching proximity domain ID, and return index
1381 	 * of matching entry as node ID.
1382 	 */
1383 	node = start = NODE_DOMAIN_HASH(domain, node_cnt);
1384 	do {
1385 		if (node_domain[node].prox_domain == domain &&
1386 		    node_domain[node].exists)
1387 			return (node);
1388 		node = (node + 1) % node_cnt;
1389 	} while (node != start);
1390 	return (-1);
1391 }
1392 
1393 
1394 /*
1395  * Latencies must be within 1/(2**LGRP_LAT_TOLERANCE_SHIFT) of each other to
1396  * be considered same
1397  */
1398 #define	LGRP_LAT_TOLERANCE_SHIFT	4
1399 
1400 int	lgrp_plat_probe_lt_shift = LGRP_LAT_TOLERANCE_SHIFT;
1401 
1402 
1403 /*
1404  * Adjust latencies between nodes to be symmetric, normalize latencies between
1405  * any nodes that are within some tolerance to be same, and make local
1406  * latencies be same
1407  */
1408 static void
1409 lgrp_plat_latency_adjust(node_phys_addr_map_t *node_memory,
1410     lgrp_plat_latency_stats_t *lat_stats, lgrp_plat_probe_stats_t *probe_stats)
1411 {
1412 	int				i;
1413 	int				j;
1414 	int				k;
1415 	int				l;
1416 	u_longlong_t			max;
1417 	u_longlong_t			min;
1418 	u_longlong_t			t;
1419 	u_longlong_t			t1;
1420 	u_longlong_t			t2;
1421 	const lgrp_config_flag_t	cflag = LGRP_CONFIG_LAT_CHANGE_ALL;
1422 	int				lat_corrected[MAX_NODES][MAX_NODES];
1423 
1424 	/*
1425 	 * Nothing to do when this is an UMA machine or don't have args needed
1426 	 */
1427 	if (max_mem_nodes == 1)
1428 		return;
1429 
1430 	ASSERT(node_memory != NULL && lat_stats != NULL &&
1431 	    probe_stats != NULL);
1432 
1433 	/*
1434 	 * Make sure that latencies are symmetric between any two nodes
1435 	 * (ie. latency(node0, node1) == latency(node1, node0))
1436 	 */
1437 	for (i = 0; i < lgrp_plat_node_cnt; i++) {
1438 		if (!node_memory[i].exists)
1439 			continue;
1440 
1441 		for (j = 0; j < lgrp_plat_node_cnt; j++) {
1442 			if (!node_memory[j].exists)
1443 				continue;
1444 
1445 			t1 = lat_stats->latencies[i][j];
1446 			t2 = lat_stats->latencies[j][i];
1447 
1448 			if (t1 == 0 || t2 == 0 || t1 == t2)
1449 				continue;
1450 
1451 			/*
1452 			 * Latencies should be same
1453 			 * - Use minimum of two latencies which should be same
1454 			 * - Track suspect probe times not within tolerance of
1455 			 *   min value
1456 			 * - Remember how much values are corrected by
1457 			 */
1458 			if (t1 > t2) {
1459 				t = t2;
1460 				probe_stats->probe_errors[i][j] += t1 - t2;
1461 				if (t1 - t2 > t2 >> lgrp_plat_probe_lt_shift) {
1462 					probe_stats->probe_suspect[i][j]++;
1463 					probe_stats->probe_suspect[j][i]++;
1464 				}
1465 			} else if (t2 > t1) {
1466 				t = t1;
1467 				probe_stats->probe_errors[j][i] += t2 - t1;
1468 				if (t2 - t1 > t1 >> lgrp_plat_probe_lt_shift) {
1469 					probe_stats->probe_suspect[i][j]++;
1470 					probe_stats->probe_suspect[j][i]++;
1471 				}
1472 			}
1473 
1474 			lat_stats->latencies[i][j] =
1475 			    lat_stats->latencies[j][i] = t;
1476 			lgrp_config(cflag, t1, t);
1477 			lgrp_config(cflag, t2, t);
1478 		}
1479 	}
1480 
1481 	/*
1482 	 * Keep track of which latencies get corrected
1483 	 */
1484 	for (i = 0; i < MAX_NODES; i++)
1485 		for (j = 0; j < MAX_NODES; j++)
1486 			lat_corrected[i][j] = 0;
1487 
1488 	/*
1489 	 * For every two nodes, see whether there is another pair of nodes which
1490 	 * are about the same distance apart and make the latencies be the same
1491 	 * if they are close enough together
1492 	 */
1493 	for (i = 0; i < lgrp_plat_node_cnt; i++) {
1494 		if (!node_memory[i].exists)
1495 			continue;
1496 		for (j = 0; j < lgrp_plat_node_cnt; j++) {
1497 			if (!node_memory[j].exists)
1498 				continue;
1499 			/*
1500 			 * Pick one pair of nodes (i, j)
1501 			 * and get latency between them
1502 			 */
1503 			t1 = lat_stats->latencies[i][j];
1504 
1505 			/*
1506 			 * Skip this pair of nodes if there isn't a latency
1507 			 * for it yet
1508 			 */
1509 			if (t1 == 0)
1510 				continue;
1511 
1512 			for (k = 0; k < lgrp_plat_node_cnt; k++) {
1513 				if (!node_memory[k].exists)
1514 					continue;
1515 				for (l = 0; l < lgrp_plat_node_cnt; l++) {
1516 					if (!node_memory[l].exists)
1517 						continue;
1518 					/*
1519 					 * Pick another pair of nodes (k, l)
1520 					 * not same as (i, j) and get latency
1521 					 * between them
1522 					 */
1523 					if (k == i && l == j)
1524 						continue;
1525 
1526 					t2 = lat_stats->latencies[k][l];
1527 
1528 					/*
1529 					 * Skip this pair of nodes if there
1530 					 * isn't a latency for it yet
1531 					 */
1532 
1533 					if (t2 == 0)
1534 						continue;
1535 
1536 					/*
1537 					 * Skip nodes (k, l) if they already
1538 					 * have same latency as (i, j) or
1539 					 * their latency isn't close enough to
1540 					 * be considered/made the same
1541 					 */
1542 					if (t1 == t2 || (t1 > t2 && t1 - t2 >
1543 					    t1 >> lgrp_plat_probe_lt_shift) ||
1544 					    (t2 > t1 && t2 - t1 >
1545 					    t2 >> lgrp_plat_probe_lt_shift))
1546 						continue;
1547 
1548 					/*
1549 					 * Make latency(i, j) same as
1550 					 * latency(k, l), try to use latency
1551 					 * that has been adjusted already to get
1552 					 * more consistency (if possible), and
1553 					 * remember which latencies were
1554 					 * adjusted for next time
1555 					 */
1556 					if (lat_corrected[i][j]) {
1557 						t = t1;
1558 						lgrp_config(cflag, t2, t);
1559 						t2 = t;
1560 					} else if (lat_corrected[k][l]) {
1561 						t = t2;
1562 						lgrp_config(cflag, t1, t);
1563 						t1 = t;
1564 					} else {
1565 						if (t1 > t2)
1566 							t = t2;
1567 						else
1568 							t = t1;
1569 						lgrp_config(cflag, t1, t);
1570 						lgrp_config(cflag, t2, t);
1571 						t1 = t2 = t;
1572 					}
1573 
1574 					lat_stats->latencies[i][j] =
1575 					    lat_stats->latencies[k][l] = t;
1576 
1577 					lat_corrected[i][j] =
1578 					    lat_corrected[k][l] = 1;
1579 				}
1580 			}
1581 		}
1582 	}
1583 
1584 	/*
1585 	 * Local latencies should be same
1586 	 * - Find min and max local latencies
1587 	 * - Make all local latencies be minimum
1588 	 */
1589 	min = -1;
1590 	max = 0;
1591 	for (i = 0; i < lgrp_plat_node_cnt; i++) {
1592 		if (!node_memory[i].exists)
1593 			continue;
1594 		t = lat_stats->latencies[i][i];
1595 		if (t == 0)
1596 			continue;
1597 		if (min == -1 || t < min)
1598 			min = t;
1599 		if (t > max)
1600 			max = t;
1601 	}
1602 	if (min != max) {
1603 		for (i = 0; i < lgrp_plat_node_cnt; i++) {
1604 			int	local;
1605 
1606 			if (!node_memory[i].exists)
1607 				continue;
1608 
1609 			local = lat_stats->latencies[i][i];
1610 			if (local == 0)
1611 				continue;
1612 
1613 			/*
1614 			 * Track suspect probe times that aren't within
1615 			 * tolerance of minimum local latency and how much
1616 			 * probe times are corrected by
1617 			 */
1618 			if (local - min > min >> lgrp_plat_probe_lt_shift)
1619 				probe_stats->probe_suspect[i][i]++;
1620 
1621 			probe_stats->probe_errors[i][i] += local - min;
1622 
1623 			/*
1624 			 * Make local latencies be minimum
1625 			 */
1626 			lgrp_config(LGRP_CONFIG_LAT_CHANGE, i, min);
1627 			lat_stats->latencies[i][i] = min;
1628 		}
1629 	}
1630 
1631 	/*
1632 	 * Determine max probe time again since just adjusted latencies
1633 	 */
1634 	lat_stats->latency_max = 0;
1635 	for (i = 0; i < lgrp_plat_node_cnt; i++) {
1636 		if (!node_memory[i].exists)
1637 			continue;
1638 		for (j = 0; j < lgrp_plat_node_cnt; j++) {
1639 			if (!node_memory[j].exists)
1640 				continue;
1641 			t = lat_stats->latencies[i][j];
1642 			if (t > lat_stats->latency_max)
1643 				lat_stats->latency_max = t;
1644 		}
1645 	}
1646 }
1647 
1648 
1649 /*
1650  * Verify following about latencies between nodes:
1651  *
1652  * - Latencies should be symmetric (ie. latency(a, b) == latency(b, a))
1653  * - Local latencies same
1654  * - Local < remote
1655  * - Number of latencies seen is reasonable
1656  * - Number of occurrences of a given latency should be more than 1
1657  *
1658  * Returns:
1659  *	0	Success
1660  *	-1	Not symmetric
1661  *	-2	Local latencies not same
1662  *	-3	Local >= remote
1663  */
1664 static int
1665 lgrp_plat_latency_verify(node_phys_addr_map_t *node_memory,
1666     lgrp_plat_latency_stats_t *lat_stats)
1667 {
1668 	int				i;
1669 	int				j;
1670 	u_longlong_t			t1;
1671 	u_longlong_t			t2;
1672 
1673 	ASSERT(node_memory != NULL && lat_stats != NULL);
1674 
1675 	/*
1676 	 * Nothing to do when this is an UMA machine, lgroup topology is
1677 	 * limited to 2 levels, or there aren't any probe times yet
1678 	 */
1679 	if (max_mem_nodes == 1 || lgrp_topo_levels < 2 ||
1680 	    lat_stats->latencies[0][0] == 0)
1681 		return (0);
1682 
1683 	/*
1684 	 * Make sure that latencies are symmetric between any two nodes
1685 	 * (ie. latency(node0, node1) == latency(node1, node0))
1686 	 */
1687 	for (i = 0; i < lgrp_plat_node_cnt; i++) {
1688 		if (!node_memory[i].exists)
1689 			continue;
1690 		for (j = 0; j < lgrp_plat_node_cnt; j++) {
1691 			if (!node_memory[j].exists)
1692 				continue;
1693 			t1 = lat_stats->latencies[i][j];
1694 			t2 = lat_stats->latencies[j][i];
1695 
1696 			if (t1 == 0 || t2 == 0 || t1 == t2)
1697 				continue;
1698 
1699 			return (-1);
1700 		}
1701 	}
1702 
1703 	/*
1704 	 * Local latencies should be same
1705 	 */
1706 	t1 = lat_stats->latencies[0][0];
1707 	for (i = 1; i < lgrp_plat_node_cnt; i++) {
1708 		if (!node_memory[i].exists)
1709 			continue;
1710 
1711 		t2 = lat_stats->latencies[i][i];
1712 		if (t2 == 0)
1713 			continue;
1714 
1715 		if (t1 == 0) {
1716 			t1 = t2;
1717 			continue;
1718 		}
1719 
1720 		if (t1 != t2)
1721 			return (-2);
1722 	}
1723 
1724 	/*
1725 	 * Local latencies should be less than remote
1726 	 */
1727 	if (t1) {
1728 		for (i = 0; i < lgrp_plat_node_cnt; i++) {
1729 			if (!node_memory[i].exists)
1730 				continue;
1731 			for (j = 0; j < lgrp_plat_node_cnt; j++) {
1732 				if (!node_memory[j].exists)
1733 					continue;
1734 				t2 = lat_stats->latencies[i][j];
1735 				if (i == j || t2 == 0)
1736 					continue;
1737 
1738 				if (t1 >= t2)
1739 					return (-3);
1740 			}
1741 		}
1742 	}
1743 
1744 	return (0);
1745 }
1746 
1747 
1748 /*
1749  * Return the number of free, allocatable, or installed
1750  * pages in an lgroup
1751  * This is a copy of the MAX_MEM_NODES == 1 version of the routine
1752  * used when MPO is disabled (i.e. single lgroup) or this is the root lgroup
1753  */
1754 /* ARGSUSED */
1755 static pgcnt_t
1756 lgrp_plat_mem_size_default(lgrp_handle_t lgrphand, lgrp_mem_query_t query)
1757 {
1758 	struct memlist *mlist;
1759 	pgcnt_t npgs = 0;
1760 	extern struct memlist *phys_avail;
1761 	extern struct memlist *phys_install;
1762 
1763 	switch (query) {
1764 	case LGRP_MEM_SIZE_FREE:
1765 		return ((pgcnt_t)freemem);
1766 	case LGRP_MEM_SIZE_AVAIL:
1767 		memlist_read_lock();
1768 		for (mlist = phys_avail; mlist; mlist = mlist->next)
1769 			npgs += btop(mlist->size);
1770 		memlist_read_unlock();
1771 		return (npgs);
1772 	case LGRP_MEM_SIZE_INSTALL:
1773 		memlist_read_lock();
1774 		for (mlist = phys_install; mlist; mlist = mlist->next)
1775 			npgs += btop(mlist->size);
1776 		memlist_read_unlock();
1777 		return (npgs);
1778 	default:
1779 		return ((pgcnt_t)0);
1780 	}
1781 }
1782 
1783 
1784 /*
1785  * Update node to proximity domain mappings for given domain and return node ID
1786  */
1787 static int
1788 lgrp_plat_node_domain_update(node_domain_map_t *node_domain, int node_cnt,
1789     uint32_t domain)
1790 {
1791 	uint_t	node;
1792 	uint_t	start;
1793 
1794 	/*
1795 	 * Hash proximity domain ID into node to domain mapping table (array)
1796 	 * and add entry for it into first non-existent or matching entry found
1797 	 */
1798 	node = start = NODE_DOMAIN_HASH(domain, node_cnt);
1799 	do {
1800 		/*
1801 		 * Entry doesn't exist yet, so create one for this proximity
1802 		 * domain and return node ID which is index into mapping table.
1803 		 */
1804 		if (!node_domain[node].exists) {
1805 			node_domain[node].exists = 1;
1806 			node_domain[node].prox_domain = domain;
1807 			return (node);
1808 		}
1809 
1810 		/*
1811 		 * Entry exists for this proximity domain already, so just
1812 		 * return node ID (index into table).
1813 		 */
1814 		if (node_domain[node].prox_domain == domain)
1815 			return (node);
1816 		node = NODE_DOMAIN_HASH(node + 1, node_cnt);
1817 	} while (node != start);
1818 
1819 	/*
1820 	 * Ran out of supported number of entries which shouldn't happen....
1821 	 */
1822 	ASSERT(node != start);
1823 	return (-1);
1824 }
1825 
1826 
1827 /*
1828  * Update node memory information for given proximity domain with specified
1829  * starting and ending physical address range (and return positive numbers for
1830  * success and negative ones for errors)
1831  */
1832 static int
1833 lgrp_plat_node_memory_update(node_domain_map_t *node_domain, int node_cnt,
1834     node_phys_addr_map_t *node_memory, uint64_t start, uint64_t end,
1835     uint32_t domain)
1836 {
1837 	int	node;
1838 
1839 	/*
1840 	 * Get node number for proximity domain
1841 	 */
1842 	node = lgrp_plat_domain_to_node(node_domain, node_cnt, domain);
1843 	if (node == -1) {
1844 		node = lgrp_plat_node_domain_update(node_domain, node_cnt,
1845 		    domain);
1846 		if (node == -1)
1847 			return (-1);
1848 	}
1849 
1850 	/*
1851 	 * Create entry in table for node if it doesn't exist
1852 	 */
1853 	if (!node_memory[node].exists) {
1854 		node_memory[node].exists = 1;
1855 		node_memory[node].start = btop(start);
1856 		node_memory[node].end = btop(end);
1857 		node_memory[node].prox_domain = domain;
1858 		return (0);
1859 	}
1860 
1861 	/*
1862 	 * Entry already exists for this proximity domain
1863 	 *
1864 	 * There may be more than one SRAT memory entry for a domain, so we may
1865 	 * need to update existing start or end address for the node.
1866 	 */
1867 	if (node_memory[node].prox_domain == domain) {
1868 		if (btop(start) < node_memory[node].start)
1869 			node_memory[node].start = btop(start);
1870 		if (btop(end) > node_memory[node].end)
1871 			node_memory[node].end = btop(end);
1872 		return (1);
1873 	}
1874 	return (-2);
1875 }
1876 
1877 
1878 /*
1879  * Have to sort node by starting physical address because VM system (physical
1880  * page free list management) assumes and expects memnodes to be sorted in
1881  * ascending order by physical address.  If not, the kernel will panic in
1882  * potentially a number of different places.  (:-(
1883  * NOTE: This workaround will not be sufficient if/when hotplugging memory is
1884  *	 supported on x86/x64.
1885  */
1886 static void
1887 lgrp_plat_node_sort(node_domain_map_t *node_domain, int node_cnt,
1888     cpu_node_map_t *cpu_node, int cpu_count, node_phys_addr_map_t *node_memory)
1889 {
1890 	boolean_t	found;
1891 	int		i;
1892 	int		j;
1893 	int		n;
1894 	boolean_t	sorted;
1895 	boolean_t	swapped;
1896 
1897 	if (!lgrp_plat_node_sort_enable || node_cnt <= 1 ||
1898 	    node_domain == NULL || node_memory == NULL)
1899 		return;
1900 
1901 	/*
1902 	 * Sorted already?
1903 	 */
1904 	sorted = B_TRUE;
1905 	for (i = 0; i < node_cnt - 1; i++) {
1906 		/*
1907 		 * Skip entries that don't exist
1908 		 */
1909 		if (!node_memory[i].exists)
1910 			continue;
1911 
1912 		/*
1913 		 * Try to find next existing entry to compare against
1914 		 */
1915 		found = B_FALSE;
1916 		for (j = i + 1; j < node_cnt; j++) {
1917 			if (node_memory[j].exists) {
1918 				found = B_TRUE;
1919 				break;
1920 			}
1921 		}
1922 
1923 		/*
1924 		 * Done if no more existing entries to compare against
1925 		 */
1926 		if (found == B_FALSE)
1927 			break;
1928 
1929 		/*
1930 		 * Not sorted if starting address of current entry is bigger
1931 		 * than starting address of next existing entry
1932 		 */
1933 		if (node_memory[i].start > node_memory[j].start) {
1934 			sorted = B_FALSE;
1935 			break;
1936 		}
1937 	}
1938 
1939 	/*
1940 	 * Don't need to sort if sorted already
1941 	 */
1942 	if (sorted == B_TRUE)
1943 		return;
1944 
1945 	/*
1946 	 * Just use bubble sort since number of nodes is small
1947 	 */
1948 	n = node_cnt;
1949 	do {
1950 		swapped = B_FALSE;
1951 		n--;
1952 		for (i = 0; i < n; i++) {
1953 			/*
1954 			 * Skip entries that don't exist
1955 			 */
1956 			if (!node_memory[i].exists)
1957 				continue;
1958 
1959 			/*
1960 			 * Try to find next existing entry to compare against
1961 			 */
1962 			found = B_FALSE;
1963 			for (j = i + 1; j <= n; j++) {
1964 				if (node_memory[j].exists) {
1965 					found = B_TRUE;
1966 					break;
1967 				}
1968 			}
1969 
1970 			/*
1971 			 * Done if no more existing entries to compare against
1972 			 */
1973 			if (found == B_FALSE)
1974 				break;
1975 
1976 			if (node_memory[i].start > node_memory[j].start) {
1977 				node_phys_addr_map_t	save_addr;
1978 				node_domain_map_t	save_node;
1979 
1980 				/*
1981 				 * Swap node to proxmity domain ID assignments
1982 				 */
1983 				bcopy(&node_domain[i], &save_node,
1984 				    sizeof (node_domain_map_t));
1985 				bcopy(&node_domain[j], &node_domain[i],
1986 				    sizeof (node_domain_map_t));
1987 				bcopy(&save_node, &node_domain[j],
1988 				    sizeof (node_domain_map_t));
1989 
1990 				/*
1991 				 * Swap node to physical memory assignments
1992 				 */
1993 				bcopy(&node_memory[i], &save_addr,
1994 				    sizeof (node_phys_addr_map_t));
1995 				bcopy(&node_memory[j], &node_memory[i],
1996 				    sizeof (node_phys_addr_map_t));
1997 				bcopy(&save_addr, &node_memory[j],
1998 				    sizeof (node_phys_addr_map_t));
1999 				swapped = B_TRUE;
2000 			}
2001 		}
2002 	} while (swapped == B_TRUE);
2003 
2004 	/*
2005 	 * Check to make sure that CPUs assigned to correct node IDs now since
2006 	 * node to proximity domain ID assignments may have been changed above
2007 	 */
2008 	if (n == node_cnt - 1 || cpu_node == NULL || cpu_count < 1)
2009 		return;
2010 	for (i = 0; i < cpu_count; i++) {
2011 		int		node;
2012 
2013 		node = lgrp_plat_domain_to_node(node_domain, node_cnt,
2014 		    cpu_node[i].prox_domain);
2015 		if (cpu_node[i].node != node)
2016 			cpu_node[i].node = node;
2017 	}
2018 
2019 }
2020 
2021 
2022 /*
2023  * Return time needed to probe from current CPU to memory in given node
2024  */
2025 static hrtime_t
2026 lgrp_plat_probe_time(int to, cpu_node_map_t *cpu_node,
2027     lgrp_plat_probe_mem_config_t *probe_mem_config,
2028     lgrp_plat_latency_stats_t *lat_stats, lgrp_plat_probe_stats_t *probe_stats)
2029 {
2030 	caddr_t			buf;
2031 	hrtime_t		elapsed;
2032 	hrtime_t		end;
2033 	int			from;
2034 	int			i;
2035 	int			ipl;
2036 	hrtime_t		max;
2037 	hrtime_t		min;
2038 	hrtime_t		start;
2039 	extern int		use_sse_pagecopy;
2040 
2041 	/*
2042 	 * Determine ID of node containing current CPU
2043 	 */
2044 	from = lgrp_plat_cpu_to_node(CPU, cpu_node);
2045 	ASSERT(from >= 0 && from < lgrp_plat_node_cnt);
2046 
2047 	/*
2048 	 * Do common work for probing main memory
2049 	 */
2050 	if (lgrp_plat_probe_flags & LGRP_PLAT_PROBE_PGCPY) {
2051 		/*
2052 		 * Skip probing any nodes without memory and
2053 		 * set probe time to 0
2054 		 */
2055 		if (probe_mem_config->probe_va[to] == NULL) {
2056 			lat_stats->latencies[from][to] = 0;
2057 			return (0);
2058 		}
2059 
2060 		/*
2061 		 * Invalidate caches once instead of once every sample
2062 		 * which should cut cost of probing by a lot
2063 		 */
2064 		probe_stats->flush_cost = gethrtime();
2065 		invalidate_cache();
2066 		probe_stats->flush_cost = gethrtime() -
2067 		    probe_stats->flush_cost;
2068 		probe_stats->probe_cost_total += probe_stats->flush_cost;
2069 	}
2070 
2071 	/*
2072 	 * Probe from current CPU to given memory using specified operation
2073 	 * and take specified number of samples
2074 	 */
2075 	max = 0;
2076 	min = -1;
2077 	for (i = 0; i < lgrp_plat_probe_nsamples; i++) {
2078 		probe_stats->probe_cost = gethrtime();
2079 
2080 		/*
2081 		 * Can't measure probe time if gethrtime() isn't working yet
2082 		 */
2083 		if (probe_stats->probe_cost == 0 && gethrtime() == 0)
2084 			return (0);
2085 
2086 		if (lgrp_plat_probe_flags & LGRP_PLAT_PROBE_VENDOR) {
2087 			/*
2088 			 * Measure how long it takes to read vendor ID from
2089 			 * Northbridge
2090 			 */
2091 			elapsed = opt_probe_vendor(to, lgrp_plat_probe_nreads);
2092 		} else {
2093 			/*
2094 			 * Measure how long it takes to copy page
2095 			 * on top of itself
2096 			 */
2097 			buf = probe_mem_config->probe_va[to] + (i * PAGESIZE);
2098 
2099 			kpreempt_disable();
2100 			ipl = splhigh();
2101 			start = gethrtime();
2102 			if (use_sse_pagecopy)
2103 				hwblkpagecopy(buf, buf);
2104 			else
2105 				bcopy(buf, buf, PAGESIZE);
2106 			end = gethrtime();
2107 			elapsed = end - start;
2108 			splx(ipl);
2109 			kpreempt_enable();
2110 		}
2111 
2112 		probe_stats->probe_cost = gethrtime() -
2113 		    probe_stats->probe_cost;
2114 		probe_stats->probe_cost_total += probe_stats->probe_cost;
2115 
2116 		if (min == -1 || elapsed < min)
2117 			min = elapsed;
2118 		if (elapsed > max)
2119 			max = elapsed;
2120 	}
2121 
2122 	/*
2123 	 * Update minimum and maximum probe times between
2124 	 * these two nodes
2125 	 */
2126 	if (min < probe_stats->probe_min[from][to] ||
2127 	    probe_stats->probe_min[from][to] == 0)
2128 		probe_stats->probe_min[from][to] = min;
2129 
2130 	if (max > probe_stats->probe_max[from][to])
2131 		probe_stats->probe_max[from][to] = max;
2132 
2133 	return (min);
2134 }
2135 
2136 
2137 /*
2138  * Read boot property with CPU to APIC ID array, fill in CPU to node ID
2139  * mapping table with APIC ID for each CPU, and return number of CPU APIC IDs.
2140  *
2141  * NOTE: This code assumes that CPU IDs are assigned in order that they appear
2142  *       in in cpu_apicid_array boot property which is based on and follows
2143  *	 same ordering as processor list in ACPI MADT.  If the code in
2144  *	 usr/src/uts/i86pc/io/pcplusmp/apic.c that reads MADT and assigns
2145  *	 CPU IDs ever changes, then this code will need to change too....
2146  */
2147 static int
2148 lgrp_plat_process_cpu_apicids(cpu_node_map_t *cpu_node)
2149 {
2150 	int	boot_prop_len;
2151 	char	*boot_prop_name = BP_CPU_APICID_ARRAY;
2152 	uint8_t	cpu_apicid_array[UINT8_MAX + 1];
2153 	int	i;
2154 	int	n;
2155 
2156 	/*
2157 	 * Nothing to do when no array to fill in or not enough CPUs
2158 	 */
2159 	if (cpu_node == NULL)
2160 		return (-1);
2161 
2162 	/*
2163 	 * Check length of property value
2164 	 */
2165 	boot_prop_len = BOP_GETPROPLEN(bootops, boot_prop_name);
2166 	if (boot_prop_len <= 0 || boot_prop_len > sizeof (cpu_apicid_array))
2167 		return (-2);
2168 
2169 	/*
2170 	 * Calculate number of entries in array and return when there's just
2171 	 * one CPU since that's not very interesting for NUMA
2172 	 */
2173 	n = boot_prop_len / sizeof (uint8_t);
2174 	if (n == 1)
2175 		return (-3);
2176 
2177 	/*
2178 	 * Get CPU to APIC ID property value
2179 	 */
2180 	if (BOP_GETPROP(bootops, boot_prop_name, cpu_apicid_array) < 0)
2181 		return (-4);
2182 
2183 	/*
2184 	 * Fill in CPU to node ID mapping table with APIC ID for each CPU
2185 	 */
2186 	for (i = 0; i < n; i++) {
2187 		cpu_node[i].exists = 1;
2188 		cpu_node[i].apicid = cpu_apicid_array[i];
2189 	}
2190 
2191 	/*
2192 	 * Return number of CPUs based on number of APIC IDs
2193 	 */
2194 	return (n);
2195 }
2196 
2197 
2198 /*
2199  * Read ACPI System Locality Information Table (SLIT) to determine how far each
2200  * NUMA node is from each other
2201  */
2202 static int
2203 lgrp_plat_process_slit(struct slit *tp, uint_t node_cnt,
2204     node_phys_addr_map_t *node_memory, lgrp_plat_latency_stats_t *lat_stats)
2205 {
2206 	int		i;
2207 	int		j;
2208 	int		localities;
2209 	hrtime_t	max;
2210 	hrtime_t	min;
2211 	int		retval;
2212 	uint8_t		*slit_entries;
2213 
2214 	if (tp == NULL || !lgrp_plat_slit_enable)
2215 		return (1);
2216 
2217 	if (lat_stats == NULL)
2218 		return (2);
2219 
2220 	localities = tp->number;
2221 	if (localities != node_cnt)
2222 		return (3);
2223 
2224 	min = lat_stats->latency_min;
2225 	max = lat_stats->latency_max;
2226 
2227 	/*
2228 	 * Fill in latency matrix based on SLIT entries
2229 	 */
2230 	slit_entries = tp->entry;
2231 	for (i = 0; i < localities; i++) {
2232 		for (j = 0; j < localities; j++) {
2233 			uint8_t	latency;
2234 
2235 			latency = slit_entries[(i * localities) + j];
2236 			lat_stats->latencies[i][j] = latency;
2237 			if (latency < min || min == -1)
2238 				min = latency;
2239 			if (latency > max)
2240 				max = latency;
2241 		}
2242 	}
2243 
2244 	/*
2245 	 * Verify that latencies/distances given in SLIT look reasonable
2246 	 */
2247 	retval = lgrp_plat_latency_verify(node_memory, lat_stats);
2248 
2249 	if (retval) {
2250 		/*
2251 		 * Reinitialize (zero) latency table since SLIT doesn't look
2252 		 * right
2253 		 */
2254 		for (i = 0; i < localities; i++) {
2255 			for (j = 0; j < localities; j++)
2256 				lat_stats->latencies[i][j] = 0;
2257 		}
2258 	} else {
2259 		/*
2260 		 * Update min and max latencies seen since SLIT looks valid
2261 		 */
2262 		lat_stats->latency_min = min;
2263 		lat_stats->latency_max = max;
2264 	}
2265 
2266 	return (retval);
2267 }
2268 
2269 
2270 /*
2271  * Read ACPI System Resource Affinity Table (SRAT) to determine which CPUs
2272  * and memory are local to each other in the same NUMA node and return number
2273  * of nodes
2274  */
2275 static int
2276 lgrp_plat_process_srat(struct srat *tp, uint32_t *prox_domain_min,
2277     node_domain_map_t *node_domain, cpu_node_map_t *cpu_node, int cpu_count,
2278     node_phys_addr_map_t *node_memory)
2279 {
2280 	struct srat_item	*srat_end;
2281 	int			i;
2282 	struct srat_item	*item;
2283 	int			node_cnt;
2284 	int			proc_entry_count;
2285 
2286 	/*
2287 	 * Nothing to do when no SRAT or disabled
2288 	 */
2289 	if (tp == NULL || !lgrp_plat_srat_enable)
2290 		return (-1);
2291 
2292 	/*
2293 	 * Determine number of nodes by counting number of proximity domains in
2294 	 * SRAT and return if number of nodes is 1 or less since don't need to
2295 	 * read SRAT then
2296 	 */
2297 	node_cnt = lgrp_plat_srat_domains(tp, prox_domain_min);
2298 	if (node_cnt == 1)
2299 		return (1);
2300 	else if (node_cnt <= 0)
2301 		return (-2);
2302 
2303 	/*
2304 	 * Walk through SRAT, examining each CPU and memory entry to determine
2305 	 * which CPUs and memory belong to which node.
2306 	 */
2307 	item = tp->list;
2308 	srat_end = (struct srat_item *)(tp->hdr.len + (uintptr_t)tp);
2309 	proc_entry_count = 0;
2310 	while (item < srat_end) {
2311 		uint32_t	apic_id;
2312 		uint32_t	domain;
2313 		uint64_t	end;
2314 		uint64_t	length;
2315 		uint64_t	start;
2316 
2317 		switch (item->type) {
2318 		case SRAT_PROCESSOR:	/* CPU entry */
2319 			if (!(item->i.p.flags & SRAT_ENABLED) ||
2320 			    cpu_node == NULL)
2321 				break;
2322 
2323 			/*
2324 			 * Calculate domain (node) ID and fill in APIC ID to
2325 			 * domain/node mapping table
2326 			 */
2327 			domain = item->i.p.domain1;
2328 			for (i = 0; i < 3; i++) {
2329 				domain += item->i.p.domain2[i] <<
2330 				    ((i + 1) * 8);
2331 			}
2332 			apic_id = item->i.p.apic_id;
2333 
2334 			if (lgrp_plat_cpu_node_update(node_domain, node_cnt,
2335 			    cpu_node, cpu_count, apic_id, domain) < 0)
2336 				return (-3);
2337 
2338 			proc_entry_count++;
2339 			break;
2340 
2341 		case SRAT_MEMORY:	/* memory entry */
2342 			if (!(item->i.m.flags & SRAT_ENABLED) ||
2343 			    node_memory == NULL)
2344 				break;
2345 
2346 			/*
2347 			 * Get domain (node) ID and fill in domain/node
2348 			 * to memory mapping table
2349 			 */
2350 			domain = item->i.m.domain;
2351 			start = item->i.m.base_addr;
2352 			length = item->i.m.len;
2353 			end = start + length - 1;
2354 
2355 			if (lgrp_plat_node_memory_update(node_domain, node_cnt,
2356 			    node_memory, start, end, domain) < 0)
2357 				return (-4);
2358 			break;
2359 		case SRAT_X2APIC:	/* x2apic CPU entry */
2360 			if (!(item->i.xp.flags & SRAT_ENABLED) ||
2361 			    cpu_node == NULL)
2362 				break;
2363 
2364 			/*
2365 			 * Calculate domain (node) ID and fill in APIC ID to
2366 			 * domain/node mapping table
2367 			 */
2368 			domain = item->i.xp.domain;
2369 			apic_id = item->i.xp.x2apic_id;
2370 
2371 			if (lgrp_plat_cpu_node_update(node_domain, node_cnt,
2372 			    cpu_node, cpu_count, apic_id, domain) < 0)
2373 				return (-3);
2374 
2375 			proc_entry_count++;
2376 			break;
2377 
2378 		default:
2379 			break;
2380 		}
2381 
2382 		item = (struct srat_item *)((uintptr_t)item + item->len);
2383 	}
2384 
2385 	/*
2386 	 * Should have seen at least as many SRAT processor entries as CPUs
2387 	 */
2388 	if (proc_entry_count < cpu_count)
2389 		return (-5);
2390 
2391 	/*
2392 	 * Need to sort nodes by starting physical address since VM system
2393 	 * assumes and expects memnodes to be sorted in ascending order by
2394 	 * physical address
2395 	 */
2396 	lgrp_plat_node_sort(node_domain, node_cnt, cpu_node, cpu_count,
2397 	    node_memory);
2398 
2399 	return (node_cnt);
2400 }
2401 
2402 
2403 /*
2404  * Return number of proximity domains given in ACPI SRAT
2405  */
2406 static int
2407 lgrp_plat_srat_domains(struct srat *tp, uint32_t *prox_domain_min)
2408 {
2409 	int			domain_cnt;
2410 	uint32_t		domain_min;
2411 	struct srat_item	*end;
2412 	int			i;
2413 	struct srat_item	*item;
2414 	node_domain_map_t	node_domain[MAX_NODES];
2415 
2416 
2417 	if (tp == NULL || !lgrp_plat_srat_enable)
2418 		return (1);
2419 
2420 	/*
2421 	 * Walk through SRAT to find minimum proximity domain ID
2422 	 */
2423 	domain_min = UINT32_MAX;
2424 	item = tp->list;
2425 	end = (struct srat_item *)(tp->hdr.len + (uintptr_t)tp);
2426 	while (item < end) {
2427 		uint32_t	domain;
2428 
2429 		switch (item->type) {
2430 		case SRAT_PROCESSOR:	/* CPU entry */
2431 			if (!(item->i.p.flags & SRAT_ENABLED)) {
2432 				item = (struct srat_item *)((uintptr_t)item +
2433 				    item->len);
2434 				continue;
2435 			}
2436 			domain = item->i.p.domain1;
2437 			for (i = 0; i < 3; i++) {
2438 				domain += item->i.p.domain2[i] <<
2439 				    ((i + 1) * 8);
2440 			}
2441 			break;
2442 
2443 		case SRAT_MEMORY:	/* memory entry */
2444 			if (!(item->i.m.flags & SRAT_ENABLED)) {
2445 				item = (struct srat_item *)((uintptr_t)item +
2446 				    item->len);
2447 				continue;
2448 			}
2449 			domain = item->i.m.domain;
2450 			break;
2451 
2452 		case SRAT_X2APIC:	/* x2apic CPU entry */
2453 			if (!(item->i.xp.flags & SRAT_ENABLED)) {
2454 				item = (struct srat_item *)((uintptr_t)item +
2455 				    item->len);
2456 				continue;
2457 			}
2458 			domain = item->i.xp.domain;
2459 			break;
2460 
2461 		default:
2462 			item = (struct srat_item *)((uintptr_t)item +
2463 			    item->len);
2464 			continue;
2465 		}
2466 
2467 		/*
2468 		 * Keep track of minimum proximity domain ID
2469 		 */
2470 		if (domain < domain_min)
2471 			domain_min = domain;
2472 
2473 		item = (struct srat_item *)((uintptr_t)item + item->len);
2474 	}
2475 	if (lgrp_plat_domain_min_enable && prox_domain_min != NULL)
2476 		*prox_domain_min = domain_min;
2477 
2478 	/*
2479 	 * Walk through SRAT, examining each CPU and memory entry to determine
2480 	 * proximity domain ID for each.
2481 	 */
2482 	domain_cnt = 0;
2483 	item = tp->list;
2484 	end = (struct srat_item *)(tp->hdr.len + (uintptr_t)tp);
2485 	bzero(node_domain, MAX_NODES * sizeof (node_domain_map_t));
2486 	while (item < end) {
2487 		uint32_t	domain;
2488 		boolean_t	overflow;
2489 		uint_t		start;
2490 
2491 		switch (item->type) {
2492 		case SRAT_PROCESSOR:	/* CPU entry */
2493 			if (!(item->i.p.flags & SRAT_ENABLED)) {
2494 				item = (struct srat_item *)((uintptr_t)item +
2495 				    item->len);
2496 				continue;
2497 			}
2498 			domain = item->i.p.domain1;
2499 			for (i = 0; i < 3; i++) {
2500 				domain += item->i.p.domain2[i] <<
2501 				    ((i + 1) * 8);
2502 			}
2503 			break;
2504 
2505 		case SRAT_MEMORY:	/* memory entry */
2506 			if (!(item->i.m.flags & SRAT_ENABLED)) {
2507 				item = (struct srat_item *)((uintptr_t)item +
2508 				    item->len);
2509 				continue;
2510 			}
2511 			domain = item->i.m.domain;
2512 			break;
2513 
2514 		case SRAT_X2APIC:	/* x2apic CPU entry */
2515 			if (!(item->i.xp.flags & SRAT_ENABLED)) {
2516 				item = (struct srat_item *)((uintptr_t)item +
2517 				    item->len);
2518 				continue;
2519 			}
2520 			domain = item->i.xp.domain;
2521 			break;
2522 
2523 		default:
2524 			item = (struct srat_item *)((uintptr_t)item +
2525 			    item->len);
2526 			continue;
2527 		}
2528 
2529 		/*
2530 		 * Count and keep track of which proximity domain IDs seen
2531 		 */
2532 		start = i = domain % MAX_NODES;
2533 		overflow = B_TRUE;
2534 		do {
2535 			/*
2536 			 * Create entry for proximity domain and increment
2537 			 * count when no entry exists where proximity domain
2538 			 * hashed
2539 			 */
2540 			if (!node_domain[i].exists) {
2541 				node_domain[i].exists = 1;
2542 				node_domain[i].prox_domain = domain;
2543 				domain_cnt++;
2544 				overflow = B_FALSE;
2545 				break;
2546 			}
2547 
2548 			/*
2549 			 * Nothing to do when proximity domain seen already
2550 			 * and its entry exists
2551 			 */
2552 			if (node_domain[i].prox_domain == domain) {
2553 				overflow = B_FALSE;
2554 				break;
2555 			}
2556 
2557 			/*
2558 			 * Entry exists where proximity domain hashed, but for
2559 			 * different proximity domain so keep search for empty
2560 			 * slot to put it or matching entry whichever comes
2561 			 * first.
2562 			 */
2563 			i = (i + 1) % MAX_NODES;
2564 		} while (i != start);
2565 
2566 		/*
2567 		 * Didn't find empty or matching entry which means have more
2568 		 * proximity domains than supported nodes (:-(
2569 		 */
2570 		ASSERT(overflow != B_TRUE);
2571 		if (overflow == B_TRUE)
2572 			return (-1);
2573 
2574 		item = (struct srat_item *)((uintptr_t)item + item->len);
2575 	}
2576 	return (domain_cnt);
2577 }
2578 
2579 
2580 /*
2581  * Set lgroup latencies for 2 level lgroup topology
2582  */
2583 static void
2584 lgrp_plat_2level_setup(node_phys_addr_map_t *node_memory,
2585     lgrp_plat_latency_stats_t *lat_stats)
2586 {
2587 	int	i;
2588 
2589 	ASSERT(node_memory != NULL && lat_stats != NULL);
2590 
2591 	if (lgrp_plat_node_cnt >= 4)
2592 		cmn_err(CE_NOTE,
2593 		    "MPO only optimizing for local and remote\n");
2594 	for (i = 0; i < lgrp_plat_node_cnt; i++) {
2595 		int	j;
2596 
2597 		if (!node_memory[i].exists)
2598 			continue;
2599 		for (j = 0; j < lgrp_plat_node_cnt; j++) {
2600 			if (!node_memory[j].exists)
2601 				continue;
2602 			if (i == j)
2603 				lat_stats->latencies[i][j] = 2;
2604 			else
2605 				lat_stats->latencies[i][j] = 3;
2606 		}
2607 	}
2608 	lat_stats->latency_min = 2;
2609 	lat_stats->latency_max = 3;
2610 	lgrp_config(LGRP_CONFIG_FLATTEN, 2, 0);
2611 }
2612 
2613 
2614 /*
2615  * The following Opteron specific constants, macros, types, and routines define
2616  * PCI configuration space registers and how to read them to determine the NUMA
2617  * configuration of *supported* Opteron processors.  They provide the same
2618  * information that may be gotten from the ACPI System Resource Affinity Table
2619  * (SRAT) if it exists on the machine of interest.
2620  *
2621  * The AMD BIOS and Kernel Developer's Guide (BKDG) for the processor family
2622  * of interest describes all of these registers and their contents.  The main
2623  * registers used by this code to determine the NUMA configuration of the
2624  * machine are the node ID register for the number of NUMA nodes and the DRAM
2625  * address map registers for the physical address range of each node.
2626  *
2627  * NOTE: The format and how to determine the NUMA configuration using PCI
2628  *	 config space registers may change or may not be supported in future
2629  *	 Opteron processor families.
2630  */
2631 
2632 /*
2633  * How many bits to shift Opteron DRAM Address Map base and limit registers
2634  * to get actual value
2635  */
2636 #define	OPT_DRAMADDR_HI_LSHIFT_ADDR	40	/* shift left for address */
2637 #define	OPT_DRAMADDR_LO_LSHIFT_ADDR	8	/* shift left for address */
2638 
2639 #define	OPT_DRAMADDR_HI_MASK_ADDR	0x000000FF /* address bits 47-40 */
2640 #define	OPT_DRAMADDR_LO_MASK_ADDR	0xFFFF0000 /* address bits 39-24 */
2641 
2642 #define	OPT_DRAMADDR_LO_MASK_OFF	0xFFFFFF /* offset for address */
2643 
2644 /*
2645  * Macros to derive addresses from Opteron DRAM Address Map registers
2646  */
2647 #define	OPT_DRAMADDR_HI(reg) \
2648 	(((u_longlong_t)reg & OPT_DRAMADDR_HI_MASK_ADDR) << \
2649 	    OPT_DRAMADDR_HI_LSHIFT_ADDR)
2650 
2651 #define	OPT_DRAMADDR_LO(reg) \
2652 	(((u_longlong_t)reg & OPT_DRAMADDR_LO_MASK_ADDR) << \
2653 	    OPT_DRAMADDR_LO_LSHIFT_ADDR)
2654 
2655 #define	OPT_DRAMADDR(high, low) \
2656 	(OPT_DRAMADDR_HI(high) | OPT_DRAMADDR_LO(low))
2657 
2658 /*
2659  * Bit masks defining what's in Opteron DRAM Address Map base register
2660  */
2661 #define	OPT_DRAMBASE_LO_MASK_RE		0x1	/* read enable */
2662 #define	OPT_DRAMBASE_LO_MASK_WE		0x2	/* write enable */
2663 #define	OPT_DRAMBASE_LO_MASK_INTRLVEN	0x700	/* interleave */
2664 
2665 /*
2666  * Bit masks defining what's in Opteron DRAM Address Map limit register
2667  */
2668 #define	OPT_DRAMLIMIT_LO_MASK_DSTNODE	0x7		/* destination node */
2669 #define	OPT_DRAMLIMIT_LO_MASK_INTRLVSEL	0x700		/* interleave select */
2670 
2671 
2672 /*
2673  * Opteron Node ID register in PCI configuration space contains
2674  * number of nodes in system, etc. for Opteron K8.  The following
2675  * constants and macros define its contents, structure, and access.
2676  */
2677 
2678 /*
2679  * Bit masks defining what's in Opteron Node ID register
2680  */
2681 #define	OPT_NODE_MASK_ID	0x7	/* node ID */
2682 #define	OPT_NODE_MASK_CNT	0x70	/* node count */
2683 #define	OPT_NODE_MASK_IONODE	0x700	/* Hypertransport I/O hub node ID */
2684 #define	OPT_NODE_MASK_LCKNODE	0x7000	/* lock controller node ID */
2685 #define	OPT_NODE_MASK_CPUCNT	0xF0000	/* CPUs in system (0 means 1 CPU)  */
2686 
2687 /*
2688  * How many bits in Opteron Node ID register to shift right to get actual value
2689  */
2690 #define	OPT_NODE_RSHIFT_CNT	0x4	/* shift right for node count value */
2691 
2692 /*
2693  * Macros to get values from Opteron Node ID register
2694  */
2695 #define	OPT_NODE_CNT(reg) \
2696 	((reg & OPT_NODE_MASK_CNT) >> OPT_NODE_RSHIFT_CNT)
2697 
2698 /*
2699  * Macro to setup PCI Extended Configuration Space (ECS) address to give to
2700  * "in/out" instructions
2701  *
2702  * NOTE: Should only be used in lgrp_plat_init() before MMIO setup because any
2703  *	 other uses should just do MMIO to access PCI ECS.
2704  *	 Must enable special bit in Northbridge Configuration Register on
2705  *	 Greyhound for extended CF8 space access to be able to access PCI ECS
2706  *	 using "in/out" instructions and restore special bit after done
2707  *	 accessing PCI ECS.
2708  */
2709 #define	OPT_PCI_ECS_ADDR(bus, device, function, reg) \
2710 	(PCI_CONE | (((bus) & 0xff) << 16) | (((device & 0x1f)) << 11)  | \
2711 	    (((function) & 0x7) << 8) | ((reg) & 0xfc) | \
2712 	    ((((reg) >> 8) & 0xf) << 24))
2713 
2714 /*
2715  * PCI configuration space registers accessed by specifying
2716  * a bus, device, function, and offset.  The following constants
2717  * define the values needed to access Opteron K8 configuration
2718  * info to determine its node topology
2719  */
2720 
2721 #define	OPT_PCS_BUS_CONFIG	0	/* Hypertransport config space bus */
2722 
2723 /*
2724  * Opteron PCI configuration space register function values
2725  */
2726 #define	OPT_PCS_FUNC_HT		0	/* Hypertransport configuration */
2727 #define	OPT_PCS_FUNC_ADDRMAP	1	/* Address map configuration */
2728 #define	OPT_PCS_FUNC_DRAM	2	/* DRAM configuration */
2729 #define	OPT_PCS_FUNC_MISC	3	/* Miscellaneous configuration */
2730 
2731 /*
2732  * PCI Configuration Space register offsets
2733  */
2734 #define	OPT_PCS_OFF_VENDOR	0x0	/* device/vendor ID register */
2735 #define	OPT_PCS_OFF_DRAMBASE_HI	0x140	/* DRAM Base register (node 0) */
2736 #define	OPT_PCS_OFF_DRAMBASE_LO	0x40	/* DRAM Base register (node 0) */
2737 #define	OPT_PCS_OFF_NODEID	0x60	/* Node ID register */
2738 
2739 /*
2740  * Opteron PCI Configuration Space device IDs for nodes
2741  */
2742 #define	OPT_PCS_DEV_NODE0		24	/* device number for node 0 */
2743 
2744 
2745 /*
2746  * Opteron DRAM address map gives base and limit for physical memory in a node
2747  */
2748 typedef	struct opt_dram_addr_map {
2749 	uint32_t	base_hi;
2750 	uint32_t	base_lo;
2751 	uint32_t	limit_hi;
2752 	uint32_t	limit_lo;
2753 } opt_dram_addr_map_t;
2754 
2755 
2756 /*
2757  * Supported AMD processor families
2758  */
2759 #define	AMD_FAMILY_HAMMER	15
2760 #define	AMD_FAMILY_GREYHOUND	16
2761 
2762 /*
2763  * Whether to have is_opteron() return 1 even when processor isn't supported
2764  */
2765 uint_t	is_opteron_override = 0;
2766 
2767 /*
2768  * AMD processor family for current CPU
2769  */
2770 uint_t	opt_family = 0;
2771 
2772 
2773 /*
2774  * Determine whether we're running on a supported AMD Opteron since reading
2775  * node count and DRAM address map registers may have different format or
2776  * may not be supported across processor families
2777  */
2778 static int
2779 is_opteron(void)
2780 {
2781 
2782 	if (x86_vendor != X86_VENDOR_AMD)
2783 		return (0);
2784 
2785 	opt_family = cpuid_getfamily(CPU);
2786 	if (opt_family == AMD_FAMILY_HAMMER ||
2787 	    opt_family == AMD_FAMILY_GREYHOUND || is_opteron_override)
2788 		return (1);
2789 	else
2790 		return (0);
2791 }
2792 
2793 
2794 /*
2795  * Determine NUMA configuration for Opteron from registers that live in PCI
2796  * configuration space
2797  */
2798 static void
2799 opt_get_numa_config(uint_t *node_cnt, int *mem_intrlv,
2800     node_phys_addr_map_t *node_memory)
2801 {
2802 	uint_t				bus;
2803 	uint_t				dev;
2804 	struct opt_dram_addr_map	dram_map[MAX_NODES];
2805 	uint_t				node;
2806 	uint_t				node_info[MAX_NODES];
2807 	uint_t				off_hi;
2808 	uint_t				off_lo;
2809 	uint64_t			nb_cfg_reg;
2810 
2811 	/*
2812 	 * Read configuration registers from PCI configuration space to
2813 	 * determine node information, which memory is in each node, etc.
2814 	 *
2815 	 * Write to PCI configuration space address register to specify
2816 	 * which configuration register to read and read/write PCI
2817 	 * configuration space data register to get/set contents
2818 	 */
2819 	bus = OPT_PCS_BUS_CONFIG;
2820 	dev = OPT_PCS_DEV_NODE0;
2821 	off_hi = OPT_PCS_OFF_DRAMBASE_HI;
2822 	off_lo = OPT_PCS_OFF_DRAMBASE_LO;
2823 
2824 	/*
2825 	 * Read node ID register for node 0 to get node count
2826 	 */
2827 	node_info[0] = pci_getl_func(bus, dev, OPT_PCS_FUNC_HT,
2828 	    OPT_PCS_OFF_NODEID);
2829 	*node_cnt = OPT_NODE_CNT(node_info[0]) + 1;
2830 
2831 	/*
2832 	 * If number of nodes is more than maximum supported, then set node
2833 	 * count to 1 and treat system as UMA instead of NUMA.
2834 	 */
2835 	if (*node_cnt > MAX_NODES) {
2836 		*node_cnt = 1;
2837 		return;
2838 	}
2839 
2840 	/*
2841 	 * For Greyhound, PCI Extended Configuration Space must be enabled to
2842 	 * read high DRAM address map base and limit registers
2843 	 */
2844 	if (opt_family == AMD_FAMILY_GREYHOUND) {
2845 		nb_cfg_reg = rdmsr(MSR_AMD_NB_CFG);
2846 		if ((nb_cfg_reg & AMD_GH_NB_CFG_EN_ECS) == 0)
2847 			wrmsr(MSR_AMD_NB_CFG,
2848 			    nb_cfg_reg | AMD_GH_NB_CFG_EN_ECS);
2849 	}
2850 
2851 	for (node = 0; node < *node_cnt; node++) {
2852 		uint32_t	base_hi;
2853 		uint32_t	base_lo;
2854 		uint32_t	limit_hi;
2855 		uint32_t	limit_lo;
2856 
2857 		/*
2858 		 * Read node ID register (except for node 0 which we just read)
2859 		 */
2860 		if (node > 0) {
2861 			node_info[node] = pci_getl_func(bus, dev,
2862 			    OPT_PCS_FUNC_HT, OPT_PCS_OFF_NODEID);
2863 		}
2864 
2865 		/*
2866 		 * Read DRAM base and limit registers which specify
2867 		 * physical memory range of each node
2868 		 */
2869 		if (opt_family != AMD_FAMILY_GREYHOUND)
2870 			base_hi = 0;
2871 		else {
2872 			outl(PCI_CONFADD, OPT_PCI_ECS_ADDR(bus, dev,
2873 			    OPT_PCS_FUNC_ADDRMAP, off_hi));
2874 			base_hi = dram_map[node].base_hi =
2875 			    inl(PCI_CONFDATA);
2876 		}
2877 		base_lo = dram_map[node].base_lo = pci_getl_func(bus, dev,
2878 		    OPT_PCS_FUNC_ADDRMAP, off_lo);
2879 
2880 		if ((dram_map[node].base_lo & OPT_DRAMBASE_LO_MASK_INTRLVEN) &&
2881 		    mem_intrlv)
2882 			*mem_intrlv = *mem_intrlv + 1;
2883 
2884 		off_hi += 4;	/* high limit register offset */
2885 		if (opt_family != AMD_FAMILY_GREYHOUND)
2886 			limit_hi = 0;
2887 		else {
2888 			outl(PCI_CONFADD, OPT_PCI_ECS_ADDR(bus, dev,
2889 			    OPT_PCS_FUNC_ADDRMAP, off_hi));
2890 			limit_hi = dram_map[node].limit_hi =
2891 			    inl(PCI_CONFDATA);
2892 		}
2893 
2894 		off_lo += 4;	/* low limit register offset */
2895 		limit_lo = dram_map[node].limit_lo = pci_getl_func(bus,
2896 		    dev, OPT_PCS_FUNC_ADDRMAP, off_lo);
2897 
2898 		/*
2899 		 * Increment device number to next node and register offsets
2900 		 * for DRAM base register of next node
2901 		 */
2902 		off_hi += 4;
2903 		off_lo += 4;
2904 		dev++;
2905 
2906 		/*
2907 		 * Both read and write enable bits must be enabled in DRAM
2908 		 * address map base register for physical memory to exist in
2909 		 * node
2910 		 */
2911 		if ((base_lo & OPT_DRAMBASE_LO_MASK_RE) == 0 ||
2912 		    (base_lo & OPT_DRAMBASE_LO_MASK_WE) == 0) {
2913 			/*
2914 			 * Mark node memory as non-existent and set start and
2915 			 * end addresses to be same in node_memory[]
2916 			 */
2917 			node_memory[node].exists = 0;
2918 			node_memory[node].start = node_memory[node].end =
2919 			    (pfn_t)-1;
2920 			continue;
2921 		}
2922 
2923 		/*
2924 		 * Mark node memory as existing and remember physical address
2925 		 * range of each node for use later
2926 		 */
2927 		node_memory[node].exists = 1;
2928 
2929 		node_memory[node].start = btop(OPT_DRAMADDR(base_hi, base_lo));
2930 
2931 		node_memory[node].end = btop(OPT_DRAMADDR(limit_hi, limit_lo) |
2932 		    OPT_DRAMADDR_LO_MASK_OFF);
2933 	}
2934 
2935 	/*
2936 	 * Restore PCI Extended Configuration Space enable bit
2937 	 */
2938 	if (opt_family == AMD_FAMILY_GREYHOUND) {
2939 		if ((nb_cfg_reg & AMD_GH_NB_CFG_EN_ECS) == 0)
2940 			wrmsr(MSR_AMD_NB_CFG, nb_cfg_reg);
2941 	}
2942 }
2943 
2944 
2945 /*
2946  * Return average amount of time to read vendor ID register on Northbridge
2947  * N times on specified destination node from current CPU
2948  */
2949 static hrtime_t
2950 opt_probe_vendor(int dest_node, int nreads)
2951 {
2952 	int		cnt;
2953 	uint_t		dev;
2954 	/* LINTED: set but not used in function */
2955 	volatile uint_t	dev_vendor;
2956 	hrtime_t	elapsed;
2957 	hrtime_t	end;
2958 	int		ipl;
2959 	hrtime_t	start;
2960 
2961 	dev = OPT_PCS_DEV_NODE0 + dest_node;
2962 	kpreempt_disable();
2963 	ipl = spl8();
2964 	outl(PCI_CONFADD, PCI_CADDR1(0, dev, OPT_PCS_FUNC_DRAM,
2965 	    OPT_PCS_OFF_VENDOR));
2966 	start = gethrtime();
2967 	for (cnt = 0; cnt < nreads; cnt++)
2968 		dev_vendor = inl(PCI_CONFDATA);
2969 	end = gethrtime();
2970 	elapsed = (end - start) / nreads;
2971 	splx(ipl);
2972 	kpreempt_enable();
2973 	return (elapsed);
2974 }
2975