xref: /illumos-gate/usr/src/uts/common/os/mmapobj.c (revision ffb5616e59d0fbdc1ee94070050f240a6a4ac8e2)
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 #if defined(__sparc)
177 	uint_t	mobjs_vac_align;
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 	STRUCT_HANDLE(myphdr, mph);
1263 #if defined(__sparc)
1264 	extern int vac_size;
1265 #endif
1266 
1267 	model = get_udatamodel();
1268 	STRUCT_SET_HANDLE(mph, model, (struct myphdr *)phdrbase);
1269 
1270 	/* hsize alignment should have been checked before calling this func */
1271 	if (model == DATAMODEL_LP64) {
1272 		hsize = ehdrp->e_phentsize;
1273 		if (hsize & 7) {
1274 			return (ENOTSUP);
1275 		}
1276 	} else {
1277 		ASSERT(model == DATAMODEL_ILP32);
1278 		hsize = ((Elf32_Ehdr *)ehdrp)->e_phentsize;
1279 		if (hsize & 3) {
1280 			return (ENOTSUP);
1281 		}
1282 	}
1283 
1284 	/*
1285 	 * Determine the span of all loadable segments and calculate the
1286 	 * number of loadable segments.
1287 	 */
1288 	for (i = 0; i < nphdrs; i++) {
1289 		p_type = STRUCT_FGET(mph, x.p_type);
1290 		if (p_type == PT_LOAD || p_type == PT_SUNWBSS) {
1291 			vaddr = (caddr_t)(uintptr_t)STRUCT_FGET(mph, x.p_vaddr);
1292 			p_memsz = STRUCT_FGET(mph, x.p_memsz);
1293 
1294 			/*
1295 			 * Skip this header if it requests no memory to be
1296 			 * mapped.
1297 			 */
1298 			if (p_memsz == 0) {
1299 				STRUCT_SET_HANDLE(mph, model,
1300 				    (struct myphdr *)((size_t)STRUCT_BUF(mph) +
1301 				    hsize));
1302 				MOBJ_STAT_ADD(nomem_header);
1303 				continue;
1304 			}
1305 			if (num_segs++ == 0) {
1306 				start_addr = vaddr;
1307 				/*
1308 				 * For the first segment, we need to map from
1309 				 * the beginning of the file, so we will
1310 				 * adjust the size of the mapping to include
1311 				 * this memory.
1312 				 */
1313 				p_offset = STRUCT_FGET(mph, x.p_offset);
1314 			} else {
1315 				p_offset = 0;
1316 			}
1317 			/*
1318 			 * Check to make sure that this mapping wouldn't
1319 			 * overlap a previous mapping.
1320 			 */
1321 			if (vaddr < p_end) {
1322 				MOBJ_STAT_ADD(overlap_header);
1323 				return (ENOTSUP);
1324 			}
1325 
1326 			p_end = vaddr + p_memsz + p_offset;
1327 			p_end = (caddr_t)P2ROUNDUP((size_t)p_end, PAGESIZE);
1328 
1329 			p_align = STRUCT_FGET(mph, x.p_align);
1330 			if (p_align > 1 && p_align > max_align) {
1331 				max_align = p_align;
1332 #if defined(__sparc)
1333 				/*
1334 				 * Want to prevent aliasing by making the start
1335 				 * address be aligned to vac_size.
1336 				 */
1337 				if (max_align < vac_size) {
1338 					max_align = vac_size;
1339 					MOBJ_STAT_ADD(vac_align);
1340 				}
1341 #endif
1342 			}
1343 		}
1344 		STRUCT_SET_HANDLE(mph, model,
1345 		    (struct myphdr *)((size_t)STRUCT_BUF(mph) + hsize));
1346 	}
1347 
1348 	/*
1349 	 * The alignment should be a power of 2, if it isn't we forgive it
1350 	 * and round up.  On overflow, we'll set the alignment to max_align
1351 	 * rounded down to the nearest power of 2.
1352 	 */
1353 	if (max_align > 0 && !ISP2(max_align)) {
1354 		MOBJ_STAT_ADD(np2_align);
1355 		*align = 2 * (1L << (highbit(max_align) - 1));
1356 		if (*align < max_align ||
1357 		    (*align > UINT_MAX && model == DATAMODEL_ILP32)) {
1358 			MOBJ_STAT_ADD(np2_align_overflow);
1359 			*align = 1L << (highbit(max_align) - 1);
1360 		}
1361 	} else {
1362 		*align = max_align;
1363 	}
1364 
1365 	*loadable = num_segs;
1366 	*len = p_end - start_addr;
1367 	return (0);
1368 }
1369 
1370 /*
1371  * Check the address space to see if the virtual addresses to be used are
1372  * available.  If they are not, return errno for failure.  On success, 0
1373  * will be returned, and the virtual addresses for each mmapobj_result_t
1374  * will be reserved.  Note that a reservation could have earlier been made
1375  * for a given segment via a /dev/null mapping.  If that is the case, then
1376  * we can use that VA space for our mappings.
1377  * Note: this function will only be used for ET_EXEC binaries.
1378  */
1379 int
1380 check_exec_addrs(int loadable, mmapobj_result_t *mrp, caddr_t start_addr)
1381 {
1382 	int i;
1383 	struct as *as = curproc->p_as;
1384 	struct segvn_crargs crargs = SEGVN_ZFOD_ARGS(PROT_ZFOD, PROT_ALL);
1385 	int ret;
1386 	caddr_t myaddr;
1387 	size_t mylen;
1388 	struct seg *seg;
1389 
1390 	/* No need to reserve swap space now since it will be reserved later */
1391 	crargs.flags |= MAP_NORESERVE;
1392 	as_rangelock(as);
1393 	for (i = 0; i < loadable; i++) {
1394 
1395 		myaddr = start_addr + (size_t)mrp[i].mr_addr;
1396 		mylen = mrp[i].mr_msize;
1397 
1398 		/* See if there is a hole in the as for this range */
1399 		if (as_gap(as, mylen, &myaddr, &mylen, 0, NULL) == 0) {
1400 			ASSERT(myaddr == start_addr + (size_t)mrp[i].mr_addr);
1401 			ASSERT(mylen == mrp[i].mr_msize);
1402 
1403 #ifdef DEBUG
1404 			if (MR_GET_TYPE(mrp[i].mr_flags) == MR_PADDING) {
1405 				MOBJ_STAT_ADD(exec_padding);
1406 			}
1407 #endif
1408 			ret = as_map(as, myaddr, mylen, segvn_create, &crargs);
1409 			if (ret) {
1410 				as_rangeunlock(as);
1411 				mmapobj_unmap_exec(mrp, i, start_addr);
1412 				return (ret);
1413 			}
1414 		} else {
1415 			/*
1416 			 * There is a mapping that exists in the range
1417 			 * so check to see if it was a "reservation"
1418 			 * from /dev/null.  The mapping is from
1419 			 * /dev/null if the mapping comes from
1420 			 * segdev and the type is neither MAP_SHARED
1421 			 * nor MAP_PRIVATE.
1422 			 */
1423 			AS_LOCK_ENTER(as, &as->a_lock, RW_READER);
1424 			seg = as_findseg(as, myaddr, 0);
1425 			MOBJ_STAT_ADD(exec_addr_mapped);
1426 			if (seg && seg->s_ops == &segdev_ops &&
1427 			    ((SEGOP_GETTYPE(seg, myaddr) &
1428 			    (MAP_SHARED | MAP_PRIVATE)) == 0) &&
1429 			    myaddr >= seg->s_base &&
1430 			    myaddr + mylen <=
1431 			    seg->s_base + seg->s_size) {
1432 				MOBJ_STAT_ADD(exec_addr_devnull);
1433 				AS_LOCK_EXIT(as, &as->a_lock);
1434 				(void) as_unmap(as, myaddr, mylen);
1435 				ret = as_map(as, myaddr, mylen, segvn_create,
1436 				    &crargs);
1437 				mrp[i].mr_flags |= MR_RESV;
1438 				if (ret) {
1439 					as_rangeunlock(as);
1440 					/* Need to remap what we unmapped */
1441 					mmapobj_unmap_exec(mrp, i + 1,
1442 					    start_addr);
1443 					return (ret);
1444 				}
1445 			} else {
1446 				AS_LOCK_EXIT(as, &as->a_lock);
1447 				as_rangeunlock(as);
1448 				mmapobj_unmap_exec(mrp, i, start_addr);
1449 				MOBJ_STAT_ADD(exec_addr_in_use);
1450 				return (EADDRINUSE);
1451 			}
1452 		}
1453 	}
1454 	as_rangeunlock(as);
1455 	return (0);
1456 }
1457 
1458 /*
1459  * Walk through the ELF program headers and extract all useful information
1460  * for PT_LOAD and PT_SUNWBSS segments into mrp.
1461  * Return 0 on success or error on failure.
1462  */
1463 static int
1464 process_phdr(Ehdr *ehdrp, caddr_t phdrbase, int nphdrs, mmapobj_result_t *mrp,
1465     vnode_t *vp, uint_t *num_mapped, size_t padding, cred_t *fcred)
1466 {
1467 	int i;
1468 	caddr_t start_addr = NULL;
1469 	caddr_t vaddr;
1470 	size_t len = 0;
1471 	size_t lib_len = 0;
1472 	int ret;
1473 	int prot;
1474 	struct lib_va *lvp = NULL;
1475 	vattr_t vattr;
1476 	struct as *as = curproc->p_as;
1477 	int error;
1478 	int loadable = 0;
1479 	int current = 0;
1480 	int use_lib_va = 1;
1481 	size_t align = 0;
1482 	size_t add_pad = 0;
1483 	int hdr_seen = 0;
1484 	ushort_t e_type = ehdrp->e_type;	/* same offset 32 and 64 bit */
1485 	uint_t p_type;
1486 	offset_t p_offset;
1487 	size_t p_memsz;
1488 	size_t p_filesz;
1489 	uint_t p_flags;
1490 	int hsize;
1491 	model_t model;
1492 	STRUCT_HANDLE(myphdr, mph);
1493 
1494 	model = get_udatamodel();
1495 	STRUCT_SET_HANDLE(mph, model, (struct myphdr *)phdrbase);
1496 
1497 	/*
1498 	 * Need to make sure that hsize is aligned properly.
1499 	 * For 32bit processes, 4 byte alignment is required.
1500 	 * For 64bit processes, 8 byte alignment is required.
1501 	 * If the alignment isn't correct, we need to return failure
1502 	 * since it could cause an alignment error panic while walking
1503 	 * the phdr array.
1504 	 */
1505 	if (model == DATAMODEL_LP64) {
1506 		hsize = ehdrp->e_phentsize;
1507 		if (hsize & 7) {
1508 			MOBJ_STAT_ADD(phent_align64);
1509 			return (ENOTSUP);
1510 		}
1511 	} else {
1512 		ASSERT(model == DATAMODEL_ILP32);
1513 		hsize = ((Elf32_Ehdr *)ehdrp)->e_phentsize;
1514 		if (hsize & 3) {
1515 			MOBJ_STAT_ADD(phent_align32);
1516 			return (ENOTSUP);
1517 		}
1518 	}
1519 
1520 	if (padding != 0) {
1521 		use_lib_va = 0;
1522 	}
1523 	if (e_type == ET_DYN) {
1524 		vattr.va_mask = AT_FSID | AT_NODEID | AT_CTIME | AT_MTIME;
1525 		error = VOP_GETATTR(vp, &vattr, 0, fcred, NULL);
1526 		if (error) {
1527 			return (error);
1528 		}
1529 		/* Check to see if we already have a description for this lib */
1530 		lvp = lib_va_find(&vattr);
1531 
1532 		if (lvp != NULL) {
1533 			MOBJ_STAT_ADD(lvp_found);
1534 			if (use_lib_va) {
1535 				start_addr = mmapobj_lookup_start_addr(lvp);
1536 				if (start_addr == NULL) {
1537 					lib_va_release(lvp);
1538 					return (ENOMEM);
1539 				}
1540 			}
1541 
1542 			/*
1543 			 * loadable may be zero if the original allocator
1544 			 * of lvp hasn't finished setting it up but the rest
1545 			 * of the fields will be accurate.
1546 			 */
1547 			loadable = lvp->lv_num_segs;
1548 			len = lvp->lv_len;
1549 			align = lvp->lv_align;
1550 		}
1551 	}
1552 
1553 	/*
1554 	 * Determine the span of all loadable segments and calculate the
1555 	 * number of loadable segments, the total len spanned by the mappings
1556 	 * and the max alignment, if we didn't get them above.
1557 	 */
1558 	if (loadable == 0) {
1559 		MOBJ_STAT_ADD(no_loadable_yet);
1560 		ret = calc_loadable(ehdrp, phdrbase, nphdrs, &len,
1561 		    &loadable, &align);
1562 		if (ret != 0) {
1563 			/*
1564 			 * Since it'd be an invalid file, we shouldn't have
1565 			 * cached it previously.
1566 			 */
1567 			ASSERT(lvp == NULL);
1568 			return (ret);
1569 		}
1570 #ifdef DEBUG
1571 		if (lvp) {
1572 			ASSERT(len == lvp->lv_len);
1573 			ASSERT(align == lvp->lv_align);
1574 		}
1575 #endif
1576 	}
1577 
1578 	/* Make sure there's something to map. */
1579 	if (len == 0 || loadable == 0) {
1580 		/*
1581 		 * Since it'd be an invalid file, we shouldn't have
1582 		 * cached it previously.
1583 		 */
1584 		ASSERT(lvp == NULL);
1585 		MOBJ_STAT_ADD(nothing_to_map);
1586 		return (ENOTSUP);
1587 	}
1588 
1589 	lib_len = len;
1590 	if (padding != 0) {
1591 		loadable += 2;
1592 	}
1593 	if (loadable > *num_mapped) {
1594 		*num_mapped = loadable;
1595 		/* cleanup previous reservation */
1596 		if (start_addr) {
1597 			(void) as_unmap(as, start_addr, lib_len);
1598 		}
1599 		MOBJ_STAT_ADD(e2big);
1600 		if (lvp) {
1601 			lib_va_release(lvp);
1602 		}
1603 		return (E2BIG);
1604 	}
1605 
1606 	/*
1607 	 * We now know the size of the object to map and now we need to
1608 	 * get the start address to map it at.  It's possible we already
1609 	 * have it if we found all the info we need in the lib_va cache.
1610 	 */
1611 	if (e_type == ET_DYN && start_addr == NULL) {
1612 		/*
1613 		 * Need to make sure padding does not throw off
1614 		 * required alignment.  We can only specify an
1615 		 * alignment for the starting address to be mapped,
1616 		 * so we round padding up to the alignment and map
1617 		 * from there and then throw out the extra later.
1618 		 */
1619 		if (padding != 0) {
1620 			if (align > 1) {
1621 				add_pad = P2ROUNDUP(padding, align);
1622 				len += add_pad;
1623 				MOBJ_STAT_ADD(dyn_pad_align);
1624 			} else {
1625 				MOBJ_STAT_ADD(dyn_pad_noalign);
1626 				len += padding;	/* at beginning */
1627 			}
1628 			len += padding;	/* at end of mapping */
1629 		}
1630 		/*
1631 		 * At this point, if lvp is non-NULL, then above we
1632 		 * already found it in the cache but did not get
1633 		 * the start address since we were not going to use lib_va.
1634 		 * Since we know that lib_va will not be used, it's safe
1635 		 * to call mmapobj_alloc_start_addr and know that lvp
1636 		 * will not be modified.
1637 		 */
1638 		ASSERT(lvp ? use_lib_va == 0 : 1);
1639 		start_addr = mmapobj_alloc_start_addr(&lvp, len,
1640 		    use_lib_va, align, &vattr);
1641 		if (start_addr == NULL) {
1642 			if (lvp) {
1643 				lib_va_release(lvp);
1644 			}
1645 			MOBJ_STAT_ADD(alloc_start_fail);
1646 			return (ENOMEM);
1647 		}
1648 		/*
1649 		 * If we can't cache it, no need to hang on to it.
1650 		 * Setting lv_num_segs to non-zero will make that
1651 		 * field active and since there are too many segments
1652 		 * to cache, all future users will not try to use lv_mps.
1653 		 */
1654 		if (lvp != NULL && loadable > LIBVA_CACHED_SEGS && use_lib_va) {
1655 			lvp->lv_num_segs = loadable;
1656 			lib_va_release(lvp);
1657 			lvp = NULL;
1658 			MOBJ_STAT_ADD(lvp_nocache);
1659 		}
1660 		/*
1661 		 * Free the beginning of the mapping if the padding
1662 		 * was not aligned correctly.
1663 		 */
1664 		if (padding != 0 && add_pad != padding) {
1665 			(void) as_unmap(as, start_addr,
1666 			    add_pad - padding);
1667 			start_addr += (add_pad - padding);
1668 			MOBJ_STAT_ADD(extra_padding);
1669 		}
1670 	}
1671 
1672 	/*
1673 	 * At this point, we have reserved the virtual address space
1674 	 * for our mappings.  Now we need to start filling out the mrp
1675 	 * array to describe all of the individual mappings we are going
1676 	 * to return.
1677 	 * For ET_EXEC there has been no memory reservation since we are
1678 	 * using fixed addresses.  While filling in the mrp array below,
1679 	 * we will have the first segment biased to start at addr 0
1680 	 * and the rest will be biased by this same amount.  Thus if there
1681 	 * is padding, the first padding will start at addr 0, and the next
1682 	 * segment will start at the value of padding.
1683 	 */
1684 
1685 	/* We'll fill out padding later, so start filling in mrp at index 1 */
1686 	if (padding != 0) {
1687 		current = 1;
1688 	}
1689 
1690 	/* If we have no more need for lvp let it go now */
1691 	if (lvp != NULL && use_lib_va == 0) {
1692 		lib_va_release(lvp);
1693 		MOBJ_STAT_ADD(lvp_not_needed);
1694 		lvp = NULL;
1695 	}
1696 
1697 	/* Now fill out the mrp structs from the program headers */
1698 	STRUCT_SET_HANDLE(mph, model, (struct myphdr *)phdrbase);
1699 	for (i = 0; i < nphdrs; i++) {
1700 		p_type = STRUCT_FGET(mph, x.p_type);
1701 		if (p_type == PT_LOAD || p_type == PT_SUNWBSS) {
1702 			vaddr = (caddr_t)(uintptr_t)STRUCT_FGET(mph, x.p_vaddr);
1703 			p_memsz = STRUCT_FGET(mph, x.p_memsz);
1704 			p_filesz = STRUCT_FGET(mph, x.p_filesz);
1705 			p_offset = STRUCT_FGET(mph, x.p_offset);
1706 			p_flags = STRUCT_FGET(mph, x.p_flags);
1707 
1708 			/*
1709 			 * Skip this header if it requests no memory to be
1710 			 * mapped.
1711 			 */
1712 			if (p_memsz == 0) {
1713 				STRUCT_SET_HANDLE(mph, model,
1714 				    (struct myphdr *)((size_t)STRUCT_BUF(mph) +
1715 				    hsize));
1716 				MOBJ_STAT_ADD(no_mem_map_sz);
1717 				continue;
1718 			}
1719 
1720 			prot = 0;
1721 			if (p_flags & PF_R)
1722 				prot |= PROT_READ;
1723 			if (p_flags & PF_W)
1724 				prot |= PROT_WRITE;
1725 			if (p_flags & PF_X)
1726 				prot |= PROT_EXEC;
1727 
1728 			ASSERT(current < loadable);
1729 			mrp[current].mr_msize = p_memsz;
1730 			mrp[current].mr_fsize = p_filesz;
1731 			mrp[current].mr_offset = p_offset;
1732 			mrp[current].mr_prot = prot;
1733 
1734 			if (hdr_seen == 0 && p_filesz != 0) {
1735 				mrp[current].mr_flags = MR_HDR_ELF;
1736 				/*
1737 				 * We modify mr_addr and mr_offset because we
1738 				 * need to map the ELF header as well, and if
1739 				 * we didn't then the header could be left out
1740 				 * of the mapping that we will create later.
1741 				 * Since we're removing the offset, we need to
1742 				 * account for that in the other fields as well
1743 				 * since we will be mapping the memory from 0
1744 				 * to p_offset.
1745 				 */
1746 				if (e_type == ET_DYN) {
1747 					mrp[current].mr_offset = 0;
1748 					mrp[current].mr_msize += p_offset;
1749 					mrp[current].mr_fsize += p_offset;
1750 				} else {
1751 					ASSERT(e_type == ET_EXEC);
1752 					/*
1753 					 * Save off the start addr which will be
1754 					 * our bias for the rest of the
1755 					 * ET_EXEC mappings.
1756 					 */
1757 					start_addr = vaddr - padding;
1758 				}
1759 				mrp[current].mr_addr = (caddr_t)padding;
1760 				hdr_seen = 1;
1761 			} else {
1762 				if (e_type == ET_EXEC) {
1763 					/* bias mr_addr */
1764 					mrp[current].mr_addr =
1765 					    vaddr - (size_t)start_addr;
1766 				} else {
1767 					mrp[current].mr_addr = vaddr + padding;
1768 				}
1769 				mrp[current].mr_flags = 0;
1770 			}
1771 			current++;
1772 		}
1773 
1774 		/* Move to next phdr */
1775 		STRUCT_SET_HANDLE(mph, model,
1776 		    (struct myphdr *)((size_t)STRUCT_BUF(mph) +
1777 		    hsize));
1778 	}
1779 
1780 	/* Now fill out the padding segments */
1781 	if (padding != 0) {
1782 		mrp[0].mr_addr = NULL;
1783 		mrp[0].mr_msize = padding;
1784 		mrp[0].mr_fsize = 0;
1785 		mrp[0].mr_offset = 0;
1786 		mrp[0].mr_prot = 0;
1787 		mrp[0].mr_flags = MR_PADDING;
1788 
1789 		/* Setup padding for the last segment */
1790 		ASSERT(current == loadable - 1);
1791 		mrp[current].mr_addr = (caddr_t)lib_len + padding;
1792 		mrp[current].mr_msize = padding;
1793 		mrp[current].mr_fsize = 0;
1794 		mrp[current].mr_offset = 0;
1795 		mrp[current].mr_prot = 0;
1796 		mrp[current].mr_flags = MR_PADDING;
1797 	}
1798 
1799 	/*
1800 	 * Need to make sure address ranges desired are not in use or
1801 	 * are previously allocated reservations from /dev/null.  For
1802 	 * ET_DYN, we already made sure our address range was free.
1803 	 */
1804 	if (e_type == ET_EXEC) {
1805 		ret = check_exec_addrs(loadable, mrp, start_addr);
1806 		if (ret != 0) {
1807 			ASSERT(lvp == NULL);
1808 			MOBJ_STAT_ADD(check_exec_failed);
1809 			return (ret);
1810 		}
1811 	}
1812 
1813 	/* Finish up our business with lvp. */
1814 	if (lvp) {
1815 		ASSERT(e_type == ET_DYN);
1816 		if (lvp->lv_num_segs == 0 && loadable <= LIBVA_CACHED_SEGS) {
1817 			bcopy(mrp, lvp->lv_mps,
1818 			    loadable * sizeof (mmapobj_result_t));
1819 			membar_producer();
1820 		}
1821 		/*
1822 		 * Setting lv_num_segs to a non-zero value indicates that
1823 		 * lv_mps is now valid and can be used by other threads.
1824 		 * So, the above stores need to finish before lv_num_segs
1825 		 * is updated. lv_mps is only valid if lv_num_segs is
1826 		 * greater than LIBVA_CACHED_SEGS.
1827 		 */
1828 		lvp->lv_num_segs = loadable;
1829 		lib_va_release(lvp);
1830 		MOBJ_STAT_ADD(lvp_used);
1831 	}
1832 
1833 	/* Now that we have mrp completely filled out go map it */
1834 	ret = mmapobj_map_elf(vp, start_addr, mrp, loadable, fcred, e_type);
1835 	if (ret == 0) {
1836 		*num_mapped = loadable;
1837 	}
1838 
1839 	return (ret);
1840 }
1841 
1842 /*
1843  * Take the ELF file passed in, and do the work of mapping it.
1844  * num_mapped in - # elements in user buffer
1845  * num_mapped out - # sections mapped and length of mrp array if
1846  *			no errors.
1847  */
1848 static int
1849 doelfwork(Ehdr *ehdrp, vnode_t *vp, mmapobj_result_t *mrp,
1850     uint_t *num_mapped, size_t padding, cred_t *fcred)
1851 {
1852 	int error;
1853 	offset_t phoff;
1854 	int nphdrs;
1855 	unsigned char ei_class;
1856 	unsigned short phentsize;
1857 	ssize_t phsizep;
1858 	caddr_t phbasep;
1859 	int to_map;
1860 	model_t model;
1861 
1862 	ei_class = ehdrp->e_ident[EI_CLASS];
1863 	model = get_udatamodel();
1864 	if ((model == DATAMODEL_ILP32 && ei_class == ELFCLASS64) ||
1865 	    (model == DATAMODEL_LP64 && ei_class == ELFCLASS32)) {
1866 		MOBJ_STAT_ADD(wrong_model);
1867 		return (ENOTSUP);
1868 	}
1869 
1870 	/* Can't execute code from "noexec" mounted filesystem. */
1871 	if (ehdrp->e_type == ET_EXEC &&
1872 	    (vp->v_vfsp->vfs_flag & VFS_NOEXEC) != 0) {
1873 		MOBJ_STAT_ADD(noexec_fs);
1874 		return (EACCES);
1875 	}
1876 
1877 	/*
1878 	 * Relocatable and core files are mapped as a single flat file
1879 	 * since no interpretation is done on them by mmapobj.
1880 	 */
1881 	if (ehdrp->e_type == ET_REL || ehdrp->e_type == ET_CORE) {
1882 		to_map = padding ? 3 : 1;
1883 		if (*num_mapped < to_map) {
1884 			*num_mapped = to_map;
1885 			MOBJ_STAT_ADD(e2big_et_rel);
1886 			return (E2BIG);
1887 		}
1888 		error = mmapobj_map_flat(vp, mrp, padding, fcred);
1889 		if (error == 0) {
1890 			*num_mapped = to_map;
1891 			mrp[padding ? 1 : 0].mr_flags = MR_HDR_ELF;
1892 			MOBJ_STAT_ADD(et_rel_mapped);
1893 		}
1894 		return (error);
1895 	}
1896 
1897 	/* Check for an unknown ELF type */
1898 	if (ehdrp->e_type != ET_EXEC && ehdrp->e_type != ET_DYN) {
1899 		MOBJ_STAT_ADD(unknown_elf_type);
1900 		return (ENOTSUP);
1901 	}
1902 
1903 	if (ei_class == ELFCLASS32) {
1904 		Elf32_Ehdr *e32hdr = (Elf32_Ehdr *)ehdrp;
1905 		ASSERT(model == DATAMODEL_ILP32);
1906 		nphdrs = e32hdr->e_phnum;
1907 		phentsize = e32hdr->e_phentsize;
1908 		if (phentsize < sizeof (Elf32_Phdr)) {
1909 			MOBJ_STAT_ADD(phent32_too_small);
1910 			return (ENOTSUP);
1911 		}
1912 		phoff = e32hdr->e_phoff;
1913 	} else if (ei_class == ELFCLASS64) {
1914 		Elf64_Ehdr *e64hdr = (Elf64_Ehdr *)ehdrp;
1915 		ASSERT(model == DATAMODEL_LP64);
1916 		nphdrs = e64hdr->e_phnum;
1917 		phentsize = e64hdr->e_phentsize;
1918 		if (phentsize < sizeof (Elf64_Phdr)) {
1919 			MOBJ_STAT_ADD(phent64_too_small);
1920 			return (ENOTSUP);
1921 		}
1922 		phoff = e64hdr->e_phoff;
1923 	} else {
1924 		/* fallthrough case for an invalid ELF class */
1925 		MOBJ_STAT_ADD(inval_elf_class);
1926 		return (ENOTSUP);
1927 	}
1928 
1929 	/*
1930 	 * nphdrs should only have this value for core files which are handled
1931 	 * above as a single mapping.  If other file types ever use this
1932 	 * sentinel, then we'll add the support needed to handle this here.
1933 	 */
1934 	if (nphdrs == PN_XNUM) {
1935 		MOBJ_STAT_ADD(too_many_phdrs);
1936 		return (ENOTSUP);
1937 	}
1938 
1939 	phsizep = nphdrs * phentsize;
1940 
1941 	if (phsizep == 0) {
1942 		MOBJ_STAT_ADD(no_phsize);
1943 		return (ENOTSUP);
1944 	}
1945 
1946 	/* Make sure we only wait for memory if it's a reasonable request */
1947 	if (phsizep > mmapobj_alloc_threshold) {
1948 		MOBJ_STAT_ADD(phsize_large);
1949 		if ((phbasep = kmem_alloc(phsizep, KM_NOSLEEP)) == NULL) {
1950 			MOBJ_STAT_ADD(phsize_xtralarge);
1951 			return (ENOMEM);
1952 		}
1953 	} else {
1954 		phbasep = kmem_alloc(phsizep, KM_SLEEP);
1955 	}
1956 
1957 	if ((error = vn_rdwr(UIO_READ, vp, phbasep, phsizep,
1958 	    (offset_t)phoff, UIO_SYSSPACE, 0, (rlim64_t)0,
1959 	    fcred, NULL)) != 0) {
1960 		kmem_free(phbasep, phsizep);
1961 		return (error);
1962 	}
1963 
1964 	/* Now process the phdr's */
1965 	error = process_phdr(ehdrp, phbasep, nphdrs, mrp, vp, num_mapped,
1966 	    padding, fcred);
1967 	kmem_free(phbasep, phsizep);
1968 	return (error);
1969 }
1970 
1971 #if defined(__sparc)
1972 /*
1973  * Hack to support 64 bit kernels running AOUT 4.x programs.
1974  * This is the sizeof (struct nlist) for a 32 bit kernel.
1975  * Since AOUT programs are 32 bit only, they will never use the 64 bit
1976  * sizeof (struct nlist) and thus creating a #define is the simplest
1977  * way around this since this is a format which is not being updated.
1978  * This will be used in the place of sizeof (struct nlist) below.
1979  */
1980 #define	NLIST_SIZE	(0xC)
1981 
1982 static int
1983 doaoutwork(vnode_t *vp, mmapobj_result_t *mrp,
1984     uint_t *num_mapped, struct exec *hdr, cred_t *fcred)
1985 {
1986 	int error;
1987 	size_t size;
1988 	size_t osize;
1989 	size_t nsize;	/* nlist size */
1990 	size_t msize;
1991 	size_t zfoddiff;
1992 	caddr_t addr;
1993 	caddr_t start_addr;
1994 	struct as *as = curproc->p_as;
1995 	int prot = PROT_USER | PROT_READ | PROT_EXEC;
1996 	uint_t mflag = MAP_PRIVATE | _MAP_LOW32;
1997 	offset_t off = 0;
1998 	int segnum = 0;
1999 	uint_t to_map;
2000 	int is_library = 0;
2001 	struct segvn_crargs crargs = SEGVN_ZFOD_ARGS(PROT_ZFOD, PROT_ALL);
2002 
2003 	/* Only 32bit apps supported by this file format */
2004 	if (get_udatamodel() != DATAMODEL_ILP32) {
2005 		MOBJ_STAT_ADD(aout_64bit_try);
2006 		return (ENOTSUP);
2007 	}
2008 
2009 	/* Check to see if this is a library */
2010 	if (hdr->a_magic == ZMAGIC && hdr->a_entry < PAGESIZE) {
2011 		is_library = 1;
2012 	}
2013 
2014 	/* Can't execute code from "noexec" mounted filesystem. */
2015 	if (((vp->v_vfsp->vfs_flag & VFS_NOEXEC) != 0) && (is_library == 0)) {
2016 		MOBJ_STAT_ADD(aout_noexec);
2017 		return (EACCES);
2018 	}
2019 
2020 	/*
2021 	 * There are 2 ways to calculate the mapped size of executable:
2022 	 * 1) rounded text size + data size + bss size.
2023 	 * 2) starting offset for text + text size + data size + text relocation
2024 	 *    size + data relocation size + room for nlist data structure.
2025 	 *
2026 	 * The larger of the two sizes will be used to map this binary.
2027 	 */
2028 	osize = P2ROUNDUP(hdr->a_text, PAGESIZE) + hdr->a_data + hdr->a_bss;
2029 
2030 	off = hdr->a_magic == ZMAGIC ? 0 : sizeof (struct exec);
2031 
2032 	nsize = off + hdr->a_text + hdr->a_data + hdr->a_trsize +
2033 	    hdr->a_drsize + NLIST_SIZE;
2034 
2035 	size = MAX(osize, nsize);
2036 	if (size != nsize) {
2037 		nsize = 0;
2038 	}
2039 
2040 	/*
2041 	 * 1 seg for text and 1 seg for initialized data.
2042 	 * 1 seg for bss (if can't fit in leftover space of init data)
2043 	 * 1 seg for nlist if needed.
2044 	 */
2045 	to_map = 2 + (nsize ? 1 : 0) +
2046 	    (hdr->a_bss > PAGESIZE - P2PHASE(hdr->a_data, PAGESIZE) ? 1 : 0);
2047 	if (*num_mapped < to_map) {
2048 		*num_mapped = to_map;
2049 		MOBJ_STAT_ADD(aout_e2big);
2050 		return (E2BIG);
2051 	}
2052 
2053 	/* Reserve address space for the whole mapping */
2054 	if (is_library) {
2055 		/* We'll let VOP_MAP below pick our address for us */
2056 		addr = NULL;
2057 		MOBJ_STAT_ADD(aout_lib);
2058 	} else {
2059 		/*
2060 		 * default start address for fixed binaries from AOUT 4.x
2061 		 * standard.
2062 		 */
2063 		MOBJ_STAT_ADD(aout_fixed);
2064 		mflag |= MAP_FIXED;
2065 		addr = (caddr_t)0x2000;
2066 		as_rangelock(as);
2067 		if (as_gap(as, size, &addr, &size, 0, NULL) != 0) {
2068 			as_rangeunlock(as);
2069 			MOBJ_STAT_ADD(aout_addr_in_use);
2070 			return (EADDRINUSE);
2071 		}
2072 		crargs.flags |= MAP_NORESERVE;
2073 		error = as_map(as, addr, size, segvn_create, &crargs);
2074 		ASSERT(addr == (caddr_t)0x2000);
2075 		as_rangeunlock(as);
2076 	}
2077 
2078 	start_addr = addr;
2079 	osize = size;
2080 
2081 	/*
2082 	 * Map as large as we need, backed by file, this will be text, and
2083 	 * possibly the nlist segment.  We map over this mapping for bss and
2084 	 * initialized data segments.
2085 	 */
2086 	error = VOP_MAP(vp, off, as, &addr, size, prot, PROT_ALL,
2087 	    mflag, fcred, NULL);
2088 	if (error) {
2089 		if (!is_library) {
2090 			(void) as_unmap(as, start_addr, osize);
2091 		}
2092 		return (error);
2093 	}
2094 
2095 	/* pickup the value of start_addr and osize for libraries */
2096 	start_addr = addr;
2097 	osize = size;
2098 
2099 	/*
2100 	 * We have our initial reservation/allocation so we need to use fixed
2101 	 * addresses from now on.
2102 	 */
2103 	mflag |= MAP_FIXED;
2104 
2105 	mrp[0].mr_addr = addr;
2106 	mrp[0].mr_msize = hdr->a_text;
2107 	mrp[0].mr_fsize = hdr->a_text;
2108 	mrp[0].mr_offset = 0;
2109 	mrp[0].mr_prot = PROT_READ | PROT_EXEC;
2110 	mrp[0].mr_flags = MR_HDR_AOUT;
2111 
2112 
2113 	/*
2114 	 * Map initialized data. We are mapping over a portion of the
2115 	 * previous mapping which will be unmapped in VOP_MAP below.
2116 	 */
2117 	off = P2ROUNDUP((offset_t)(hdr->a_text), PAGESIZE);
2118 	msize = off;
2119 	addr += off;
2120 	size = hdr->a_data;
2121 	error = VOP_MAP(vp, off, as, &addr, size, PROT_ALL, PROT_ALL,
2122 	    mflag, fcred, NULL);
2123 	if (error) {
2124 		(void) as_unmap(as, start_addr, osize);
2125 		return (error);
2126 	}
2127 	msize += size;
2128 	mrp[1].mr_addr = addr;
2129 	mrp[1].mr_msize = size;
2130 	mrp[1].mr_fsize = size;
2131 	mrp[1].mr_offset = 0;
2132 	mrp[1].mr_prot = PROT_READ | PROT_WRITE | PROT_EXEC;
2133 	mrp[1].mr_flags = 0;
2134 
2135 	/* Need to zero out remainder of page */
2136 	addr += hdr->a_data;
2137 	zfoddiff = P2PHASE((size_t)addr, PAGESIZE);
2138 	if (zfoddiff) {
2139 		label_t ljb;
2140 
2141 		MOBJ_STAT_ADD(aout_zfoddiff);
2142 		zfoddiff = PAGESIZE - zfoddiff;
2143 		if (on_fault(&ljb)) {
2144 			no_fault();
2145 			MOBJ_STAT_ADD(aout_uzero_fault);
2146 			(void) as_unmap(as, start_addr, osize);
2147 			return (EFAULT);
2148 		}
2149 		uzero(addr, zfoddiff);
2150 		no_fault();
2151 	}
2152 	msize += zfoddiff;
2153 	segnum = 2;
2154 
2155 	/* Map bss */
2156 	if (hdr->a_bss > zfoddiff) {
2157 		struct segvn_crargs crargs =
2158 		    SEGVN_ZFOD_ARGS(PROT_ZFOD, PROT_ALL);
2159 		MOBJ_STAT_ADD(aout_map_bss);
2160 		addr += zfoddiff;
2161 		size = hdr->a_bss - zfoddiff;
2162 		as_rangelock(as);
2163 		(void) as_unmap(as, addr, size);
2164 		error = as_map(as, addr, size, segvn_create, &crargs);
2165 		as_rangeunlock(as);
2166 		msize += size;
2167 
2168 		if (error) {
2169 			MOBJ_STAT_ADD(aout_bss_fail);
2170 			(void) as_unmap(as, start_addr, osize);
2171 			return (error);
2172 		}
2173 		mrp[2].mr_addr = addr;
2174 		mrp[2].mr_msize = size;
2175 		mrp[2].mr_fsize = 0;
2176 		mrp[2].mr_offset = 0;
2177 		mrp[2].mr_prot = PROT_READ | PROT_WRITE | PROT_EXEC;
2178 		mrp[2].mr_flags = 0;
2179 
2180 		addr += size;
2181 		segnum = 3;
2182 	}
2183 
2184 	/*
2185 	 * If we have extra bits left over, we need to include that in how
2186 	 * much we mapped to make sure the nlist logic is correct
2187 	 */
2188 	msize = P2ROUNDUP(msize, PAGESIZE);
2189 
2190 	if (nsize && msize < nsize) {
2191 		MOBJ_STAT_ADD(aout_nlist);
2192 		mrp[segnum].mr_addr = addr;
2193 		mrp[segnum].mr_msize = nsize - msize;
2194 		mrp[segnum].mr_fsize = 0;
2195 		mrp[segnum].mr_offset = 0;
2196 		mrp[segnum].mr_prot = PROT_READ | PROT_EXEC;
2197 		mrp[segnum].mr_flags = 0;
2198 	}
2199 
2200 	*num_mapped = to_map;
2201 	return (0);
2202 }
2203 #endif
2204 
2205 /*
2206  * These are the two types of files that we can interpret and we want to read
2207  * in enough info to cover both types when looking at the initial header.
2208  */
2209 #define	MAX_HEADER_SIZE	(MAX(sizeof (Ehdr), sizeof (struct exec)))
2210 
2211 /*
2212  * Map vp passed in in an interpreted manner.  ELF and AOUT files will be
2213  * interpreted and mapped appropriately for execution.
2214  * num_mapped in - # elements in mrp
2215  * num_mapped out - # sections mapped and length of mrp array if
2216  *		    no errors or E2BIG returned.
2217  *
2218  * Returns 0 on success, errno value on failure.
2219  */
2220 static int
2221 mmapobj_map_interpret(vnode_t *vp, mmapobj_result_t *mrp,
2222     uint_t *num_mapped, size_t padding, cred_t *fcred)
2223 {
2224 	int error = 0;
2225 	vattr_t vattr;
2226 	struct lib_va *lvp;
2227 	caddr_t start_addr;
2228 	model_t model;
2229 
2230 	/*
2231 	 * header has to be aligned to the native size of ulong_t in order
2232 	 * to avoid an unaligned access when dereferencing the header as
2233 	 * a ulong_t.  Thus we allocate our array on the stack of type
2234 	 * ulong_t and then have header, which we dereference later as a char
2235 	 * array point at lheader.
2236 	 */
2237 	ulong_t lheader[(MAX_HEADER_SIZE / (sizeof (ulong_t))) + 1];
2238 	caddr_t header = (caddr_t)&lheader;
2239 
2240 	vattr.va_mask = AT_FSID | AT_NODEID | AT_CTIME | AT_MTIME | AT_SIZE;
2241 	error = VOP_GETATTR(vp, &vattr, 0, fcred, NULL);
2242 	if (error) {
2243 		return (error);
2244 	}
2245 
2246 	/*
2247 	 * Check lib_va to see if we already have a full description
2248 	 * for this library.  This is the fast path and only used for
2249 	 * ET_DYN ELF files (dynamic libraries).
2250 	 */
2251 	if (padding == 0 && (lvp = lib_va_find(&vattr)) != NULL) {
2252 		int num_segs;
2253 
2254 		model = get_udatamodel();
2255 		if ((model == DATAMODEL_ILP32 &&
2256 		    lvp->lv_flags & LV_ELF64) ||
2257 		    (model == DATAMODEL_LP64 &&
2258 		    lvp->lv_flags & LV_ELF32)) {
2259 			lib_va_release(lvp);
2260 			MOBJ_STAT_ADD(fast_wrong_model);
2261 			return (ENOTSUP);
2262 		}
2263 		num_segs = lvp->lv_num_segs;
2264 		if (*num_mapped < num_segs) {
2265 			*num_mapped = num_segs;
2266 			lib_va_release(lvp);
2267 			MOBJ_STAT_ADD(fast_e2big);
2268 			return (E2BIG);
2269 		}
2270 
2271 		/*
2272 		 * Check to see if we have all the mappable program headers
2273 		 * cached.
2274 		 */
2275 		if (num_segs <= LIBVA_CACHED_SEGS && num_segs != 0) {
2276 			MOBJ_STAT_ADD(fast);
2277 			start_addr = mmapobj_lookup_start_addr(lvp);
2278 			if (start_addr == NULL) {
2279 				lib_va_release(lvp);
2280 				return (ENOMEM);
2281 			}
2282 
2283 			bcopy(lvp->lv_mps, mrp,
2284 			    num_segs * sizeof (mmapobj_result_t));
2285 
2286 			error = mmapobj_map_elf(vp, start_addr, mrp,
2287 			    num_segs, fcred, ET_DYN);
2288 
2289 			lib_va_release(lvp);
2290 			if (error == 0) {
2291 				*num_mapped = num_segs;
2292 				MOBJ_STAT_ADD(fast_success);
2293 			}
2294 			return (error);
2295 		}
2296 		MOBJ_STAT_ADD(fast_not_now);
2297 
2298 		/* Release it for now since we'll look it up below */
2299 		lib_va_release(lvp);
2300 	}
2301 
2302 	/*
2303 	 * Time to see if this is a file we can interpret.  If it's smaller
2304 	 * than this, then we can't interpret it.
2305 	 */
2306 	if (vattr.va_size < MAX_HEADER_SIZE) {
2307 		MOBJ_STAT_ADD(small_file);
2308 		return (ENOTSUP);
2309 	}
2310 
2311 	if ((error = vn_rdwr(UIO_READ, vp, header, MAX_HEADER_SIZE, 0,
2312 	    UIO_SYSSPACE, 0, (rlim64_t)0, fcred, NULL)) != 0) {
2313 		MOBJ_STAT_ADD(read_error);
2314 		return (error);
2315 	}
2316 
2317 	/* Verify file type */
2318 	if (header[EI_MAG0] == ELFMAG0 && header[EI_MAG1] == ELFMAG1 &&
2319 	    header[EI_MAG2] == ELFMAG2 && header[EI_MAG3] == ELFMAG3) {
2320 		return (doelfwork((Ehdr *)lheader, vp, mrp, num_mapped,
2321 		    padding, fcred));
2322 	}
2323 
2324 #if defined(__sparc)
2325 	/* On sparc, check for 4.X AOUT format */
2326 	switch (((struct exec *)header)->a_magic) {
2327 	case OMAGIC:
2328 	case ZMAGIC:
2329 	case NMAGIC:
2330 		return (doaoutwork(vp, mrp, num_mapped,
2331 		    (struct exec *)lheader, fcred));
2332 	}
2333 #endif
2334 
2335 	/* Unsupported type */
2336 	MOBJ_STAT_ADD(unsupported);
2337 	return (ENOTSUP);
2338 }
2339 
2340 /*
2341  * Given a vnode, map it as either a flat file or interpret it and map
2342  * it according to the rules of the file type.
2343  * *num_mapped will contain the size of the mmapobj_result_t array passed in.
2344  * If padding is non-zero, the mappings will be padded by that amount
2345  * rounded up to the nearest pagesize.
2346  * If the mapping is successful, *num_mapped will contain the number of
2347  * distinct mappings created, and mrp will point to the array of
2348  * mmapobj_result_t's which describe these mappings.
2349  *
2350  * On error, -1 is returned and errno is set appropriately.
2351  * A special error case will set errno to E2BIG when there are more than
2352  * *num_mapped mappings to be created and *num_mapped will be set to the
2353  * number of mappings needed.
2354  */
2355 int
2356 mmapobj(vnode_t *vp, uint_t flags, mmapobj_result_t *mrp,
2357     uint_t *num_mapped, size_t padding, cred_t *fcred)
2358 {
2359 	int to_map;
2360 	int error = 0;
2361 
2362 	ASSERT((padding & PAGEOFFSET) == 0);
2363 	ASSERT((flags & ~MMOBJ_ALL_FLAGS) == 0);
2364 	ASSERT(num_mapped != NULL);
2365 	ASSERT((flags & MMOBJ_PADDING) ? padding != 0 : padding == 0);
2366 
2367 	if ((flags & MMOBJ_INTERPRET) == 0) {
2368 		to_map = padding ? 3 : 1;
2369 		if (*num_mapped < to_map) {
2370 			*num_mapped = to_map;
2371 			MOBJ_STAT_ADD(flat_e2big);
2372 			return (E2BIG);
2373 		}
2374 		error = mmapobj_map_flat(vp, mrp, padding, fcred);
2375 
2376 		if (error) {
2377 			return (error);
2378 		}
2379 		*num_mapped = to_map;
2380 		return (0);
2381 	}
2382 
2383 	error = mmapobj_map_interpret(vp, mrp, num_mapped, padding, fcred);
2384 	return (error);
2385 }
2386