2 * Copyright (c) 2000-2007 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/machine/vm_types.h>
75 #include <mach_debug/zone_info.h>
77 #include <kern/kern_types.h>
78 #include <kern/assert.h>
79 #include <kern/host.h>
80 #include <kern/macro_help.h>
81 #include <kern/sched.h>
82 #include <kern/lock.h>
83 #include <kern/sched_prim.h>
84 #include <kern/misc_protos.h>
85 #include <kern/thread_call.h>
86 #include <kern/zalloc.h>
87 #include <kern/kalloc.h>
90 #include <vm/vm_map.h>
91 #include <vm/vm_kern.h>
92 #include <vm/vm_page.h>
94 #include <machine/machparam.h>
96 #include <libkern/OSDebug.h>
97 #include <sys/kdebug.h>
100 /* for fake zone stat routines */
101 #include <ppc/savearea.h>
102 #include <ppc/mappings.h>
105 int check_freed_element
= 0;
108 /* Detect use of zone elt after freeing it by two methods:
109 * (1) Range-check the free-list "next" ptr for sanity.
110 * (2) Store the ptr in two different words, and compare them against
111 * each other when re-using the zone elt, to detect modifications;
116 #define is_kernel_data_addr(a) \
117 (!(a) || (IS_SYS_VA(a) && !((a) & (sizeof(long)-1))))
119 #else /* !defined(__alpha) */
121 #define is_kernel_data_addr(a) \
122 (!(a) || ((a) >= vm_min_kernel_address && !((a) & 0x3)))
124 #endif /* defined(__alpha) */
126 /* Should we set all words of the zone element to an illegal address
127 * when it is freed, to help catch usage after freeing? The down-side
128 * is that this obscures the identity of the freed element.
130 boolean_t zfree_clear
= FALSE
;
132 #define ADD_TO_ZONE(zone, element) \
137 i < zone->elem_size/sizeof(vm_offset_t) - 1; \
139 ((vm_offset_t *)(element))[i] = 0xdeadbeef; \
141 ((vm_offset_t *)(element))[0] = (zone)->free_elements; \
142 (zone)->free_elements = (vm_offset_t) (element); \
146 #define REMOVE_FROM_ZONE(zone, ret, type) \
148 (ret) = (type) (zone)->free_elements; \
149 if ((ret) != (type) 0) { \
150 if (!is_kernel_data_addr(((vm_offset_t *)(ret))[0])) { \
151 panic("A freed zone element has been modified.\n"); \
154 (zone)->free_elements = *((vm_offset_t *)(ret)); \
157 #else /* MACH_ASSERT */
159 #define ADD_TO_ZONE(zone, element) \
161 *((vm_offset_t *)(element)) = (zone)->free_elements; \
162 if (check_freed_element) { \
163 if ((zone)->elem_size >= (2 * sizeof(vm_offset_t))) \
164 ((vm_offset_t *)(element))[((zone)->elem_size/sizeof(vm_offset_t))-1] = \
165 (zone)->free_elements; \
167 (zone)->free_elements = (vm_offset_t) (element); \
171 #define REMOVE_FROM_ZONE(zone, ret, type) \
173 (ret) = (type) (zone)->free_elements; \
174 if ((ret) != (type) 0) { \
175 if (check_freed_element) { \
176 if ((zone)->elem_size >= (2 * sizeof(vm_offset_t)) && \
177 ((vm_offset_t *)(ret))[((zone)->elem_size/sizeof(vm_offset_t))-1] != \
178 ((vm_offset_t *)(ret))[0]) \
179 panic("a freed zone element has been modified");\
182 (zone)->free_elements = *((vm_offset_t *)(ret)); \
186 #endif /* MACH_ASSERT */
189 #define zone_debug_enabled(z) z->active_zones.next
190 #define ROUNDUP(x,y) ((((x)+(y)-1)/(y))*(y))
191 #define ZONE_DEBUG_OFFSET ROUNDUP(sizeof(queue_chain_t),16)
192 #endif /* ZONE_DEBUG */
195 * Support for garbage collection of unused zone pages:
198 struct zone_page_table_entry
{
199 struct zone_page_table_entry
*link
;
210 void zone_page_alloc(
214 void zone_page_free_element(
215 struct zone_page_table_entry
**free_pages
,
219 void zone_page_collect(
223 boolean_t
zone_page_collectable(
232 thread_call_param_t p0
,
233 thread_call_param_t p1
);
236 #if ZONE_DEBUG && MACH_KDB
240 #endif /* ZONE_DEBUG && MACH_KDB */
242 vm_map_t zone_map
= VM_MAP_NULL
;
244 zone_t zone_zone
= ZONE_NULL
; /* the zone containing other zones */
247 * The VM system gives us an initial chunk of memory.
248 * It has to be big enough to allocate the zone_zone
252 vm_size_t zdata_size
;
254 #define lock_zone(zone) \
256 lck_mtx_lock(&(zone)->lock); \
259 #define unlock_zone(zone) \
261 lck_mtx_unlock(&(zone)->lock); \
264 #define zone_wakeup(zone) thread_wakeup((event_t)(zone))
265 #define zone_sleep(zone) \
266 (void) lck_mtx_sleep(&(zone)->lock, 0, (event_t)(zone), THREAD_UNINT);
269 #define lock_zone_init(zone) \
272 (void) snprintf(_name, sizeof (_name), "zone.%s", (zone)->zone_name); \
273 lck_grp_attr_setdefault(&(zone)->lock_grp_attr); \
274 lck_grp_init(&(zone)->lock_grp, _name, &(zone)->lock_grp_attr); \
275 lck_attr_setdefault(&(zone)->lock_attr); \
276 lck_mtx_init_ext(&(zone)->lock, &(zone)->lock_ext, \
277 &(zone)->lock_grp, &(zone)->lock_attr); \
280 #define lock_try_zone(zone) lck_mtx_try_lock(&zone->lock)
282 kern_return_t
zget_space(
284 vm_offset_t
*result
);
286 decl_simple_lock_data(,zget_space_lock
)
287 vm_offset_t zalloc_next_space
;
288 vm_offset_t zalloc_end_of_space
;
289 vm_size_t zalloc_wasted_space
;
292 * Garbage collection map information
294 struct zone_page_table_entry
* zone_page_table
;
295 vm_offset_t zone_map_min_address
;
296 vm_offset_t zone_map_max_address
;
297 unsigned int zone_pages
;
300 * Exclude more than one concurrent garbage collection
302 decl_mutex_data(, zone_gc_lock
)
305 #define from_zone_map(addr, size) \
306 ((vm_offset_t)(addr) >= zone_map_min_address && \
307 ((vm_offset_t)(addr) + size -1) < zone_map_max_address)
309 #define from_zone_map(addr, size) \
310 ((vm_offset_t)(zone_virtual_addr((vm_map_address_t)addr)) >= zone_map_min_address && \
311 ((vm_offset_t)(zone_virtual_addr((vm_map_address_t)addr)) + size -1) < zone_map_max_address)
314 #define ZONE_PAGE_USED 0
315 #define ZONE_PAGE_UNUSED -1
319 * Protects first_zone, last_zone, num_zones,
320 * and the next_zone field of zones.
322 decl_simple_lock_data(, all_zones_lock
)
325 unsigned int num_zones
;
327 boolean_t zone_gc_allowed
= TRUE
;
328 boolean_t zone_gc_forced
= FALSE
;
329 unsigned zone_gc_last_tick
= 0;
330 unsigned zone_gc_max_rate
= 0; /* in ticks */
334 * zinit initializes a new zone. The zone data structures themselves
335 * are stored in a zone, which is initially a static structure that
336 * is initialized by zone_init.
340 vm_size_t size
, /* the size of an element */
341 vm_size_t max
, /* maximum memory to use */
342 vm_size_t alloc
, /* allocation size */
343 const char *name
) /* a name for the zone */
347 if (zone_zone
== ZONE_NULL
) {
348 if (zget_space(sizeof(struct zone
), (vm_offset_t
*)&z
)
352 z
= (zone_t
) zalloc(zone_zone
);
357 * Round off all the parameters appropriately.
359 if (size
< sizeof(z
->free_elements
))
360 size
= sizeof(z
->free_elements
);
361 size
= ((size
-1) + sizeof(z
->free_elements
)) -
362 ((size
-1) % sizeof(z
->free_elements
));
365 alloc
= round_page(alloc
);
366 max
= round_page(max
);
368 * we look for an allocation size with less than 1% waste
369 * up to 5 pages in size...
370 * otherwise, we look for an allocation size with least fragmentation
371 * in the range of 1 - 5 pages
372 * This size will be used unless
373 * the user suggestion is larger AND has less fragmentation
376 if ((size
< PAGE_SIZE
) && (PAGE_SIZE
% size
<= PAGE_SIZE
/ 10))
380 { vm_size_t best
, waste
; unsigned int i
;
384 for (i
= 1; i
<= 5; i
++) {
385 vm_size_t tsize
, twaste
;
387 tsize
= i
* PAGE_SIZE
;
389 if ((tsize
% size
) < (tsize
/ 100)) {
391 goto use_this_allocation
;
393 twaste
= tsize
% size
;
395 best
= tsize
, waste
= twaste
;
397 if (alloc
<= best
|| (alloc
% size
>= waste
))
401 if (max
&& (max
< alloc
))
404 z
->free_elements
= 0;
408 z
->alloc_size
= alloc
;
411 z
->doing_alloc
= FALSE
;
413 z
->exhaustible
= FALSE
;
414 z
->collectable
= TRUE
;
415 z
->allows_foreign
= FALSE
;
416 z
->expandable
= TRUE
;
418 z
->async_pending
= FALSE
;
421 z
->active_zones
.next
= z
->active_zones
.prev
= NULL
;
422 zone_debug_enable(z
);
423 #endif /* ZONE_DEBUG */
427 * Add the zone to the all-zones list.
430 z
->next_zone
= ZONE_NULL
;
431 thread_call_setup(&z
->call_async_alloc
, zalloc_async
, z
);
432 simple_lock(&all_zones_lock
);
434 last_zone
= &z
->next_zone
;
436 simple_unlock(&all_zones_lock
);
442 * Cram the given memory into the specified zone.
446 register zone_t zone
,
450 register vm_size_t elem_size
;
451 vm_offset_t newmem
= (vm_offset_t
) newaddr
;
453 /* Basic sanity checks */
454 assert(zone
!= ZONE_NULL
&& newmem
!= (vm_offset_t
)0);
455 assert(!zone
->collectable
|| zone
->allows_foreign
456 || (from_zone_map(newmem
, size
)));
458 elem_size
= zone
->elem_size
;
461 while (size
>= elem_size
) {
462 ADD_TO_ZONE(zone
, newmem
);
463 if (from_zone_map(newmem
, elem_size
))
464 zone_page_alloc(newmem
, elem_size
);
465 zone
->count
++; /* compensate for ADD_TO_ZONE */
468 zone
->cur_size
+= elem_size
;
474 * Contiguous space allocator for non-paged zones. Allocates "size" amount
475 * of memory from zone_map.
483 vm_offset_t new_space
= 0;
484 vm_size_t space_to_add
= 0;
486 simple_lock(&zget_space_lock
);
487 while ((zalloc_next_space
+ size
) > zalloc_end_of_space
) {
489 * Add at least one page to allocation area.
492 space_to_add
= round_page(size
);
494 if (new_space
== 0) {
495 kern_return_t retval
;
497 * Memory cannot be wired down while holding
498 * any locks that the pageout daemon might
499 * need to free up pages. [Making the zget_space
500 * lock a complex lock does not help in this
503 * Unlock and allocate memory. Because several
504 * threads might try to do this at once, don't
505 * use the memory before checking for available
509 simple_unlock(&zget_space_lock
);
511 retval
= kernel_memory_allocate(zone_map
, &new_space
,
512 space_to_add
, 0, KMA_KOBJECT
|KMA_NOPAGEWAIT
);
513 if (retval
!= KERN_SUCCESS
)
516 if (space_to_add
== PAGE_SIZE
)
517 new_space
= zone_alias_addr(new_space
);
519 zone_page_init(new_space
, space_to_add
,
521 simple_lock(&zget_space_lock
);
527 * Memory was allocated in a previous iteration.
529 * Check whether the new region is contiguous
533 if (new_space
!= zalloc_end_of_space
) {
535 * Throw away the remainder of the
536 * old space, and start a new one.
538 zalloc_wasted_space
+=
539 zalloc_end_of_space
- zalloc_next_space
;
540 zalloc_next_space
= new_space
;
543 zalloc_end_of_space
= new_space
+ space_to_add
;
547 *result
= zalloc_next_space
;
548 zalloc_next_space
+= size
;
549 simple_unlock(&zget_space_lock
);
552 kmem_free(zone_map
, new_space
, space_to_add
);
554 return(KERN_SUCCESS
);
559 * Steal memory for the zone package. Called from
560 * vm_page_bootstrap().
563 zone_steal_memory(void)
565 zdata_size
= round_page(128*sizeof(struct zone
));
566 zdata
= (vm_offset_t
)((char *)pmap_steal_memory(zdata_size
) - (char *)0);
571 * Fill a zone with enough memory to contain at least nelem elements.
572 * Memory is obtained with kmem_alloc_wired from the kernel_map.
573 * Return the number of elements actually put into the zone, which may
574 * be more than the caller asked for since the memory allocation is
575 * rounded up to a full page.
590 size
= nelem
* zone
->elem_size
;
591 size
= round_page(size
);
592 kr
= kmem_alloc_wired(kernel_map
, &memory
, size
);
593 if (kr
!= KERN_SUCCESS
)
596 zone_change(zone
, Z_FOREIGN
, TRUE
);
597 zcram(zone
, (void *)memory
, size
);
598 nalloc
= size
/ zone
->elem_size
;
599 assert(nalloc
>= nelem
);
605 * Initialize the "zone of zones" which uses fixed memory allocated
606 * earlier in memory initialization. zone_bootstrap is called
612 vm_size_t zone_zone_size
;
613 vm_offset_t zone_zone_space
;
616 /* see if we want freed zone element checking */
617 if (PE_parse_boot_argn("-zc", temp_buf
, sizeof (temp_buf
))) {
618 check_freed_element
= 1;
621 simple_lock_init(&all_zones_lock
, 0);
623 first_zone
= ZONE_NULL
;
624 last_zone
= &first_zone
;
627 simple_lock_init(&zget_space_lock
, 0);
628 zalloc_next_space
= zdata
;
629 zalloc_end_of_space
= zdata
+ zdata_size
;
630 zalloc_wasted_space
= 0;
632 /* assertion: nobody else called zinit before us */
633 assert(zone_zone
== ZONE_NULL
);
634 zone_zone
= zinit(sizeof(struct zone
), 128 * sizeof(struct zone
),
635 sizeof(struct zone
), "zones");
636 zone_change(zone_zone
, Z_COLLECT
, FALSE
);
637 zone_zone_size
= zalloc_end_of_space
- zalloc_next_space
;
638 zget_space(zone_zone_size
, &zone_zone_space
);
639 zcram(zone_zone
, (void *)zone_zone_space
, zone_zone_size
);
644 vm_size_t max_zonemap_size
)
646 kern_return_t retval
;
647 vm_offset_t zone_min
;
648 vm_offset_t zone_max
;
649 vm_size_t zone_table_size
;
651 retval
= kmem_suballoc(kernel_map
, &zone_min
, max_zonemap_size
,
652 FALSE
, VM_FLAGS_ANYWHERE
, &zone_map
);
654 if (retval
!= KERN_SUCCESS
)
655 panic("zone_init: kmem_suballoc failed");
656 zone_max
= zone_min
+ round_page(max_zonemap_size
);
658 * Setup garbage collection information:
660 zone_table_size
= atop_32(zone_max
- zone_min
) *
661 sizeof(struct zone_page_table_entry
);
662 if (kmem_alloc_wired(zone_map
, (vm_offset_t
*) &zone_page_table
,
663 zone_table_size
) != KERN_SUCCESS
)
665 zone_min
= (vm_offset_t
)zone_page_table
+ round_page(zone_table_size
);
666 zone_pages
= atop_32(zone_max
- zone_min
);
667 zone_map_min_address
= zone_min
;
668 zone_map_max_address
= zone_max
;
669 mutex_init(&zone_gc_lock
, 0);
670 zone_page_init(zone_min
, zone_max
- zone_min
, ZONE_PAGE_UNUSED
);
675 * zalloc returns an element from the specified zone.
679 register zone_t zone
,
683 kern_return_t retval
;
685 assert(zone
!= ZONE_NULL
);
689 REMOVE_FROM_ZONE(zone
, addr
, vm_offset_t
);
691 while ((addr
== 0) && canblock
&& (zone
->doing_gc
)) {
692 zone
->waiting
= TRUE
;
694 REMOVE_FROM_ZONE(zone
, addr
, vm_offset_t
);
697 while ((addr
== 0) && canblock
) {
699 * If nothing was there, try to get more
701 if (zone
->doing_alloc
) {
703 * Someone is allocating memory for this zone.
704 * Wait for it to show up, then try again.
706 zone
->waiting
= TRUE
;
710 if ((zone
->cur_size
+ zone
->elem_size
) >
712 if (zone
->exhaustible
)
714 if (zone
->expandable
) {
716 * We're willing to overflow certain
717 * zones, but not without complaining.
719 * This is best used in conjunction
720 * with the collectable flag. What we
721 * want is an assurance we can get the
722 * memory back, assuming there's no
725 zone
->max_size
+= (zone
->max_size
>> 1);
729 panic("zalloc: zone \"%s\" empty.", zone
->zone_name
);
732 zone
->doing_alloc
= TRUE
;
735 if (zone
->collectable
) {
737 vm_size_t alloc_size
;
742 if (vm_pool_low() || retry
>= 1)
744 round_page(zone
->elem_size
);
746 alloc_size
= zone
->alloc_size
;
748 retval
= kernel_memory_allocate(zone_map
,
749 &space
, alloc_size
, 0,
750 KMA_KOBJECT
|KMA_NOPAGEWAIT
);
751 if (retval
== KERN_SUCCESS
) {
753 if (alloc_size
== PAGE_SIZE
)
754 space
= zone_alias_addr(space
);
756 zone_page_init(space
, alloc_size
,
758 zcram(zone
, (void *)space
, alloc_size
);
761 } else if (retval
!= KERN_RESOURCE_SHORTAGE
) {
766 printf("zalloc did gc\n");
769 panic("zalloc: \"%s\" (%d elements) retry fail %d", zone
->zone_name
, zone
->count
, retval
);
775 zone
->doing_alloc
= FALSE
;
777 zone
->waiting
= FALSE
;
780 REMOVE_FROM_ZONE(zone
, addr
, vm_offset_t
);
782 retval
== KERN_RESOURCE_SHORTAGE
) {
790 retval
= zget_space(zone
->elem_size
, &space
);
793 zone
->doing_alloc
= FALSE
;
795 zone
->waiting
= FALSE
;
796 thread_wakeup((event_t
)zone
);
798 if (retval
== KERN_SUCCESS
) {
800 zone
->cur_size
+= zone
->elem_size
;
802 if (zone_debug_enabled(zone
)) {
803 enqueue_tail(&zone
->active_zones
, (queue_entry_t
)space
);
807 zone_page_alloc(space
, zone
->elem_size
);
809 if (zone_debug_enabled(zone
))
810 space
+= ZONE_DEBUG_OFFSET
;
815 if (retval
== KERN_RESOURCE_SHORTAGE
) {
821 panic("zalloc: \"%s\" (%d elements) zget_space returned %d", zone
->zone_name
, zone
->count
, retval
);
826 REMOVE_FROM_ZONE(zone
, addr
, vm_offset_t
);
829 if ((addr
== 0) && !canblock
&& (zone
->async_pending
== FALSE
) && (zone
->exhaustible
== FALSE
) && (!vm_pool_low())) {
830 zone
->async_pending
= TRUE
;
832 thread_call_enter(&zone
->call_async_alloc
);
834 REMOVE_FROM_ZONE(zone
, addr
, vm_offset_t
);
838 if (addr
&& zone_debug_enabled(zone
)) {
839 enqueue_tail(&zone
->active_zones
, (queue_entry_t
)addr
);
840 addr
+= ZONE_DEBUG_OFFSET
;
847 TRACE_MACHLEAKS(ZALLOC_CODE
, ZALLOC_CODE_2
, zone
->elem_size
, addr
);
849 return((void *)addr
);
855 register zone_t zone
)
857 return( zalloc_canblock(zone
, TRUE
) );
862 register zone_t zone
)
864 return( zalloc_canblock(zone
, FALSE
) );
869 thread_call_param_t p0
,
870 __unused thread_call_param_t p1
)
874 elt
= zalloc_canblock((zone_t
)p0
, TRUE
);
875 zfree((zone_t
)p0
, elt
);
876 lock_zone(((zone_t
)p0
));
877 ((zone_t
)p0
)->async_pending
= FALSE
;
878 unlock_zone(((zone_t
)p0
));
883 * zget returns an element from the specified zone
884 * and immediately returns nothing if there is nothing there.
886 * This form should be used when you can not block (like when
887 * processing an interrupt).
891 register zone_t zone
)
893 register vm_offset_t addr
;
895 assert( zone
!= ZONE_NULL
);
897 if (!lock_try_zone(zone
))
900 REMOVE_FROM_ZONE(zone
, addr
, vm_offset_t
);
902 if (addr
&& zone_debug_enabled(zone
)) {
903 enqueue_tail(&zone
->active_zones
, (queue_entry_t
)addr
);
904 addr
+= ZONE_DEBUG_OFFSET
;
906 #endif /* ZONE_DEBUG */
909 return((void *) addr
);
912 /* Keep this FALSE by default. Large memory machine run orders of magnitude
913 slower in debug mode when true. Use debugger to enable if needed */
914 /* static */ boolean_t zone_check
= FALSE
;
916 static zone_t zone_last_bogus_zone
= ZONE_NULL
;
917 static vm_offset_t zone_last_bogus_elem
= 0;
921 register zone_t zone
,
924 vm_offset_t elem
= (vm_offset_t
) addr
;
927 /* Basic sanity checks */
928 if (zone
== ZONE_NULL
|| elem
== (vm_offset_t
)0)
929 panic("zfree: NULL");
930 /* zone_gc assumes zones are never freed */
931 if (zone
== zone_zone
)
932 panic("zfree: freeing to zone_zone breaks zone_gc!");
935 TRACE_MACHLEAKS(ZFREE_CODE
, ZFREE_CODE_2
, zone
->elem_size
, (int)addr
);
937 if (zone
->collectable
&& !zone
->allows_foreign
&&
938 !from_zone_map(elem
, zone
->elem_size
)) {
940 panic("zfree: non-allocated memory in collectable zone!");
942 zone_last_bogus_zone
= zone
;
943 zone_last_bogus_elem
= elem
;
949 if (zone_debug_enabled(zone
)) {
952 elem
-= ZONE_DEBUG_OFFSET
;
954 /* check the zone's consistency */
956 for (tmp_elem
= queue_first(&zone
->active_zones
);
957 !queue_end(tmp_elem
, &zone
->active_zones
);
958 tmp_elem
= queue_next(tmp_elem
))
959 if (elem
== (vm_offset_t
)tmp_elem
)
961 if (elem
!= (vm_offset_t
)tmp_elem
)
962 panic("zfree()ing element from wrong zone");
964 remqueue(&zone
->active_zones
, (queue_t
) elem
);
966 #endif /* ZONE_DEBUG */
970 /* check the zone's consistency */
972 for (this = zone
->free_elements
;
974 this = * (vm_offset_t
*) this)
975 if (!pmap_kernel_va(this) || this == elem
)
978 ADD_TO_ZONE(zone
, elem
);
981 * If elements have one or more pages, and memory is low,
982 * request to run the garbage collection in the zone the next
983 * time the pageout thread runs.
985 if (zone
->elem_size
>= PAGE_SIZE
&&
987 zone_gc_forced
= TRUE
;
993 /* Change a zone's flags.
994 * This routine must be called immediately after zinit.
1002 assert( zone
!= ZONE_NULL
);
1003 assert( value
== TRUE
|| value
== FALSE
);
1007 zone
->exhaustible
= value
;
1010 zone
->collectable
= value
;
1013 zone
->expandable
= value
;
1016 zone
->allows_foreign
= value
;
1020 panic("Zone_change: Wrong Item Type!");
1027 * Return the expected number of free elements in the zone.
1028 * This calculation will be incorrect if items are zfree'd that
1029 * were never zalloc'd/zget'd. The correct way to stuff memory
1030 * into a zone is by zcram.
1034 zone_free_count(zone_t zone
)
1036 integer_t free_count
;
1039 free_count
= zone
->cur_size
/zone
->elem_size
- zone
->count
;
1042 assert(free_count
>= 0);
1048 * zprealloc preallocates wired memory, exanding the specified
1049 * zone to the specified size
1059 if (kmem_alloc_wired(zone_map
, &addr
, size
) != KERN_SUCCESS
)
1061 zone_page_init(addr
, size
, ZONE_PAGE_USED
);
1062 zcram(zone
, (void *)addr
, size
);
1067 * Zone garbage collection subroutines
1071 zone_page_collectable(
1075 struct zone_page_table_entry
*zp
;
1079 addr
= zone_virtual_addr(addr
);
1082 if (!from_zone_map(addr
, size
))
1083 panic("zone_page_collectable");
1086 i
= atop_32(addr
-zone_map_min_address
);
1087 j
= atop_32((addr
+size
-1) - zone_map_min_address
);
1089 for (zp
= zone_page_table
+ i
; i
<= j
; zp
++, i
++)
1090 if (zp
->collect_count
== zp
->alloc_count
)
1101 struct zone_page_table_entry
*zp
;
1105 addr
= zone_virtual_addr(addr
);
1108 if (!from_zone_map(addr
, size
))
1109 panic("zone_page_keep");
1112 i
= atop_32(addr
-zone_map_min_address
);
1113 j
= atop_32((addr
+size
-1) - zone_map_min_address
);
1115 for (zp
= zone_page_table
+ i
; i
<= j
; zp
++, i
++)
1116 zp
->collect_count
= 0;
1124 struct zone_page_table_entry
*zp
;
1128 addr
= zone_virtual_addr(addr
);
1131 if (!from_zone_map(addr
, size
))
1132 panic("zone_page_collect");
1135 i
= atop_32(addr
-zone_map_min_address
);
1136 j
= atop_32((addr
+size
-1) - zone_map_min_address
);
1138 for (zp
= zone_page_table
+ i
; i
<= j
; zp
++, i
++)
1139 ++zp
->collect_count
;
1148 struct zone_page_table_entry
*zp
;
1152 addr
= zone_virtual_addr(addr
);
1155 if (!from_zone_map(addr
, size
))
1156 panic("zone_page_init");
1159 i
= atop_32(addr
-zone_map_min_address
);
1160 j
= atop_32((addr
+size
-1) - zone_map_min_address
);
1162 for (zp
= zone_page_table
+ i
; i
<= j
; zp
++, i
++) {
1163 zp
->alloc_count
= value
;
1164 zp
->collect_count
= 0;
1173 struct zone_page_table_entry
*zp
;
1177 addr
= zone_virtual_addr(addr
);
1180 if (!from_zone_map(addr
, size
))
1181 panic("zone_page_alloc");
1184 i
= atop_32(addr
-zone_map_min_address
);
1185 j
= atop_32((addr
+size
-1) - zone_map_min_address
);
1187 for (zp
= zone_page_table
+ i
; i
<= j
; zp
++, i
++) {
1189 * Set alloc_count to (ZONE_PAGE_USED + 1) if
1190 * it was previously set to ZONE_PAGE_UNUSED.
1192 if (zp
->alloc_count
== ZONE_PAGE_UNUSED
)
1193 zp
->alloc_count
= 1;
1200 zone_page_free_element(
1201 struct zone_page_table_entry
**free_pages
,
1205 struct zone_page_table_entry
*zp
;
1209 addr
= zone_virtual_addr(addr
);
1212 if (!from_zone_map(addr
, size
))
1213 panic("zone_page_free_element");
1216 i
= atop_32(addr
-zone_map_min_address
);
1217 j
= atop_32((addr
+size
-1) - zone_map_min_address
);
1219 for (zp
= zone_page_table
+ i
; i
<= j
; zp
++, i
++) {
1220 if (zp
->collect_count
> 0)
1221 --zp
->collect_count
;
1222 if (--zp
->alloc_count
== 0) {
1223 zp
->alloc_count
= ZONE_PAGE_UNUSED
;
1224 zp
->collect_count
= 0;
1226 zp
->link
= *free_pages
;
1233 /* This is used for walking through a zone's free element list.
1235 struct zone_free_element
{
1236 struct zone_free_element
* next
;
1240 * Add a linked list of pages starting at base back into the zone
1241 * free list. Tail points to the last element on the list.
1244 #define ADD_LIST_TO_ZONE(zone, base, tail) \
1246 (tail)->next = (void *)((zone)->free_elements); \
1247 if (check_freed_element) { \
1248 if ((zone)->elem_size >= (2 * sizeof(vm_offset_t))) \
1249 ((vm_offset_t *)(tail))[((zone)->elem_size/sizeof(vm_offset_t))-1] = \
1250 (zone)->free_elements; \
1252 (zone)->free_elements = (unsigned long)(base); \
1256 * Add an element to the chain pointed to by prev.
1259 #define ADD_ELEMENT(zone, prev, elem) \
1261 (prev)->next = (elem); \
1262 if (check_freed_element) { \
1263 if ((zone)->elem_size >= (2 * sizeof(vm_offset_t))) \
1264 ((vm_offset_t *)(prev))[((zone)->elem_size/sizeof(vm_offset_t))-1] = \
1265 (vm_offset_t)(elem); \
1272 uint32_t elems_collected
,
1277 /* Zone garbage collection
1279 * zone_gc will walk through all the free elements in all the
1280 * zones that are marked collectable looking for reclaimable
1281 * pages. zone_gc is called by consider_zone_gc when the system
1282 * begins to run out of memory.
1287 unsigned int max_zones
;
1290 struct zone_page_table_entry
*zp
, *zone_free_pages
;
1292 mutex_lock(&zone_gc_lock
);
1294 simple_lock(&all_zones_lock
);
1295 max_zones
= num_zones
;
1297 simple_unlock(&all_zones_lock
);
1300 for (i
= 0; i
< zone_pages
; i
++)
1301 assert(zone_page_table
[i
].collect_count
== 0);
1302 #endif /* MACH_ASSERT */
1304 zone_free_pages
= NULL
;
1306 for (i
= 0; i
< max_zones
; i
++, z
= z
->next_zone
) {
1308 vm_size_t elt_size
, size_freed
;
1309 struct zone_free_element
*elt
, *base_elt
, *base_prev
, *prev
, *scan
, *keep
, *tail
;
1311 assert(z
!= ZONE_NULL
);
1313 if (!z
->collectable
)
1318 elt_size
= z
->elem_size
;
1321 * Do a quick feasability check before we scan the zone:
1322 * skip unless there is likelihood of getting pages back
1323 * (i.e we need a whole allocation block's worth of free
1324 * elements before we can garbage collect) and
1325 * the zone has more than 10 percent of it's elements free
1326 * or the element size is a multiple of the PAGE_SIZE
1328 if ((elt_size
& PAGE_MASK
) &&
1329 (((z
->cur_size
- z
->count
* elt_size
) <= (2 * z
->alloc_size
)) ||
1330 ((z
->cur_size
- z
->count
* elt_size
) <= (z
->cur_size
/ 10)))) {
1338 * Snatch all of the free elements away from the zone.
1341 scan
= (void *)z
->free_elements
;
1342 z
->free_elements
= 0;
1349 * Determine which elements we can attempt to collect
1350 * and count them up in the page table. Foreign elements
1351 * are returned to the zone.
1354 prev
= (void *)&scan
;
1356 n
= 0; tail
= keep
= NULL
;
1357 while (elt
!= NULL
) {
1358 if (from_zone_map(elt
, elt_size
)) {
1359 zone_page_collect((vm_offset_t
)elt
, elt_size
);
1364 ++zgc_stats
.elems_collected
;
1370 ADD_ELEMENT(z
, tail
, elt
);
1374 ADD_ELEMENT(z
, prev
, elt
->next
);
1376 ADD_ELEMENT(z
, tail
, NULL
);
1380 * Dribble back the elements we are keeping.
1384 if (z
->waiting
== TRUE
) {
1388 ADD_LIST_TO_ZONE(z
, keep
, tail
);
1394 while ((elt
!= NULL
) && (++m
< 50)) {
1399 ADD_LIST_TO_ZONE(z
, base_elt
, prev
);
1400 ADD_ELEMENT(z
, base_prev
, elt
);
1417 * Return any remaining elements.
1423 ADD_LIST_TO_ZONE(z
, keep
, tail
);
1431 * Determine which pages we can reclaim and
1432 * free those elements.
1437 n
= 0; tail
= keep
= NULL
;
1438 while (elt
!= NULL
) {
1439 if (zone_page_collectable((vm_offset_t
)elt
, elt_size
)) {
1440 size_freed
+= elt_size
;
1441 zone_page_free_element(&zone_free_pages
,
1442 (vm_offset_t
)elt
, elt_size
);
1446 ++zgc_stats
.elems_freed
;
1449 zone_page_keep((vm_offset_t
)elt
, elt_size
);
1454 ADD_ELEMENT(z
, tail
, elt
);
1459 ADD_ELEMENT(z
, tail
, NULL
);
1461 ++zgc_stats
.elems_kept
;
1465 * Dribble back the elements we are keeping,
1466 * and update the zone size info.
1472 z
->cur_size
-= size_freed
;
1476 ADD_LIST_TO_ZONE(z
, keep
, tail
);
1486 n
= 0; tail
= keep
= NULL
;
1491 * Return any remaining elements, and update
1492 * the zone size info.
1497 if (size_freed
> 0 || keep
!= NULL
) {
1499 z
->cur_size
-= size_freed
;
1502 ADD_LIST_TO_ZONE(z
, keep
, tail
);
1507 z
->doing_gc
= FALSE
;
1516 * Reclaim the pages we are freeing.
1519 while ((zp
= zone_free_pages
) != NULL
) {
1520 zone_free_pages
= zp
->link
;
1522 z
= zone_virtual_addr((vm_map_address_t
)z
);
1524 kmem_free(zone_map
, zone_map_min_address
+ PAGE_SIZE
*
1525 (zp
- zone_page_table
), PAGE_SIZE
);
1526 ++zgc_stats
.pgs_freed
;
1529 mutex_unlock(&zone_gc_lock
);
1535 * Called by the pageout daemon when the system needs more free pages.
1539 consider_zone_gc(void)
1542 * By default, don't attempt zone GC more frequently
1543 * than once / 1 minutes.
1546 if (zone_gc_max_rate
== 0)
1547 zone_gc_max_rate
= (60 << SCHED_TICK_SHIFT
) + 1;
1549 if (zone_gc_allowed
&&
1550 ((sched_tick
> (zone_gc_last_tick
+ zone_gc_max_rate
)) ||
1552 zone_gc_forced
= FALSE
;
1553 zone_gc_last_tick
= sched_tick
;
1558 struct fake_zone_info
{
1560 void (*func
)(int *, vm_size_t
*, vm_size_t
*, vm_size_t
*, vm_size_t
*,
1564 static struct fake_zone_info fake_zones
[] = {
1566 .name
= "kernel_stacks",
1567 .func
= stack_fake_zone_info
,
1571 .name
= "save_areas",
1572 .func
= save_fake_zone_info
,
1575 .name
= "pmap_mappings",
1576 .func
= mapping_fake_zone_info
,
1581 .name
= "page_tables",
1582 .func
= pt_fake_zone_info
,
1586 .name
= "kalloc.large",
1587 .func
= kalloc_fake_zone_info
,
1594 zone_name_array_t
*namesp
,
1595 mach_msg_type_number_t
*namesCntp
,
1596 zone_info_array_t
*infop
,
1597 mach_msg_type_number_t
*infoCntp
)
1600 vm_offset_t names_addr
;
1601 vm_size_t names_size
;
1603 vm_offset_t info_addr
;
1604 vm_size_t info_size
;
1605 unsigned int max_zones
, i
;
1610 size_t num_fake_zones
;
1612 if (host
== HOST_NULL
)
1613 return KERN_INVALID_HOST
;
1615 num_fake_zones
= sizeof fake_zones
/ sizeof fake_zones
[0];
1618 * We assume that zones aren't freed once allocated.
1619 * We won't pick up any zones that are allocated later.
1622 simple_lock(&all_zones_lock
);
1623 max_zones
= num_zones
+ num_fake_zones
;
1625 simple_unlock(&all_zones_lock
);
1627 if (max_zones
<= *namesCntp
) {
1628 /* use in-line memory */
1629 names_size
= *namesCntp
* sizeof *names
;
1632 names_size
= round_page(max_zones
* sizeof *names
);
1633 kr
= kmem_alloc_pageable(ipc_kernel_map
,
1634 &names_addr
, names_size
);
1635 if (kr
!= KERN_SUCCESS
)
1637 names
= (zone_name_t
*) names_addr
;
1640 if (max_zones
<= *infoCntp
) {
1641 /* use in-line memory */
1642 info_size
= *infoCntp
* sizeof *info
;
1645 info_size
= round_page(max_zones
* sizeof *info
);
1646 kr
= kmem_alloc_pageable(ipc_kernel_map
,
1647 &info_addr
, info_size
);
1648 if (kr
!= KERN_SUCCESS
) {
1649 if (names
!= *namesp
)
1650 kmem_free(ipc_kernel_map
,
1651 names_addr
, names_size
);
1655 info
= (zone_info_t
*) info_addr
;
1660 for (i
= 0; i
< num_zones
; i
++) {
1663 assert(z
!= ZONE_NULL
);
1669 simple_lock(&all_zones_lock
);
1671 simple_unlock(&all_zones_lock
);
1673 /* assuming here the name data is static */
1674 (void) strncpy(zn
->zn_name
, zcopy
.zone_name
,
1675 sizeof zn
->zn_name
);
1676 zn
->zn_name
[sizeof zn
->zn_name
- 1] = '\0';
1678 zi
->zi_count
= zcopy
.count
;
1679 zi
->zi_cur_size
= zcopy
.cur_size
;
1680 zi
->zi_max_size
= zcopy
.max_size
;
1681 zi
->zi_elem_size
= zcopy
.elem_size
;
1682 zi
->zi_alloc_size
= zcopy
.alloc_size
;
1683 zi
->zi_exhaustible
= zcopy
.exhaustible
;
1684 zi
->zi_collectable
= zcopy
.collectable
;
1691 * loop through the fake zones and fill them using the specialized
1694 for (i
= 0; i
< num_fake_zones
; i
++) {
1695 strncpy(zn
->zn_name
, fake_zones
[i
].name
, sizeof zn
->zn_name
);
1696 zn
->zn_name
[sizeof zn
->zn_name
- 1] = '\0';
1697 fake_zones
[i
].func(&zi
->zi_count
, &zi
->zi_cur_size
,
1698 &zi
->zi_max_size
, &zi
->zi_elem_size
,
1699 &zi
->zi_alloc_size
, &zi
->zi_collectable
,
1700 &zi
->zi_exhaustible
);
1705 if (names
!= *namesp
) {
1709 used
= max_zones
* sizeof *names
;
1711 if (used
!= names_size
)
1712 bzero((char *) (names_addr
+ used
), names_size
- used
);
1714 kr
= vm_map_copyin(ipc_kernel_map
, (vm_map_address_t
)names_addr
,
1715 (vm_map_size_t
)names_size
, TRUE
, ©
);
1716 assert(kr
== KERN_SUCCESS
);
1718 *namesp
= (zone_name_t
*) copy
;
1720 *namesCntp
= max_zones
;
1722 if (info
!= *infop
) {
1726 used
= max_zones
* sizeof *info
;
1728 if (used
!= info_size
)
1729 bzero((char *) (info_addr
+ used
), info_size
- used
);
1731 kr
= vm_map_copyin(ipc_kernel_map
, (vm_map_address_t
)info_addr
,
1732 (vm_map_size_t
)info_size
, TRUE
, ©
);
1733 assert(kr
== KERN_SUCCESS
);
1735 *infop
= (zone_info_t
*) copy
;
1737 *infoCntp
= max_zones
;
1739 return KERN_SUCCESS
;
1743 #include <ddb/db_command.h>
1744 #include <ddb/db_output.h>
1745 #include <kern/kern_print.h>
1747 const char *zone_labels
=
1748 "ENTRY COUNT TOT_SZ MAX_SZ ELT_SZ ALLOC_SZ NAME";
1755 void db_zone_check_active(
1757 void db_zone_print_active(
1759 #endif /* ZONE_DEBUG */
1760 void db_zone_print_free(
1770 db_printf("%8x %8x %8x %8x %6x %8x %s ",
1771 addr
, zcopy
.count
, zcopy
.cur_size
,
1772 zcopy
.max_size
, zcopy
.elem_size
,
1773 zcopy
.alloc_size
, zcopy
.zone_name
);
1774 if (zcopy
.exhaustible
)
1776 if (zcopy
.collectable
)
1778 if (zcopy
.expandable
)
1785 db_show_one_zone(db_expr_t addr
, boolean_t have_addr
,
1786 __unused db_expr_t count
, __unused
char *modif
)
1788 struct zone
*z
= (zone_t
)((char *)0 + addr
);
1790 if (z
== ZONE_NULL
|| !have_addr
){
1791 db_error("No Zone\n");
1795 db_printf("%s\n", zone_labels
);
1801 db_show_all_zones(__unused db_expr_t addr
, boolean_t have_addr
, db_expr_t count
,
1802 __unused
char *modif
)
1808 * Don't risk hanging by unconditionally locking,
1809 * risk of incoherent data is small (zones aren't freed).
1811 have_addr
= simple_lock_try(&all_zones_lock
);
1815 simple_unlock(&all_zones_lock
);
1818 db_printf("%s\n", zone_labels
);
1819 for ( ; count
> 0; count
--) {
1821 db_error("Mangled Zone List\n");
1825 total
+= z
->cur_size
,
1827 have_addr
= simple_lock_try(&all_zones_lock
);
1830 simple_unlock(&all_zones_lock
);
1833 db_printf("\nTotal %8x", total
);
1834 db_printf("\n\nzone_gc() has reclaimed %d pages\n", zgc_stats
.pgs_freed
);
1839 db_zone_check_active(
1845 if (!zone_debug_enabled(zone
) || !zone_check
)
1847 tmp_elem
= queue_first(&zone
->active_zones
);
1848 while (count
< zone
->count
) {
1850 if (tmp_elem
== 0) {
1851 printf("unexpected zero element, zone=%p, count=%d\n",
1856 if (queue_end(tmp_elem
, &zone
->active_zones
)) {
1857 printf("unexpected queue_end, zone=%p, count=%d\n",
1862 tmp_elem
= queue_next(tmp_elem
);
1864 if (!queue_end(tmp_elem
, &zone
->active_zones
)) {
1865 printf("not at queue_end, zone=%p, tmp_elem=%p\n",
1872 db_zone_print_active(
1878 if (!zone_debug_enabled(zone
)) {
1879 printf("zone %p debug not enabled\n", zone
);
1883 printf("zone_check FALSE\n");
1887 printf("zone %p, active elements %d\n", zone
, zone
->count
);
1888 printf("active list:\n");
1889 tmp_elem
= queue_first(&zone
->active_zones
);
1890 while (count
< zone
->count
) {
1891 printf(" %p", tmp_elem
);
1893 if ((count
% 6) == 0)
1895 if (tmp_elem
== 0) {
1896 printf("\nunexpected zero element, count=%d\n", count
);
1899 if (queue_end(tmp_elem
, &zone
->active_zones
)) {
1900 printf("\nunexpected queue_end, count=%d\n", count
);
1903 tmp_elem
= queue_next(tmp_elem
);
1905 if (!queue_end(tmp_elem
, &zone
->active_zones
))
1906 printf("\nnot at queue_end, tmp_elem=%p\n", tmp_elem
);
1910 #endif /* ZONE_DEBUG */
1920 freecount
= zone_free_count(zone
);
1921 printf("zone %p, free elements %d\n", zone
, freecount
);
1922 printf("free list:\n");
1923 elem
= zone
->free_elements
;
1924 while (count
< freecount
) {
1925 printf(" 0x%x", elem
);
1927 if ((count
% 6) == 0)
1930 printf("\nunexpected zero element, count=%d\n", count
);
1933 elem
= *((vm_offset_t
*)elem
);
1936 printf("\nnot at end of free list, elem=0x%x\n", elem
);
1941 #endif /* MACH_KDB */
1946 /* should we care about locks here ? */
1954 char *elt
= (char *)prev
;
1956 if (!zone_debug_enabled(z
))
1958 elt
-= ZONE_DEBUG_OFFSET
;
1959 elt
= (char *) queue_next((queue_t
) elt
);
1960 if ((queue_t
) elt
== &z
->active_zones
)
1962 elt
+= ZONE_DEBUG_OFFSET
;
1972 if (!zone_debug_enabled(z
))
1974 if (queue_empty(&z
->active_zones
))
1976 elt
= (char *)queue_first(&z
->active_zones
);
1977 elt
+= ZONE_DEBUG_OFFSET
;
1982 * Second arg controls how many zone elements are printed:
1985 * n, n > 0 => last n on active list
1994 boolean_t print
= (tail
!= 0);
1998 if (z
->count
< tail
)
2000 tail
= z
->count
- tail
;
2001 for (elt
= first_element(z
); elt
; elt
= next_element(z
, elt
)) {
2002 if (print
&& tail
<= count
)
2003 db_printf("%8x\n", elt
);
2006 assert(count
== z
->count
);
2009 #endif /* MACH_KDB */
2011 #define zone_in_use(z) ( z->count || z->free_elements )
2017 if (zone_debug_enabled(z
) || zone_in_use(z
) ||
2018 z
->alloc_size
< (z
->elem_size
+ ZONE_DEBUG_OFFSET
))
2020 queue_init(&z
->active_zones
);
2021 z
->elem_size
+= ZONE_DEBUG_OFFSET
;
2028 if (!zone_debug_enabled(z
) || zone_in_use(z
))
2030 z
->elem_size
-= ZONE_DEBUG_OFFSET
;
2031 z
->active_zones
.next
= z
->active_zones
.prev
= NULL
;
2033 #endif /* ZONE_DEBUG */