xref: /titanic_50/usr/src/uts/common/os/mmapobj.c (revision be6d98b192e41ad1e1d164e3b5e9b66ff01873c2)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #include <sys/types.h>
27 #include <sys/sysmacros.h>
28 #include <sys/kmem.h>
29 #include <sys/param.h>
30 #include <sys/systm.h>
31 #include <sys/errno.h>
32 #include <sys/mman.h>
33 #include <sys/cmn_err.h>
34 #include <sys/cred.h>
35 #include <sys/vmsystm.h>
36 #include <sys/debug.h>
37 #include <vm/as.h>
38 #include <vm/seg.h>
39 #include <sys/vmparam.h>
40 #include <sys/vfs.h>
41 #include <sys/elf.h>
42 #include <sys/machelf.h>
43 #include <sys/corectl.h>
44 #include <sys/exec.h>
45 #include <sys/exechdr.h>
46 #include <sys/autoconf.h>
47 #include <sys/mem.h>
48 #include <vm/seg_dev.h>
49 #include <sys/vmparam.h>
50 #include <sys/mmapobj.h>
51 #include <sys/atomic.h>
52 
53 /*
54  * Theory statement:
55  *
56  * The main driving force behind mmapobj is to interpret and map ELF files
57  * inside of the kernel instead of having the linker be responsible for this.
58  *
59  * mmapobj also supports the AOUT 4.x binary format as well as flat files in
60  * a read only manner.
61  *
62  * When interpreting and mapping an ELF file, mmapobj will map each PT_LOAD
63  * or PT_SUNWBSS segment according to the ELF standard.  Refer to the "Linker
64  * and Libraries Guide" for more information about the standard and mapping
65  * rules.
66  *
67  * Having mmapobj interpret and map objects will allow the kernel to make the
68  * best decision for where to place the mappings for said objects.  Thus, we
69  * can make optimizations inside of the kernel for specific platforms or
70  * cache mapping information to make mapping objects faster.
71  *
72  * The lib_va_hash will be one such optimization.  For each ELF object that
73  * mmapobj is asked to interpret, we will attempt to cache the information
74  * about the PT_LOAD and PT_SUNWBSS sections to speed up future mappings of
75  * the same objects.  We will cache up to LIBVA_CACHED_SEGS (see below) program
76  * headers which should cover a majority of the libraries out there without
77  * wasting space.  In order to make sure that the cached information is valid,
78  * we check the passed in vnode's mtime and ctime to make sure the vnode
79  * has not been modified since the last time we used it.
80  *
81  * In addition, the lib_va_hash may contain a preferred starting VA for the
82  * object which can be useful for platforms which support a shared context.
83  * This will increase the likelyhood that library text can be shared among
84  * many different processes.  We limit the reserved VA space for 32 bit objects
85  * in order to minimize fragmenting the processes address space.
86  *
87  * In addition to the above, the mmapobj interface allows for padding to be
88  * requested before the first mapping and after the last mapping created.
89  * When padding is requested, no additional optimizations will be made for
90  * that request.
91  */
92 
93 /*
94  * Threshold to prevent allocating too much kernel memory to read in the
95  * program headers for an object.  If it requires more than below,
96  * we will use a KM_NOSLEEP allocation to allocate memory to hold all of the
97  * program headers which could possibly fail.  If less memory than below is
98  * needed, then we use a KM_SLEEP allocation and are willing to wait for the
99  * memory if we need to.
100  */
101 size_t mmapobj_alloc_threshold = 65536;
102 
103 /* Debug stats for test coverage */
104 #ifdef DEBUG
105 struct mobj_stats {
106 	uint_t	mobjs_unmap_called;
107 	uint_t	mobjs_remap_devnull;
108 	uint_t	mobjs_lookup_start;
109 	uint_t	mobjs_alloc_start;
110 	uint_t	mobjs_alloc_vmem;
111 	uint_t	mobjs_add_collision;
112 	uint_t	mobjs_get_addr;
113 	uint_t	mobjs_map_flat_no_padding;
114 	uint_t	mobjs_map_flat_padding;
115 	uint_t	mobjs_map_ptload_text;
116 	uint_t	mobjs_map_ptload_initdata;
117 	uint_t	mobjs_map_ptload_preread;
118 	uint_t	mobjs_map_ptload_unaligned_text;
119 	uint_t	mobjs_map_ptload_unaligned_map_fail;
120 	uint_t	mobjs_map_ptload_unaligned_read_fail;
121 	uint_t	mobjs_zfoddiff;
122 	uint_t	mobjs_zfoddiff_nowrite;
123 	uint_t	mobjs_zfodextra;
124 	uint_t	mobjs_ptload_failed;
125 	uint_t	mobjs_map_elf_no_holes;
126 	uint_t	mobjs_unmap_hole;
127 	uint_t	mobjs_nomem_header;
128 	uint_t	mobjs_overlap_header;
129 	uint_t	mobjs_np2_align;
130 	uint_t	mobjs_np2_align_overflow;
131 	uint_t	mobjs_exec_padding;
132 	uint_t	mobjs_exec_addr_mapped;
133 	uint_t	mobjs_exec_addr_devnull;
134 	uint_t	mobjs_exec_addr_in_use;
135 	uint_t	mobjs_lvp_found;
136 	uint_t	mobjs_no_loadable_yet;
137 	uint_t	mobjs_nothing_to_map;
138 	uint_t	mobjs_e2big;
139 	uint_t	mobjs_dyn_pad_align;
140 	uint_t	mobjs_dyn_pad_noalign;
141 	uint_t	mobjs_alloc_start_fail;
142 	uint_t	mobjs_lvp_nocache;
143 	uint_t	mobjs_extra_padding;
144 	uint_t	mobjs_lvp_not_needed;
145 	uint_t	mobjs_no_mem_map_sz;
146 	uint_t	mobjs_check_exec_failed;
147 	uint_t	mobjs_lvp_used;
148 	uint_t	mobjs_wrong_model;
149 	uint_t	mobjs_noexec_fs;
150 	uint_t	mobjs_e2big_et_rel;
151 	uint_t	mobjs_et_rel_mapped;
152 	uint_t	mobjs_unknown_elf_type;
153 	uint_t	mobjs_phent32_too_small;
154 	uint_t	mobjs_phent64_too_small;
155 	uint_t	mobjs_inval_elf_class;
156 	uint_t	mobjs_too_many_phdrs;
157 	uint_t	mobjs_no_phsize;
158 	uint_t	mobjs_phsize_large;
159 	uint_t	mobjs_phsize_xtralarge;
160 	uint_t	mobjs_fast_wrong_model;
161 	uint_t	mobjs_fast_e2big;
162 	uint_t	mobjs_fast;
163 	uint_t	mobjs_fast_success;
164 	uint_t	mobjs_fast_not_now;
165 	uint_t	mobjs_small_file;
166 	uint_t	mobjs_read_error;
167 	uint_t	mobjs_unsupported;
168 	uint_t	mobjs_flat_e2big;
169 	uint_t	mobjs_phent_align32;
170 	uint_t	mobjs_phent_align64;
171 	uint_t	mobjs_lib_va_find_hit;
172 	uint_t	mobjs_lib_va_find_delay_delete;
173 	uint_t	mobjs_lib_va_find_delete;
174 	uint_t	mobjs_lib_va_add_delay_delete;
175 	uint_t	mobjs_lib_va_add_delete;
176 	uint_t	mobjs_min_align;
177 #if defined(__sparc)
178 	uint_t	mobjs_aout_uzero_fault;
179 	uint_t	mobjs_aout_64bit_try;
180 	uint_t	mobjs_aout_noexec;
181 	uint_t	mobjs_aout_e2big;
182 	uint_t	mobjs_aout_lib;
183 	uint_t	mobjs_aout_fixed;
184 	uint_t	mobjs_aout_zfoddiff;
185 	uint_t	mobjs_aout_map_bss;
186 	uint_t	mobjs_aout_bss_fail;
187 	uint_t	mobjs_aout_nlist;
188 	uint_t	mobjs_aout_addr_in_use;
189 #endif
190 } mobj_stats;
191 
192 #define	MOBJ_STAT_ADD(stat)		((mobj_stats.mobjs_##stat)++)
193 #else
194 #define	MOBJ_STAT_ADD(stat)
195 #endif
196 
197 /* lv_flags values - bitmap */
198 #define	LV_ELF32	0x1		/* 32 bit ELF file */
199 #define	LV_ELF64	0x2		/* 64 bit ELF file */
200 #define	LV_DEL		0x4		/* delete when lv_refcnt hits zero */
201 
202 /*
203  * Note: lv_num_segs will denote how many segments this file has and will
204  * only be set after the lv_mps array has been filled out.
205  * lv_mps can only be valid if lv_num_segs is non-zero.
206  */
207 struct lib_va {
208 	struct lib_va		*lv_next;
209 	caddr_t			lv_base_va;	/* start va for library */
210 	ssize_t			lv_len;		/* total va span of library */
211 	size_t			lv_align;	/* minimum alignment */
212 	uint64_t		lv_nodeid;	/* filesystem node id */
213 	uint64_t		lv_fsid;	/* filesystem id */
214 	timestruc_t		lv_ctime;	/* last time file was changed */
215 	timestruc_t		lv_mtime;	/* or modified */
216 	mmapobj_result_t	lv_mps[LIBVA_CACHED_SEGS]; /* cached pheaders */
217 	int			lv_num_segs;	/* # segs for this file */
218 	int			lv_flags;
219 	uint_t			lv_refcnt;	/* number of holds on struct */
220 };
221 
222 #define	LIB_VA_SIZE	1024
223 #define	LIB_VA_MASK	(LIB_VA_SIZE - 1)
224 #define	LIB_VA_MUTEX_SHIFT	3
225 
226 #if (LIB_VA_SIZE & (LIB_VA_SIZE - 1))
227 #error	"LIB_VA_SIZE is not a power of 2"
228 #endif
229 
230 static struct lib_va *lib_va_hash[LIB_VA_SIZE];
231 static kmutex_t lib_va_hash_mutex[LIB_VA_SIZE >> LIB_VA_MUTEX_SHIFT];
232 
233 #define	LIB_VA_HASH_MUTEX(index)					\
234 	(&lib_va_hash_mutex[index >> LIB_VA_MUTEX_SHIFT])
235 
236 #define	LIB_VA_HASH(nodeid)						\
237 	(((nodeid) ^ ((nodeid) << 7) ^ ((nodeid) << 13)) & LIB_VA_MASK)
238 
239 #define	LIB_VA_MATCH_ID(arg1, arg2)					\
240 	((arg1)->lv_nodeid == (arg2)->va_nodeid &&			\
241 	(arg1)->lv_fsid == (arg2)->va_fsid)
242 
243 #define	LIB_VA_MATCH_TIME(arg1, arg2)					\
244 	((arg1)->lv_ctime.tv_sec == (arg2)->va_ctime.tv_sec &&		\
245 	(arg1)->lv_mtime.tv_sec == (arg2)->va_mtime.tv_sec &&		\
246 	(arg1)->lv_ctime.tv_nsec == (arg2)->va_ctime.tv_nsec &&		\
247 	(arg1)->lv_mtime.tv_nsec == (arg2)->va_mtime.tv_nsec)
248 
249 #define	LIB_VA_MATCH(arg1, arg2)					\
250 	(LIB_VA_MATCH_ID(arg1, arg2) && LIB_VA_MATCH_TIME(arg1, arg2))
251 
252 /*
253  * In order to map libraries at the same VA in many processes, we need to carve
254  * out our own address space for them which is unique across many processes.
255  * We use different arenas for 32 bit and 64 bit libraries.
256  *
257  * Since the 32 bit address space is relatively small, we limit the number of
258  * libraries which try to use consistent virtual addresses to lib_threshold.
259  * For 64 bit libraries there is no such limit since the address space is large.
260  */
261 static vmem_t *lib_va_32_arena;
262 static vmem_t *lib_va_64_arena;
263 uint_t lib_threshold = 20;	/* modifiable via /etc/system */
264 
265 /*
266  * Number of 32 bit and 64 bit libraries in lib_va hash.
267  */
268 static uint_t libs_mapped_32 = 0;
269 static uint_t libs_mapped_64 = 0;
270 
271 /*
272  * Initialize the VA span of the lib_va arenas to about half of the VA space
273  * of a user process.  These VAs will be used for optimized allocation of
274  * libraries, such that subsequent mappings of the same library will attempt
275  * to use the same VA as previous mappings of that library.
276  */
277 void
278 lib_va_init(void)
279 {
280 	size_t start;
281 	size_t end;
282 	size_t len;
283 	/*
284 	 * On 32 bit sparc, the user stack and /lib/ld.so.1 will both live
285 	 * above the end address that we choose.  On 32bit x86 only
286 	 * /lib/ld.so.1 will live above the end address that we choose
287 	 * because the user stack is at the bottom of the address space.
288 	 *
289 	 * We estimate the size of ld.so.1 to be 512K which leaves significant
290 	 * room for growth without needing to change this value. Thus it is
291 	 * safe for libraries to be mapped up to that address.
292 	 *
293 	 * If the length of ld.so.1 were to grow beyond 512K then
294 	 * a library who has a reserved address in that range would always
295 	 * fail to get that address and would have to call map_addr
296 	 * to get an unused address range.  On DEBUG kernels, we will check
297 	 * on the first use of lib_va that our address does not overlap
298 	 * ld.so.1, and if it does, then we'll print a cmn_err message.
299 	 */
300 #if defined(__sparc)
301 	end = _userlimit32 - DFLSSIZ - (512 * 1024);
302 #elif defined(__i386) || defined(__amd64)
303 	end = _userlimit32 - (512 * 1024);
304 #else
305 #error	"no recognized machine type is defined"
306 #endif
307 	len = end >> 1;
308 	len = P2ROUNDUP(len, PAGESIZE);
309 	start = end - len;
310 	lib_va_32_arena = vmem_create("lib_va_32", (void *)start, len,
311 	    PAGESIZE, NULL, NULL, NULL, 0, VM_NOSLEEP | VMC_IDENTIFIER);
312 
313 #if defined(_LP64)
314 	/*
315 	 * The user stack and /lib/ld.so.1 will both live above the end address
316 	 * that we choose.  We estimate the size of a mapped ld.so.1 to be 2M
317 	 * which leaves significant room for growth without needing to change
318 	 * this value. Thus it is safe for libraries to be mapped up to
319 	 * that address.  The same considerations for the size of ld.so.1 that
320 	 * were mentioned above also apply here.
321 	 */
322 	end = _userlimit - DFLSSIZ - (2 * 1024 * 1024);
323 	len = end >> 1;
324 	len = P2ROUNDUP(len, PAGESIZE);
325 	start = end - len;
326 	lib_va_64_arena = vmem_create("lib_va_64", (void *)start, len,
327 	    PAGESIZE, NULL, NULL, NULL, 0, VM_NOSLEEP | VMC_IDENTIFIER);
328 #endif
329 }
330 
331 /*
332  * Free up the resources associated with lvp as well as lvp itself.
333  * We also decrement the number of libraries mapped via a lib_va
334  * cached virtual address.
335  */
336 void
337 lib_va_free(struct lib_va *lvp)
338 {
339 	int is_64bit = lvp->lv_flags & LV_ELF64;
340 	ASSERT(lvp->lv_refcnt == 0);
341 
342 	if (lvp->lv_base_va != NULL) {
343 		vmem_xfree(is_64bit ? lib_va_64_arena : lib_va_32_arena,
344 		    lvp->lv_base_va, lvp->lv_len);
345 		if (is_64bit) {
346 			atomic_add_32(&libs_mapped_64, -1);
347 		} else {
348 			atomic_add_32(&libs_mapped_32, -1);
349 		}
350 	}
351 	kmem_free(lvp, sizeof (struct lib_va));
352 }
353 
354 /*
355  * See if the file associated with the vap passed in is in the lib_va hash.
356  * If it is and the file has not been modified since last use, then
357  * return a pointer to that data.  Otherwise, return NULL if the file has
358  * changed or the file was not found in the hash.
359  */
360 static struct lib_va *
361 lib_va_find(vattr_t *vap)
362 {
363 	struct lib_va *lvp;
364 	struct lib_va *del = NULL;
365 	struct lib_va **tmp;
366 	uint_t index;
367 	index = LIB_VA_HASH(vap->va_nodeid);
368 
369 	mutex_enter(LIB_VA_HASH_MUTEX(index));
370 	tmp = &lib_va_hash[index];
371 	while (*tmp != NULL) {
372 		lvp = *tmp;
373 		if (LIB_VA_MATCH_ID(lvp, vap)) {
374 			if (LIB_VA_MATCH_TIME(lvp, vap)) {
375 				ASSERT((lvp->lv_flags & LV_DEL) == 0);
376 				lvp->lv_refcnt++;
377 				MOBJ_STAT_ADD(lib_va_find_hit);
378 			} else {
379 				/*
380 				 * file was updated since last use.
381 				 * need to remove it from list.
382 				 */
383 				del = lvp;
384 				*tmp = del->lv_next;
385 				del->lv_next = NULL;
386 				/*
387 				 * If we can't delete it now, mark it for later
388 				 */
389 				if (del->lv_refcnt) {
390 					MOBJ_STAT_ADD(lib_va_find_delay_delete);
391 					del->lv_flags |= LV_DEL;
392 					del = NULL;
393 				}
394 				lvp = NULL;
395 			}
396 			mutex_exit(LIB_VA_HASH_MUTEX(index));
397 			if (del) {
398 				ASSERT(del->lv_refcnt == 0);
399 				MOBJ_STAT_ADD(lib_va_find_delete);
400 				lib_va_free(del);
401 			}
402 			return (lvp);
403 		}
404 		tmp = &lvp->lv_next;
405 	}
406 	mutex_exit(LIB_VA_HASH_MUTEX(index));
407 	return (NULL);
408 }
409 
410 /*
411  * Add a new entry to the lib_va hash.
412  * Search the hash while holding the appropriate mutex to make sure that the
413  * data is not already in the cache.  If we find data that is in the cache
414  * already and has not been modified since last use, we return NULL.  If it
415  * has been modified since last use, we will remove that entry from
416  * the hash and it will be deleted once it's reference count reaches zero.
417  * If there is no current entry in the hash we will add the new entry and
418  * return it to the caller who is responsible for calling lib_va_release to
419  * drop their reference count on it.
420  *
421  * lv_num_segs will be set to zero since the caller needs to add that
422  * information to the data structure.
423  */
424 static struct lib_va *
425 lib_va_add_hash(caddr_t base_va, ssize_t len, size_t align, vattr_t *vap)
426 {
427 	struct lib_va *lvp;
428 	uint_t index;
429 	model_t model;
430 	struct lib_va **tmp;
431 	struct lib_va *del = NULL;
432 
433 	model = get_udatamodel();
434 	index = LIB_VA_HASH(vap->va_nodeid);
435 
436 	lvp = kmem_alloc(sizeof (struct lib_va), KM_SLEEP);
437 
438 	mutex_enter(LIB_VA_HASH_MUTEX(index));
439 
440 	/*
441 	 * Make sure not adding same data a second time.
442 	 * The hash chains should be relatively short and adding
443 	 * is a relatively rare event, so it's worth the check.
444 	 */
445 	tmp = &lib_va_hash[index];
446 	while (*tmp != NULL) {
447 		if (LIB_VA_MATCH_ID(*tmp, vap)) {
448 			if (LIB_VA_MATCH_TIME(*tmp, vap)) {
449 				mutex_exit(LIB_VA_HASH_MUTEX(index));
450 				kmem_free(lvp, sizeof (struct lib_va));
451 				return (NULL);
452 			}
453 
454 			/*
455 			 * We have the same nodeid and fsid but the file has
456 			 * been modified since we last saw it.
457 			 * Need to remove the old node and add this new
458 			 * one.
459 			 * Could probably use a callback mechanism to make
460 			 * this cleaner.
461 			 */
462 			ASSERT(del == NULL);
463 			del = *tmp;
464 			*tmp = del->lv_next;
465 			del->lv_next = NULL;
466 
467 			/*
468 			 * Check to see if we can free it.  If lv_refcnt
469 			 * is greater than zero, than some other thread
470 			 * has a reference to the one we want to delete
471 			 * and we can not delete it.  All of this is done
472 			 * under the lib_va_hash_mutex lock so it is atomic.
473 			 */
474 			if (del->lv_refcnt) {
475 				MOBJ_STAT_ADD(lib_va_add_delay_delete);
476 				del->lv_flags |= LV_DEL;
477 				del = NULL;
478 			}
479 			/* tmp is already advanced */
480 			continue;
481 		}
482 		tmp = &((*tmp)->lv_next);
483 	}
484 
485 	lvp->lv_base_va = base_va;
486 	lvp->lv_len = len;
487 	lvp->lv_align = align;
488 	lvp->lv_nodeid = vap->va_nodeid;
489 	lvp->lv_fsid = vap->va_fsid;
490 	lvp->lv_ctime.tv_sec = vap->va_ctime.tv_sec;
491 	lvp->lv_ctime.tv_nsec = vap->va_ctime.tv_nsec;
492 	lvp->lv_mtime.tv_sec = vap->va_mtime.tv_sec;
493 	lvp->lv_mtime.tv_nsec = vap->va_mtime.tv_nsec;
494 	lvp->lv_next = NULL;
495 	lvp->lv_refcnt = 1;
496 
497 	/* Caller responsible for filling this and lv_mps out */
498 	lvp->lv_num_segs = 0;
499 
500 	if (model == DATAMODEL_LP64) {
501 		lvp->lv_flags = LV_ELF64;
502 	} else {
503 		ASSERT(model == DATAMODEL_ILP32);
504 		lvp->lv_flags = LV_ELF32;
505 	}
506 
507 	if (base_va != NULL) {
508 		if (model == DATAMODEL_LP64) {
509 			atomic_add_32(&libs_mapped_64, 1);
510 		} else {
511 			ASSERT(model == DATAMODEL_ILP32);
512 			atomic_add_32(&libs_mapped_32, 1);
513 		}
514 	}
515 	ASSERT(*tmp == NULL);
516 	*tmp = lvp;
517 	mutex_exit(LIB_VA_HASH_MUTEX(index));
518 	if (del) {
519 		ASSERT(del->lv_refcnt == 0);
520 		MOBJ_STAT_ADD(lib_va_add_delete);
521 		lib_va_free(del);
522 	}
523 	return (lvp);
524 }
525 
526 /*
527  * Release the hold on lvp which was acquired by lib_va_find or lib_va_add_hash.
528  * In addition, if this is the last hold and lvp is marked for deletion,
529  * free up it's reserved address space and free the structure.
530  */
531 static void
532 lib_va_release(struct lib_va *lvp)
533 {
534 	uint_t index;
535 	int to_del = 0;
536 
537 	ASSERT(lvp->lv_refcnt > 0);
538 
539 	index = LIB_VA_HASH(lvp->lv_nodeid);
540 	mutex_enter(LIB_VA_HASH_MUTEX(index));
541 	if (--lvp->lv_refcnt == 0 && (lvp->lv_flags & LV_DEL)) {
542 		to_del = 1;
543 	}
544 	mutex_exit(LIB_VA_HASH_MUTEX(index));
545 	if (to_del) {
546 		ASSERT(lvp->lv_next == 0);
547 		lib_va_free(lvp);
548 	}
549 }
550 
551 /*
552  * Dummy function for mapping through /dev/null
553  * Normally I would have used mmmmap in common/io/mem.c
554  * but that is a static function, and for /dev/null, it
555  * just returns -1.
556  */
557 /* ARGSUSED */
558 static int
559 mmapobj_dummy(dev_t dev, off_t off, int prot)
560 {
561 	return (-1);
562 }
563 
564 /*
565  * Called when an error occurred which requires mmapobj to return failure.
566  * All mapped objects will be unmapped and /dev/null mappings will be
567  * reclaimed if necessary.
568  * num_mapped is the number of elements of mrp which have been mapped, and
569  * num_segs is the total number of elements in mrp.
570  * For e_type ET_EXEC, we need to unmap all of the elements in mrp since
571  * we had already made reservations for them.
572  * If num_mapped equals num_segs, then we know that we had fully mapped
573  * the file and only need to clean up the segments described.
574  * If they are not equal, then for ET_DYN we will unmap the range from the
575  * end of the last mapped segment to the end of the last segment in mrp
576  * since we would have made a reservation for that memory earlier.
577  * If e_type is passed in as zero, num_mapped must equal num_segs.
578  */
579 void
580 mmapobj_unmap(mmapobj_result_t *mrp, int num_mapped, int num_segs,
581     ushort_t e_type)
582 {
583 	int i;
584 	struct as *as = curproc->p_as;
585 	caddr_t addr;
586 	size_t size;
587 
588 	if (e_type == ET_EXEC) {
589 		num_mapped = num_segs;
590 	}
591 #ifdef DEBUG
592 	if (e_type == 0) {
593 		ASSERT(num_mapped == num_segs);
594 	}
595 #endif
596 
597 	MOBJ_STAT_ADD(unmap_called);
598 	for (i = 0; i < num_mapped; i++) {
599 
600 		/*
601 		 * If we are going to have to create a mapping we need to
602 		 * make sure that no one else will use the address we
603 		 * need to remap between the time it is unmapped and
604 		 * mapped below.
605 		 */
606 		if (mrp[i].mr_flags & MR_RESV) {
607 			as_rangelock(as);
608 		}
609 		/* Always need to unmap what we mapped */
610 		(void) as_unmap(as, mrp[i].mr_addr, mrp[i].mr_msize);
611 
612 		/* Need to reclaim /dev/null reservation from earlier */
613 		if (mrp[i].mr_flags & MR_RESV) {
614 			struct segdev_crargs dev_a;
615 
616 			ASSERT(e_type != ET_DYN);
617 			/*
618 			 * Use seg_dev segment driver for /dev/null mapping.
619 			 */
620 			dev_a.mapfunc = mmapobj_dummy;
621 			dev_a.dev = makedevice(mm_major, M_NULL);
622 			dev_a.offset = 0;
623 			dev_a.type = 0;		/* neither PRIVATE nor SHARED */
624 			dev_a.prot = dev_a.maxprot = (uchar_t)PROT_NONE;
625 			dev_a.hat_attr = 0;
626 			dev_a.hat_flags = 0;
627 
628 			(void) as_map(as, mrp[i].mr_addr, mrp[i].mr_msize,
629 			    segdev_create, &dev_a);
630 			MOBJ_STAT_ADD(remap_devnull);
631 			as_rangeunlock(as);
632 		}
633 	}
634 
635 	if (num_mapped != num_segs) {
636 		ASSERT(e_type == ET_DYN);
637 		/* Need to unmap any reservation made after last mapped seg */
638 		if (num_mapped == 0) {
639 			addr = mrp[0].mr_addr;
640 		} else {
641 			addr = mrp[num_mapped - 1].mr_addr +
642 			    mrp[num_mapped - 1].mr_msize;
643 		}
644 		size = (size_t)mrp[num_segs - 1].mr_addr +
645 		    mrp[num_segs - 1].mr_msize - (size_t)addr;
646 		(void) as_unmap(as, addr, size);
647 
648 		/*
649 		 * Now we need to unmap the holes between mapped segs.
650 		 * Note that we have not mapped all of the segments and thus
651 		 * the holes between segments would not have been unmapped
652 		 * yet.  If num_mapped == num_segs, then all of the holes
653 		 * between segments would have already been unmapped.
654 		 */
655 
656 		for (i = 1; i < num_mapped; i++) {
657 			addr = mrp[i - 1].mr_addr + mrp[i - 1].mr_msize;
658 			size = mrp[i].mr_addr - addr;
659 			(void) as_unmap(as, addr, size);
660 		}
661 	}
662 }
663 
664 /*
665  * We need to add the start address into mrp so that the unmap function
666  * has absolute addresses to use.
667  */
668 static void
669 mmapobj_unmap_exec(mmapobj_result_t *mrp, int num_mapped, caddr_t start_addr)
670 {
671 	int i;
672 
673 	for (i = 0; i < num_mapped; i++) {
674 		mrp[i].mr_addr += (size_t)start_addr;
675 	}
676 	mmapobj_unmap(mrp, num_mapped, num_mapped, ET_EXEC);
677 }
678 
679 static caddr_t
680 mmapobj_lookup_start_addr(struct lib_va *lvp)
681 {
682 	struct as *as = curproc->p_as;
683 	struct segvn_crargs crargs = SEGVN_ZFOD_ARGS(PROT_USER, PROT_ALL);
684 	int error;
685 	uint_t ma_flags = _MAP_LOW32;
686 	caddr_t base = NULL;
687 	size_t len;
688 	size_t align;
689 
690 	ASSERT(lvp != NULL);
691 	MOBJ_STAT_ADD(lookup_start);
692 
693 	as_rangelock(as);
694 
695 	base = lvp->lv_base_va;
696 	len = lvp->lv_len;
697 
698 	/*
699 	 * If we don't have an expected base address, or the one that we want
700 	 * to use is not available, go get an acceptable address range.
701 	 */
702 	if (base == NULL || as_gap(as, len, &base, &len, 0, NULL)) {
703 
704 		if (lvp->lv_flags & LV_ELF64) {
705 			ma_flags = 0;
706 		}
707 
708 		align = lvp->lv_align;
709 		if (align > 1) {
710 			ma_flags |= MAP_ALIGN;
711 		}
712 
713 		base = (caddr_t)align;
714 		map_addr(&base, len, 0, 1, ma_flags);
715 	}
716 
717 	/*
718 	 * Need to reserve the address space we're going to use.
719 	 * Don't reserve swap space since we'll be mapping over this.
720 	 */
721 	if (base != NULL) {
722 		crargs.flags |= MAP_NORESERVE;
723 		error = as_map(as, base, len, segvn_create, &crargs);
724 		if (error) {
725 			base = NULL;
726 		}
727 	}
728 
729 	as_rangeunlock(as);
730 	return (base);
731 }
732 
733 /*
734  * Get the starting address for a given file to be mapped and return it
735  * to the caller.  If we're using lib_va and we need to allocate an address,
736  * we will attempt to allocate it from the global reserved pool such that the
737  * same address can be used in the future for this file.  If we can't use the
738  * reserved address then we just get one that will fit in our address space.
739  *
740  * Returns the starting virtual address for the range to be mapped or NULL
741  * if an error is encountered. If we successfully insert the requested info
742  * into the lib_va hash, then *lvpp will be set to point to this lib_va
743  * structure.  The structure will have a hold on it and thus lib_va_release
744  * needs to be called on it by the caller.  This function will not fill out
745  * lv_mps or lv_num_segs since it does not have enough information to do so.
746  * The caller is responsible for doing this making sure that any modifications
747  * to lv_mps are visible before setting lv_num_segs.
748  */
749 static caddr_t
750 mmapobj_alloc_start_addr(struct lib_va **lvpp, size_t len, int use_lib_va,
751     size_t align, vattr_t *vap)
752 {
753 	struct as *as = curproc->p_as;
754 	struct segvn_crargs crargs = SEGVN_ZFOD_ARGS(PROT_USER, PROT_ALL);
755 	int error;
756 	model_t model;
757 	uint_t ma_flags = _MAP_LOW32;
758 	caddr_t base = NULL;
759 	vmem_t *model_vmem;
760 
761 	ASSERT(lvpp != NULL);
762 
763 	MOBJ_STAT_ADD(alloc_start);
764 	model = get_udatamodel();
765 
766 	if (model == DATAMODEL_LP64) {
767 		ma_flags = 0;
768 		model_vmem = lib_va_64_arena;
769 	} else {
770 		ASSERT(model == DATAMODEL_ILP32);
771 		model_vmem = lib_va_32_arena;
772 	}
773 
774 	if (align > 1) {
775 		ma_flags |= MAP_ALIGN;
776 	}
777 	if (use_lib_va) {
778 		if (model == DATAMODEL_LP64 || libs_mapped_32 < lib_threshold) {
779 			base = vmem_xalloc(model_vmem, len, align, 0, 0, NULL,
780 			    NULL, VM_NOSLEEP | VM_ENDALLOC);
781 			MOBJ_STAT_ADD(alloc_vmem);
782 		}
783 #ifdef DEBUG
784 		/*
785 		 * Check to see if we've run into ld.so.1.
786 		 * If this is the first library we've mapped and we can not
787 		 * use our reserved address space, then it's likely that
788 		 * ld.so.1 is occupying some of this space and the
789 		 * model_vmem arena bounds need to be changed.  If we've run
790 		 * into something else besides ld.so.1 we'll see this message
791 		 * on the first use of mmapobj and should ignore the message.
792 		 */
793 		if (base != NULL && libs_mapped_32 == 0 &&
794 		    model == DATAMODEL_ILP32 &&
795 		    as_gap(as, len, &base, &len, 0, NULL)) {
796 			cmn_err(CE_NOTE,
797 			    "lib_va_32_arena may not be optimized");
798 		} else if (base != NULL && libs_mapped_64 == 0 &&
799 		    model == DATAMODEL_LP64 &&
800 		    as_gap(as, len, &base, &len, 0, NULL)) {
801 			cmn_err(CE_NOTE,
802 			    "lib_va_64_arena may not be optimized");
803 		}
804 #endif
805 		/*
806 		 * Even if the address fails to fit in our address space,
807 		 * or we can't use a reserved address,
808 		 * we should still save it off in lib_va_hash.
809 		 */
810 		*lvpp = lib_va_add_hash(base, len, align, vap);
811 
812 		/*
813 		 * Check for collision on insertion and free up our VA space.
814 		 * This is expected to be rare, so we'll just reset base to
815 		 * NULL instead of looking it up in the lib_va hash.
816 		 */
817 		if (*lvpp == NULL) {
818 			if (base != NULL) {
819 				vmem_xfree(model_vmem, base, len);
820 				base = NULL;
821 				MOBJ_STAT_ADD(add_collision);
822 			}
823 		}
824 	}
825 
826 	as_rangelock(as);
827 
828 	/*
829 	 * If we don't have an expected base address, or the one that we want
830 	 * to use is not available, go get an acceptable address range.
831 	 */
832 	if (base == NULL || as_gap(as, len, &base, &len, 0, NULL)) {
833 		MOBJ_STAT_ADD(get_addr);
834 		base = (caddr_t)align;
835 		map_addr(&base, len, 0, 1, ma_flags);
836 	}
837 
838 	/*
839 	 * Need to reserve the address space we're going to use.
840 	 * Don't reserve swap space since we'll be mapping over this.
841 	 */
842 	if (base != NULL) {
843 		/* Don't reserve swap space since we'll be mapping over this */
844 		crargs.flags |= MAP_NORESERVE;
845 		error = as_map(as, base, len, segvn_create, &crargs);
846 		if (error) {
847 			base = NULL;
848 		}
849 	}
850 
851 	as_rangeunlock(as);
852 	return (base);
853 }
854 
855 /*
856  * Map the file associated with vp into the address space as a single
857  * read only private mapping.
858  * Returns 0 for success, and non-zero for failure to map the file.
859  */
860 static int
861 mmapobj_map_flat(vnode_t *vp, mmapobj_result_t *mrp, size_t padding,
862     cred_t *fcred)
863 {
864 	int error = 0;
865 	struct as *as = curproc->p_as;
866 	caddr_t addr = NULL;
867 	caddr_t start_addr;
868 	size_t len;
869 	size_t pad_len;
870 	int prot = PROT_USER | PROT_READ;
871 	uint_t ma_flags = _MAP_LOW32;
872 	vattr_t vattr;
873 	struct segvn_crargs crargs = SEGVN_ZFOD_ARGS(PROT_USER, PROT_ALL);
874 
875 	if (get_udatamodel() == DATAMODEL_LP64) {
876 		ma_flags = 0;
877 	}
878 
879 	vattr.va_mask = AT_SIZE;
880 	error = VOP_GETATTR(vp, &vattr, 0, fcred, NULL);
881 	if (error) {
882 		return (error);
883 	}
884 
885 	len = vattr.va_size;
886 
887 	ma_flags |= MAP_PRIVATE;
888 	if (padding == 0) {
889 		MOBJ_STAT_ADD(map_flat_no_padding);
890 		error = VOP_MAP(vp, 0, as, &addr, len, prot, PROT_ALL,
891 		    ma_flags, fcred, NULL);
892 		if (error == 0) {
893 			mrp[0].mr_addr = addr;
894 			mrp[0].mr_msize = len;
895 			mrp[0].mr_fsize = len;
896 			mrp[0].mr_offset = 0;
897 			mrp[0].mr_prot = prot;
898 			mrp[0].mr_flags = 0;
899 		}
900 		return (error);
901 	}
902 
903 	/* padding was requested so there's more work to be done */
904 	MOBJ_STAT_ADD(map_flat_padding);
905 
906 	/* No need to reserve swap space now since it will be reserved later */
907 	crargs.flags |= MAP_NORESERVE;
908 
909 	/* Need to setup padding which can only be in PAGESIZE increments. */
910 	ASSERT((padding & PAGEOFFSET) == 0);
911 	pad_len = len + (2 * padding);
912 
913 	as_rangelock(as);
914 	map_addr(&addr, pad_len, 0, 1, ma_flags);
915 	error = as_map(as, addr, pad_len, segvn_create, &crargs);
916 	as_rangeunlock(as);
917 	if (error) {
918 		return (error);
919 	}
920 	start_addr = addr;
921 	addr += padding;
922 	ma_flags |= MAP_FIXED;
923 	error = VOP_MAP(vp, 0, as, &addr, len, prot, PROT_ALL, ma_flags,
924 	    fcred, NULL);
925 	if (error == 0) {
926 		mrp[0].mr_addr = start_addr;
927 		mrp[0].mr_msize = padding;
928 		mrp[0].mr_fsize = 0;
929 		mrp[0].mr_offset = 0;
930 		mrp[0].mr_prot = 0;
931 		mrp[0].mr_flags = MR_PADDING;
932 
933 		mrp[1].mr_addr = addr;
934 		mrp[1].mr_msize = len;
935 		mrp[1].mr_fsize = len;
936 		mrp[1].mr_offset = 0;
937 		mrp[1].mr_prot = prot;
938 		mrp[1].mr_flags = 0;
939 
940 		mrp[2].mr_addr = addr + P2ROUNDUP(len, PAGESIZE);
941 		mrp[2].mr_msize = padding;
942 		mrp[2].mr_fsize = 0;
943 		mrp[2].mr_offset = 0;
944 		mrp[2].mr_prot = 0;
945 		mrp[2].mr_flags = MR_PADDING;
946 	} else {
947 		/* Need to cleanup the as_map from earlier */
948 		(void) as_unmap(as, start_addr, pad_len);
949 	}
950 	return (error);
951 }
952 
953 /*
954  * Map a PT_LOAD or PT_SUNWBSS section of an executable file into the user's
955  * address space.
956  * vp - vnode to be mapped in
957  * addr - start address
958  * len - length of vp to be mapped
959  * zfodlen - length of zero filled memory after len above
960  * offset - offset into file where mapping should start
961  * prot - protections for this mapping
962  * fcred - credentials for the file associated with vp at open time.
963  */
964 static int
965 mmapobj_map_ptload(struct vnode *vp, caddr_t addr, size_t len, size_t zfodlen,
966     off_t offset, int prot, cred_t *fcred)
967 {
968 	int error = 0;
969 	caddr_t zfodbase, oldaddr;
970 	size_t oldlen;
971 	size_t end;
972 	size_t zfoddiff;
973 	label_t ljb;
974 	struct as *as = curproc->p_as;
975 	model_t model;
976 	int full_page;
977 
978 	/*
979 	 * See if addr and offset are aligned such that we can map in
980 	 * full pages instead of partial pages.
981 	 */
982 	full_page = (((uintptr_t)addr & PAGEOFFSET) ==
983 	    ((uintptr_t)offset & PAGEOFFSET));
984 
985 	model = get_udatamodel();
986 
987 	oldaddr = addr;
988 	addr = (caddr_t)((uintptr_t)addr & (uintptr_t)PAGEMASK);
989 	if (len) {
990 		spgcnt_t availm, npages;
991 		int preread;
992 		uint_t mflag = MAP_PRIVATE | MAP_FIXED;
993 
994 		if (model == DATAMODEL_ILP32) {
995 			mflag |= _MAP_LOW32;
996 		}
997 		/* We may need to map in extra bytes */
998 		oldlen = len;
999 		len += ((size_t)oldaddr & PAGEOFFSET);
1000 
1001 		if (full_page) {
1002 			offset = (off_t)((uintptr_t)offset & PAGEMASK);
1003 			if ((prot & (PROT_WRITE | PROT_EXEC)) == PROT_EXEC) {
1004 				mflag |= MAP_TEXT;
1005 				MOBJ_STAT_ADD(map_ptload_text);
1006 			} else {
1007 				mflag |= MAP_INITDATA;
1008 				MOBJ_STAT_ADD(map_ptload_initdata);
1009 			}
1010 
1011 			/*
1012 			 * maxprot is passed as PROT_ALL so that mdb can
1013 			 * write to this segment.
1014 			 */
1015 			if (error = VOP_MAP(vp, (offset_t)offset, as, &addr,
1016 			    len, prot, PROT_ALL, mflag, fcred, NULL)) {
1017 				return (error);
1018 			}
1019 
1020 			/*
1021 			 * If the segment can fit and is relatively small, then
1022 			 * we prefault the entire segment in.  This is based
1023 			 * on the model that says the best working set of a
1024 			 * small program is all of its pages.
1025 			 * We only do this if freemem will not drop below
1026 			 * lotsfree since we don't want to induce paging.
1027 			 */
1028 			npages = (spgcnt_t)btopr(len);
1029 			availm = freemem - lotsfree;
1030 			preread = (npages < availm && len < PGTHRESH) ? 1 : 0;
1031 
1032 			/*
1033 			 * If we aren't prefaulting the segment,
1034 			 * increment "deficit", if necessary to ensure
1035 			 * that pages will become available when this
1036 			 * process starts executing.
1037 			 */
1038 			if (preread == 0 && npages > availm &&
1039 			    deficit < lotsfree) {
1040 				deficit += MIN((pgcnt_t)(npages - availm),
1041 				    lotsfree - deficit);
1042 			}
1043 
1044 			if (preread) {
1045 				(void) as_faulta(as, addr, len);
1046 				MOBJ_STAT_ADD(map_ptload_preread);
1047 			}
1048 		} else {
1049 			/*
1050 			 * addr and offset were not aligned such that we could
1051 			 * use VOP_MAP, thus we need to as_map the memory we
1052 			 * need and then read the data in from disk.
1053 			 * This code path is a corner case which should never
1054 			 * be taken, but hand crafted binaries could trigger
1055 			 * this logic and it needs to work correctly.
1056 			 */
1057 			MOBJ_STAT_ADD(map_ptload_unaligned_text);
1058 			as_rangelock(as);
1059 			(void) as_unmap(as, addr, len);
1060 
1061 			/*
1062 			 * We use zfod_argsp because we need to be able to
1063 			 * write to the mapping and then we'll change the
1064 			 * protections later if they are incorrect.
1065 			 */
1066 			error = as_map(as, addr, len, segvn_create, zfod_argsp);
1067 			as_rangeunlock(as);
1068 			if (error) {
1069 				MOBJ_STAT_ADD(map_ptload_unaligned_map_fail);
1070 				return (error);
1071 			}
1072 
1073 			/* Now read in the data from disk */
1074 			error = vn_rdwr(UIO_READ, vp, oldaddr, oldlen, offset,
1075 			    UIO_USERSPACE, 0, (rlim64_t)0, fcred, NULL);
1076 			if (error) {
1077 				MOBJ_STAT_ADD(map_ptload_unaligned_read_fail);
1078 				return (error);
1079 			}
1080 
1081 			/*
1082 			 * Now set protections.
1083 			 */
1084 			if (prot != PROT_ZFOD) {
1085 				(void) as_setprot(as, addr, len, prot);
1086 			}
1087 		}
1088 	}
1089 
1090 	if (zfodlen) {
1091 		end = (size_t)addr + len;
1092 		zfodbase = (caddr_t)P2ROUNDUP(end, PAGESIZE);
1093 		zfoddiff = (uintptr_t)zfodbase - end;
1094 		if (zfoddiff) {
1095 			MOBJ_STAT_ADD(zfoddiff);
1096 			if ((prot & PROT_WRITE) == 0) {
1097 				(void) as_setprot(as, (caddr_t)end,
1098 				    zfoddiff, prot | PROT_WRITE);
1099 				MOBJ_STAT_ADD(zfoddiff_nowrite);
1100 			}
1101 			if (on_fault(&ljb)) {
1102 				no_fault();
1103 				if ((prot & PROT_WRITE) == 0) {
1104 					(void) as_setprot(as, (caddr_t)end,
1105 					    zfoddiff, prot);
1106 				}
1107 				return (EFAULT);
1108 			}
1109 			uzero((void *)end, zfoddiff);
1110 			no_fault();
1111 
1112 			/*
1113 			 * Remove write protection to return to original state
1114 			 */
1115 			if ((prot & PROT_WRITE) == 0) {
1116 				(void) as_setprot(as, (caddr_t)end,
1117 				    zfoddiff, prot);
1118 			}
1119 		}
1120 		if (zfodlen > zfoddiff) {
1121 			struct segvn_crargs crargs =
1122 			    SEGVN_ZFOD_ARGS(prot, PROT_ALL);
1123 
1124 			MOBJ_STAT_ADD(zfodextra);
1125 			zfodlen -= zfoddiff;
1126 			crargs.szc = AS_MAP_NO_LPOOB;
1127 
1128 
1129 			as_rangelock(as);
1130 			(void) as_unmap(as, (caddr_t)zfodbase, zfodlen);
1131 			error = as_map(as, (caddr_t)zfodbase,
1132 			    zfodlen, segvn_create, &crargs);
1133 			as_rangeunlock(as);
1134 			if (error) {
1135 				return (error);
1136 			}
1137 		}
1138 	}
1139 	return (0);
1140 }
1141 
1142 /*
1143  * Map the ELF file represented by vp into the users address space.  The
1144  * first mapping will start at start_addr and there will be num_elements
1145  * mappings.  The mappings are described by the data in mrp which may be
1146  * modified upon returning from this function.
1147  * Returns 0 for success or errno for failure.
1148  */
1149 static int
1150 mmapobj_map_elf(struct vnode *vp, caddr_t start_addr, mmapobj_result_t *mrp,
1151     int num_elements, cred_t *fcred, ushort_t e_type)
1152 {
1153 	int i;
1154 	int ret;
1155 	caddr_t lo;
1156 	caddr_t hi;
1157 	struct as *as = curproc->p_as;
1158 
1159 	for (i = 0; i < num_elements; i++) {
1160 		caddr_t addr;
1161 		size_t p_memsz;
1162 		size_t p_filesz;
1163 		size_t zfodlen;
1164 		offset_t p_offset;
1165 		size_t dif;
1166 		int prot;
1167 
1168 		/* Always need to adjust mr_addr */
1169 		addr = start_addr + (size_t)(mrp[i].mr_addr);
1170 		mrp[i].mr_addr =
1171 		    (caddr_t)((uintptr_t)addr & (uintptr_t)PAGEMASK);
1172 
1173 		/* Padding has already been mapped */
1174 		if (MR_GET_TYPE(mrp[i].mr_flags) == MR_PADDING) {
1175 			continue;
1176 		}
1177 		p_memsz = mrp[i].mr_msize;
1178 		p_filesz = mrp[i].mr_fsize;
1179 		zfodlen = p_memsz - p_filesz;
1180 		p_offset = mrp[i].mr_offset;
1181 		dif = (uintptr_t)(addr) & PAGEOFFSET;
1182 		prot = mrp[i].mr_prot | PROT_USER;
1183 		ret = mmapobj_map_ptload(vp, addr, p_filesz, zfodlen,
1184 		    p_offset, prot, fcred);
1185 		if (ret != 0) {
1186 			MOBJ_STAT_ADD(ptload_failed);
1187 			mmapobj_unmap(mrp, i, num_elements, e_type);
1188 			return (ret);
1189 		}
1190 
1191 		/* Need to cleanup mrp to reflect the actual values used */
1192 		mrp[i].mr_msize += dif;
1193 		mrp[i].mr_offset = (size_t)addr & PAGEOFFSET;
1194 	}
1195 
1196 	/* Also need to unmap any holes created above */
1197 	if (num_elements == 1) {
1198 		MOBJ_STAT_ADD(map_elf_no_holes);
1199 		return (0);
1200 	}
1201 	if (e_type == ET_EXEC) {
1202 		return (0);
1203 	}
1204 
1205 	as_rangelock(as);
1206 	lo = start_addr;
1207 	hi = mrp[0].mr_addr;
1208 
1209 	/* Remove holes made by the rest of the segments */
1210 	for (i = 0; i < num_elements - 1; i++) {
1211 		lo = (caddr_t)P2ROUNDUP((size_t)(mrp[i].mr_addr) +
1212 		    mrp[i].mr_msize, PAGESIZE);
1213 		hi = mrp[i + 1].mr_addr;
1214 		if (lo < hi) {
1215 			/*
1216 			 * If as_unmap fails we just use up a bit of extra
1217 			 * space
1218 			 */
1219 			(void) as_unmap(as, (caddr_t)lo,
1220 			    (size_t)hi - (size_t)lo);
1221 			MOBJ_STAT_ADD(unmap_hole);
1222 		}
1223 	}
1224 	as_rangeunlock(as);
1225 
1226 	return (0);
1227 }
1228 
1229 /* Ugly hack to get STRUCT_* macros to work below */
1230 struct myphdr {
1231 	Phdr		x;	/* native version */
1232 };
1233 
1234 struct myphdr32 {
1235 	Elf32_Phdr	x;
1236 };
1237 
1238 /*
1239  * Calculate and return the number of loadable segments in the ELF Phdr
1240  * represented by phdrbase as well as the len of the total mapping and
1241  * the max alignment that is needed for a given segment.  On success,
1242  * 0 is returned, and *len, *loadable and *align have been filled out.
1243  * On failure, errno will be returned, which in this case is ENOTSUP
1244  * if we were passed an ELF file with overlapping segments.
1245  */
1246 static int
1247 calc_loadable(Ehdr *ehdrp, caddr_t phdrbase, int nphdrs, size_t *len,
1248     int *loadable, size_t *align)
1249 {
1250 	int i;
1251 	int hsize;
1252 	model_t model;
1253 	uint_t p_type;
1254 	offset_t p_offset;
1255 	size_t p_memsz;
1256 	size_t p_align;
1257 	caddr_t vaddr;
1258 	int num_segs = 0;
1259 	caddr_t start_addr = NULL;
1260 	caddr_t p_end = NULL;
1261 	size_t max_align = 0;
1262 	size_t min_align = PAGESIZE;	/* needed for vmem_xalloc */
1263 	STRUCT_HANDLE(myphdr, mph);
1264 #if defined(__sparc)
1265 	extern int vac_size;
1266 
1267 	/*
1268 	 * Want to prevent aliasing by making the start address at least be
1269 	 * aligned to vac_size.
1270 	 */
1271 	min_align = MAX(PAGESIZE, vac_size);
1272 #endif
1273 
1274 	model = get_udatamodel();
1275 	STRUCT_SET_HANDLE(mph, model, (struct myphdr *)phdrbase);
1276 
1277 	/* hsize alignment should have been checked before calling this func */
1278 	if (model == DATAMODEL_LP64) {
1279 		hsize = ehdrp->e_phentsize;
1280 		if (hsize & 7) {
1281 			return (ENOTSUP);
1282 		}
1283 	} else {
1284 		ASSERT(model == DATAMODEL_ILP32);
1285 		hsize = ((Elf32_Ehdr *)ehdrp)->e_phentsize;
1286 		if (hsize & 3) {
1287 			return (ENOTSUP);
1288 		}
1289 	}
1290 
1291 	/*
1292 	 * Determine the span of all loadable segments and calculate the
1293 	 * number of loadable segments.
1294 	 */
1295 	for (i = 0; i < nphdrs; i++) {
1296 		p_type = STRUCT_FGET(mph, x.p_type);
1297 		if (p_type == PT_LOAD || p_type == PT_SUNWBSS) {
1298 			vaddr = (caddr_t)(uintptr_t)STRUCT_FGET(mph, x.p_vaddr);
1299 			p_memsz = STRUCT_FGET(mph, x.p_memsz);
1300 
1301 			/*
1302 			 * Skip this header if it requests no memory to be
1303 			 * mapped.
1304 			 */
1305 			if (p_memsz == 0) {
1306 				STRUCT_SET_HANDLE(mph, model,
1307 				    (struct myphdr *)((size_t)STRUCT_BUF(mph) +
1308 				    hsize));
1309 				MOBJ_STAT_ADD(nomem_header);
1310 				continue;
1311 			}
1312 			if (num_segs++ == 0) {
1313 				start_addr = vaddr;
1314 				/*
1315 				 * For the first segment, we need to map from
1316 				 * the beginning of the file, so we will
1317 				 * adjust the size of the mapping to include
1318 				 * this memory.
1319 				 */
1320 				p_offset = STRUCT_FGET(mph, x.p_offset);
1321 			} else {
1322 				p_offset = 0;
1323 			}
1324 			/*
1325 			 * Check to make sure that this mapping wouldn't
1326 			 * overlap a previous mapping.
1327 			 */
1328 			if (vaddr < p_end) {
1329 				MOBJ_STAT_ADD(overlap_header);
1330 				return (ENOTSUP);
1331 			}
1332 
1333 			p_end = vaddr + p_memsz + p_offset;
1334 			p_end = (caddr_t)P2ROUNDUP((size_t)p_end, PAGESIZE);
1335 
1336 			p_align = STRUCT_FGET(mph, x.p_align);
1337 			if (p_align > 1 && p_align > max_align) {
1338 				max_align = p_align;
1339 				if (max_align < min_align) {
1340 					max_align = min_align;
1341 					MOBJ_STAT_ADD(min_align);
1342 				}
1343 			}
1344 		}
1345 		STRUCT_SET_HANDLE(mph, model,
1346 		    (struct myphdr *)((size_t)STRUCT_BUF(mph) + hsize));
1347 	}
1348 
1349 	/*
1350 	 * The alignment should be a power of 2, if it isn't we forgive it
1351 	 * and round up.  On overflow, we'll set the alignment to max_align
1352 	 * rounded down to the nearest power of 2.
1353 	 */
1354 	if (max_align > 0 && !ISP2(max_align)) {
1355 		MOBJ_STAT_ADD(np2_align);
1356 		*align = 2 * (1L << (highbit(max_align) - 1));
1357 		if (*align < max_align ||
1358 		    (*align > UINT_MAX && model == DATAMODEL_ILP32)) {
1359 			MOBJ_STAT_ADD(np2_align_overflow);
1360 			*align = 1L << (highbit(max_align) - 1);
1361 		}
1362 	} else {
1363 		*align = max_align;
1364 	}
1365 
1366 	ASSERT(*align >= PAGESIZE || *align == 0);
1367 
1368 	*loadable = num_segs;
1369 	*len = p_end - start_addr;
1370 	return (0);
1371 }
1372 
1373 /*
1374  * Check the address space to see if the virtual addresses to be used are
1375  * available.  If they are not, return errno for failure.  On success, 0
1376  * will be returned, and the virtual addresses for each mmapobj_result_t
1377  * will be reserved.  Note that a reservation could have earlier been made
1378  * for a given segment via a /dev/null mapping.  If that is the case, then
1379  * we can use that VA space for our mappings.
1380  * Note: this function will only be used for ET_EXEC binaries.
1381  */
1382 int
1383 check_exec_addrs(int loadable, mmapobj_result_t *mrp, caddr_t start_addr)
1384 {
1385 	int i;
1386 	struct as *as = curproc->p_as;
1387 	struct segvn_crargs crargs = SEGVN_ZFOD_ARGS(PROT_ZFOD, PROT_ALL);
1388 	int ret;
1389 	caddr_t myaddr;
1390 	size_t mylen;
1391 	struct seg *seg;
1392 
1393 	/* No need to reserve swap space now since it will be reserved later */
1394 	crargs.flags |= MAP_NORESERVE;
1395 	as_rangelock(as);
1396 	for (i = 0; i < loadable; i++) {
1397 
1398 		myaddr = start_addr + (size_t)mrp[i].mr_addr;
1399 		mylen = mrp[i].mr_msize;
1400 
1401 		/* See if there is a hole in the as for this range */
1402 		if (as_gap(as, mylen, &myaddr, &mylen, 0, NULL) == 0) {
1403 			ASSERT(myaddr == start_addr + (size_t)mrp[i].mr_addr);
1404 			ASSERT(mylen == mrp[i].mr_msize);
1405 
1406 #ifdef DEBUG
1407 			if (MR_GET_TYPE(mrp[i].mr_flags) == MR_PADDING) {
1408 				MOBJ_STAT_ADD(exec_padding);
1409 			}
1410 #endif
1411 			ret = as_map(as, myaddr, mylen, segvn_create, &crargs);
1412 			if (ret) {
1413 				as_rangeunlock(as);
1414 				mmapobj_unmap_exec(mrp, i, start_addr);
1415 				return (ret);
1416 			}
1417 		} else {
1418 			/*
1419 			 * There is a mapping that exists in the range
1420 			 * so check to see if it was a "reservation"
1421 			 * from /dev/null.  The mapping is from
1422 			 * /dev/null if the mapping comes from
1423 			 * segdev and the type is neither MAP_SHARED
1424 			 * nor MAP_PRIVATE.
1425 			 */
1426 			AS_LOCK_ENTER(as, &as->a_lock, RW_READER);
1427 			seg = as_findseg(as, myaddr, 0);
1428 			MOBJ_STAT_ADD(exec_addr_mapped);
1429 			if (seg && seg->s_ops == &segdev_ops &&
1430 			    ((SEGOP_GETTYPE(seg, myaddr) &
1431 			    (MAP_SHARED | MAP_PRIVATE)) == 0) &&
1432 			    myaddr >= seg->s_base &&
1433 			    myaddr + mylen <=
1434 			    seg->s_base + seg->s_size) {
1435 				MOBJ_STAT_ADD(exec_addr_devnull);
1436 				AS_LOCK_EXIT(as, &as->a_lock);
1437 				(void) as_unmap(as, myaddr, mylen);
1438 				ret = as_map(as, myaddr, mylen, segvn_create,
1439 				    &crargs);
1440 				mrp[i].mr_flags |= MR_RESV;
1441 				if (ret) {
1442 					as_rangeunlock(as);
1443 					/* Need to remap what we unmapped */
1444 					mmapobj_unmap_exec(mrp, i + 1,
1445 					    start_addr);
1446 					return (ret);
1447 				}
1448 			} else {
1449 				AS_LOCK_EXIT(as, &as->a_lock);
1450 				as_rangeunlock(as);
1451 				mmapobj_unmap_exec(mrp, i, start_addr);
1452 				MOBJ_STAT_ADD(exec_addr_in_use);
1453 				return (EADDRINUSE);
1454 			}
1455 		}
1456 	}
1457 	as_rangeunlock(as);
1458 	return (0);
1459 }
1460 
1461 /*
1462  * Walk through the ELF program headers and extract all useful information
1463  * for PT_LOAD and PT_SUNWBSS segments into mrp.
1464  * Return 0 on success or error on failure.
1465  */
1466 static int
1467 process_phdr(Ehdr *ehdrp, caddr_t phdrbase, int nphdrs, mmapobj_result_t *mrp,
1468     vnode_t *vp, uint_t *num_mapped, size_t padding, cred_t *fcred)
1469 {
1470 	int i;
1471 	caddr_t start_addr = NULL;
1472 	caddr_t vaddr;
1473 	size_t len = 0;
1474 	size_t lib_len = 0;
1475 	int ret;
1476 	int prot;
1477 	struct lib_va *lvp = NULL;
1478 	vattr_t vattr;
1479 	struct as *as = curproc->p_as;
1480 	int error;
1481 	int loadable = 0;
1482 	int current = 0;
1483 	int use_lib_va = 1;
1484 	size_t align = 0;
1485 	size_t add_pad = 0;
1486 	int hdr_seen = 0;
1487 	ushort_t e_type = ehdrp->e_type;	/* same offset 32 and 64 bit */
1488 	uint_t p_type;
1489 	offset_t p_offset;
1490 	size_t p_memsz;
1491 	size_t p_filesz;
1492 	uint_t p_flags;
1493 	int hsize;
1494 	model_t model;
1495 	STRUCT_HANDLE(myphdr, mph);
1496 
1497 	model = get_udatamodel();
1498 	STRUCT_SET_HANDLE(mph, model, (struct myphdr *)phdrbase);
1499 
1500 	/*
1501 	 * Need to make sure that hsize is aligned properly.
1502 	 * For 32bit processes, 4 byte alignment is required.
1503 	 * For 64bit processes, 8 byte alignment is required.
1504 	 * If the alignment isn't correct, we need to return failure
1505 	 * since it could cause an alignment error panic while walking
1506 	 * the phdr array.
1507 	 */
1508 	if (model == DATAMODEL_LP64) {
1509 		hsize = ehdrp->e_phentsize;
1510 		if (hsize & 7) {
1511 			MOBJ_STAT_ADD(phent_align64);
1512 			return (ENOTSUP);
1513 		}
1514 	} else {
1515 		ASSERT(model == DATAMODEL_ILP32);
1516 		hsize = ((Elf32_Ehdr *)ehdrp)->e_phentsize;
1517 		if (hsize & 3) {
1518 			MOBJ_STAT_ADD(phent_align32);
1519 			return (ENOTSUP);
1520 		}
1521 	}
1522 
1523 	if (padding != 0) {
1524 		use_lib_va = 0;
1525 	}
1526 	if (e_type == ET_DYN) {
1527 		vattr.va_mask = AT_FSID | AT_NODEID | AT_CTIME | AT_MTIME;
1528 		error = VOP_GETATTR(vp, &vattr, 0, fcred, NULL);
1529 		if (error) {
1530 			return (error);
1531 		}
1532 		/* Check to see if we already have a description for this lib */
1533 		lvp = lib_va_find(&vattr);
1534 
1535 		if (lvp != NULL) {
1536 			MOBJ_STAT_ADD(lvp_found);
1537 			if (use_lib_va) {
1538 				start_addr = mmapobj_lookup_start_addr(lvp);
1539 				if (start_addr == NULL) {
1540 					lib_va_release(lvp);
1541 					return (ENOMEM);
1542 				}
1543 			}
1544 
1545 			/*
1546 			 * loadable may be zero if the original allocator
1547 			 * of lvp hasn't finished setting it up but the rest
1548 			 * of the fields will be accurate.
1549 			 */
1550 			loadable = lvp->lv_num_segs;
1551 			len = lvp->lv_len;
1552 			align = lvp->lv_align;
1553 		}
1554 	}
1555 
1556 	/*
1557 	 * Determine the span of all loadable segments and calculate the
1558 	 * number of loadable segments, the total len spanned by the mappings
1559 	 * and the max alignment, if we didn't get them above.
1560 	 */
1561 	if (loadable == 0) {
1562 		MOBJ_STAT_ADD(no_loadable_yet);
1563 		ret = calc_loadable(ehdrp, phdrbase, nphdrs, &len,
1564 		    &loadable, &align);
1565 		if (ret != 0) {
1566 			/*
1567 			 * Since it'd be an invalid file, we shouldn't have
1568 			 * cached it previously.
1569 			 */
1570 			ASSERT(lvp == NULL);
1571 			return (ret);
1572 		}
1573 #ifdef DEBUG
1574 		if (lvp) {
1575 			ASSERT(len == lvp->lv_len);
1576 			ASSERT(align == lvp->lv_align);
1577 		}
1578 #endif
1579 	}
1580 
1581 	/* Make sure there's something to map. */
1582 	if (len == 0 || loadable == 0) {
1583 		/*
1584 		 * Since it'd be an invalid file, we shouldn't have
1585 		 * cached it previously.
1586 		 */
1587 		ASSERT(lvp == NULL);
1588 		MOBJ_STAT_ADD(nothing_to_map);
1589 		return (ENOTSUP);
1590 	}
1591 
1592 	lib_len = len;
1593 	if (padding != 0) {
1594 		loadable += 2;
1595 	}
1596 	if (loadable > *num_mapped) {
1597 		*num_mapped = loadable;
1598 		/* cleanup previous reservation */
1599 		if (start_addr) {
1600 			(void) as_unmap(as, start_addr, lib_len);
1601 		}
1602 		MOBJ_STAT_ADD(e2big);
1603 		if (lvp) {
1604 			lib_va_release(lvp);
1605 		}
1606 		return (E2BIG);
1607 	}
1608 
1609 	/*
1610 	 * We now know the size of the object to map and now we need to
1611 	 * get the start address to map it at.  It's possible we already
1612 	 * have it if we found all the info we need in the lib_va cache.
1613 	 */
1614 	if (e_type == ET_DYN && start_addr == NULL) {
1615 		/*
1616 		 * Need to make sure padding does not throw off
1617 		 * required alignment.  We can only specify an
1618 		 * alignment for the starting address to be mapped,
1619 		 * so we round padding up to the alignment and map
1620 		 * from there and then throw out the extra later.
1621 		 */
1622 		if (padding != 0) {
1623 			if (align > 1) {
1624 				add_pad = P2ROUNDUP(padding, align);
1625 				len += add_pad;
1626 				MOBJ_STAT_ADD(dyn_pad_align);
1627 			} else {
1628 				MOBJ_STAT_ADD(dyn_pad_noalign);
1629 				len += padding;	/* at beginning */
1630 			}
1631 			len += padding;	/* at end of mapping */
1632 		}
1633 		/*
1634 		 * At this point, if lvp is non-NULL, then above we
1635 		 * already found it in the cache but did not get
1636 		 * the start address since we were not going to use lib_va.
1637 		 * Since we know that lib_va will not be used, it's safe
1638 		 * to call mmapobj_alloc_start_addr and know that lvp
1639 		 * will not be modified.
1640 		 */
1641 		ASSERT(lvp ? use_lib_va == 0 : 1);
1642 		start_addr = mmapobj_alloc_start_addr(&lvp, len,
1643 		    use_lib_va, align, &vattr);
1644 		if (start_addr == NULL) {
1645 			if (lvp) {
1646 				lib_va_release(lvp);
1647 			}
1648 			MOBJ_STAT_ADD(alloc_start_fail);
1649 			return (ENOMEM);
1650 		}
1651 		/*
1652 		 * If we can't cache it, no need to hang on to it.
1653 		 * Setting lv_num_segs to non-zero will make that
1654 		 * field active and since there are too many segments
1655 		 * to cache, all future users will not try to use lv_mps.
1656 		 */
1657 		if (lvp != NULL && loadable > LIBVA_CACHED_SEGS && use_lib_va) {
1658 			lvp->lv_num_segs = loadable;
1659 			lib_va_release(lvp);
1660 			lvp = NULL;
1661 			MOBJ_STAT_ADD(lvp_nocache);
1662 		}
1663 		/*
1664 		 * Free the beginning of the mapping if the padding
1665 		 * was not aligned correctly.
1666 		 */
1667 		if (padding != 0 && add_pad != padding) {
1668 			(void) as_unmap(as, start_addr,
1669 			    add_pad - padding);
1670 			start_addr += (add_pad - padding);
1671 			MOBJ_STAT_ADD(extra_padding);
1672 		}
1673 	}
1674 
1675 	/*
1676 	 * At this point, we have reserved the virtual address space
1677 	 * for our mappings.  Now we need to start filling out the mrp
1678 	 * array to describe all of the individual mappings we are going
1679 	 * to return.
1680 	 * For ET_EXEC there has been no memory reservation since we are
1681 	 * using fixed addresses.  While filling in the mrp array below,
1682 	 * we will have the first segment biased to start at addr 0
1683 	 * and the rest will be biased by this same amount.  Thus if there
1684 	 * is padding, the first padding will start at addr 0, and the next
1685 	 * segment will start at the value of padding.
1686 	 */
1687 
1688 	/* We'll fill out padding later, so start filling in mrp at index 1 */
1689 	if (padding != 0) {
1690 		current = 1;
1691 	}
1692 
1693 	/* If we have no more need for lvp let it go now */
1694 	if (lvp != NULL && use_lib_va == 0) {
1695 		lib_va_release(lvp);
1696 		MOBJ_STAT_ADD(lvp_not_needed);
1697 		lvp = NULL;
1698 	}
1699 
1700 	/* Now fill out the mrp structs from the program headers */
1701 	STRUCT_SET_HANDLE(mph, model, (struct myphdr *)phdrbase);
1702 	for (i = 0; i < nphdrs; i++) {
1703 		p_type = STRUCT_FGET(mph, x.p_type);
1704 		if (p_type == PT_LOAD || p_type == PT_SUNWBSS) {
1705 			vaddr = (caddr_t)(uintptr_t)STRUCT_FGET(mph, x.p_vaddr);
1706 			p_memsz = STRUCT_FGET(mph, x.p_memsz);
1707 			p_filesz = STRUCT_FGET(mph, x.p_filesz);
1708 			p_offset = STRUCT_FGET(mph, x.p_offset);
1709 			p_flags = STRUCT_FGET(mph, x.p_flags);
1710 
1711 			/*
1712 			 * Skip this header if it requests no memory to be
1713 			 * mapped.
1714 			 */
1715 			if (p_memsz == 0) {
1716 				STRUCT_SET_HANDLE(mph, model,
1717 				    (struct myphdr *)((size_t)STRUCT_BUF(mph) +
1718 				    hsize));
1719 				MOBJ_STAT_ADD(no_mem_map_sz);
1720 				continue;
1721 			}
1722 
1723 			prot = 0;
1724 			if (p_flags & PF_R)
1725 				prot |= PROT_READ;
1726 			if (p_flags & PF_W)
1727 				prot |= PROT_WRITE;
1728 			if (p_flags & PF_X)
1729 				prot |= PROT_EXEC;
1730 
1731 			ASSERT(current < loadable);
1732 			mrp[current].mr_msize = p_memsz;
1733 			mrp[current].mr_fsize = p_filesz;
1734 			mrp[current].mr_offset = p_offset;
1735 			mrp[current].mr_prot = prot;
1736 
1737 			if (hdr_seen == 0 && p_filesz != 0) {
1738 				mrp[current].mr_flags = MR_HDR_ELF;
1739 				/*
1740 				 * We modify mr_addr and mr_offset because we
1741 				 * need to map the ELF header as well, and if
1742 				 * we didn't then the header could be left out
1743 				 * of the mapping that we will create later.
1744 				 * Since we're removing the offset, we need to
1745 				 * account for that in the other fields as well
1746 				 * since we will be mapping the memory from 0
1747 				 * to p_offset.
1748 				 */
1749 				if (e_type == ET_DYN) {
1750 					mrp[current].mr_offset = 0;
1751 					mrp[current].mr_msize += p_offset;
1752 					mrp[current].mr_fsize += p_offset;
1753 				} else {
1754 					ASSERT(e_type == ET_EXEC);
1755 					/*
1756 					 * Save off the start addr which will be
1757 					 * our bias for the rest of the
1758 					 * ET_EXEC mappings.
1759 					 */
1760 					start_addr = vaddr - padding;
1761 				}
1762 				mrp[current].mr_addr = (caddr_t)padding;
1763 				hdr_seen = 1;
1764 			} else {
1765 				if (e_type == ET_EXEC) {
1766 					/* bias mr_addr */
1767 					mrp[current].mr_addr =
1768 					    vaddr - (size_t)start_addr;
1769 				} else {
1770 					mrp[current].mr_addr = vaddr + padding;
1771 				}
1772 				mrp[current].mr_flags = 0;
1773 			}
1774 			current++;
1775 		}
1776 
1777 		/* Move to next phdr */
1778 		STRUCT_SET_HANDLE(mph, model,
1779 		    (struct myphdr *)((size_t)STRUCT_BUF(mph) +
1780 		    hsize));
1781 	}
1782 
1783 	/* Now fill out the padding segments */
1784 	if (padding != 0) {
1785 		mrp[0].mr_addr = NULL;
1786 		mrp[0].mr_msize = padding;
1787 		mrp[0].mr_fsize = 0;
1788 		mrp[0].mr_offset = 0;
1789 		mrp[0].mr_prot = 0;
1790 		mrp[0].mr_flags = MR_PADDING;
1791 
1792 		/* Setup padding for the last segment */
1793 		ASSERT(current == loadable - 1);
1794 		mrp[current].mr_addr = (caddr_t)lib_len + padding;
1795 		mrp[current].mr_msize = padding;
1796 		mrp[current].mr_fsize = 0;
1797 		mrp[current].mr_offset = 0;
1798 		mrp[current].mr_prot = 0;
1799 		mrp[current].mr_flags = MR_PADDING;
1800 	}
1801 
1802 	/*
1803 	 * Need to make sure address ranges desired are not in use or
1804 	 * are previously allocated reservations from /dev/null.  For
1805 	 * ET_DYN, we already made sure our address range was free.
1806 	 */
1807 	if (e_type == ET_EXEC) {
1808 		ret = check_exec_addrs(loadable, mrp, start_addr);
1809 		if (ret != 0) {
1810 			ASSERT(lvp == NULL);
1811 			MOBJ_STAT_ADD(check_exec_failed);
1812 			return (ret);
1813 		}
1814 	}
1815 
1816 	/* Finish up our business with lvp. */
1817 	if (lvp) {
1818 		ASSERT(e_type == ET_DYN);
1819 		if (lvp->lv_num_segs == 0 && loadable <= LIBVA_CACHED_SEGS) {
1820 			bcopy(mrp, lvp->lv_mps,
1821 			    loadable * sizeof (mmapobj_result_t));
1822 			membar_producer();
1823 		}
1824 		/*
1825 		 * Setting lv_num_segs to a non-zero value indicates that
1826 		 * lv_mps is now valid and can be used by other threads.
1827 		 * So, the above stores need to finish before lv_num_segs
1828 		 * is updated. lv_mps is only valid if lv_num_segs is
1829 		 * greater than LIBVA_CACHED_SEGS.
1830 		 */
1831 		lvp->lv_num_segs = loadable;
1832 		lib_va_release(lvp);
1833 		MOBJ_STAT_ADD(lvp_used);
1834 	}
1835 
1836 	/* Now that we have mrp completely filled out go map it */
1837 	ret = mmapobj_map_elf(vp, start_addr, mrp, loadable, fcred, e_type);
1838 	if (ret == 0) {
1839 		*num_mapped = loadable;
1840 	}
1841 
1842 	return (ret);
1843 }
1844 
1845 /*
1846  * Take the ELF file passed in, and do the work of mapping it.
1847  * num_mapped in - # elements in user buffer
1848  * num_mapped out - # sections mapped and length of mrp array if
1849  *			no errors.
1850  */
1851 static int
1852 doelfwork(Ehdr *ehdrp, vnode_t *vp, mmapobj_result_t *mrp,
1853     uint_t *num_mapped, size_t padding, cred_t *fcred)
1854 {
1855 	int error;
1856 	offset_t phoff;
1857 	int nphdrs;
1858 	unsigned char ei_class;
1859 	unsigned short phentsize;
1860 	ssize_t phsizep;
1861 	caddr_t phbasep;
1862 	int to_map;
1863 	model_t model;
1864 
1865 	ei_class = ehdrp->e_ident[EI_CLASS];
1866 	model = get_udatamodel();
1867 	if ((model == DATAMODEL_ILP32 && ei_class == ELFCLASS64) ||
1868 	    (model == DATAMODEL_LP64 && ei_class == ELFCLASS32)) {
1869 		MOBJ_STAT_ADD(wrong_model);
1870 		return (ENOTSUP);
1871 	}
1872 
1873 	/* Can't execute code from "noexec" mounted filesystem. */
1874 	if (ehdrp->e_type == ET_EXEC &&
1875 	    (vp->v_vfsp->vfs_flag & VFS_NOEXEC) != 0) {
1876 		MOBJ_STAT_ADD(noexec_fs);
1877 		return (EACCES);
1878 	}
1879 
1880 	/*
1881 	 * Relocatable and core files are mapped as a single flat file
1882 	 * since no interpretation is done on them by mmapobj.
1883 	 */
1884 	if (ehdrp->e_type == ET_REL || ehdrp->e_type == ET_CORE) {
1885 		to_map = padding ? 3 : 1;
1886 		if (*num_mapped < to_map) {
1887 			*num_mapped = to_map;
1888 			MOBJ_STAT_ADD(e2big_et_rel);
1889 			return (E2BIG);
1890 		}
1891 		error = mmapobj_map_flat(vp, mrp, padding, fcred);
1892 		if (error == 0) {
1893 			*num_mapped = to_map;
1894 			mrp[padding ? 1 : 0].mr_flags = MR_HDR_ELF;
1895 			MOBJ_STAT_ADD(et_rel_mapped);
1896 		}
1897 		return (error);
1898 	}
1899 
1900 	/* Check for an unknown ELF type */
1901 	if (ehdrp->e_type != ET_EXEC && ehdrp->e_type != ET_DYN) {
1902 		MOBJ_STAT_ADD(unknown_elf_type);
1903 		return (ENOTSUP);
1904 	}
1905 
1906 	if (ei_class == ELFCLASS32) {
1907 		Elf32_Ehdr *e32hdr = (Elf32_Ehdr *)ehdrp;
1908 		ASSERT(model == DATAMODEL_ILP32);
1909 		nphdrs = e32hdr->e_phnum;
1910 		phentsize = e32hdr->e_phentsize;
1911 		if (phentsize < sizeof (Elf32_Phdr)) {
1912 			MOBJ_STAT_ADD(phent32_too_small);
1913 			return (ENOTSUP);
1914 		}
1915 		phoff = e32hdr->e_phoff;
1916 	} else if (ei_class == ELFCLASS64) {
1917 		Elf64_Ehdr *e64hdr = (Elf64_Ehdr *)ehdrp;
1918 		ASSERT(model == DATAMODEL_LP64);
1919 		nphdrs = e64hdr->e_phnum;
1920 		phentsize = e64hdr->e_phentsize;
1921 		if (phentsize < sizeof (Elf64_Phdr)) {
1922 			MOBJ_STAT_ADD(phent64_too_small);
1923 			return (ENOTSUP);
1924 		}
1925 		phoff = e64hdr->e_phoff;
1926 	} else {
1927 		/* fallthrough case for an invalid ELF class */
1928 		MOBJ_STAT_ADD(inval_elf_class);
1929 		return (ENOTSUP);
1930 	}
1931 
1932 	/*
1933 	 * nphdrs should only have this value for core files which are handled
1934 	 * above as a single mapping.  If other file types ever use this
1935 	 * sentinel, then we'll add the support needed to handle this here.
1936 	 */
1937 	if (nphdrs == PN_XNUM) {
1938 		MOBJ_STAT_ADD(too_many_phdrs);
1939 		return (ENOTSUP);
1940 	}
1941 
1942 	phsizep = nphdrs * phentsize;
1943 
1944 	if (phsizep == 0) {
1945 		MOBJ_STAT_ADD(no_phsize);
1946 		return (ENOTSUP);
1947 	}
1948 
1949 	/* Make sure we only wait for memory if it's a reasonable request */
1950 	if (phsizep > mmapobj_alloc_threshold) {
1951 		MOBJ_STAT_ADD(phsize_large);
1952 		if ((phbasep = kmem_alloc(phsizep, KM_NOSLEEP)) == NULL) {
1953 			MOBJ_STAT_ADD(phsize_xtralarge);
1954 			return (ENOMEM);
1955 		}
1956 	} else {
1957 		phbasep = kmem_alloc(phsizep, KM_SLEEP);
1958 	}
1959 
1960 	if ((error = vn_rdwr(UIO_READ, vp, phbasep, phsizep,
1961 	    (offset_t)phoff, UIO_SYSSPACE, 0, (rlim64_t)0,
1962 	    fcred, NULL)) != 0) {
1963 		kmem_free(phbasep, phsizep);
1964 		return (error);
1965 	}
1966 
1967 	/* Now process the phdr's */
1968 	error = process_phdr(ehdrp, phbasep, nphdrs, mrp, vp, num_mapped,
1969 	    padding, fcred);
1970 	kmem_free(phbasep, phsizep);
1971 	return (error);
1972 }
1973 
1974 #if defined(__sparc)
1975 /*
1976  * Hack to support 64 bit kernels running AOUT 4.x programs.
1977  * This is the sizeof (struct nlist) for a 32 bit kernel.
1978  * Since AOUT programs are 32 bit only, they will never use the 64 bit
1979  * sizeof (struct nlist) and thus creating a #define is the simplest
1980  * way around this since this is a format which is not being updated.
1981  * This will be used in the place of sizeof (struct nlist) below.
1982  */
1983 #define	NLIST_SIZE	(0xC)
1984 
1985 static int
1986 doaoutwork(vnode_t *vp, mmapobj_result_t *mrp,
1987     uint_t *num_mapped, struct exec *hdr, cred_t *fcred)
1988 {
1989 	int error;
1990 	size_t size;
1991 	size_t osize;
1992 	size_t nsize;	/* nlist size */
1993 	size_t msize;
1994 	size_t zfoddiff;
1995 	caddr_t addr;
1996 	caddr_t start_addr;
1997 	struct as *as = curproc->p_as;
1998 	int prot = PROT_USER | PROT_READ | PROT_EXEC;
1999 	uint_t mflag = MAP_PRIVATE | _MAP_LOW32;
2000 	offset_t off = 0;
2001 	int segnum = 0;
2002 	uint_t to_map;
2003 	int is_library = 0;
2004 	struct segvn_crargs crargs = SEGVN_ZFOD_ARGS(PROT_ZFOD, PROT_ALL);
2005 
2006 	/* Only 32bit apps supported by this file format */
2007 	if (get_udatamodel() != DATAMODEL_ILP32) {
2008 		MOBJ_STAT_ADD(aout_64bit_try);
2009 		return (ENOTSUP);
2010 	}
2011 
2012 	/* Check to see if this is a library */
2013 	if (hdr->a_magic == ZMAGIC && hdr->a_entry < PAGESIZE) {
2014 		is_library = 1;
2015 	}
2016 
2017 	/* Can't execute code from "noexec" mounted filesystem. */
2018 	if (((vp->v_vfsp->vfs_flag & VFS_NOEXEC) != 0) && (is_library == 0)) {
2019 		MOBJ_STAT_ADD(aout_noexec);
2020 		return (EACCES);
2021 	}
2022 
2023 	/*
2024 	 * There are 2 ways to calculate the mapped size of executable:
2025 	 * 1) rounded text size + data size + bss size.
2026 	 * 2) starting offset for text + text size + data size + text relocation
2027 	 *    size + data relocation size + room for nlist data structure.
2028 	 *
2029 	 * The larger of the two sizes will be used to map this binary.
2030 	 */
2031 	osize = P2ROUNDUP(hdr->a_text, PAGESIZE) + hdr->a_data + hdr->a_bss;
2032 
2033 	off = hdr->a_magic == ZMAGIC ? 0 : sizeof (struct exec);
2034 
2035 	nsize = off + hdr->a_text + hdr->a_data + hdr->a_trsize +
2036 	    hdr->a_drsize + NLIST_SIZE;
2037 
2038 	size = MAX(osize, nsize);
2039 	if (size != nsize) {
2040 		nsize = 0;
2041 	}
2042 
2043 	/*
2044 	 * 1 seg for text and 1 seg for initialized data.
2045 	 * 1 seg for bss (if can't fit in leftover space of init data)
2046 	 * 1 seg for nlist if needed.
2047 	 */
2048 	to_map = 2 + (nsize ? 1 : 0) +
2049 	    (hdr->a_bss > PAGESIZE - P2PHASE(hdr->a_data, PAGESIZE) ? 1 : 0);
2050 	if (*num_mapped < to_map) {
2051 		*num_mapped = to_map;
2052 		MOBJ_STAT_ADD(aout_e2big);
2053 		return (E2BIG);
2054 	}
2055 
2056 	/* Reserve address space for the whole mapping */
2057 	if (is_library) {
2058 		/* We'll let VOP_MAP below pick our address for us */
2059 		addr = NULL;
2060 		MOBJ_STAT_ADD(aout_lib);
2061 	} else {
2062 		/*
2063 		 * default start address for fixed binaries from AOUT 4.x
2064 		 * standard.
2065 		 */
2066 		MOBJ_STAT_ADD(aout_fixed);
2067 		mflag |= MAP_FIXED;
2068 		addr = (caddr_t)0x2000;
2069 		as_rangelock(as);
2070 		if (as_gap(as, size, &addr, &size, 0, NULL) != 0) {
2071 			as_rangeunlock(as);
2072 			MOBJ_STAT_ADD(aout_addr_in_use);
2073 			return (EADDRINUSE);
2074 		}
2075 		crargs.flags |= MAP_NORESERVE;
2076 		error = as_map(as, addr, size, segvn_create, &crargs);
2077 		ASSERT(addr == (caddr_t)0x2000);
2078 		as_rangeunlock(as);
2079 	}
2080 
2081 	start_addr = addr;
2082 	osize = size;
2083 
2084 	/*
2085 	 * Map as large as we need, backed by file, this will be text, and
2086 	 * possibly the nlist segment.  We map over this mapping for bss and
2087 	 * initialized data segments.
2088 	 */
2089 	error = VOP_MAP(vp, off, as, &addr, size, prot, PROT_ALL,
2090 	    mflag, fcred, NULL);
2091 	if (error) {
2092 		if (!is_library) {
2093 			(void) as_unmap(as, start_addr, osize);
2094 		}
2095 		return (error);
2096 	}
2097 
2098 	/* pickup the value of start_addr and osize for libraries */
2099 	start_addr = addr;
2100 	osize = size;
2101 
2102 	/*
2103 	 * We have our initial reservation/allocation so we need to use fixed
2104 	 * addresses from now on.
2105 	 */
2106 	mflag |= MAP_FIXED;
2107 
2108 	mrp[0].mr_addr = addr;
2109 	mrp[0].mr_msize = hdr->a_text;
2110 	mrp[0].mr_fsize = hdr->a_text;
2111 	mrp[0].mr_offset = 0;
2112 	mrp[0].mr_prot = PROT_READ | PROT_EXEC;
2113 	mrp[0].mr_flags = MR_HDR_AOUT;
2114 
2115 
2116 	/*
2117 	 * Map initialized data. We are mapping over a portion of the
2118 	 * previous mapping which will be unmapped in VOP_MAP below.
2119 	 */
2120 	off = P2ROUNDUP((offset_t)(hdr->a_text), PAGESIZE);
2121 	msize = off;
2122 	addr += off;
2123 	size = hdr->a_data;
2124 	error = VOP_MAP(vp, off, as, &addr, size, PROT_ALL, PROT_ALL,
2125 	    mflag, fcred, NULL);
2126 	if (error) {
2127 		(void) as_unmap(as, start_addr, osize);
2128 		return (error);
2129 	}
2130 	msize += size;
2131 	mrp[1].mr_addr = addr;
2132 	mrp[1].mr_msize = size;
2133 	mrp[1].mr_fsize = size;
2134 	mrp[1].mr_offset = 0;
2135 	mrp[1].mr_prot = PROT_READ | PROT_WRITE | PROT_EXEC;
2136 	mrp[1].mr_flags = 0;
2137 
2138 	/* Need to zero out remainder of page */
2139 	addr += hdr->a_data;
2140 	zfoddiff = P2PHASE((size_t)addr, PAGESIZE);
2141 	if (zfoddiff) {
2142 		label_t ljb;
2143 
2144 		MOBJ_STAT_ADD(aout_zfoddiff);
2145 		zfoddiff = PAGESIZE - zfoddiff;
2146 		if (on_fault(&ljb)) {
2147 			no_fault();
2148 			MOBJ_STAT_ADD(aout_uzero_fault);
2149 			(void) as_unmap(as, start_addr, osize);
2150 			return (EFAULT);
2151 		}
2152 		uzero(addr, zfoddiff);
2153 		no_fault();
2154 	}
2155 	msize += zfoddiff;
2156 	segnum = 2;
2157 
2158 	/* Map bss */
2159 	if (hdr->a_bss > zfoddiff) {
2160 		struct segvn_crargs crargs =
2161 		    SEGVN_ZFOD_ARGS(PROT_ZFOD, PROT_ALL);
2162 		MOBJ_STAT_ADD(aout_map_bss);
2163 		addr += zfoddiff;
2164 		size = hdr->a_bss - zfoddiff;
2165 		as_rangelock(as);
2166 		(void) as_unmap(as, addr, size);
2167 		error = as_map(as, addr, size, segvn_create, &crargs);
2168 		as_rangeunlock(as);
2169 		msize += size;
2170 
2171 		if (error) {
2172 			MOBJ_STAT_ADD(aout_bss_fail);
2173 			(void) as_unmap(as, start_addr, osize);
2174 			return (error);
2175 		}
2176 		mrp[2].mr_addr = addr;
2177 		mrp[2].mr_msize = size;
2178 		mrp[2].mr_fsize = 0;
2179 		mrp[2].mr_offset = 0;
2180 		mrp[2].mr_prot = PROT_READ | PROT_WRITE | PROT_EXEC;
2181 		mrp[2].mr_flags = 0;
2182 
2183 		addr += size;
2184 		segnum = 3;
2185 	}
2186 
2187 	/*
2188 	 * If we have extra bits left over, we need to include that in how
2189 	 * much we mapped to make sure the nlist logic is correct
2190 	 */
2191 	msize = P2ROUNDUP(msize, PAGESIZE);
2192 
2193 	if (nsize && msize < nsize) {
2194 		MOBJ_STAT_ADD(aout_nlist);
2195 		mrp[segnum].mr_addr = addr;
2196 		mrp[segnum].mr_msize = nsize - msize;
2197 		mrp[segnum].mr_fsize = 0;
2198 		mrp[segnum].mr_offset = 0;
2199 		mrp[segnum].mr_prot = PROT_READ | PROT_EXEC;
2200 		mrp[segnum].mr_flags = 0;
2201 	}
2202 
2203 	*num_mapped = to_map;
2204 	return (0);
2205 }
2206 #endif
2207 
2208 /*
2209  * These are the two types of files that we can interpret and we want to read
2210  * in enough info to cover both types when looking at the initial header.
2211  */
2212 #define	MAX_HEADER_SIZE	(MAX(sizeof (Ehdr), sizeof (struct exec)))
2213 
2214 /*
2215  * Map vp passed in in an interpreted manner.  ELF and AOUT files will be
2216  * interpreted and mapped appropriately for execution.
2217  * num_mapped in - # elements in mrp
2218  * num_mapped out - # sections mapped and length of mrp array if
2219  *		    no errors or E2BIG returned.
2220  *
2221  * Returns 0 on success, errno value on failure.
2222  */
2223 static int
2224 mmapobj_map_interpret(vnode_t *vp, mmapobj_result_t *mrp,
2225     uint_t *num_mapped, size_t padding, cred_t *fcred)
2226 {
2227 	int error = 0;
2228 	vattr_t vattr;
2229 	struct lib_va *lvp;
2230 	caddr_t start_addr;
2231 	model_t model;
2232 
2233 	/*
2234 	 * header has to be aligned to the native size of ulong_t in order
2235 	 * to avoid an unaligned access when dereferencing the header as
2236 	 * a ulong_t.  Thus we allocate our array on the stack of type
2237 	 * ulong_t and then have header, which we dereference later as a char
2238 	 * array point at lheader.
2239 	 */
2240 	ulong_t lheader[(MAX_HEADER_SIZE / (sizeof (ulong_t))) + 1];
2241 	caddr_t header = (caddr_t)&lheader;
2242 
2243 	vattr.va_mask = AT_FSID | AT_NODEID | AT_CTIME | AT_MTIME | AT_SIZE;
2244 	error = VOP_GETATTR(vp, &vattr, 0, fcred, NULL);
2245 	if (error) {
2246 		return (error);
2247 	}
2248 
2249 	/*
2250 	 * Check lib_va to see if we already have a full description
2251 	 * for this library.  This is the fast path and only used for
2252 	 * ET_DYN ELF files (dynamic libraries).
2253 	 */
2254 	if (padding == 0 && (lvp = lib_va_find(&vattr)) != NULL) {
2255 		int num_segs;
2256 
2257 		model = get_udatamodel();
2258 		if ((model == DATAMODEL_ILP32 &&
2259 		    lvp->lv_flags & LV_ELF64) ||
2260 		    (model == DATAMODEL_LP64 &&
2261 		    lvp->lv_flags & LV_ELF32)) {
2262 			lib_va_release(lvp);
2263 			MOBJ_STAT_ADD(fast_wrong_model);
2264 			return (ENOTSUP);
2265 		}
2266 		num_segs = lvp->lv_num_segs;
2267 		if (*num_mapped < num_segs) {
2268 			*num_mapped = num_segs;
2269 			lib_va_release(lvp);
2270 			MOBJ_STAT_ADD(fast_e2big);
2271 			return (E2BIG);
2272 		}
2273 
2274 		/*
2275 		 * Check to see if we have all the mappable program headers
2276 		 * cached.
2277 		 */
2278 		if (num_segs <= LIBVA_CACHED_SEGS && num_segs != 0) {
2279 			MOBJ_STAT_ADD(fast);
2280 			start_addr = mmapobj_lookup_start_addr(lvp);
2281 			if (start_addr == NULL) {
2282 				lib_va_release(lvp);
2283 				return (ENOMEM);
2284 			}
2285 
2286 			bcopy(lvp->lv_mps, mrp,
2287 			    num_segs * sizeof (mmapobj_result_t));
2288 
2289 			error = mmapobj_map_elf(vp, start_addr, mrp,
2290 			    num_segs, fcred, ET_DYN);
2291 
2292 			lib_va_release(lvp);
2293 			if (error == 0) {
2294 				*num_mapped = num_segs;
2295 				MOBJ_STAT_ADD(fast_success);
2296 			}
2297 			return (error);
2298 		}
2299 		MOBJ_STAT_ADD(fast_not_now);
2300 
2301 		/* Release it for now since we'll look it up below */
2302 		lib_va_release(lvp);
2303 	}
2304 
2305 	/*
2306 	 * Time to see if this is a file we can interpret.  If it's smaller
2307 	 * than this, then we can't interpret it.
2308 	 */
2309 	if (vattr.va_size < MAX_HEADER_SIZE) {
2310 		MOBJ_STAT_ADD(small_file);
2311 		return (ENOTSUP);
2312 	}
2313 
2314 	if ((error = vn_rdwr(UIO_READ, vp, header, MAX_HEADER_SIZE, 0,
2315 	    UIO_SYSSPACE, 0, (rlim64_t)0, fcred, NULL)) != 0) {
2316 		MOBJ_STAT_ADD(read_error);
2317 		return (error);
2318 	}
2319 
2320 	/* Verify file type */
2321 	if (header[EI_MAG0] == ELFMAG0 && header[EI_MAG1] == ELFMAG1 &&
2322 	    header[EI_MAG2] == ELFMAG2 && header[EI_MAG3] == ELFMAG3) {
2323 		return (doelfwork((Ehdr *)lheader, vp, mrp, num_mapped,
2324 		    padding, fcred));
2325 	}
2326 
2327 #if defined(__sparc)
2328 	/* On sparc, check for 4.X AOUT format */
2329 	switch (((struct exec *)header)->a_magic) {
2330 	case OMAGIC:
2331 	case ZMAGIC:
2332 	case NMAGIC:
2333 		return (doaoutwork(vp, mrp, num_mapped,
2334 		    (struct exec *)lheader, fcred));
2335 	}
2336 #endif
2337 
2338 	/* Unsupported type */
2339 	MOBJ_STAT_ADD(unsupported);
2340 	return (ENOTSUP);
2341 }
2342 
2343 /*
2344  * Given a vnode, map it as either a flat file or interpret it and map
2345  * it according to the rules of the file type.
2346  * *num_mapped will contain the size of the mmapobj_result_t array passed in.
2347  * If padding is non-zero, the mappings will be padded by that amount
2348  * rounded up to the nearest pagesize.
2349  * If the mapping is successful, *num_mapped will contain the number of
2350  * distinct mappings created, and mrp will point to the array of
2351  * mmapobj_result_t's which describe these mappings.
2352  *
2353  * On error, -1 is returned and errno is set appropriately.
2354  * A special error case will set errno to E2BIG when there are more than
2355  * *num_mapped mappings to be created and *num_mapped will be set to the
2356  * number of mappings needed.
2357  */
2358 int
2359 mmapobj(vnode_t *vp, uint_t flags, mmapobj_result_t *mrp,
2360     uint_t *num_mapped, size_t padding, cred_t *fcred)
2361 {
2362 	int to_map;
2363 	int error = 0;
2364 
2365 	ASSERT((padding & PAGEOFFSET) == 0);
2366 	ASSERT((flags & ~MMOBJ_ALL_FLAGS) == 0);
2367 	ASSERT(num_mapped != NULL);
2368 	ASSERT((flags & MMOBJ_PADDING) ? padding != 0 : padding == 0);
2369 
2370 	if ((flags & MMOBJ_INTERPRET) == 0) {
2371 		to_map = padding ? 3 : 1;
2372 		if (*num_mapped < to_map) {
2373 			*num_mapped = to_map;
2374 			MOBJ_STAT_ADD(flat_e2big);
2375 			return (E2BIG);
2376 		}
2377 		error = mmapobj_map_flat(vp, mrp, padding, fcred);
2378 
2379 		if (error) {
2380 			return (error);
2381 		}
2382 		*num_mapped = to_map;
2383 		return (0);
2384 	}
2385 
2386 	error = mmapobj_map_interpret(vp, mrp, num_mapped, padding, fcred);
2387 	return (error);
2388 }
2389