2 * Copyright (c) 2000-2009 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
32 * Mach Operating System
33 * Copyright (c) 1991,1990,1989,1988,1987 Carnegie Mellon University
34 * All Rights Reserved.
36 * Permission to use, copy, modify and distribute this software and its
37 * documentation is hereby granted, provided that both the copyright
38 * notice and this permission notice appear in all copies of the
39 * software, derivative works or modified versions, and any portions
40 * thereof, and that both notices appear in supporting documentation.
42 * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
43 * CONDITION. CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND FOR
44 * ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
46 * Carnegie Mellon requests users of this software to return to
48 * Software Distribution Coordinator or Software.Distribution@CS.CMU.EDU
49 * School of Computer Science
50 * Carnegie Mellon University
51 * Pittsburgh PA 15213-3890
53 * any improvements or extensions that they make and grant Carnegie Mellon
54 * the rights to redistribute these changes.
60 * Author: Avadis Tevanian, Jr.
62 * Zone-based memory allocator. A zone is a collection of fixed size
63 * data blocks for which quick allocation/deallocation is possible.
65 #include <zone_debug.h>
66 #include <zone_alias_addr.h>
70 #include <mach/mach_types.h>
71 #include <mach/vm_param.h>
72 #include <mach/kern_return.h>
73 #include <mach/mach_host_server.h>
74 #include <mach/task_server.h>
75 #include <mach/machine/vm_types.h>
76 #include <mach_debug/zone_info.h>
78 #include <kern/kern_types.h>
79 #include <kern/assert.h>
80 #include <kern/host.h>
81 #include <kern/macro_help.h>
82 #include <kern/sched.h>
83 #include <kern/locks.h>
84 #include <kern/sched_prim.h>
85 #include <kern/misc_protos.h>
86 #include <kern/thread_call.h>
87 #include <kern/zalloc.h>
88 #include <kern/kalloc.h>
91 #include <vm/vm_map.h>
92 #include <vm/vm_kern.h>
93 #include <vm/vm_page.h>
95 #include <machine/machparam.h>
97 #include <libkern/OSDebug.h>
98 #include <sys/kdebug.h>
101 * Zone Corruption Debugging
103 * We provide three methods to detect use of a zone element after it's been freed. These
104 * checks are enabled by specifying "-zc" and/or "-zp" in the boot-args:
106 * (1) Range-check the free-list "next" ptr for sanity.
107 * (2) Store the ptr in two different words, and compare them against
108 * each other when re-using the zone element, to detect modifications.
109 * (3) poison the freed memory by overwriting it with 0xdeadbeef.
111 * The first two checks are fairly light weight and are enabled by specifying "-zc"
112 * in the boot-args. If you want more aggressive checking for use-after-free bugs
113 * and you don't mind the additional overhead, then turn on poisoning by adding
114 * "-zp" to the boot-args in addition to "-zc". If you specify -zp without -zc,
115 * it still poisons the memory when it's freed, but doesn't check if the memory
116 * has been altered later when it's reallocated.
119 boolean_t check_freed_element
= FALSE
; /* enabled by -zc in boot-args */
120 boolean_t zfree_clear
= FALSE
; /* enabled by -zp in boot-args */
123 * Fake zones for things that want to report via zprint but are not actually zones.
125 struct fake_zone_info
{
129 vm_size_t
*, vm_size_t
*, vm_size_t
*, vm_size_t
*,
130 uint64_t *, int *, int *, int *);
133 static struct fake_zone_info fake_zones
[] = {
135 .name
= "kernel_stacks",
136 .init
= stack_fake_zone_init
,
137 .query
= stack_fake_zone_info
,
139 #if defined(__i386__) || defined (__x86_64__)
141 .name
= "page_tables",
142 .init
= pt_fake_zone_init
,
143 .query
= pt_fake_zone_info
,
147 .name
= "kalloc.large",
148 .init
= kalloc_fake_zone_init
,
149 .query
= kalloc_fake_zone_info
,
152 unsigned int num_fake_zones
= sizeof(fake_zones
)/sizeof(fake_zones
[0]);
157 boolean_t zinfo_per_task
= FALSE
; /* enabled by -zinfop in boot-args */
158 #define ZINFO_SLOTS 200 /* for now */
159 #define ZONES_MAX (ZINFO_SLOTS - num_fake_zones - 1)
162 * Allocation helper macros
164 #define is_kernel_data_addr(a) (!(a) || ((a) >= vm_min_kernel_address && !((a) & 0x3)))
166 #define ADD_TO_ZONE(zone, element) \
171 i < zone->elem_size/sizeof(uint32_t); \
173 ((uint32_t *)(element))[i] = 0xdeadbeef; \
175 *((vm_offset_t *)(element)) = (zone)->free_elements; \
176 if (check_freed_element) { \
177 if ((zone)->elem_size >= (2 * sizeof(vm_offset_t))) \
178 ((vm_offset_t *)(element))[((zone)->elem_size/sizeof(vm_offset_t))-1] = \
179 (zone)->free_elements; \
181 (zone)->free_elements = (vm_offset_t) (element); \
185 #define REMOVE_FROM_ZONE(zone, ret, type) \
187 (ret) = (type) (zone)->free_elements; \
188 if ((ret) != (type) 0) { \
189 if (check_freed_element) { \
190 if (!is_kernel_data_addr(((vm_offset_t *)(ret))[0]) || \
191 ((zone)->elem_size >= (2 * sizeof(vm_offset_t)) && \
192 ((vm_offset_t *)(ret))[((zone)->elem_size/sizeof(vm_offset_t))-1] != \
193 ((vm_offset_t *)(ret))[0])) \
194 panic("a freed zone element has been modified");\
197 for (ii = sizeof(vm_offset_t) / sizeof(uint32_t); \
198 ii < (zone)->elem_size/sizeof(uint32_t) - sizeof(vm_offset_t) / sizeof(uint32_t); \
200 if (((uint32_t *)(ret))[ii] != (uint32_t)0xdeadbeef) \
201 panic("a freed zone element has been modified");\
205 (zone)->sum_count++; \
206 (zone)->free_elements = *((vm_offset_t *)(ret)); \
211 #define zone_debug_enabled(z) z->active_zones.next
212 #define ROUNDUP(x,y) ((((x)+(y)-1)/(y))*(y))
213 #define ZONE_DEBUG_OFFSET ROUNDUP(sizeof(queue_chain_t),16)
214 #endif /* ZONE_DEBUG */
217 * Support for garbage collection of unused zone pages:
220 struct zone_page_table_entry
{
221 struct zone_page_table_entry
*link
;
232 void zone_page_alloc(
236 void zone_page_free_element(
237 struct zone_page_table_entry
**free_pages
,
241 void zone_page_collect(
245 boolean_t
zone_page_collectable(
254 thread_call_param_t p0
,
255 thread_call_param_t p1
);
257 void zone_display_zprint( void );
259 #if ZONE_DEBUG && MACH_KDB
263 #endif /* ZONE_DEBUG && MACH_KDB */
265 vm_map_t zone_map
= VM_MAP_NULL
;
267 zone_t zone_zone
= ZONE_NULL
; /* the zone containing other zones */
269 zone_t zinfo_zone
= ZONE_NULL
; /* zone of per-task zone info */
272 * The VM system gives us an initial chunk of memory.
273 * It has to be big enough to allocate the zone_zone
277 vm_size_t zdata_size
;
279 #define lock_zone(zone) \
281 lck_mtx_lock_spin(&(zone)->lock); \
284 #define unlock_zone(zone) \
286 lck_mtx_unlock(&(zone)->lock); \
289 #define zone_wakeup(zone) thread_wakeup((event_t)(zone))
290 #define zone_sleep(zone) \
291 (void) lck_mtx_sleep(&(zone)->lock, LCK_SLEEP_SPIN, (event_t)(zone), THREAD_UNINT);
294 #define lock_zone_init(zone) \
297 (void) snprintf(_name, sizeof (_name), "zone.%s", (zone)->zone_name); \
298 lck_grp_attr_setdefault(&(zone)->lock_grp_attr); \
299 lck_grp_init(&(zone)->lock_grp, _name, &(zone)->lock_grp_attr); \
300 lck_attr_setdefault(&(zone)->lock_attr); \
301 lck_mtx_init_ext(&(zone)->lock, &(zone)->lock_ext, \
302 &(zone)->lock_grp, &(zone)->lock_attr); \
305 #define lock_try_zone(zone) lck_mtx_try_lock_spin(&zone->lock)
307 kern_return_t
zget_space(
310 vm_offset_t
*result
);
312 decl_simple_lock_data(,zget_space_lock
)
313 vm_offset_t zalloc_next_space
;
314 vm_offset_t zalloc_end_of_space
;
315 vm_size_t zalloc_wasted_space
;
318 * Garbage collection map information
320 struct zone_page_table_entry
* zone_page_table
;
321 vm_offset_t zone_map_min_address
;
322 vm_offset_t zone_map_max_address
;
323 unsigned int zone_pages
;
326 * Exclude more than one concurrent garbage collection
328 decl_lck_mtx_data(, zone_gc_lock
)
330 lck_attr_t zone_lck_attr
;
331 lck_grp_t zone_lck_grp
;
332 lck_grp_attr_t zone_lck_grp_attr
;
333 lck_mtx_ext_t zone_lck_ext
;
337 #define from_zone_map(addr, size) \
338 ((vm_offset_t)(addr) >= zone_map_min_address && \
339 ((vm_offset_t)(addr) + size -1) < zone_map_max_address)
341 #define from_zone_map(addr, size) \
342 ((vm_offset_t)(zone_virtual_addr((vm_map_address_t)addr)) >= zone_map_min_address && \
343 ((vm_offset_t)(zone_virtual_addr((vm_map_address_t)addr)) + size -1) < zone_map_max_address)
346 #define ZONE_PAGE_USED 0
347 #define ZONE_PAGE_UNUSED -1
351 * Protects first_zone, last_zone, num_zones,
352 * and the next_zone field of zones.
354 decl_simple_lock_data(, all_zones_lock
)
357 unsigned int num_zones
;
359 boolean_t zone_gc_allowed
= TRUE
;
360 boolean_t zone_gc_forced
= FALSE
;
361 boolean_t panic_include_zprint
= FALSE
;
362 boolean_t zone_gc_allowed_by_time_throttle
= TRUE
;
365 * Zone leak debugging code
367 * When enabled, this code keeps a log to track allocations to a particular zone that have not
368 * yet been freed. Examining this log will reveal the source of a zone leak. The log is allocated
369 * only when logging is enabled, so there is no effect on the system when it's turned off. Logging is
372 * Enable the logging via the boot-args. Add the parameter "zlog=<zone>" to boot-args where <zone>
373 * is the name of the zone you wish to log.
375 * This code only tracks one zone, so you need to identify which one is leaking first.
376 * Generally, you'll know you have a leak when you get a "zalloc retry failed 3" panic from the zone
377 * garbage collector. Note that the zone name printed in the panic message is not necessarily the one
378 * containing the leak. So do a zprint from gdb and locate the zone with the bloated size. This
379 * is most likely the problem zone, so set zlog in boot-args to this zone name, reboot and re-run the test. The
380 * next time it panics with this message, examine the log using the kgmacros zstack, findoldest and countpcs.
381 * See the help in the kgmacros for usage info.
384 * Zone corruption logging
386 * Logging can also be used to help identify the source of a zone corruption. First, identify the zone
387 * that is being corrupted, then add "-zc zlog=<zone name>" to the boot-args. When -zc is used in conjunction
388 * with zlog, it changes the logging style to track both allocations and frees to the zone. So when the
389 * corruption is detected, examining the log will show you the stack traces of the callers who last allocated
390 * and freed any particular element in the zone. Use the findelem kgmacro with the address of the element that's been
391 * corrupted to examine its history. This should lead to the source of the corruption.
394 static int log_records
; /* size of the log, expressed in number of records */
396 #define MAX_ZONE_NAME 32 /* max length of a zone name we can take from the boot-args */
398 static char zone_name_to_log
[MAX_ZONE_NAME
] = ""; /* the zone name we're logging, if any */
401 * The number of records in the log is configurable via the zrecs parameter in boot-args. Set this to
402 * the number of records you want in the log. For example, "zrecs=1000" sets it to 1000 records. Note
403 * that the larger the size of the log, the slower the system will run due to linear searching in the log,
404 * but one doesn't generally care about performance when tracking down a leak. The log is capped at 8000
405 * records since going much larger than this tends to make the system unresponsive and unbootable on small
406 * memory configurations. The default value is 4000 records.
408 #if defined(__LP64__)
409 #define ZRECORDS_MAX 16000 /* Max records allowed in the log */
411 #define ZRECORDS_MAX 8000 /* Max records allowed in the log */
413 #define ZRECORDS_DEFAULT 4000 /* default records in log if zrecs is not specificed in boot-args */
416 * Each record in the log contains a pointer to the zone element it refers to, a "time" number that allows
417 * the records to be ordered chronologically, and a small array to hold the pc's from the stack trace. A
418 * record is added to the log each time a zalloc() is done in the zone_of_interest. For leak debugging,
419 * the record is cleared when a zfree() is done. For corruption debugging, the log tracks both allocs and frees.
420 * If the log fills, old records are replaced as if it were a circular buffer.
424 void *z_element
; /* the element that was zalloc'ed of zfree'ed */
425 uint32_t z_opcode
:1, /* whether it was a zalloc or zfree */
426 z_time
:31; /* time index when operation was done */
427 void *z_pc
[MAX_ZTRACE_DEPTH
]; /* stack trace of caller */
431 * Opcodes for the z_opcode field:
438 * The allocation log and all the related variables are protected by the zone lock for the zone_of_interest
441 static struct zrecord
*zrecords
; /* the log itself, dynamically allocated when logging is enabled */
442 static int zcurrent
= 0; /* index of the next slot in the log to use */
443 static int zrecorded
= 0; /* number of allocations recorded in the log */
444 static unsigned int ztime
= 0; /* a timestamp of sorts */
445 static zone_t zone_of_interest
= NULL
; /* the zone being watched; corresponds to zone_name_to_log */
448 * Decide if we want to log this zone by doing a string compare between a zone name and the name
449 * of the zone to log. Return true if the strings are equal, false otherwise. Because it's not
450 * possible to include spaces in strings passed in via the boot-args, a period in the logname will
451 * match a space in the zone name.
455 log_this_zone(const char *zonename
, const char *logname
)
458 const char *zc
= zonename
;
459 const char *lc
= logname
;
462 * Compare the strings. We bound the compare by MAX_ZONE_NAME.
465 for (len
= 1; len
<= MAX_ZONE_NAME
; zc
++, lc
++, len
++) {
468 * If the current characters don't match, check for a space in
469 * in the zone name and a corresponding period in the log name.
470 * If that's not there, then the strings don't match.
473 if (*zc
!= *lc
&& !(*zc
== ' ' && *lc
== '.'))
477 * The strings are equal so far. If we're at the end, then it's a match.
489 * Test if we want to log this zalloc/zfree event. We log if this is the zone we're interested in and
490 * the buffer for the records has been allocated.
493 #define DO_LOGGING(z) (zrecords && (z) == zone_of_interest)
495 extern boolean_t zlog_ready
;
499 #pragma mark Zone Leak Detection
502 * The zone leak detector, abbreviated 'zleak', keeps track of a subset of the currently outstanding
503 * allocations made by the zone allocator. Every z_sample_factor allocations in each zone, we capture a
504 * backtrace. Every free, we examine the table and determine if the allocation was being tracked,
505 * and stop tracking it if it was being tracked.
507 * We track the allocations in the zallocations hash table, which stores the address that was returned from
508 * the zone allocator. Each stored entry in the zallocations table points to an entry in the ztraces table, which
509 * stores the backtrace associated with that allocation. This provides uniquing for the relatively large
510 * backtraces - we don't store them more than once.
512 * Data collection begins when the zone map is 50% full, and only occurs for zones that are taking up
513 * a large amount of virtual space.
515 #define ZLEAK_STATE_ENABLED 0x01 /* Zone leak monitoring should be turned on if zone_map fills up. */
516 #define ZLEAK_STATE_ACTIVE 0x02 /* We are actively collecting traces. */
517 #define ZLEAK_STATE_ACTIVATING 0x04 /* Some thread is doing setup; others should move along. */
518 #define ZLEAK_STATE_FAILED 0x08 /* Attempt to allocate tables failed. We will not try again. */
519 uint32_t zleak_state
= 0; /* State of collection, as above */
521 boolean_t panic_include_ztrace
= FALSE
; /* Enable zleak logging on panic */
522 vm_size_t zleak_global_tracking_threshold
; /* Size of zone map at which to start collecting data */
523 vm_size_t zleak_per_zone_tracking_threshold
; /* Size a zone will have before we will collect data on it */
524 unsigned int z_sample_factor
= 1000; /* Allocations per sample attempt */
527 * Counters for allocation statistics.
530 /* Times two active records want to occupy the same spot */
531 unsigned int z_alloc_collisions
= 0;
532 unsigned int z_trace_collisions
= 0;
534 /* Times a new record lands on a spot previously occupied by a freed allocation */
535 unsigned int z_alloc_overwrites
= 0;
536 unsigned int z_trace_overwrites
= 0;
538 /* Times a new alloc or trace is put into the hash table */
539 unsigned int z_alloc_recorded
= 0;
540 unsigned int z_trace_recorded
= 0;
542 /* Times zleak_log returned false due to not being able to acquire the lock */
543 unsigned int z_total_conflicts
= 0;
546 #pragma mark struct zallocation
548 * Structure for keeping track of an allocation
549 * An allocation bucket is in use if its element is not NULL
552 uintptr_t za_element
; /* the element that was zalloc'ed or zfree'ed, NULL if bucket unused */
553 vm_size_t za_size
; /* how much memory did this allocation take up? */
554 uint32_t za_trace_index
; /* index into ztraces for backtrace associated with allocation */
555 /* TODO: #if this out */
556 uint32_t za_hit_count
; /* for determining effectiveness of hash function */
559 /* Size must be a power of two for the zhash to be able to just mask off bits instead of mod */
560 #define ZLEAK_ALLOCATION_MAP_NUM 16384
561 #define ZLEAK_TRACE_MAP_NUM 8192
563 uint32_t zleak_alloc_buckets
= ZLEAK_ALLOCATION_MAP_NUM
;
564 uint32_t zleak_trace_buckets
= ZLEAK_TRACE_MAP_NUM
;
566 vm_size_t zleak_max_zonemap_size
;
568 /* Hashmaps of allocations and their corresponding traces */
569 static struct zallocation
* zallocations
;
570 static struct ztrace
* ztraces
;
572 /* not static so that panic can see this, see kern/debug.c */
573 struct ztrace
* top_ztrace
;
575 /* Lock to protect zallocations, ztraces, and top_ztrace from concurrent modification. */
576 static lck_mtx_t zleak_lock
;
577 static lck_attr_t zleak_lock_attr
;
578 static lck_grp_t zleak_lock_grp
;
579 static lck_grp_attr_t zleak_lock_grp_attr
;
582 * Initializes the zone leak monitor. Called from zone_init()
585 zleak_init(vm_size_t max_zonemap_size
)
587 char scratch_buf
[16];
588 boolean_t zleak_enable_flag
= FALSE
;
590 zleak_max_zonemap_size
= max_zonemap_size
;
591 zleak_global_tracking_threshold
= max_zonemap_size
/ 2;
592 zleak_per_zone_tracking_threshold
= zleak_global_tracking_threshold
/ 8;
594 /* -zleakoff (flag to disable zone leak monitor) */
595 if (PE_parse_boot_argn("-zleakoff", scratch_buf
, sizeof(scratch_buf
))) {
596 zleak_enable_flag
= FALSE
;
597 printf("zone leak detection disabled\n");
599 zleak_enable_flag
= TRUE
;
600 printf("zone leak detection enabled\n");
603 /* zfactor=XXXX (override how often to sample the zone allocator) */
604 if (PE_parse_boot_argn("zfactor", &z_sample_factor
, sizeof(z_sample_factor
))) {
605 printf("Zone leak factor override:%u\n", z_sample_factor
);
608 /* zleak-allocs=XXXX (override number of buckets in zallocations) */
609 if (PE_parse_boot_argn("zleak-allocs", &zleak_alloc_buckets
, sizeof(zleak_alloc_buckets
))) {
610 printf("Zone leak alloc buckets override:%u\n", zleak_alloc_buckets
);
611 /* uses 'is power of 2' trick: (0x01000 & 0x00FFF == 0) */
612 if (zleak_alloc_buckets
== 0 || (zleak_alloc_buckets
& (zleak_alloc_buckets
-1))) {
613 printf("Override isn't a power of two, bad things might happen!");
617 /* zleak-traces=XXXX (override number of buckets in ztraces) */
618 if (PE_parse_boot_argn("zleak-traces", &zleak_trace_buckets
, sizeof(zleak_trace_buckets
))) {
619 printf("Zone leak trace buckets override:%u\n", zleak_trace_buckets
);
620 /* uses 'is power of 2' trick: (0x01000 & 0x00FFF == 0) */
621 if (zleak_trace_buckets
== 0 || (zleak_trace_buckets
& (zleak_trace_buckets
-1))) {
622 printf("Override isn't a power of two, bad things might happen!");
626 /* allocate the zleak_lock */
627 lck_grp_attr_setdefault(&zleak_lock_grp_attr
);
628 lck_grp_init(&zleak_lock_grp
, "zleak_lock", &zleak_lock_grp_attr
);
629 lck_attr_setdefault(&zleak_lock_attr
);
630 lck_mtx_init(&zleak_lock
, &zleak_lock_grp
, &zleak_lock_attr
);
632 if (zleak_enable_flag
) {
633 zleak_state
= ZLEAK_STATE_ENABLED
;
640 * Support for kern.zleak.active sysctl - a simplified
641 * simplified version of the zleak_state variable.
644 get_zleak_state(void)
646 if (zleak_state
& ZLEAK_STATE_FAILED
)
648 if (zleak_state
& ZLEAK_STATE_ACTIVE
)
659 kern_return_t retval
;
660 vm_size_t z_alloc_size
= zleak_alloc_buckets
* sizeof(struct zallocation
);
661 vm_size_t z_trace_size
= zleak_trace_buckets
* sizeof(struct ztrace
);
662 void *allocations_ptr
= NULL
;
663 void *traces_ptr
= NULL
;
665 /* Only one thread attempts to activate at a time */
666 if (zleak_state
& (ZLEAK_STATE_ACTIVE
| ZLEAK_STATE_ACTIVATING
| ZLEAK_STATE_FAILED
)) {
670 /* Indicate that we're doing the setup */
671 lck_mtx_lock_spin(&zleak_lock
);
672 if (zleak_state
& (ZLEAK_STATE_ACTIVE
| ZLEAK_STATE_ACTIVATING
| ZLEAK_STATE_FAILED
)) {
673 lck_mtx_unlock(&zleak_lock
);
677 zleak_state
|= ZLEAK_STATE_ACTIVATING
;
678 lck_mtx_unlock(&zleak_lock
);
680 /* Allocate and zero tables */
681 retval
= kmem_alloc_kobject(kernel_map
, (vm_offset_t
*)&allocations_ptr
, z_alloc_size
);
682 if (retval
!= KERN_SUCCESS
) {
686 retval
= kmem_alloc_kobject(kernel_map
, (vm_offset_t
*)&traces_ptr
, z_trace_size
);
687 if (retval
!= KERN_SUCCESS
) {
691 bzero(allocations_ptr
, z_alloc_size
);
692 bzero(traces_ptr
, z_trace_size
);
694 /* Everything's set. Install tables, mark active. */
695 zallocations
= allocations_ptr
;
696 ztraces
= traces_ptr
;
699 * Initialize the top_ztrace to the first entry in ztraces,
700 * so we don't have to check for null in zleak_log
702 top_ztrace
= &ztraces
[0];
705 * Note that we do need a barrier between installing
706 * the tables and setting the active flag, because the zfree()
707 * path accesses the table without a lock if we're active.
709 lck_mtx_lock_spin(&zleak_lock
);
710 zleak_state
|= ZLEAK_STATE_ACTIVE
;
711 zleak_state
&= ~ZLEAK_STATE_ACTIVATING
;
712 lck_mtx_unlock(&zleak_lock
);
718 * If we fail to allocate memory, don't further tax
719 * the system by trying again.
721 lck_mtx_lock_spin(&zleak_lock
);
722 zleak_state
|= ZLEAK_STATE_FAILED
;
723 zleak_state
&= ~ZLEAK_STATE_ACTIVATING
;
724 lck_mtx_unlock(&zleak_lock
);
726 if (allocations_ptr
!= NULL
) {
727 kmem_free(kernel_map
, (vm_offset_t
)allocations_ptr
, z_alloc_size
);
730 if (traces_ptr
!= NULL
) {
731 kmem_free(kernel_map
, (vm_offset_t
)traces_ptr
, z_trace_size
);
738 * TODO: What about allocations that never get deallocated,
739 * especially ones with unique backtraces? Should we wait to record
740 * until after boot has completed?
741 * (How many persistent zallocs are there?)
745 * This function records the allocation in the allocations table,
746 * and stores the associated backtrace in the traces table
747 * (or just increments the refcount if the trace is already recorded)
748 * If the allocation slot is in use, the old allocation is replaced with the new allocation, and
749 * the associated trace's refcount is decremented.
750 * If the trace slot is in use, it returns.
751 * The refcount is incremented by the amount of memory the allocation consumes.
752 * The return value indicates whether to try again next time.
755 zleak_log(uintptr_t* bt
,
758 vm_size_t allocation_size
)
760 /* Quit if there's someone else modifying the hash tables */
761 if (!lck_mtx_try_lock_spin(&zleak_lock
)) {
766 struct zallocation
* allocation
= &zallocations
[hashaddr(addr
, zleak_alloc_buckets
)];
768 uint32_t trace_index
= hashbacktrace(bt
, depth
, zleak_trace_buckets
);
769 struct ztrace
* trace
= &ztraces
[trace_index
];
771 allocation
->za_hit_count
++;
772 trace
->zt_hit_count
++;
775 * If the allocation bucket we want to be in is occupied, and if the occupier
776 * has the same trace as us, just bail.
778 if (allocation
->za_element
!= (uintptr_t) 0 && trace_index
== allocation
->za_trace_index
) {
779 z_alloc_collisions
++;
781 lck_mtx_unlock(&zleak_lock
);
785 /* STEP 1: Store the backtrace in the traces array. */
786 /* A size of zero indicates that the trace bucket is free. */
788 if (trace
->zt_size
> 0 && bcmp(trace
->zt_stack
, bt
, (depth
* sizeof(uintptr_t))) != 0 ) {
790 * Different unique trace with same hash!
791 * Just bail - if we're trying to record the leaker, hopefully the other trace will be deallocated
792 * and get out of the way for later chances
794 trace
->zt_collisions
++;
795 z_trace_collisions
++;
797 lck_mtx_unlock(&zleak_lock
);
799 } else if (trace
->zt_size
> 0) {
800 /* Same trace, already added, so increment refcount */
801 trace
->zt_size
+= allocation_size
;
803 /* Found an unused trace bucket, record the trace here! */
804 if (trace
->zt_depth
!= 0) /* if this slot was previously used but not currently in use */
805 z_trace_overwrites
++;
808 trace
->zt_size
= allocation_size
;
809 memcpy(trace
->zt_stack
, bt
, (depth
* sizeof(uintptr_t)) );
811 trace
->zt_depth
= depth
;
812 trace
->zt_collisions
= 0;
815 /* STEP 2: Store the allocation record in the allocations array. */
817 if (allocation
->za_element
!= (uintptr_t) 0) {
819 * Straight up replace any allocation record that was there. We don't want to do the work
820 * to preserve the allocation entries that were there, because we only record a subset of the
821 * allocations anyways.
824 z_alloc_collisions
++;
826 struct ztrace
* associated_trace
= &ztraces
[allocation
->za_trace_index
];
827 /* Knock off old allocation's size, not the new allocation */
828 associated_trace
->zt_size
-= allocation
->za_size
;
829 } else if (allocation
->za_trace_index
!= 0) {
830 /* Slot previously used but not currently in use */
831 z_alloc_overwrites
++;
834 allocation
->za_element
= addr
;
835 allocation
->za_trace_index
= trace_index
;
836 allocation
->za_size
= allocation_size
;
840 if (top_ztrace
->zt_size
< trace
->zt_size
)
843 lck_mtx_unlock(&zleak_lock
);
848 * Free the allocation record and release the stacktrace.
849 * This should be as fast as possible because it will be called for every free.
852 zleak_free(uintptr_t addr
,
853 vm_size_t allocation_size
)
855 if (addr
== (uintptr_t) 0)
858 struct zallocation
* allocation
= &zallocations
[hashaddr(addr
, zleak_alloc_buckets
)];
860 /* Double-checked locking: check to find out if we're interested, lock, check to make
861 * sure it hasn't changed, then modify it, and release the lock.
864 if (allocation
->za_element
== addr
&& allocation
->za_trace_index
< zleak_trace_buckets
) {
865 /* if the allocation was the one, grab the lock, check again, then delete it */
866 lck_mtx_lock_spin(&zleak_lock
);
868 if (allocation
->za_element
== addr
&& allocation
->za_trace_index
< zleak_trace_buckets
) {
869 struct ztrace
*trace
;
871 /* allocation_size had better match what was passed into zleak_log - otherwise someone is freeing into the wrong zone! */
872 if (allocation
->za_size
!= allocation_size
) {
873 panic("Freeing as size %lu memory that was allocated with size %lu\n",
874 (uintptr_t)allocation_size
, (uintptr_t)allocation
->za_size
);
877 trace
= &ztraces
[allocation
->za_trace_index
];
879 /* size of 0 indicates trace bucket is unused */
880 if (trace
->zt_size
> 0) {
881 trace
->zt_size
-= allocation_size
;
884 /* A NULL element means the allocation bucket is unused */
885 allocation
->za_element
= 0;
887 lck_mtx_unlock(&zleak_lock
);
891 #endif /* CONFIG_ZLEAKS */
893 /* These functions outside of CONFIG_ZLEAKS because they are also used in
894 * mbuf.c for mbuf leak-detection. This is why they lack the z_ prefix.
898 * This function captures a backtrace from the current stack and
899 * returns the number of frames captured, limited by max_frames.
900 * It's fast because it does no checking to make sure there isn't bad data.
901 * Since it's only called from threads that we're going to keep executing,
902 * if there's bad data we were going to die eventually.
903 * This seems to work for x86 and X86_64.
904 * ARMTODO: Test it on ARM, I think it will work but I can't test it. If it works, remove the ifdef.
905 * If this function is inlined, it doesn't record the frame of the function it's inside.
906 * (because there's no stack frame!)
909 fastbacktrace(uintptr_t* bt
, uint32_t max_frames
)
911 #if defined(__x86_64__) || defined(__i386__)
912 uintptr_t* frameptr
= NULL
, *frameptr_next
= NULL
;
913 uintptr_t retaddr
= 0;
914 uint32_t frame_index
= 0, frames
= 0;
915 uintptr_t kstackb
, kstackt
;
917 kstackb
= current_thread()->kernel_stack
;
918 kstackt
= kstackb
+ kernel_stack_size
;
919 /* Load stack frame pointer (EBP on x86) into frameptr */
920 frameptr
= __builtin_frame_address(0);
922 while (frameptr
!= NULL
&& frame_index
< max_frames
) {
923 /* Next frame pointer is pointed to by the previous one */
924 frameptr_next
= (uintptr_t*) *frameptr
;
926 /* Bail if we see a zero in the stack frame, that means we've reached the top of the stack */
927 /* That also means the return address is worthless, so don't record it */
928 if (frameptr_next
== NULL
)
930 /* Verify thread stack bounds */
931 if (((uintptr_t)frameptr_next
> kstackt
) || ((uintptr_t)frameptr_next
< kstackb
))
933 /* Pull return address from one spot above the frame pointer */
934 retaddr
= *(frameptr
+ 1);
936 /* Store it in the backtrace array */
937 bt
[frame_index
++] = retaddr
;
939 frameptr
= frameptr_next
;
942 /* Save the number of frames captured for return value */
943 frames
= frame_index
;
945 /* Fill in the rest of the backtrace with zeros */
946 while (frame_index
< max_frames
)
947 bt
[frame_index
++] = 0;
951 return OSBacktrace((void*)bt
, max_frames
);
955 /* "Thomas Wang's 32/64 bit mix functions." http://www.concentric.net/~Ttwang/tech/inthash.htm */
957 hash_mix(uintptr_t x
)
980 hashbacktrace(uintptr_t* bt
, uint32_t depth
, uint32_t max_size
)
984 uintptr_t mask
= max_size
- 1;
990 hash
= hash_mix(hash
) & mask
;
992 assert(hash
< max_size
);
994 return (uint32_t) hash
;
998 * TODO: Determine how well distributed this is
999 * max_size must be a power of 2. i.e 0x10000 because 0x10000-1 is 0x0FFFF which is a great bitmask
1002 hashaddr(uintptr_t pt
, uint32_t max_size
)
1005 uintptr_t mask
= max_size
- 1;
1007 hash
= hash_mix(pt
) & mask
;
1009 assert(hash
< max_size
);
1011 return (uint32_t) hash
;
1014 /* End of all leak-detection code */
1018 * zinit initializes a new zone. The zone data structures themselves
1019 * are stored in a zone, which is initially a static structure that
1020 * is initialized by zone_init.
1024 vm_size_t size
, /* the size of an element */
1025 vm_size_t max
, /* maximum memory to use */
1026 vm_size_t alloc
, /* allocation size */
1027 const char *name
) /* a name for the zone */
1031 if (zone_zone
== ZONE_NULL
) {
1032 if (zget_space(NULL
, sizeof(struct zone
), (vm_offset_t
*)&z
)
1036 z
= (zone_t
) zalloc(zone_zone
);
1041 * Round off all the parameters appropriately.
1043 if (size
< sizeof(z
->free_elements
))
1044 size
= sizeof(z
->free_elements
);
1045 size
= ((size
-1) + sizeof(z
->free_elements
)) -
1046 ((size
-1) % sizeof(z
->free_elements
));
1049 alloc
= round_page(alloc
);
1050 max
= round_page(max
);
1052 * we look for an allocation size with less than 1% waste
1053 * up to 5 pages in size...
1054 * otherwise, we look for an allocation size with least fragmentation
1055 * in the range of 1 - 5 pages
1056 * This size will be used unless
1057 * the user suggestion is larger AND has less fragmentation
1060 if ((size
< PAGE_SIZE
) && (PAGE_SIZE
% size
<= PAGE_SIZE
/ 10))
1064 { vm_size_t best
, waste
; unsigned int i
;
1066 waste
= best
% size
;
1068 for (i
= 1; i
<= 5; i
++) {
1069 vm_size_t tsize
, twaste
;
1071 tsize
= i
* PAGE_SIZE
;
1073 if ((tsize
% size
) < (tsize
/ 100)) {
1075 goto use_this_allocation
;
1077 twaste
= tsize
% size
;
1079 best
= tsize
, waste
= twaste
;
1081 if (alloc
<= best
|| (alloc
% size
>= waste
))
1084 use_this_allocation
:
1085 if (max
&& (max
< alloc
))
1088 z
->free_elements
= 0;
1091 z
->elem_size
= size
;
1092 z
->alloc_size
= alloc
;
1093 z
->zone_name
= name
;
1096 z
->doing_alloc
= FALSE
;
1097 z
->doing_gc
= FALSE
;
1098 z
->exhaustible
= FALSE
;
1099 z
->collectable
= TRUE
;
1100 z
->allows_foreign
= FALSE
;
1101 z
->expandable
= TRUE
;
1103 z
->async_pending
= FALSE
;
1104 z
->caller_acct
= TRUE
;
1105 z
->noencrypt
= FALSE
;
1110 z
->zleak_capture
= 0;
1111 z
->zleak_on
= FALSE
;
1112 #endif /* CONFIG_ZLEAKS */
1115 z
->active_zones
.next
= z
->active_zones
.prev
= NULL
;
1116 zone_debug_enable(z
);
1117 #endif /* ZONE_DEBUG */
1121 * Add the zone to the all-zones list.
1122 * If we are tracking zone info per task, and we have
1123 * already used all the available stat slots, then keep
1124 * using the overflow zone slot.
1126 z
->next_zone
= ZONE_NULL
;
1127 thread_call_setup(&z
->call_async_alloc
, zalloc_async
, z
);
1128 simple_lock(&all_zones_lock
);
1130 last_zone
= &z
->next_zone
;
1131 z
->index
= num_zones
;
1132 if (zinfo_per_task
) {
1133 if (num_zones
> ZONES_MAX
)
1134 z
->index
= ZONES_MAX
;
1137 simple_unlock(&all_zones_lock
);
1140 * Check if we should be logging this zone. If so, remember the zone pointer.
1143 if (log_this_zone(z
->zone_name
, zone_name_to_log
)) {
1144 zone_of_interest
= z
;
1148 * If we want to log a zone, see if we need to allocate buffer space for the log. Some vm related zones are
1149 * zinit'ed before we can do a kmem_alloc, so we have to defer allocation in that case. zlog_ready is set to
1150 * TRUE once enough of the VM system is up and running to allow a kmem_alloc to work. If we want to log one
1151 * of the VM related zones that's set up early on, we will skip allocation of the log until zinit is called again
1152 * later on some other zone. So note we may be allocating a buffer to log a zone other than the one being initialized
1156 if (zone_of_interest
!= NULL
&& zrecords
== NULL
&& zlog_ready
) {
1157 if (kmem_alloc(kernel_map
, (vm_offset_t
*)&zrecords
, log_records
* sizeof(struct zrecord
)) == KERN_SUCCESS
) {
1160 * We got the memory for the log. Zero it out since the code needs this to identify unused records.
1161 * At this point, everything is set up and we're ready to start logging this zone.
1164 bzero((void *)zrecords
, log_records
* sizeof(struct zrecord
));
1165 printf("zone: logging started for zone %s (%p)\n", zone_of_interest
->zone_name
, zone_of_interest
);
1168 printf("zone: couldn't allocate memory for zrecords, turning off zleak logging\n");
1169 zone_of_interest
= NULL
;
1177 * Cram the given memory into the specified zone.
1181 register zone_t zone
,
1185 register vm_size_t elem_size
;
1186 vm_offset_t newmem
= (vm_offset_t
) newaddr
;
1188 /* Basic sanity checks */
1189 assert(zone
!= ZONE_NULL
&& newmem
!= (vm_offset_t
)0);
1190 assert(!zone
->collectable
|| zone
->allows_foreign
1191 || (from_zone_map(newmem
, size
)));
1193 elem_size
= zone
->elem_size
;
1196 while (size
>= elem_size
) {
1197 ADD_TO_ZONE(zone
, newmem
);
1198 if (from_zone_map(newmem
, elem_size
))
1199 zone_page_alloc(newmem
, elem_size
);
1200 zone
->count
++; /* compensate for ADD_TO_ZONE */
1202 newmem
+= elem_size
;
1203 zone
->cur_size
+= elem_size
;
1209 * Contiguous space allocator for non-paged zones. Allocates "size" amount
1210 * of memory from zone_map.
1217 vm_offset_t
*result
)
1219 vm_offset_t new_space
= 0;
1220 vm_size_t space_to_add
= 0;
1222 simple_lock(&zget_space_lock
);
1223 while ((zalloc_next_space
+ size
) > zalloc_end_of_space
) {
1225 * Add at least one page to allocation area.
1228 space_to_add
= round_page(size
);
1230 if (new_space
== 0) {
1231 kern_return_t retval
;
1232 int zflags
= KMA_KOBJECT
|KMA_NOPAGEWAIT
;
1235 * Memory cannot be wired down while holding
1236 * any locks that the pageout daemon might
1237 * need to free up pages. [Making the zget_space
1238 * lock a complex lock does not help in this
1241 * Unlock and allocate memory. Because several
1242 * threads might try to do this at once, don't
1243 * use the memory before checking for available
1247 simple_unlock(&zget_space_lock
);
1249 if (zone
== NULL
|| zone
->noencrypt
)
1250 zflags
|= KMA_NOENCRYPT
;
1252 retval
= kernel_memory_allocate(zone_map
, &new_space
, space_to_add
, 0, zflags
);
1253 if (retval
!= KERN_SUCCESS
)
1256 if (space_to_add
== PAGE_SIZE
)
1257 new_space
= zone_alias_addr(new_space
);
1259 zone_page_init(new_space
, space_to_add
,
1261 simple_lock(&zget_space_lock
);
1267 * Memory was allocated in a previous iteration.
1269 * Check whether the new region is contiguous
1273 if (new_space
!= zalloc_end_of_space
) {
1275 * Throw away the remainder of the
1276 * old space, and start a new one.
1278 zalloc_wasted_space
+=
1279 zalloc_end_of_space
- zalloc_next_space
;
1280 zalloc_next_space
= new_space
;
1283 zalloc_end_of_space
= new_space
+ space_to_add
;
1287 *result
= zalloc_next_space
;
1288 zalloc_next_space
+= size
;
1289 simple_unlock(&zget_space_lock
);
1292 kmem_free(zone_map
, new_space
, space_to_add
);
1294 return(KERN_SUCCESS
);
1299 * Steal memory for the zone package. Called from
1300 * vm_page_bootstrap().
1303 zone_steal_memory(void)
1305 zdata_size
= round_page(128*sizeof(struct zone
));
1306 zdata
= (vm_offset_t
)((char *)pmap_steal_memory(zdata_size
) - (char *)0);
1311 * Fill a zone with enough memory to contain at least nelem elements.
1312 * Memory is obtained with kmem_alloc_kobject from the kernel_map.
1313 * Return the number of elements actually put into the zone, which may
1314 * be more than the caller asked for since the memory allocation is
1315 * rounded up to a full page.
1330 size
= nelem
* zone
->elem_size
;
1331 size
= round_page(size
);
1332 kr
= kmem_alloc_kobject(kernel_map
, &memory
, size
);
1333 if (kr
!= KERN_SUCCESS
)
1336 zone_change(zone
, Z_FOREIGN
, TRUE
);
1337 zcram(zone
, (void *)memory
, size
);
1338 nalloc
= (int)(size
/ zone
->elem_size
);
1339 assert(nalloc
>= nelem
);
1345 * Initialize the "zone of zones" which uses fixed memory allocated
1346 * earlier in memory initialization. zone_bootstrap is called
1350 zone_bootstrap(void)
1352 vm_size_t zone_zone_size
;
1353 vm_offset_t zone_zone_space
;
1357 /* enable zone checks by default, to try and catch offenders... */
1359 /* 7968354: turn "-zc" back off */
1360 check_freed_element
= TRUE
;
1361 /* 7995202: turn "-zp" back off */
1365 /* ... but allow them to be turned off explicitely */
1366 if (PE_parse_boot_argn("-no_zc", temp_buf
, sizeof (temp_buf
))) {
1367 check_freed_element
= FALSE
;
1369 if (PE_parse_boot_argn("-no_zp", temp_buf
, sizeof (temp_buf
))) {
1370 zfree_clear
= FALSE
;
1374 /* see if we want freed zone element checking and/or poisoning */
1375 if (PE_parse_boot_argn("-zc", temp_buf
, sizeof (temp_buf
))) {
1376 check_freed_element
= TRUE
;
1379 if (PE_parse_boot_argn("-zp", temp_buf
, sizeof (temp_buf
))) {
1383 if (PE_parse_boot_argn("-zinfop", temp_buf
, sizeof (temp_buf
))) {
1384 zinfo_per_task
= TRUE
;
1388 * Check for and set up zone leak detection if requested via boot-args. We recognized two
1391 * zlog=<zone_to_log>
1392 * zrecs=<num_records_in_log>
1394 * The zlog arg is used to specify the zone name that should be logged, and zrecs is used to
1395 * control the size of the log. If zrecs is not specified, a default value is used.
1398 if (PE_parse_boot_argn("zlog", zone_name_to_log
, sizeof(zone_name_to_log
)) == TRUE
) {
1399 if (PE_parse_boot_argn("zrecs", &log_records
, sizeof(log_records
)) == TRUE
) {
1402 * Don't allow more than ZRECORDS_MAX records even if the user asked for more.
1403 * This prevents accidentally hogging too much kernel memory and making the system
1407 log_records
= MIN(ZRECORDS_MAX
, log_records
);
1410 log_records
= ZRECORDS_DEFAULT
;
1414 simple_lock_init(&all_zones_lock
, 0);
1416 first_zone
= ZONE_NULL
;
1417 last_zone
= &first_zone
;
1420 simple_lock_init(&zget_space_lock
, 0);
1421 zalloc_next_space
= zdata
;
1422 zalloc_end_of_space
= zdata
+ zdata_size
;
1423 zalloc_wasted_space
= 0;
1425 /* assertion: nobody else called zinit before us */
1426 assert(zone_zone
== ZONE_NULL
);
1427 zone_zone
= zinit(sizeof(struct zone
), 128 * sizeof(struct zone
),
1428 sizeof(struct zone
), "zones");
1429 zone_change(zone_zone
, Z_COLLECT
, FALSE
);
1430 zone_change(zone_zone
, Z_CALLERACCT
, FALSE
);
1431 zone_change(zone_zone
, Z_NOENCRYPT
, TRUE
);
1433 zone_zone_size
= zalloc_end_of_space
- zalloc_next_space
;
1434 zget_space(NULL
, zone_zone_size
, &zone_zone_space
);
1435 zcram(zone_zone
, (void *)zone_zone_space
, zone_zone_size
);
1437 /* initialize fake zones and zone info if tracking by task */
1438 if (zinfo_per_task
) {
1439 vm_size_t zisize
= sizeof(zinfo_usage_store_t
) * ZINFO_SLOTS
;
1442 for (i
= 0; i
< num_fake_zones
; i
++)
1443 fake_zones
[i
].init(ZINFO_SLOTS
- num_fake_zones
+ i
);
1444 zinfo_zone
= zinit(zisize
, zisize
* CONFIG_TASK_MAX
,
1445 zisize
, "per task zinfo");
1446 zone_change(zinfo_zone
, Z_CALLERACCT
, FALSE
);
1451 zinfo_task_init(task_t task
)
1453 if (zinfo_per_task
) {
1454 task
->tkm_zinfo
= zalloc(zinfo_zone
);
1455 memset(task
->tkm_zinfo
, 0, sizeof(zinfo_usage_store_t
) * ZINFO_SLOTS
);
1457 task
->tkm_zinfo
= NULL
;
1462 zinfo_task_free(task_t task
)
1464 assert(task
!= kernel_task
);
1465 if (task
->tkm_zinfo
!= NULL
) {
1466 zfree(zinfo_zone
, task
->tkm_zinfo
);
1467 task
->tkm_zinfo
= NULL
;
1473 vm_size_t max_zonemap_size
)
1475 kern_return_t retval
;
1476 vm_offset_t zone_min
;
1477 vm_offset_t zone_max
;
1478 vm_size_t zone_table_size
;
1480 retval
= kmem_suballoc(kernel_map
, &zone_min
, max_zonemap_size
,
1481 FALSE
, VM_FLAGS_ANYWHERE
| VM_FLAGS_PERMANENT
,
1484 if (retval
!= KERN_SUCCESS
)
1485 panic("zone_init: kmem_suballoc failed");
1486 zone_max
= zone_min
+ round_page(max_zonemap_size
);
1488 * Setup garbage collection information:
1490 zone_table_size
= atop_kernel(zone_max
- zone_min
) *
1491 sizeof(struct zone_page_table_entry
);
1492 if (kmem_alloc_kobject(zone_map
, (vm_offset_t
*) &zone_page_table
,
1493 zone_table_size
) != KERN_SUCCESS
)
1495 zone_min
= (vm_offset_t
)zone_page_table
+ round_page(zone_table_size
);
1496 zone_pages
= (unsigned int)atop_kernel(zone_max
- zone_min
);
1497 zone_map_min_address
= zone_min
;
1498 zone_map_max_address
= zone_max
;
1500 lck_grp_attr_setdefault(&zone_lck_grp_attr
);
1501 lck_grp_init(&zone_lck_grp
, "zones", &zone_lck_grp_attr
);
1502 lck_attr_setdefault(&zone_lck_attr
);
1503 lck_mtx_init_ext(&zone_gc_lock
, &zone_lck_ext
, &zone_lck_grp
, &zone_lck_attr
);
1505 zone_page_init(zone_min
, zone_max
- zone_min
, ZONE_PAGE_UNUSED
);
1509 * Initialize the zone leak monitor
1511 zleak_init(max_zonemap_size
);
1512 #endif /* CONFIG_ZLEAKS */
1515 extern volatile SInt32 kfree_nop_count
;
1518 #pragma mark zalloc_canblock
1521 * zalloc returns an element from the specified zone.
1525 register zone_t zone
,
1529 kern_return_t retval
;
1530 uintptr_t zbt
[MAX_ZTRACE_DEPTH
]; /* used in zone leak logging and zone leak detection */
1535 uint32_t zleak_tracedepth
= 0; /* log this allocation if nonzero */
1536 #endif /* CONFIG_ZLEAKS */
1538 assert(zone
!= ZONE_NULL
);
1543 * If zone logging is turned on and this is the zone we're tracking, grab a backtrace.
1546 if (DO_LOGGING(zone
))
1547 numsaved
= OSBacktrace((void*) zbt
, MAX_ZTRACE_DEPTH
);
1551 * Zone leak detection: capture a backtrace every z_sample_factor
1552 * allocations in this zone.
1554 if (zone
->zleak_on
&& (zone
->zleak_capture
++ % z_sample_factor
== 0)) {
1555 zone
->zleak_capture
= 1;
1557 /* Avoid backtracing twice if zone logging is on */
1559 zleak_tracedepth
= fastbacktrace(zbt
, MAX_ZTRACE_DEPTH
);
1561 zleak_tracedepth
= numsaved
;
1563 #endif /* CONFIG_ZLEAKS */
1565 REMOVE_FROM_ZONE(zone
, addr
, vm_offset_t
);
1567 while ((addr
== 0) && canblock
&& (zone
->doing_gc
)) {
1568 zone
->waiting
= TRUE
;
1570 REMOVE_FROM_ZONE(zone
, addr
, vm_offset_t
);
1573 while ((addr
== 0) && canblock
) {
1575 * If nothing was there, try to get more
1577 if (zone
->doing_alloc
) {
1579 * Someone is allocating memory for this zone.
1580 * Wait for it to show up, then try again.
1582 zone
->waiting
= TRUE
;
1586 if ((zone
->cur_size
+ zone
->elem_size
) >
1588 if (zone
->exhaustible
)
1590 if (zone
->expandable
) {
1592 * We're willing to overflow certain
1593 * zones, but not without complaining.
1595 * This is best used in conjunction
1596 * with the collectable flag. What we
1597 * want is an assurance we can get the
1598 * memory back, assuming there's no
1601 zone
->max_size
+= (zone
->max_size
>> 1);
1605 panic("zalloc: zone \"%s\" empty.", zone
->zone_name
);
1608 zone
->doing_alloc
= TRUE
;
1611 if (zone
->collectable
) {
1613 vm_size_t alloc_size
;
1617 int zflags
= KMA_KOBJECT
|KMA_NOPAGEWAIT
;
1619 if (vm_pool_low() || retry
>= 1)
1621 round_page(zone
->elem_size
);
1623 alloc_size
= zone
->alloc_size
;
1625 if (zone
->noencrypt
)
1626 zflags
|= KMA_NOENCRYPT
;
1628 retval
= kernel_memory_allocate(zone_map
, &space
, alloc_size
, 0, zflags
);
1629 if (retval
== KERN_SUCCESS
) {
1631 if (alloc_size
== PAGE_SIZE
)
1632 space
= zone_alias_addr(space
);
1636 if ((zleak_state
& (ZLEAK_STATE_ENABLED
| ZLEAK_STATE_ACTIVE
)) == ZLEAK_STATE_ENABLED
) {
1637 if (zone_map
->size
>= zleak_global_tracking_threshold
) {
1640 kr
= zleak_activate();
1641 if (kr
!= KERN_SUCCESS
) {
1642 printf("Failed to activate live zone leak debugging (%d).\n", kr
);
1647 if ((zleak_state
& ZLEAK_STATE_ACTIVE
) && !(zone
->zleak_on
)) {
1648 if (zone
->cur_size
> zleak_per_zone_tracking_threshold
) {
1649 zone
->zleak_on
= TRUE
;
1652 #endif /* CONFIG_ZLEAKS */
1654 zone_page_init(space
, alloc_size
,
1656 zcram(zone
, (void *)space
, alloc_size
);
1659 } else if (retval
!= KERN_RESOURCE_SHORTAGE
) {
1664 printf("zalloc did gc\n");
1665 zone_display_zprint();
1668 panic_include_zprint
= TRUE
;
1670 if ((zleak_state
& ZLEAK_STATE_ACTIVE
)) {
1671 panic_include_ztrace
= TRUE
;
1673 #endif /* CONFIG_ZLEAKS */
1674 /* TODO: Change this to something more descriptive, perhaps
1675 * 'zone_map exhausted' only if we get retval 3 (KERN_NO_SPACE).
1677 panic("zalloc: \"%s\" (%d elements) retry fail %d, kfree_nop_count: %d", zone
->zone_name
, zone
->count
, retval
, (int)kfree_nop_count
);
1684 zone
->doing_alloc
= FALSE
;
1685 if (zone
->waiting
) {
1686 zone
->waiting
= FALSE
;
1689 REMOVE_FROM_ZONE(zone
, addr
, vm_offset_t
);
1691 retval
== KERN_RESOURCE_SHORTAGE
) {
1699 retval
= zget_space(zone
, zone
->elem_size
, &space
);
1702 zone
->doing_alloc
= FALSE
;
1703 if (zone
->waiting
) {
1704 zone
->waiting
= FALSE
;
1705 thread_wakeup((event_t
)zone
);
1707 if (retval
== KERN_SUCCESS
) {
1710 zone
->cur_size
+= zone
->elem_size
;
1712 if (zone_debug_enabled(zone
)) {
1713 enqueue_tail(&zone
->active_zones
, (queue_entry_t
)space
);
1717 zone_page_alloc(space
, zone
->elem_size
);
1719 if (zone_debug_enabled(zone
))
1720 space
+= ZONE_DEBUG_OFFSET
;
1725 if (retval
== KERN_RESOURCE_SHORTAGE
) {
1732 * Equivalent to a 'retry fail 3', we're out of address space in the zone_map
1733 * (if it returned KERN_NO_SPACE)
1735 if (retval
== KERN_NO_SPACE
) {
1736 panic_include_zprint
= TRUE
;
1738 if ((zleak_state
& ZLEAK_STATE_ACTIVE
)) {
1739 panic_include_ztrace
= TRUE
;
1741 #endif /* CONFIG_ZLEAKS */
1743 panic("zalloc: \"%s\" (%d elements) zget_space returned %d", zone
->zone_name
, zone
->count
, retval
);
1748 REMOVE_FROM_ZONE(zone
, addr
, vm_offset_t
);
1752 /* Zone leak detection:
1753 * If we're sampling this allocation, add it to the zleaks hash table.
1755 if (addr
&& zleak_tracedepth
> 0) {
1756 /* Sampling can fail if another sample is happening at the same time in a different zone. */
1757 if (!zleak_log(zbt
, addr
, zleak_tracedepth
, zone
->elem_size
)) {
1758 /* If it failed, roll back the counter so we sample the next allocation instead. */
1759 zone
->zleak_capture
= z_sample_factor
;
1762 #endif /* CONFIG_ZLEAKS */
1766 * See if we should be logging allocations in this zone. Logging is rarely done except when a leak is
1767 * suspected, so this code rarely executes. We need to do this code while still holding the zone lock
1768 * since it protects the various log related data structures.
1771 if (DO_LOGGING(zone
) && addr
) {
1774 * Look for a place to record this new allocation. We implement two different logging strategies
1775 * depending on whether we're looking for the source of a zone leak or a zone corruption. When looking
1776 * for a leak, we want to log as many allocations as possible in order to clearly identify the leaker
1777 * among all the records. So we look for an unused slot in the log and fill that in before overwriting
1778 * an old entry. When looking for a corrution however, it's better to have a chronological log of all
1779 * the allocations and frees done in the zone so that the history of operations for a specific zone
1780 * element can be inspected. So in this case, we treat the log as a circular buffer and overwrite the
1781 * oldest entry whenever a new one needs to be added.
1783 * The check_freed_element flag tells us what style of logging to do. It's set if we're supposed to be
1784 * doing corruption style logging (indicated via -zc in the boot-args).
1787 if (!check_freed_element
&& zrecords
[zcurrent
].z_element
&& zrecorded
< log_records
) {
1790 * If we get here, we're doing leak style logging and there's still some unused entries in
1791 * the log (since zrecorded is smaller than the size of the log). Look for an unused slot
1792 * starting at zcurrent and wrap-around if we reach the end of the buffer. If the buffer
1793 * is already full, we just fall through and overwrite the element indexed by zcurrent.
1796 for (i
= zcurrent
; i
< log_records
; i
++) {
1797 if (zrecords
[i
].z_element
== NULL
) {
1803 for (i
= 0; i
< zcurrent
; i
++) {
1804 if (zrecords
[i
].z_element
== NULL
) {
1812 * Save a record of this allocation
1816 if (zrecords
[zcurrent
].z_element
== NULL
)
1819 zrecords
[zcurrent
].z_element
= (void *)addr
;
1820 zrecords
[zcurrent
].z_time
= ztime
++;
1821 zrecords
[zcurrent
].z_opcode
= ZOP_ALLOC
;
1823 for (i
= 0; i
< numsaved
; i
++)
1824 zrecords
[zcurrent
].z_pc
[i
] = (void*) zbt
[i
];
1826 for (; i
< MAX_ZTRACE_DEPTH
; i
++)
1827 zrecords
[zcurrent
].z_pc
[i
] = 0;
1831 if (zcurrent
>= log_records
)
1835 if ((addr
== 0) && !canblock
&& (zone
->async_pending
== FALSE
) && (zone
->exhaustible
== FALSE
) && (!vm_pool_low())) {
1836 zone
->async_pending
= TRUE
;
1838 thread_call_enter(&zone
->call_async_alloc
);
1840 REMOVE_FROM_ZONE(zone
, addr
, vm_offset_t
);
1844 if (addr
&& zone_debug_enabled(zone
)) {
1845 enqueue_tail(&zone
->active_zones
, (queue_entry_t
)addr
);
1846 addr
+= ZONE_DEBUG_OFFSET
;
1854 #endif /* CONFIG_ZLEAKS */
1859 TRACE_MACHLEAKS(ZALLOC_CODE
, ZALLOC_CODE_2
, zone
->elem_size
, addr
);
1862 thread_t thr
= current_thread();
1864 zinfo_usage_t zinfo
;
1866 if (zone
->caller_acct
)
1867 thr
->tkm_private
.alloc
+= zone
->elem_size
;
1869 thr
->tkm_shared
.alloc
+= zone
->elem_size
;
1871 if ((task
= thr
->task
) != NULL
&& (zinfo
= task
->tkm_zinfo
) != NULL
)
1872 OSAddAtomic64(zone
->elem_size
, (int64_t *)&zinfo
[zone
->index
].alloc
);
1874 return((void *)addr
);
1880 register zone_t zone
)
1882 return( zalloc_canblock(zone
, TRUE
) );
1887 register zone_t zone
)
1889 return( zalloc_canblock(zone
, FALSE
) );
1894 thread_call_param_t p0
,
1895 __unused thread_call_param_t p1
)
1899 elt
= zalloc_canblock((zone_t
)p0
, TRUE
);
1900 zfree((zone_t
)p0
, elt
);
1901 lock_zone(((zone_t
)p0
));
1902 ((zone_t
)p0
)->async_pending
= FALSE
;
1903 unlock_zone(((zone_t
)p0
));
1908 * zget returns an element from the specified zone
1909 * and immediately returns nothing if there is nothing there.
1911 * This form should be used when you can not block (like when
1912 * processing an interrupt).
1914 * XXX: It seems like only vm_page_grab_fictitious_common uses this, and its
1915 * friend vm_page_more_fictitious can block, so it doesn't seem like
1916 * this is used for interrupts any more....
1920 register zone_t zone
)
1922 register vm_offset_t addr
;
1925 uintptr_t zbt
[MAX_ZTRACE_DEPTH
]; /* used for zone leak detection */
1926 uint32_t zleak_tracedepth
= 0; /* log this allocation if nonzero */
1927 #endif /* CONFIG_ZLEAKS */
1929 assert( zone
!= ZONE_NULL
);
1931 if (!lock_try_zone(zone
))
1936 * Zone leak detection: capture a backtrace
1938 if (zone
->zleak_on
&& (zone
->zleak_capture
++ % z_sample_factor
== 0)) {
1939 zone
->zleak_capture
= 1;
1940 zleak_tracedepth
= fastbacktrace(zbt
, MAX_ZTRACE_DEPTH
);
1942 #endif /* CONFIG_ZLEAKS */
1944 REMOVE_FROM_ZONE(zone
, addr
, vm_offset_t
);
1946 if (addr
&& zone_debug_enabled(zone
)) {
1947 enqueue_tail(&zone
->active_zones
, (queue_entry_t
)addr
);
1948 addr
+= ZONE_DEBUG_OFFSET
;
1950 #endif /* ZONE_DEBUG */
1954 * Zone leak detection: record the allocation
1956 if (zone
->zleak_on
&& zleak_tracedepth
> 0 && addr
) {
1957 /* Sampling can fail if another sample is happening at the same time in a different zone. */
1958 if (!zleak_log(zbt
, addr
, zleak_tracedepth
, zone
->elem_size
)) {
1959 /* If it failed, roll back the counter so we sample the next allocation instead. */
1960 zone
->zleak_capture
= z_sample_factor
;
1967 #endif /* CONFIG_ZLEAKS */
1971 return((void *) addr
);
1974 /* Keep this FALSE by default. Large memory machine run orders of magnitude
1975 slower in debug mode when true. Use debugger to enable if needed */
1976 /* static */ boolean_t zone_check
= FALSE
;
1978 static zone_t zone_last_bogus_zone
= ZONE_NULL
;
1979 static vm_offset_t zone_last_bogus_elem
= 0;
1983 register zone_t zone
,
1986 vm_offset_t elem
= (vm_offset_t
) addr
;
1987 void *zbt
[MAX_ZTRACE_DEPTH
]; /* only used if zone logging is enabled via boot-args */
1990 assert(zone
!= ZONE_NULL
);
1993 * If zone logging is turned on and this is the zone we're tracking, grab a backtrace.
1996 if (DO_LOGGING(zone
))
1997 numsaved
= OSBacktrace(&zbt
[0], MAX_ZTRACE_DEPTH
);
2000 /* Basic sanity checks */
2001 if (zone
== ZONE_NULL
|| elem
== (vm_offset_t
)0)
2002 panic("zfree: NULL");
2003 /* zone_gc assumes zones are never freed */
2004 if (zone
== zone_zone
)
2005 panic("zfree: freeing to zone_zone breaks zone_gc!");
2008 TRACE_MACHLEAKS(ZFREE_CODE
, ZFREE_CODE_2
, zone
->elem_size
, (uintptr_t)addr
);
2010 if (zone
->collectable
&& !zone
->allows_foreign
&&
2011 !from_zone_map(elem
, zone
->elem_size
)) {
2013 panic("zfree: non-allocated memory in collectable zone!");
2015 zone_last_bogus_zone
= zone
;
2016 zone_last_bogus_elem
= elem
;
2023 * See if we're doing logging on this zone. There are two styles of logging used depending on
2024 * whether we're trying to catch a leak or corruption. See comments above in zalloc for details.
2027 if (DO_LOGGING(zone
)) {
2030 if (check_freed_element
) {
2033 * We're logging to catch a corruption. Add a record of this zfree operation
2037 if (zrecords
[zcurrent
].z_element
== NULL
)
2040 zrecords
[zcurrent
].z_element
= (void *)addr
;
2041 zrecords
[zcurrent
].z_time
= ztime
++;
2042 zrecords
[zcurrent
].z_opcode
= ZOP_FREE
;
2044 for (i
= 0; i
< numsaved
; i
++)
2045 zrecords
[zcurrent
].z_pc
[i
] = zbt
[i
];
2047 for (; i
< MAX_ZTRACE_DEPTH
; i
++)
2048 zrecords
[zcurrent
].z_pc
[i
] = 0;
2052 if (zcurrent
>= log_records
)
2058 * We're logging to catch a leak. Remove any record we might have for this
2059 * element since it's being freed. Note that we may not find it if the buffer
2060 * overflowed and that's OK. Since the log is of a limited size, old records
2061 * get overwritten if there are more zallocs than zfrees.
2064 for (i
= 0; i
< log_records
; i
++) {
2065 if (zrecords
[i
].z_element
== addr
) {
2066 zrecords
[i
].z_element
= NULL
;
2077 if (zone_debug_enabled(zone
)) {
2080 elem
-= ZONE_DEBUG_OFFSET
;
2082 /* check the zone's consistency */
2084 for (tmp_elem
= queue_first(&zone
->active_zones
);
2085 !queue_end(tmp_elem
, &zone
->active_zones
);
2086 tmp_elem
= queue_next(tmp_elem
))
2087 if (elem
== (vm_offset_t
)tmp_elem
)
2089 if (elem
!= (vm_offset_t
)tmp_elem
)
2090 panic("zfree()ing element from wrong zone");
2092 remqueue((queue_t
) elem
);
2094 #endif /* ZONE_DEBUG */
2098 /* check the zone's consistency */
2100 for (this = zone
->free_elements
;
2102 this = * (vm_offset_t
*) this)
2103 if (!pmap_kernel_va(this) || this == elem
)
2106 ADD_TO_ZONE(zone
, elem
);
2108 if (zone
->count
< 0)
2109 panic("zfree: count < 0!");
2117 * Zone leak detection: un-track the allocation
2119 if (zone
->zleak_on
) {
2120 zleak_free(elem
, zone
->elem_size
);
2122 #endif /* CONFIG_ZLEAKS */
2125 * If elements have one or more pages, and memory is low,
2126 * request to run the garbage collection in the zone the next
2127 * time the pageout thread runs.
2129 if (zone
->elem_size
>= PAGE_SIZE
&&
2131 zone_gc_forced
= TRUE
;
2136 thread_t thr
= current_thread();
2138 zinfo_usage_t zinfo
;
2140 if (zone
->caller_acct
)
2141 thr
->tkm_private
.free
+= zone
->elem_size
;
2143 thr
->tkm_shared
.free
+= zone
->elem_size
;
2144 if ((task
= thr
->task
) != NULL
&& (zinfo
= task
->tkm_zinfo
) != NULL
)
2145 OSAddAtomic64(zone
->elem_size
,
2146 (int64_t *)&zinfo
[zone
->index
].free
);
2151 /* Change a zone's flags.
2152 * This routine must be called immediately after zinit.
2160 assert( zone
!= ZONE_NULL
);
2161 assert( value
== TRUE
|| value
== FALSE
);
2165 zone
->noencrypt
= value
;
2168 zone
->exhaustible
= value
;
2171 zone
->collectable
= value
;
2174 zone
->expandable
= value
;
2177 zone
->allows_foreign
= value
;
2180 zone
->caller_acct
= value
;
2184 panic("Zone_change: Wrong Item Type!");
2191 * Return the expected number of free elements in the zone.
2192 * This calculation will be incorrect if items are zfree'd that
2193 * were never zalloc'd/zget'd. The correct way to stuff memory
2194 * into a zone is by zcram.
2198 zone_free_count(zone_t zone
)
2200 integer_t free_count
;
2203 free_count
= (integer_t
)(zone
->cur_size
/zone
->elem_size
- zone
->count
);
2206 assert(free_count
>= 0);
2212 * zprealloc preallocates wired memory, exanding the specified
2213 * zone to the specified size
2223 if (kmem_alloc_kobject(zone_map
, &addr
, size
) != KERN_SUCCESS
)
2225 zone_page_init(addr
, size
, ZONE_PAGE_USED
);
2226 zcram(zone
, (void *)addr
, size
);
2231 * Zone garbage collection subroutines
2235 zone_page_collectable(
2239 struct zone_page_table_entry
*zp
;
2243 addr
= zone_virtual_addr(addr
);
2246 if (!from_zone_map(addr
, size
))
2247 panic("zone_page_collectable");
2250 i
= (natural_t
)atop_kernel(addr
-zone_map_min_address
);
2251 j
= (natural_t
)atop_kernel((addr
+size
-1) - zone_map_min_address
);
2253 for (zp
= zone_page_table
+ i
; i
<= j
; zp
++, i
++)
2254 if (zp
->collect_count
== zp
->alloc_count
)
2265 struct zone_page_table_entry
*zp
;
2269 addr
= zone_virtual_addr(addr
);
2272 if (!from_zone_map(addr
, size
))
2273 panic("zone_page_keep");
2276 i
= (natural_t
)atop_kernel(addr
-zone_map_min_address
);
2277 j
= (natural_t
)atop_kernel((addr
+size
-1) - zone_map_min_address
);
2279 for (zp
= zone_page_table
+ i
; i
<= j
; zp
++, i
++)
2280 zp
->collect_count
= 0;
2288 struct zone_page_table_entry
*zp
;
2292 addr
= zone_virtual_addr(addr
);
2295 if (!from_zone_map(addr
, size
))
2296 panic("zone_page_collect");
2299 i
= (natural_t
)atop_kernel(addr
-zone_map_min_address
);
2300 j
= (natural_t
)atop_kernel((addr
+size
-1) - zone_map_min_address
);
2302 for (zp
= zone_page_table
+ i
; i
<= j
; zp
++, i
++)
2303 ++zp
->collect_count
;
2312 struct zone_page_table_entry
*zp
;
2316 addr
= zone_virtual_addr(addr
);
2319 if (!from_zone_map(addr
, size
))
2320 panic("zone_page_init");
2323 i
= (natural_t
)atop_kernel(addr
-zone_map_min_address
);
2324 j
= (natural_t
)atop_kernel((addr
+size
-1) - zone_map_min_address
);
2326 for (zp
= zone_page_table
+ i
; i
<= j
; zp
++, i
++) {
2327 zp
->alloc_count
= value
;
2328 zp
->collect_count
= 0;
2337 struct zone_page_table_entry
*zp
;
2341 addr
= zone_virtual_addr(addr
);
2344 if (!from_zone_map(addr
, size
))
2345 panic("zone_page_alloc");
2348 i
= (natural_t
)atop_kernel(addr
-zone_map_min_address
);
2349 j
= (natural_t
)atop_kernel((addr
+size
-1) - zone_map_min_address
);
2351 for (zp
= zone_page_table
+ i
; i
<= j
; zp
++, i
++) {
2353 * Set alloc_count to (ZONE_PAGE_USED + 1) if
2354 * it was previously set to ZONE_PAGE_UNUSED.
2356 if (zp
->alloc_count
== ZONE_PAGE_UNUSED
)
2357 zp
->alloc_count
= 1;
2364 zone_page_free_element(
2365 struct zone_page_table_entry
**free_pages
,
2369 struct zone_page_table_entry
*zp
;
2373 addr
= zone_virtual_addr(addr
);
2376 if (!from_zone_map(addr
, size
))
2377 panic("zone_page_free_element");
2380 i
= (natural_t
)atop_kernel(addr
-zone_map_min_address
);
2381 j
= (natural_t
)atop_kernel((addr
+size
-1) - zone_map_min_address
);
2383 for (zp
= zone_page_table
+ i
; i
<= j
; zp
++, i
++) {
2384 if (zp
->collect_count
> 0)
2385 --zp
->collect_count
;
2386 if (--zp
->alloc_count
== 0) {
2387 zp
->alloc_count
= ZONE_PAGE_UNUSED
;
2388 zp
->collect_count
= 0;
2390 zp
->link
= *free_pages
;
2397 /* This is used for walking through a zone's free element list.
2399 struct zone_free_element
{
2400 struct zone_free_element
* next
;
2404 * Add a linked list of pages starting at base back into the zone
2405 * free list. Tail points to the last element on the list.
2408 #define ADD_LIST_TO_ZONE(zone, base, tail) \
2410 (tail)->next = (void *)((zone)->free_elements); \
2411 if (check_freed_element) { \
2412 if ((zone)->elem_size >= (2 * sizeof(vm_offset_t))) \
2413 ((vm_offset_t *)(tail))[((zone)->elem_size/sizeof(vm_offset_t))-1] = \
2414 (zone)->free_elements; \
2416 (zone)->free_elements = (unsigned long)(base); \
2420 * Add an element to the chain pointed to by prev.
2423 #define ADD_ELEMENT(zone, prev, elem) \
2425 (prev)->next = (elem); \
2426 if (check_freed_element) { \
2427 if ((zone)->elem_size >= (2 * sizeof(vm_offset_t))) \
2428 ((vm_offset_t *)(prev))[((zone)->elem_size/sizeof(vm_offset_t))-1] = \
2429 (vm_offset_t)(elem); \
2436 uint32_t elems_collected
,
2441 /* Zone garbage collection
2443 * zone_gc will walk through all the free elements in all the
2444 * zones that are marked collectable looking for reclaimable
2445 * pages. zone_gc is called by consider_zone_gc when the system
2446 * begins to run out of memory.
2451 unsigned int max_zones
;
2454 struct zone_page_table_entry
*zp
, *zone_free_pages
;
2456 lck_mtx_lock(&zone_gc_lock
);
2458 simple_lock(&all_zones_lock
);
2459 max_zones
= num_zones
;
2461 simple_unlock(&all_zones_lock
);
2464 for (i
= 0; i
< zone_pages
; i
++)
2465 assert(zone_page_table
[i
].collect_count
== 0);
2466 #endif /* MACH_ASSERT */
2468 zone_free_pages
= NULL
;
2470 for (i
= 0; i
< max_zones
; i
++, z
= z
->next_zone
) {
2472 vm_size_t elt_size
, size_freed
;
2473 struct zone_free_element
*elt
, *base_elt
, *base_prev
, *prev
, *scan
, *keep
, *tail
;
2475 assert(z
!= ZONE_NULL
);
2477 if (!z
->collectable
)
2482 elt_size
= z
->elem_size
;
2485 * Do a quick feasability check before we scan the zone:
2486 * skip unless there is likelihood of getting pages back
2487 * (i.e we need a whole allocation block's worth of free
2488 * elements before we can garbage collect) and
2489 * the zone has more than 10 percent of it's elements free
2490 * or the element size is a multiple of the PAGE_SIZE
2492 if ((elt_size
& PAGE_MASK
) &&
2493 (((z
->cur_size
- z
->count
* elt_size
) <= (2 * z
->alloc_size
)) ||
2494 ((z
->cur_size
- z
->count
* elt_size
) <= (z
->cur_size
/ 10)))) {
2502 * Snatch all of the free elements away from the zone.
2505 scan
= (void *)z
->free_elements
;
2506 z
->free_elements
= 0;
2513 * Determine which elements we can attempt to collect
2514 * and count them up in the page table. Foreign elements
2515 * are returned to the zone.
2518 prev
= (void *)&scan
;
2520 n
= 0; tail
= keep
= NULL
;
2521 while (elt
!= NULL
) {
2522 if (from_zone_map(elt
, elt_size
)) {
2523 zone_page_collect((vm_offset_t
)elt
, elt_size
);
2528 ++zgc_stats
.elems_collected
;
2534 ADD_ELEMENT(z
, tail
, elt
);
2538 ADD_ELEMENT(z
, prev
, elt
->next
);
2540 ADD_ELEMENT(z
, tail
, NULL
);
2544 * Dribble back the elements we are keeping.
2548 if (z
->waiting
== TRUE
) {
2552 ADD_LIST_TO_ZONE(z
, keep
, tail
);
2558 while ((elt
!= NULL
) && (++m
< 50)) {
2563 ADD_LIST_TO_ZONE(z
, base_elt
, prev
);
2564 ADD_ELEMENT(z
, base_prev
, elt
);
2581 * Return any remaining elements.
2587 ADD_LIST_TO_ZONE(z
, keep
, tail
);
2595 * Determine which pages we can reclaim and
2596 * free those elements.
2601 n
= 0; tail
= keep
= NULL
;
2602 while (elt
!= NULL
) {
2603 if (zone_page_collectable((vm_offset_t
)elt
, elt_size
)) {
2604 size_freed
+= elt_size
;
2605 zone_page_free_element(&zone_free_pages
,
2606 (vm_offset_t
)elt
, elt_size
);
2610 ++zgc_stats
.elems_freed
;
2613 zone_page_keep((vm_offset_t
)elt
, elt_size
);
2618 ADD_ELEMENT(z
, tail
, elt
);
2623 ADD_ELEMENT(z
, tail
, NULL
);
2625 ++zgc_stats
.elems_kept
;
2629 * Dribble back the elements we are keeping,
2630 * and update the zone size info.
2636 z
->cur_size
-= size_freed
;
2640 ADD_LIST_TO_ZONE(z
, keep
, tail
);
2650 n
= 0; tail
= keep
= NULL
;
2655 * Return any remaining elements, and update
2656 * the zone size info.
2661 if (size_freed
> 0 || keep
!= NULL
) {
2663 z
->cur_size
-= size_freed
;
2666 ADD_LIST_TO_ZONE(z
, keep
, tail
);
2671 z
->doing_gc
= FALSE
;
2680 * Reclaim the pages we are freeing.
2683 while ((zp
= zone_free_pages
) != NULL
) {
2684 zone_free_pages
= zp
->link
;
2686 z
= (zone_t
)zone_virtual_addr((vm_map_address_t
)z
);
2688 kmem_free(zone_map
, zone_map_min_address
+ PAGE_SIZE
*
2689 (zp
- zone_page_table
), PAGE_SIZE
);
2690 ++zgc_stats
.pgs_freed
;
2693 lck_mtx_unlock(&zone_gc_lock
);
2699 * Called by the pageout daemon when the system needs more free pages.
2703 consider_zone_gc(boolean_t force
)
2706 if (zone_gc_allowed
&&
2707 (zone_gc_allowed_by_time_throttle
||
2710 zone_gc_forced
= FALSE
;
2711 zone_gc_allowed_by_time_throttle
= FALSE
; /* reset periodically */
2717 * By default, don't attempt zone GC more frequently
2718 * than once / 1 minutes.
2721 compute_zone_gc_throttle(void *arg __unused
)
2723 zone_gc_allowed_by_time_throttle
= TRUE
;
2730 mach_zone_name_array_t
*namesp
,
2731 mach_msg_type_number_t
*namesCntp
,
2732 task_zone_info_array_t
*infop
,
2733 mach_msg_type_number_t
*infoCntp
)
2735 mach_zone_name_t
*names
;
2736 vm_offset_t names_addr
;
2737 vm_size_t names_size
;
2738 task_zone_info_t
*info
;
2739 vm_offset_t info_addr
;
2740 vm_size_t info_size
;
2741 unsigned int max_zones
, i
;
2743 mach_zone_name_t
*zn
;
2744 task_zone_info_t
*zi
;
2751 if (task
== TASK_NULL
)
2752 return KERN_INVALID_TASK
;
2755 * We assume that zones aren't freed once allocated.
2756 * We won't pick up any zones that are allocated later.
2759 simple_lock(&all_zones_lock
);
2760 max_zones
= (unsigned int)(num_zones
+ num_fake_zones
);
2762 simple_unlock(&all_zones_lock
);
2764 names_size
= round_page(max_zones
* sizeof *names
);
2765 kr
= kmem_alloc_pageable(ipc_kernel_map
,
2766 &names_addr
, names_size
);
2767 if (kr
!= KERN_SUCCESS
)
2769 names
= (mach_zone_name_t
*) names_addr
;
2771 info_size
= round_page(max_zones
* sizeof *info
);
2772 kr
= kmem_alloc_pageable(ipc_kernel_map
,
2773 &info_addr
, info_size
);
2774 if (kr
!= KERN_SUCCESS
) {
2775 kmem_free(ipc_kernel_map
,
2776 names_addr
, names_size
);
2780 info
= (task_zone_info_t
*) info_addr
;
2785 for (i
= 0; i
< max_zones
- num_fake_zones
; i
++) {
2788 assert(z
!= ZONE_NULL
);
2794 simple_lock(&all_zones_lock
);
2796 simple_unlock(&all_zones_lock
);
2798 /* assuming here the name data is static */
2799 (void) strncpy(zn
->mzn_name
, zcopy
.zone_name
,
2800 sizeof zn
->mzn_name
);
2801 zn
->mzn_name
[sizeof zn
->mzn_name
- 1] = '\0';
2803 zi
->tzi_count
= (uint64_t)zcopy
.count
;
2804 zi
->tzi_cur_size
= (uint64_t)zcopy
.cur_size
;
2805 zi
->tzi_max_size
= (uint64_t)zcopy
.max_size
;
2806 zi
->tzi_elem_size
= (uint64_t)zcopy
.elem_size
;
2807 zi
->tzi_alloc_size
= (uint64_t)zcopy
.alloc_size
;
2808 zi
->tzi_sum_size
= zcopy
.sum_count
* zcopy
.elem_size
;
2809 zi
->tzi_exhaustible
= (uint64_t)zcopy
.exhaustible
;
2810 zi
->tzi_collectable
= (uint64_t)zcopy
.collectable
;
2811 zi
->tzi_caller_acct
= (uint64_t)zcopy
.caller_acct
;
2812 if (task
->tkm_zinfo
!= NULL
) {
2813 zi
->tzi_task_alloc
= task
->tkm_zinfo
[zcopy
.index
].alloc
;
2814 zi
->tzi_task_free
= task
->tkm_zinfo
[zcopy
.index
].free
;
2816 zi
->tzi_task_alloc
= 0;
2817 zi
->tzi_task_free
= 0;
2824 * loop through the fake zones and fill them using the specialized
2827 for (i
= 0; i
< num_fake_zones
; i
++) {
2828 int count
, collectable
, exhaustible
, caller_acct
, index
;
2829 vm_size_t cur_size
, max_size
, elem_size
, alloc_size
;
2832 strncpy(zn
->mzn_name
, fake_zones
[i
].name
, sizeof zn
->mzn_name
);
2833 zn
->mzn_name
[sizeof zn
->mzn_name
- 1] = '\0';
2834 fake_zones
[i
].query(&count
, &cur_size
,
2835 &max_size
, &elem_size
,
2836 &alloc_size
, &sum_size
,
2837 &collectable
, &exhaustible
, &caller_acct
);
2838 zi
->tzi_count
= (uint64_t)count
;
2839 zi
->tzi_cur_size
= (uint64_t)cur_size
;
2840 zi
->tzi_max_size
= (uint64_t)max_size
;
2841 zi
->tzi_elem_size
= (uint64_t)elem_size
;
2842 zi
->tzi_alloc_size
= (uint64_t)alloc_size
;
2843 zi
->tzi_sum_size
= sum_size
;
2844 zi
->tzi_collectable
= (uint64_t)collectable
;
2845 zi
->tzi_exhaustible
= (uint64_t)exhaustible
;
2846 zi
->tzi_caller_acct
= (uint64_t)caller_acct
;
2847 if (task
->tkm_zinfo
!= NULL
) {
2848 index
= ZINFO_SLOTS
- num_fake_zones
+ i
;
2849 zi
->tzi_task_alloc
= task
->tkm_zinfo
[index
].alloc
;
2850 zi
->tzi_task_free
= task
->tkm_zinfo
[index
].free
;
2852 zi
->tzi_task_alloc
= 0;
2853 zi
->tzi_task_free
= 0;
2859 used
= max_zones
* sizeof *names
;
2860 if (used
!= names_size
)
2861 bzero((char *) (names_addr
+ used
), names_size
- used
);
2863 kr
= vm_map_copyin(ipc_kernel_map
, (vm_map_address_t
)names_addr
,
2864 (vm_map_size_t
)names_size
, TRUE
, ©
);
2865 assert(kr
== KERN_SUCCESS
);
2867 *namesp
= (mach_zone_name_t
*) copy
;
2868 *namesCntp
= max_zones
;
2870 used
= max_zones
* sizeof *info
;
2872 if (used
!= info_size
)
2873 bzero((char *) (info_addr
+ used
), info_size
- used
);
2875 kr
= vm_map_copyin(ipc_kernel_map
, (vm_map_address_t
)info_addr
,
2876 (vm_map_size_t
)info_size
, TRUE
, ©
);
2877 assert(kr
== KERN_SUCCESS
);
2879 *infop
= (task_zone_info_t
*) copy
;
2880 *infoCntp
= max_zones
;
2882 return KERN_SUCCESS
;
2888 mach_zone_name_array_t
*namesp
,
2889 mach_msg_type_number_t
*namesCntp
,
2890 mach_zone_info_array_t
*infop
,
2891 mach_msg_type_number_t
*infoCntp
)
2893 mach_zone_name_t
*names
;
2894 vm_offset_t names_addr
;
2895 vm_size_t names_size
;
2896 mach_zone_info_t
*info
;
2897 vm_offset_t info_addr
;
2898 vm_size_t info_size
;
2899 unsigned int max_zones
, i
;
2901 mach_zone_name_t
*zn
;
2902 mach_zone_info_t
*zi
;
2909 if (host
== HOST_NULL
)
2910 return KERN_INVALID_HOST
;
2912 num_fake_zones
= sizeof fake_zones
/ sizeof fake_zones
[0];
2915 * We assume that zones aren't freed once allocated.
2916 * We won't pick up any zones that are allocated later.
2919 simple_lock(&all_zones_lock
);
2920 max_zones
= (unsigned int)(num_zones
+ num_fake_zones
);
2922 simple_unlock(&all_zones_lock
);
2924 names_size
= round_page(max_zones
* sizeof *names
);
2925 kr
= kmem_alloc_pageable(ipc_kernel_map
,
2926 &names_addr
, names_size
);
2927 if (kr
!= KERN_SUCCESS
)
2929 names
= (mach_zone_name_t
*) names_addr
;
2931 info_size
= round_page(max_zones
* sizeof *info
);
2932 kr
= kmem_alloc_pageable(ipc_kernel_map
,
2933 &info_addr
, info_size
);
2934 if (kr
!= KERN_SUCCESS
) {
2935 kmem_free(ipc_kernel_map
,
2936 names_addr
, names_size
);
2940 info
= (mach_zone_info_t
*) info_addr
;
2945 for (i
= 0; i
< max_zones
- num_fake_zones
; i
++) {
2948 assert(z
!= ZONE_NULL
);
2954 simple_lock(&all_zones_lock
);
2956 simple_unlock(&all_zones_lock
);
2958 /* assuming here the name data is static */
2959 (void) strncpy(zn
->mzn_name
, zcopy
.zone_name
,
2960 sizeof zn
->mzn_name
);
2961 zn
->mzn_name
[sizeof zn
->mzn_name
- 1] = '\0';
2963 zi
->mzi_count
= (uint64_t)zcopy
.count
;
2964 zi
->mzi_cur_size
= (uint64_t)zcopy
.cur_size
;
2965 zi
->mzi_max_size
= (uint64_t)zcopy
.max_size
;
2966 zi
->mzi_elem_size
= (uint64_t)zcopy
.elem_size
;
2967 zi
->mzi_alloc_size
= (uint64_t)zcopy
.alloc_size
;
2968 zi
->mzi_sum_size
= zcopy
.sum_count
* zcopy
.elem_size
;
2969 zi
->mzi_exhaustible
= (uint64_t)zcopy
.exhaustible
;
2970 zi
->mzi_collectable
= (uint64_t)zcopy
.collectable
;
2976 * loop through the fake zones and fill them using the specialized
2979 for (i
= 0; i
< num_fake_zones
; i
++) {
2980 int count
, collectable
, exhaustible
, caller_acct
;
2981 vm_size_t cur_size
, max_size
, elem_size
, alloc_size
;
2984 strncpy(zn
->mzn_name
, fake_zones
[i
].name
, sizeof zn
->mzn_name
);
2985 zn
->mzn_name
[sizeof zn
->mzn_name
- 1] = '\0';
2986 fake_zones
[i
].query(&count
, &cur_size
,
2987 &max_size
, &elem_size
,
2988 &alloc_size
, &sum_size
,
2989 &collectable
, &exhaustible
, &caller_acct
);
2990 zi
->mzi_count
= (uint64_t)count
;
2991 zi
->mzi_cur_size
= (uint64_t)cur_size
;
2992 zi
->mzi_max_size
= (uint64_t)max_size
;
2993 zi
->mzi_elem_size
= (uint64_t)elem_size
;
2994 zi
->mzi_alloc_size
= (uint64_t)alloc_size
;
2995 zi
->mzi_sum_size
= sum_size
;
2996 zi
->mzi_collectable
= (uint64_t)collectable
;
2997 zi
->mzi_exhaustible
= (uint64_t)exhaustible
;
3003 used
= max_zones
* sizeof *names
;
3004 if (used
!= names_size
)
3005 bzero((char *) (names_addr
+ used
), names_size
- used
);
3007 kr
= vm_map_copyin(ipc_kernel_map
, (vm_map_address_t
)names_addr
,
3008 (vm_map_size_t
)names_size
, TRUE
, ©
);
3009 assert(kr
== KERN_SUCCESS
);
3011 *namesp
= (mach_zone_name_t
*) copy
;
3012 *namesCntp
= max_zones
;
3014 used
= max_zones
* sizeof *info
;
3016 if (used
!= info_size
)
3017 bzero((char *) (info_addr
+ used
), info_size
- used
);
3019 kr
= vm_map_copyin(ipc_kernel_map
, (vm_map_address_t
)info_addr
,
3020 (vm_map_size_t
)info_size
, TRUE
, ©
);
3021 assert(kr
== KERN_SUCCESS
);
3023 *infop
= (mach_zone_info_t
*) copy
;
3024 *infoCntp
= max_zones
;
3026 return KERN_SUCCESS
;
3030 * host_zone_info - LEGACY user interface for Mach zone information
3031 * Should use mach_zone_info() instead!
3036 zone_name_array_t
*namesp
,
3037 mach_msg_type_number_t
*namesCntp
,
3038 zone_info_array_t
*infop
,
3039 mach_msg_type_number_t
*infoCntp
)
3042 vm_offset_t names_addr
;
3043 vm_size_t names_size
;
3045 vm_offset_t info_addr
;
3046 vm_size_t info_size
;
3047 unsigned int max_zones
, i
;
3057 if (host
== HOST_NULL
)
3058 return KERN_INVALID_HOST
;
3060 #if defined(__LP64__)
3061 if (!thread_is_64bit(current_thread()))
3062 return KERN_NOT_SUPPORTED
;
3064 if (thread_is_64bit(current_thread()))
3065 return KERN_NOT_SUPPORTED
;
3068 num_fake_zones
= sizeof fake_zones
/ sizeof fake_zones
[0];
3071 * We assume that zones aren't freed once allocated.
3072 * We won't pick up any zones that are allocated later.
3075 simple_lock(&all_zones_lock
);
3076 max_zones
= (unsigned int)(num_zones
+ num_fake_zones
);
3078 simple_unlock(&all_zones_lock
);
3080 names_size
= round_page(max_zones
* sizeof *names
);
3081 kr
= kmem_alloc_pageable(ipc_kernel_map
,
3082 &names_addr
, names_size
);
3083 if (kr
!= KERN_SUCCESS
)
3085 names
= (zone_name_t
*) names_addr
;
3087 info_size
= round_page(max_zones
* sizeof *info
);
3088 kr
= kmem_alloc_pageable(ipc_kernel_map
,
3089 &info_addr
, info_size
);
3090 if (kr
!= KERN_SUCCESS
) {
3091 kmem_free(ipc_kernel_map
,
3092 names_addr
, names_size
);
3096 info
= (zone_info_t
*) info_addr
;
3101 for (i
= 0; i
< max_zones
- num_fake_zones
; i
++) {
3104 assert(z
!= ZONE_NULL
);
3110 simple_lock(&all_zones_lock
);
3112 simple_unlock(&all_zones_lock
);
3114 /* assuming here the name data is static */
3115 (void) strncpy(zn
->zn_name
, zcopy
.zone_name
,
3116 sizeof zn
->zn_name
);
3117 zn
->zn_name
[sizeof zn
->zn_name
- 1] = '\0';
3119 zi
->zi_count
= zcopy
.count
;
3120 zi
->zi_cur_size
= zcopy
.cur_size
;
3121 zi
->zi_max_size
= zcopy
.max_size
;
3122 zi
->zi_elem_size
= zcopy
.elem_size
;
3123 zi
->zi_alloc_size
= zcopy
.alloc_size
;
3124 zi
->zi_exhaustible
= zcopy
.exhaustible
;
3125 zi
->zi_collectable
= zcopy
.collectable
;
3132 * loop through the fake zones and fill them using the specialized
3135 for (i
= 0; i
< num_fake_zones
; i
++) {
3138 strncpy(zn
->zn_name
, fake_zones
[i
].name
, sizeof zn
->zn_name
);
3139 zn
->zn_name
[sizeof zn
->zn_name
- 1] = '\0';
3140 fake_zones
[i
].query(&zi
->zi_count
, &zi
->zi_cur_size
,
3141 &zi
->zi_max_size
, &zi
->zi_elem_size
,
3142 &zi
->zi_alloc_size
, &sum_space
,
3143 &zi
->zi_collectable
, &zi
->zi_exhaustible
, &caller_acct
);
3148 used
= max_zones
* sizeof *names
;
3149 if (used
!= names_size
)
3150 bzero((char *) (names_addr
+ used
), names_size
- used
);
3152 kr
= vm_map_copyin(ipc_kernel_map
, (vm_map_address_t
)names_addr
,
3153 (vm_map_size_t
)names_size
, TRUE
, ©
);
3154 assert(kr
== KERN_SUCCESS
);
3156 *namesp
= (zone_name_t
*) copy
;
3157 *namesCntp
= max_zones
;
3159 used
= max_zones
* sizeof *info
;
3160 if (used
!= info_size
)
3161 bzero((char *) (info_addr
+ used
), info_size
- used
);
3163 kr
= vm_map_copyin(ipc_kernel_map
, (vm_map_address_t
)info_addr
,
3164 (vm_map_size_t
)info_size
, TRUE
, ©
);
3165 assert(kr
== KERN_SUCCESS
);
3167 *infop
= (zone_info_t
*) copy
;
3168 *infoCntp
= max_zones
;
3170 return KERN_SUCCESS
;
3173 extern unsigned int stack_total
;
3174 extern unsigned long long stack_allocs
;
3176 #if defined(__i386__) || defined (__x86_64__)
3177 extern unsigned int inuse_ptepages_count
;
3178 extern long long alloc_ptepages_count
;
3181 void zone_display_zprint()
3186 if(first_zone
!=NULL
) {
3187 the_zone
= first_zone
;
3188 for (i
= 0; i
< num_zones
; i
++) {
3189 if(the_zone
->cur_size
> (1024*1024)) {
3190 printf("%.20s:\t%lu\n",the_zone
->zone_name
,(uintptr_t)the_zone
->cur_size
);
3193 if(the_zone
->next_zone
== NULL
) {
3197 the_zone
= the_zone
->next_zone
;
3201 printf("Kernel Stacks:\t%lu\n",(uintptr_t)(kernel_stack_size
* stack_total
));
3203 #if defined(__i386__) || defined (__x86_64__)
3204 printf("PageTables:\t%lu\n",(uintptr_t)(PAGE_SIZE
* inuse_ptepages_count
));
3207 printf("Kalloc.Large:\t%lu\n",(uintptr_t)kalloc_large_total
);
3213 #include <ddb/db_command.h>
3214 #include <ddb/db_output.h>
3215 #include <kern/kern_print.h>
3217 const char *zone_labels
=
3218 "ENTRY COUNT TOT_SZ MAX_SZ ELT_SZ ALLOC_SZ NAME";
3225 void db_zone_check_active(
3227 void db_zone_print_active(
3229 #endif /* ZONE_DEBUG */
3230 void db_zone_print_free(
3240 db_printf("%8x %8x %8x %8x %6x %8x %s ",
3241 addr
, zcopy
.count
, zcopy
.cur_size
,
3242 zcopy
.max_size
, zcopy
.elem_size
,
3243 zcopy
.alloc_size
, zcopy
.zone_name
);
3244 if (zcopy
.exhaustible
)
3246 if (zcopy
.collectable
)
3248 if (zcopy
.expandable
)
3250 if (zcopy
.caller_acct
)
3257 db_show_one_zone(db_expr_t addr
, boolean_t have_addr
,
3258 __unused db_expr_t count
, __unused
char *modif
)
3260 struct zone
*z
= (zone_t
)((char *)0 + addr
);
3262 if (z
== ZONE_NULL
|| !have_addr
){
3263 db_error("No Zone\n");
3267 db_printf("%s\n", zone_labels
);
3273 db_show_all_zones(__unused db_expr_t addr
, boolean_t have_addr
, db_expr_t count
,
3274 __unused
char *modif
)
3280 * Don't risk hanging by unconditionally locking,
3281 * risk of incoherent data is small (zones aren't freed).
3283 have_addr
= simple_lock_try(&all_zones_lock
);
3287 simple_unlock(&all_zones_lock
);
3290 db_printf("%s\n", zone_labels
);
3291 for ( ; count
> 0; count
--) {
3293 db_error("Mangled Zone List\n");
3297 total
+= z
->cur_size
,
3299 have_addr
= simple_lock_try(&all_zones_lock
);
3302 simple_unlock(&all_zones_lock
);
3305 db_printf("\nTotal %8x", total
);
3306 db_printf("\n\nzone_gc() has reclaimed %d pages\n", zgc_stats
.pgs_freed
);
3311 db_zone_check_active(
3317 if (!zone_debug_enabled(zone
) || !zone_check
)
3319 tmp_elem
= queue_first(&zone
->active_zones
);
3320 while (count
< zone
->count
) {
3322 if (tmp_elem
== 0) {
3323 printf("unexpected zero element, zone=%p, count=%d\n",
3328 if (queue_end(tmp_elem
, &zone
->active_zones
)) {
3329 printf("unexpected queue_end, zone=%p, count=%d\n",
3334 tmp_elem
= queue_next(tmp_elem
);
3336 if (!queue_end(tmp_elem
, &zone
->active_zones
)) {
3337 printf("not at queue_end, zone=%p, tmp_elem=%p\n",
3344 db_zone_print_active(
3350 if (!zone_debug_enabled(zone
)) {
3351 printf("zone %p debug not enabled\n", zone
);
3355 printf("zone_check FALSE\n");
3359 printf("zone %p, active elements %d\n", zone
, zone
->count
);
3360 printf("active list:\n");
3361 tmp_elem
= queue_first(&zone
->active_zones
);
3362 while (count
< zone
->count
) {
3363 printf(" %p", tmp_elem
);
3365 if ((count
% 6) == 0)
3367 if (tmp_elem
== 0) {
3368 printf("\nunexpected zero element, count=%d\n", count
);
3371 if (queue_end(tmp_elem
, &zone
->active_zones
)) {
3372 printf("\nunexpected queue_end, count=%d\n", count
);
3375 tmp_elem
= queue_next(tmp_elem
);
3377 if (!queue_end(tmp_elem
, &zone
->active_zones
))
3378 printf("\nnot at queue_end, tmp_elem=%p\n", tmp_elem
);
3382 #endif /* ZONE_DEBUG */
3392 freecount
= zone_free_count(zone
);
3393 printf("zone %p, free elements %d\n", zone
, freecount
);
3394 printf("free list:\n");
3395 elem
= zone
->free_elements
;
3396 while (count
< freecount
) {
3397 printf(" 0x%x", elem
);
3399 if ((count
% 6) == 0)
3402 printf("\nunexpected zero element, count=%d\n", count
);
3405 elem
= *((vm_offset_t
*)elem
);
3408 printf("\nnot at end of free list, elem=0x%x\n", elem
);
3413 #endif /* MACH_KDB */
3418 /* should we care about locks here ? */
3426 char *elt
= (char *)prev
;
3428 if (!zone_debug_enabled(z
))
3430 elt
-= ZONE_DEBUG_OFFSET
;
3431 elt
= (char *) queue_next((queue_t
) elt
);
3432 if ((queue_t
) elt
== &z
->active_zones
)
3434 elt
+= ZONE_DEBUG_OFFSET
;
3444 if (!zone_debug_enabled(z
))
3446 if (queue_empty(&z
->active_zones
))
3448 elt
= (char *)queue_first(&z
->active_zones
);
3449 elt
+= ZONE_DEBUG_OFFSET
;
3454 * Second arg controls how many zone elements are printed:
3457 * n, n > 0 => last n on active list
3466 boolean_t print
= (tail
!= 0);
3470 if (z
->count
< tail
)
3472 tail
= z
->count
- tail
;
3473 for (elt
= first_element(z
); elt
; elt
= next_element(z
, elt
)) {
3474 if (print
&& tail
<= count
)
3475 db_printf("%8x\n", elt
);
3478 assert(count
== z
->count
);
3481 #endif /* MACH_KDB */
3483 #define zone_in_use(z) ( z->count || z->free_elements )
3489 if (zone_debug_enabled(z
) || zone_in_use(z
) ||
3490 z
->alloc_size
< (z
->elem_size
+ ZONE_DEBUG_OFFSET
))
3492 queue_init(&z
->active_zones
);
3493 z
->elem_size
+= ZONE_DEBUG_OFFSET
;
3500 if (!zone_debug_enabled(z
) || zone_in_use(z
))
3502 z
->elem_size
-= ZONE_DEBUG_OFFSET
;
3503 z
->active_zones
.next
= z
->active_zones
.prev
= NULL
;
3507 #endif /* ZONE_DEBUG */