xref: /netbsd-src/sys/uvm/uvm_amap.c (revision 5e4c038a45edbc7d63b7c2daa76e29f88b64a4e3)
1 /*	$NetBSD: uvm_amap.c,v 1.43 2002/03/28 06:06:29 nathanw Exp $	*/
2 
3 /*
4  *
5  * Copyright (c) 1997 Charles D. Cranor and Washington University.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *      This product includes software developed by Charles D. Cranor and
19  *      Washington University.
20  * 4. The name of the author may not be used to endorse or promote products
21  *    derived from this software without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
24  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
26  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
27  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
28  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
32  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33  */
34 
35 /*
36  * uvm_amap.c: amap operations
37  */
38 
39 /*
40  * this file contains functions that perform operations on amaps.  see
41  * uvm_amap.h for a brief explanation of the role of amaps in uvm.
42  */
43 
44 #include <sys/cdefs.h>
45 __KERNEL_RCSID(0, "$NetBSD: uvm_amap.c,v 1.43 2002/03/28 06:06:29 nathanw Exp $");
46 
47 #undef UVM_AMAP_INLINE		/* enable/disable amap inlines */
48 
49 #include "opt_uvmhist.h"
50 
51 #include <sys/param.h>
52 #include <sys/systm.h>
53 #include <sys/proc.h>
54 #include <sys/malloc.h>
55 #include <sys/kernel.h>
56 #include <sys/pool.h>
57 
58 #define UVM_AMAP_C		/* ensure disabled inlines are in */
59 #include <uvm/uvm.h>
60 #include <uvm/uvm_swap.h>
61 
62 /*
63  * pool for allocation of vm_map structures.  note that the pool has
64  * its own simplelock for its protection.  also note that in order to
65  * avoid an endless loop, the amap pool's allocator cannot allocate
66  * memory from an amap (it currently goes through the kernel uobj, so
67  * we are ok).
68  */
69 
70 struct pool uvm_amap_pool;
71 
72 /*
73  * local functions
74  */
75 
76 static struct vm_amap *amap_alloc1 __P((int, int, int));
77 
78 #ifdef UVM_AMAP_PPREF
79 /*
80  * what is ppref?   ppref is an _optional_ amap feature which is used
81  * to keep track of reference counts on a per-page basis.  it is enabled
82  * when UVM_AMAP_PPREF is defined.
83  *
84  * when enabled, an array of ints is allocated for the pprefs.  this
85  * array is allocated only when a partial reference is added to the
86  * map (either by unmapping part of the amap, or gaining a reference
87  * to only a part of an amap).  if the malloc of the array fails
88  * (M_NOWAIT), then we set the array pointer to PPREF_NONE to indicate
89  * that we tried to do ppref's but couldn't alloc the array so just
90  * give up (after all, this is an optional feature!).
91  *
92  * the array is divided into page sized "chunks."   for chunks of length 1,
93  * the chunk reference count plus one is stored in that chunk's slot.
94  * for chunks of length > 1 the first slot contains (the reference count
95  * plus one) * -1.    [the negative value indicates that the length is
96  * greater than one.]   the second slot of the chunk contains the length
97  * of the chunk.   here is an example:
98  *
99  * actual REFS:  2  2  2  2  3  1  1  0  0  0  4  4  0  1  1  1
100  *       ppref: -3  4  x  x  4 -2  2 -1  3  x -5  2  1 -2  3  x
101  *              <----------><-><----><-------><----><-><------->
102  * (x = don't care)
103  *
104  * this allows us to allow one int to contain the ref count for the whole
105  * chunk.    note that the "plus one" part is needed because a reference
106  * count of zero is neither positive or negative (need a way to tell
107  * if we've got one zero or a bunch of them).
108  *
109  * here are some in-line functions to help us.
110  */
111 
112 static __inline void pp_getreflen __P((int *, int, int *, int *));
113 static __inline void pp_setreflen __P((int *, int, int, int));
114 
115 /*
116  * pp_getreflen: get the reference and length for a specific offset
117  *
118  * => ppref's amap must be locked
119  */
120 static __inline void
121 pp_getreflen(ppref, offset, refp, lenp)
122 	int *ppref, offset, *refp, *lenp;
123 {
124 
125 	if (ppref[offset] > 0) {		/* chunk size must be 1 */
126 		*refp = ppref[offset] - 1;	/* don't forget to adjust */
127 		*lenp = 1;
128 	} else {
129 		*refp = (ppref[offset] * -1) - 1;
130 		*lenp = ppref[offset+1];
131 	}
132 }
133 
134 /*
135  * pp_setreflen: set the reference and length for a specific offset
136  *
137  * => ppref's amap must be locked
138  */
139 static __inline void
140 pp_setreflen(ppref, offset, ref, len)
141 	int *ppref, offset, ref, len;
142 {
143 	if (len == 1) {
144 		ppref[offset] = ref + 1;
145 	} else {
146 		ppref[offset] = (ref + 1) * -1;
147 		ppref[offset+1] = len;
148 	}
149 }
150 #endif
151 
152 /*
153  * amap_init: called at boot time to init global amap data structures
154  */
155 
156 void
157 amap_init(void)
158 {
159 
160 	/*
161 	 * Initialize the vm_amap pool.
162 	 */
163 
164 	pool_init(&uvm_amap_pool, sizeof(struct vm_amap), 0, 0, 0,
165 	    "amappl", &pool_allocator_nointr);
166 }
167 
168 /*
169  * amap_alloc1: internal function that allocates an amap, but does not
170  *	init the overlay.
171  *
172  * => lock on returned amap is init'd
173  */
174 static inline struct vm_amap *
175 amap_alloc1(slots, padslots, waitf)
176 	int slots, padslots, waitf;
177 {
178 	struct vm_amap *amap;
179 	int totalslots;
180 
181 	amap = pool_get(&uvm_amap_pool, (waitf == M_WAITOK) ? PR_WAITOK : 0);
182 	if (amap == NULL)
183 		return(NULL);
184 
185 	totalslots = malloc_roundup((slots + padslots) * sizeof(int)) /
186 	    sizeof(int);
187 	simple_lock_init(&amap->am_l);
188 	amap->am_ref = 1;
189 	amap->am_flags = 0;
190 #ifdef UVM_AMAP_PPREF
191 	amap->am_ppref = NULL;
192 #endif
193 	amap->am_maxslot = totalslots;
194 	amap->am_nslot = slots;
195 	amap->am_nused = 0;
196 
197 	amap->am_slots = malloc(totalslots * sizeof(int), M_UVMAMAP,
198 	    waitf);
199 	if (amap->am_slots == NULL)
200 		goto fail1;
201 
202 	amap->am_bckptr = malloc(totalslots * sizeof(int), M_UVMAMAP, waitf);
203 	if (amap->am_bckptr == NULL)
204 		goto fail2;
205 
206 	amap->am_anon = malloc(totalslots * sizeof(struct vm_anon *),
207 	    M_UVMAMAP, waitf);
208 	if (amap->am_anon == NULL)
209 		goto fail3;
210 
211 	return(amap);
212 
213 fail3:
214 	free(amap->am_bckptr, M_UVMAMAP);
215 fail2:
216 	free(amap->am_slots, M_UVMAMAP);
217 fail1:
218 	pool_put(&uvm_amap_pool, amap);
219 	return (NULL);
220 }
221 
222 /*
223  * amap_alloc: allocate an amap to manage "sz" bytes of anonymous VM
224  *
225  * => caller should ensure sz is a multiple of PAGE_SIZE
226  * => reference count to new amap is set to one
227  * => new amap is returned unlocked
228  */
229 
230 struct vm_amap *
231 amap_alloc(sz, padsz, waitf)
232 	vaddr_t sz, padsz;
233 	int waitf;
234 {
235 	struct vm_amap *amap;
236 	int slots, padslots;
237 	UVMHIST_FUNC("amap_alloc"); UVMHIST_CALLED(maphist);
238 
239 	AMAP_B2SLOT(slots, sz);
240 	AMAP_B2SLOT(padslots, padsz);
241 
242 	amap = amap_alloc1(slots, padslots, waitf);
243 	if (amap)
244 		memset(amap->am_anon, 0,
245 		    amap->am_maxslot * sizeof(struct vm_anon *));
246 
247 	UVMHIST_LOG(maphist,"<- done, amap = 0x%x, sz=%d", amap, sz, 0, 0);
248 	return(amap);
249 }
250 
251 
252 /*
253  * amap_free: free an amap
254  *
255  * => the amap must be unlocked
256  * => the amap should have a zero reference count and be empty
257  */
258 void
259 amap_free(amap)
260 	struct vm_amap *amap;
261 {
262 	UVMHIST_FUNC("amap_free"); UVMHIST_CALLED(maphist);
263 
264 	KASSERT(amap->am_ref == 0 && amap->am_nused == 0);
265 	LOCK_ASSERT(!simple_lock_held(&amap->am_l));
266 	free(amap->am_slots, M_UVMAMAP);
267 	free(amap->am_bckptr, M_UVMAMAP);
268 	free(amap->am_anon, M_UVMAMAP);
269 #ifdef UVM_AMAP_PPREF
270 	if (amap->am_ppref && amap->am_ppref != PPREF_NONE)
271 		free(amap->am_ppref, M_UVMAMAP);
272 #endif
273 	pool_put(&uvm_amap_pool, amap);
274 	UVMHIST_LOG(maphist,"<- done, freed amap = 0x%x", amap, 0, 0, 0);
275 }
276 
277 /*
278  * amap_extend: extend the size of an amap (if needed)
279  *
280  * => called from uvm_map when we want to extend an amap to cover
281  *    a new mapping (rather than allocate a new one)
282  * => amap should be unlocked (we will lock it)
283  * => to safely extend an amap it should have a reference count of
284  *    one (thus it can't be shared)
285  * => XXXCDC: needs a waitflag or failure return value?
286  * => XXXCDC: support padding at this level?
287  */
288 void
289 amap_extend(entry, addsize)
290 	struct vm_map_entry *entry;
291 	vsize_t addsize;
292 {
293 	struct vm_amap *amap = entry->aref.ar_amap;
294 	int slotoff = entry->aref.ar_pageoff;
295 	int slotmapped, slotadd, slotneed, slotadded, slotalloc;
296 #ifdef UVM_AMAP_PPREF
297 	int *newppref, *oldppref;
298 #endif
299 	int *newsl, *newbck, *oldsl, *oldbck;
300 	struct vm_anon **newover, **oldover;
301 	UVMHIST_FUNC("amap_extend"); UVMHIST_CALLED(maphist);
302 
303 	UVMHIST_LOG(maphist, "  (entry=0x%x, addsize=0x%x)", entry,addsize,0,0);
304 
305 	/*
306 	 * first, determine how many slots we need in the amap.  don't
307 	 * forget that ar_pageoff could be non-zero: this means that
308 	 * there are some unused slots before us in the amap.
309 	 */
310 
311 	amap_lock(amap);					/* lock! */
312 
313 	AMAP_B2SLOT(slotmapped, entry->end - entry->start); /* slots mapped */
314 	AMAP_B2SLOT(slotadd, addsize);			/* slots to add */
315 	slotneed = slotoff + slotmapped + slotadd;
316 
317 	/*
318 	 * case 1: we already have enough slots in the map and thus
319 	 * only need to bump the reference counts on the slots we are
320 	 * adding.
321 	 */
322 
323 	if (amap->am_nslot >= slotneed) {
324 #ifdef UVM_AMAP_PPREF
325 		if (amap->am_ppref && amap->am_ppref != PPREF_NONE) {
326 			amap_pp_adjref(amap, slotoff + slotmapped, slotadd, 1);
327 		}
328 #endif
329 		amap_unlock(amap);
330 		UVMHIST_LOG(maphist,"<- done (case 1), amap = 0x%x, sltneed=%d",
331 		    amap, slotneed, 0, 0);
332 		return;				/* done! */
333 	}
334 
335 	/*
336 	 * case 2: we pre-allocated slots for use and we just need to
337 	 * bump nslot up to take account for these slots.
338 	 */
339 	if (amap->am_maxslot >= slotneed) {
340 #ifdef UVM_AMAP_PPREF
341 		if (amap->am_ppref && amap->am_ppref != PPREF_NONE) {
342 			if ((slotoff + slotmapped) < amap->am_nslot)
343 				amap_pp_adjref(amap, slotoff + slotmapped,
344 				    (amap->am_nslot - (slotoff + slotmapped)),
345 				    1);
346 			pp_setreflen(amap->am_ppref, amap->am_nslot, 1,
347 			   slotneed - amap->am_nslot);
348 		}
349 #endif
350 		amap->am_nslot = slotneed;
351 		amap_unlock(amap);
352 		/*
353 		 * no need to zero am_anon since that was done at
354 		 * alloc time and we never shrink an allocation.
355 		 */
356 		UVMHIST_LOG(maphist,"<- done (case 2), amap = 0x%x, slotneed=%d",
357 		    amap, slotneed, 0, 0);
358 		return;
359 	}
360 
361 	/*
362 	 * case 3: we need to malloc a new amap and copy all the amap
363 	 * data over from old amap to the new one.
364 	 *
365 	 * XXXCDC: could we take advantage of a kernel realloc()?
366 	 */
367 
368 	amap_unlock(amap);	/* unlock in case we sleep in malloc */
369 	slotalloc = malloc_roundup(slotneed * sizeof(int)) / sizeof(int);
370 #ifdef UVM_AMAP_PPREF
371 	newppref = NULL;
372 	if (amap->am_ppref && amap->am_ppref != PPREF_NONE) {
373 		newppref = malloc(slotalloc * sizeof(int), M_UVMAMAP,
374 		    M_NOWAIT);
375 		if (newppref == NULL) {
376 			/* give up if malloc fails */
377 			free(amap->am_ppref, M_UVMAMAP);
378 			amap->am_ppref = PPREF_NONE;
379 		}
380 	}
381 #endif
382 	newsl = malloc(slotalloc * sizeof(int), M_UVMAMAP, M_WAITOK);
383 	newbck = malloc(slotalloc * sizeof(int), M_UVMAMAP, M_WAITOK);
384 	newover = malloc(slotalloc * sizeof(struct vm_anon *),
385 	    M_UVMAMAP, M_WAITOK);
386 	amap_lock(amap);			/* re-lock! */
387 	KASSERT(amap->am_maxslot < slotneed);
388 
389 	/*
390 	 * now copy everything over to new malloc'd areas...
391 	 */
392 
393 	slotadded = slotalloc - amap->am_nslot;
394 
395 	/* do am_slots */
396 	oldsl = amap->am_slots;
397 	memcpy(newsl, oldsl, sizeof(int) * amap->am_nused);
398 	amap->am_slots = newsl;
399 
400 	/* do am_anon */
401 	oldover = amap->am_anon;
402 	memcpy(newover, oldover, sizeof(struct vm_anon *) * amap->am_nslot);
403 	memset(newover + amap->am_nslot, 0, sizeof(struct vm_anon *) * slotadded);
404 	amap->am_anon = newover;
405 
406 	/* do am_bckptr */
407 	oldbck = amap->am_bckptr;
408 	memcpy(newbck, oldbck, sizeof(int) * amap->am_nslot);
409 	amap->am_bckptr = newbck;
410 
411 #ifdef UVM_AMAP_PPREF
412 	/* do ppref */
413 	oldppref = amap->am_ppref;
414 	if (newppref) {
415 		memcpy(newppref, oldppref, sizeof(int) * amap->am_nslot);
416 		memset(newppref + amap->am_nslot, 0, sizeof(int) * slotadded);
417 		amap->am_ppref = newppref;
418 		if ((slotoff + slotmapped) < amap->am_nslot)
419 			amap_pp_adjref(amap, slotoff + slotmapped,
420 			    (amap->am_nslot - (slotoff + slotmapped)), 1);
421 		pp_setreflen(newppref, amap->am_nslot, 1,
422 		    slotneed - amap->am_nslot);
423 	}
424 #endif
425 
426 	/* update master values */
427 	amap->am_nslot = slotneed;
428 	amap->am_maxslot = slotalloc;
429 
430 	amap_unlock(amap);
431 	free(oldsl, M_UVMAMAP);
432 	free(oldbck, M_UVMAMAP);
433 	free(oldover, M_UVMAMAP);
434 #ifdef UVM_AMAP_PPREF
435 	if (oldppref && oldppref != PPREF_NONE)
436 		free(oldppref, M_UVMAMAP);
437 #endif
438 	UVMHIST_LOG(maphist,"<- done (case 3), amap = 0x%x, slotneed=%d",
439 	    amap, slotneed, 0, 0);
440 }
441 
442 /*
443  * amap_share_protect: change protection of anons in a shared amap
444  *
445  * for shared amaps, given the current data structure layout, it is
446  * not possible for us to directly locate all maps referencing the
447  * shared anon (to change the protection).  in order to protect data
448  * in shared maps we use pmap_page_protect().  [this is useful for IPC
449  * mechanisms like map entry passing that may want to write-protect
450  * all mappings of a shared amap.]  we traverse am_anon or am_slots
451  * depending on the current state of the amap.
452  *
453  * => entry's map and amap must be locked by the caller
454  */
455 void
456 amap_share_protect(entry, prot)
457 	struct vm_map_entry *entry;
458 	vm_prot_t prot;
459 {
460 	struct vm_amap *amap = entry->aref.ar_amap;
461 	int slots, lcv, slot, stop;
462 
463 	LOCK_ASSERT(simple_lock_held(&amap->am_l));
464 
465 	AMAP_B2SLOT(slots, (entry->end - entry->start));
466 	stop = entry->aref.ar_pageoff + slots;
467 
468 	if (slots < amap->am_nused) {
469 		/* cheaper to traverse am_anon */
470 		for (lcv = entry->aref.ar_pageoff ; lcv < stop ; lcv++) {
471 			if (amap->am_anon[lcv] == NULL)
472 				continue;
473 			if (amap->am_anon[lcv]->u.an_page != NULL)
474 				pmap_page_protect(amap->am_anon[lcv]->u.an_page,
475 						  prot);
476 		}
477 		return;
478 	}
479 
480 	/* cheaper to traverse am_slots */
481 	for (lcv = 0 ; lcv < amap->am_nused ; lcv++) {
482 		slot = amap->am_slots[lcv];
483 		if (slot < entry->aref.ar_pageoff || slot >= stop)
484 			continue;
485 		if (amap->am_anon[slot]->u.an_page != NULL)
486 			pmap_page_protect(amap->am_anon[slot]->u.an_page, prot);
487 	}
488 }
489 
490 /*
491  * amap_wipeout: wipeout all anon's in an amap; then free the amap!
492  *
493  * => called from amap_unref when the final reference to an amap is
494  *	discarded (i.e. when reference count == 1)
495  * => the amap should be locked (by the caller)
496  */
497 
498 void
499 amap_wipeout(amap)
500 	struct vm_amap *amap;
501 {
502 	int lcv, slot;
503 	struct vm_anon *anon;
504 	UVMHIST_FUNC("amap_wipeout"); UVMHIST_CALLED(maphist);
505 	UVMHIST_LOG(maphist,"(amap=0x%x)", amap, 0,0,0);
506 
507 	amap_unlock(amap);
508 	for (lcv = 0 ; lcv < amap->am_nused ; lcv++) {
509 		int refs;
510 
511 		slot = amap->am_slots[lcv];
512 		anon = amap->am_anon[slot];
513 
514 		if (anon == NULL || anon->an_ref == 0)
515 			panic("amap_wipeout: corrupt amap");
516 
517 		simple_lock(&anon->an_lock);
518 		UVMHIST_LOG(maphist,"  processing anon 0x%x, ref=%d", anon,
519 		    anon->an_ref, 0, 0);
520 		refs = --anon->an_ref;
521 		simple_unlock(&anon->an_lock);
522 		if (refs == 0) {
523 
524 			/*
525 			 * we had the last reference to a vm_anon. free it.
526 			 */
527 
528 			uvm_anfree(anon);
529 		}
530 
531 		/*
532 		 * XXX
533 		 * releasing the swap space held by an N anons is an O(N^2)
534 		 * operation because of the implementation of extents.
535 		 * if there are many anons, tearing down an exiting process'
536 		 * address space can take many seconds, which causes very
537 		 * annoying pauses.  we yield here to give other processes
538 		 * a chance to run.  this should be removed once the performance
539 		 * of swap space management is improved.
540 		 */
541 
542 		if (curproc->p_cpu->ci_schedstate.spc_flags & SPCF_SHOULDYIELD)
543 			preempt(NULL);
544 	}
545 
546 	/*
547 	 * now we free the map
548 	 */
549 
550 	amap->am_ref = 0;	/* ... was one */
551 	amap->am_nused = 0;
552 	amap_free(amap);	/* will unlock and free amap */
553 	UVMHIST_LOG(maphist,"<- done!", 0,0,0,0);
554 }
555 
556 /*
557  * amap_copy: ensure that a map entry's "needs_copy" flag is false
558  *	by copying the amap if necessary.
559  *
560  * => an entry with a null amap pointer will get a new (blank) one.
561  * => the map that the map entry belongs to must be locked by caller.
562  * => the amap currently attached to "entry" (if any) must be unlocked.
563  * => if canchunk is true, then we may clip the entry into a chunk
564  * => "startva" and "endva" are used only if canchunk is true.  they are
565  *     used to limit chunking (e.g. if you have a large space that you
566  *     know you are going to need to allocate amaps for, there is no point
567  *     in allowing that to be chunked)
568  */
569 
570 void
571 amap_copy(map, entry, waitf, canchunk, startva, endva)
572 	struct vm_map *map;
573 	struct vm_map_entry *entry;
574 	int waitf;
575 	boolean_t canchunk;
576 	vaddr_t startva, endva;
577 {
578 	struct vm_amap *amap, *srcamap;
579 	int slots, lcv;
580 	vaddr_t chunksize;
581 	UVMHIST_FUNC("amap_copy"); UVMHIST_CALLED(maphist);
582 	UVMHIST_LOG(maphist, "  (map=%p, entry=%p, waitf=%d)",
583 		    map, entry, waitf, 0);
584 
585 	/*
586 	 * is there a map to copy?   if not, create one from scratch.
587 	 */
588 
589 	if (entry->aref.ar_amap == NULL) {
590 
591 		/*
592 		 * check to see if we have a large amap that we can
593 		 * chunk.  we align startva/endva to chunk-sized
594 		 * boundaries and then clip to them.
595 		 */
596 
597 		if (canchunk && atop(entry->end - entry->start) >=
598 		    UVM_AMAP_LARGE) {
599 			/* convert slots to bytes */
600 			chunksize = UVM_AMAP_CHUNK << PAGE_SHIFT;
601 			startva = (startva / chunksize) * chunksize;
602 			endva = roundup(endva, chunksize);
603 			UVMHIST_LOG(maphist, "  chunk amap ==> clip 0x%x->0x%x"
604 			    "to 0x%x->0x%x", entry->start, entry->end, startva,
605 			    endva);
606 			UVM_MAP_CLIP_START(map, entry, startva);
607 			/* watch out for endva wrap-around! */
608 			if (endva >= startva)
609 				UVM_MAP_CLIP_END(map, entry, endva);
610 		}
611 
612 		UVMHIST_LOG(maphist, "<- done [creating new amap 0x%x->0x%x]",
613 		entry->start, entry->end, 0, 0);
614 		entry->aref.ar_pageoff = 0;
615 		entry->aref.ar_amap = amap_alloc(entry->end - entry->start, 0,
616 		    waitf);
617 		if (entry->aref.ar_amap != NULL)
618 			entry->etype &= ~UVM_ET_NEEDSCOPY;
619 		return;
620 	}
621 
622 	/*
623 	 * first check and see if we are the only map entry
624 	 * referencing the amap we currently have.  if so, then we can
625 	 * just take it over rather than copying it.  note that we are
626 	 * reading am_ref with the amap unlocked... the value can only
627 	 * be one if we have the only reference to the amap (via our
628 	 * locked map).  if we are greater than one we fall through to
629 	 * the next case (where we double check the value).
630 	 */
631 
632 	if (entry->aref.ar_amap->am_ref == 1) {
633 		entry->etype &= ~UVM_ET_NEEDSCOPY;
634 		UVMHIST_LOG(maphist, "<- done [ref cnt = 1, took it over]",
635 		    0, 0, 0, 0);
636 		return;
637 	}
638 
639 	/*
640 	 * looks like we need to copy the map.
641 	 */
642 
643 	UVMHIST_LOG(maphist,"  amap=%p, ref=%d, must copy it",
644 	    entry->aref.ar_amap, entry->aref.ar_amap->am_ref, 0, 0);
645 	AMAP_B2SLOT(slots, entry->end - entry->start);
646 	amap = amap_alloc1(slots, 0, waitf);
647 	if (amap == NULL) {
648 		UVMHIST_LOG(maphist, "  amap_alloc1 failed", 0,0,0,0);
649 		return;
650 	}
651 	srcamap = entry->aref.ar_amap;
652 	amap_lock(srcamap);
653 
654 	/*
655 	 * need to double check reference count now that we've got the
656 	 * src amap locked down.  the reference count could have
657 	 * changed while we were in malloc.  if the reference count
658 	 * dropped down to one we take over the old map rather than
659 	 * copying the amap.
660 	 */
661 
662 	if (srcamap->am_ref == 1) {		/* take it over? */
663 		entry->etype &= ~UVM_ET_NEEDSCOPY;
664 		amap->am_ref--;		/* drop final reference to map */
665 		amap_unlock(amap);
666 		amap_free(amap);	/* dispose of new (unused) amap */
667 		amap_unlock(srcamap);
668 		return;
669 	}
670 
671 	/*
672 	 * we must copy it now.
673 	 */
674 
675 	UVMHIST_LOG(maphist, "  copying amap now",0, 0, 0, 0);
676 	for (lcv = 0 ; lcv < slots; lcv++) {
677 		amap->am_anon[lcv] =
678 		    srcamap->am_anon[entry->aref.ar_pageoff + lcv];
679 		if (amap->am_anon[lcv] == NULL)
680 			continue;
681 		simple_lock(&amap->am_anon[lcv]->an_lock);
682 		amap->am_anon[lcv]->an_ref++;
683 		simple_unlock(&amap->am_anon[lcv]->an_lock);
684 		amap->am_bckptr[lcv] = amap->am_nused;
685 		amap->am_slots[amap->am_nused] = lcv;
686 		amap->am_nused++;
687 	}
688 	memset(&amap->am_anon[lcv], 0,
689 	    (amap->am_maxslot - lcv) * sizeof(struct vm_anon *));
690 
691 	/*
692 	 * drop our reference to the old amap (srcamap) and unlock.
693 	 * we know that the reference count on srcamap is greater than
694 	 * one (we checked above), so there is no way we could drop
695 	 * the count to zero.  [and no need to worry about freeing it]
696 	 */
697 
698 	srcamap->am_ref--;
699 	if (srcamap->am_ref == 1 && (srcamap->am_flags & AMAP_SHARED) != 0)
700 		srcamap->am_flags &= ~AMAP_SHARED;   /* clear shared flag */
701 #ifdef UVM_AMAP_PPREF
702 	if (srcamap->am_ppref && srcamap->am_ppref != PPREF_NONE) {
703 		amap_pp_adjref(srcamap, entry->aref.ar_pageoff,
704 		    (entry->end - entry->start) >> PAGE_SHIFT, -1);
705 	}
706 #endif
707 
708 	amap_unlock(srcamap);
709 
710 	/*
711 	 * install new amap.
712 	 */
713 
714 	entry->aref.ar_pageoff = 0;
715 	entry->aref.ar_amap = amap;
716 	entry->etype &= ~UVM_ET_NEEDSCOPY;
717 	UVMHIST_LOG(maphist, "<- done",0, 0, 0, 0);
718 }
719 
720 /*
721  * amap_cow_now: resolve all copy-on-write faults in an amap now for fork(2)
722  *
723  *	called during fork(2) when the parent process has a wired map
724  *	entry.   in that case we want to avoid write-protecting pages
725  *	in the parent's map (e.g. like what you'd do for a COW page)
726  *	so we resolve the COW here.
727  *
728  * => assume parent's entry was wired, thus all pages are resident.
729  * => assume pages that are loaned out (loan_count) are already mapped
730  *	read-only in all maps, and thus no need for us to worry about them
731  * => assume both parent and child vm_map's are locked
732  * => caller passes child's map/entry in to us
733  * => if we run out of memory we will unlock the amap and sleep _with_ the
734  *	parent and child vm_map's locked(!).    we have to do this since
735  *	we are in the middle of a fork(2) and we can't let the parent
736  *	map change until we are done copying all the map entrys.
737  * => XXXCDC: out of memory should cause fork to fail, but there is
738  *	currently no easy way to do this (needs fix)
739  * => page queues must be unlocked (we may lock them)
740  */
741 
742 void
743 amap_cow_now(map, entry)
744 	struct vm_map *map;
745 	struct vm_map_entry *entry;
746 {
747 	struct vm_amap *amap = entry->aref.ar_amap;
748 	int lcv, slot;
749 	struct vm_anon *anon, *nanon;
750 	struct vm_page *pg, *npg;
751 
752 	/*
753 	 * note that if we unlock the amap then we must ReStart the "lcv" for
754 	 * loop because some other process could reorder the anon's in the
755 	 * am_anon[] array on us while the lock is dropped.
756 	 */
757 
758 ReStart:
759 	amap_lock(amap);
760 
761 	for (lcv = 0 ; lcv < amap->am_nused ; lcv++) {
762 
763 		/*
764 		 * get the page
765 		 */
766 
767 		slot = amap->am_slots[lcv];
768 		anon = amap->am_anon[slot];
769 		simple_lock(&anon->an_lock);
770 		pg = anon->u.an_page;
771 
772 		/*
773 		 * page must be resident since parent is wired
774 		 */
775 
776 		if (pg == NULL)
777 		    panic("amap_cow_now: non-resident wired page in anon %p",
778 			anon);
779 
780 		/*
781 		 * if the anon ref count is one and the page is not loaned,
782 		 * then we are safe (the child has exclusive access to the
783 		 * page).  if the page is loaned, then it must already be
784 		 * mapped read-only.
785 		 *
786 		 * we only need to get involved when these are not true.
787 		 * [note: if loan_count == 0, then the anon must own the page]
788 		 */
789 
790 		if (anon->an_ref > 1 && pg->loan_count == 0) {
791 
792 			/*
793 			 * if the page is busy then we have to unlock, wait for
794 			 * it and then restart.
795 			 */
796 			if (pg->flags & PG_BUSY) {
797 				pg->flags |= PG_WANTED;
798 				amap_unlock(amap);
799 				UVM_UNLOCK_AND_WAIT(pg, &anon->an_lock, FALSE,
800 				    "cownow", 0);
801 				goto ReStart;
802 			}
803 
804 			/*
805 			 * ok, time to do a copy-on-write to a new anon
806 			 */
807 			nanon = uvm_analloc();
808 			if (nanon) {
809 				/* nanon is locked! */
810 				npg = uvm_pagealloc(NULL, 0, nanon, 0);
811 			} else
812 				npg = NULL;	/* XXX: quiet gcc warning */
813 
814 			if (nanon == NULL || npg == NULL) {
815 				/* out of memory */
816 				/*
817 				 * XXXCDC: we should cause fork to fail, but
818 				 * we can't ...
819 				 */
820 				if (nanon) {
821 					nanon->an_ref--;
822 					simple_unlock(&nanon->an_lock);
823 					uvm_anfree(nanon);
824 				}
825 				simple_unlock(&anon->an_lock);
826 				amap_unlock(amap);
827 				uvm_wait("cownowpage");
828 				goto ReStart;
829 			}
830 
831 			/*
832 			 * got it... now we can copy the data and replace anon
833 			 * with our new one...
834 			 */
835 
836 			uvm_pagecopy(pg, npg);		/* old -> new */
837 			anon->an_ref--;			/* can't drop to zero */
838 			amap->am_anon[slot] = nanon;	/* replace */
839 
840 			/*
841 			 * drop PG_BUSY on new page ... since we have had it's
842 			 * owner locked the whole time it can't be
843 			 * PG_RELEASED | PG_WANTED.
844 			 */
845 
846 			npg->flags &= ~(PG_BUSY|PG_FAKE);
847 			UVM_PAGE_OWN(npg, NULL);
848 			uvm_lock_pageq();
849 			uvm_pageactivate(npg);
850 			uvm_unlock_pageq();
851 			simple_unlock(&nanon->an_lock);
852 		}
853 		simple_unlock(&anon->an_lock);
854 	}
855 	amap_unlock(amap);
856 }
857 
858 /*
859  * amap_splitref: split a single reference into two separate references
860  *
861  * => called from uvm_map's clip routines
862  * => origref's map should be locked
863  * => origref->ar_amap should be unlocked (we will lock)
864  */
865 void
866 amap_splitref(origref, splitref, offset)
867 	struct vm_aref *origref, *splitref;
868 	vaddr_t offset;
869 {
870 	int leftslots;
871 
872 	AMAP_B2SLOT(leftslots, offset);
873 	if (leftslots == 0)
874 		panic("amap_splitref: split at zero offset");
875 
876 	amap_lock(origref->ar_amap);
877 
878 	/*
879 	 * now: amap is locked and we have a valid am_mapped array.
880 	 */
881 
882 	if (origref->ar_amap->am_nslot - origref->ar_pageoff - leftslots <= 0)
883 		panic("amap_splitref: map size check failed");
884 
885 #ifdef UVM_AMAP_PPREF
886         /*
887 	 * establish ppref before we add a duplicate reference to the amap
888 	 */
889 	if (origref->ar_amap->am_ppref == NULL)
890 		amap_pp_establish(origref->ar_amap);
891 #endif
892 
893 	splitref->ar_amap = origref->ar_amap;
894 	splitref->ar_amap->am_ref++;		/* not a share reference */
895 	splitref->ar_pageoff = origref->ar_pageoff + leftslots;
896 
897 	amap_unlock(origref->ar_amap);
898 }
899 
900 #ifdef UVM_AMAP_PPREF
901 
902 /*
903  * amap_pp_establish: add a ppref array to an amap, if possible
904  *
905  * => amap locked by caller
906  */
907 void
908 amap_pp_establish(amap)
909 	struct vm_amap *amap;
910 {
911 	amap->am_ppref = malloc(sizeof(int) * amap->am_maxslot,
912 	    M_UVMAMAP, M_NOWAIT);
913 
914 	/*
915 	 * if we fail then we just won't use ppref for this amap
916 	 */
917 
918 	if (amap->am_ppref == NULL) {
919 		amap->am_ppref = PPREF_NONE;	/* not using it */
920 		return;
921 	}
922 	memset(amap->am_ppref, 0, sizeof(int) * amap->am_maxslot);
923 	pp_setreflen(amap->am_ppref, 0, amap->am_ref, amap->am_nslot);
924 	return;
925 }
926 
927 /*
928  * amap_pp_adjref: adjust reference count to a part of an amap using the
929  * per-page reference count array.
930  *
931  * => map and amap locked by caller
932  * => caller must check that ppref != PPREF_NONE before calling
933  */
934 void
935 amap_pp_adjref(amap, curslot, slotlen, adjval)
936 	struct vm_amap *amap;
937 	int curslot;
938 	vsize_t slotlen;
939 	int adjval;
940 {
941 	int stopslot, *ppref, lcv, prevlcv;
942 	int ref, len, prevref, prevlen;
943 
944 	stopslot = curslot + slotlen;
945 	ppref = amap->am_ppref;
946 	prevlcv = 0;
947 
948 	/*
949 	 * first advance to the correct place in the ppref array,
950 	 * fragment if needed.
951 	 */
952 
953 	for (lcv = 0 ; lcv < curslot ; lcv += len) {
954 		pp_getreflen(ppref, lcv, &ref, &len);
955 		if (lcv + len > curslot) {     /* goes past start? */
956 			pp_setreflen(ppref, lcv, ref, curslot - lcv);
957 			pp_setreflen(ppref, curslot, ref, len - (curslot -lcv));
958 			len = curslot - lcv;   /* new length of entry @ lcv */
959 		}
960 		prevlcv = lcv;
961 	}
962 	if (lcv != 0)
963 		pp_getreflen(ppref, prevlcv, &prevref, &prevlen);
964 	else {
965 		/* Ensure that the "prevref == ref" test below always
966 		 * fails, since we're starting from the beginning of
967 		 * the ppref array; that is, there is no previous
968 		 * chunk.
969 		 */
970 		prevref = -1;
971 		prevlen = 0;
972 	}
973 
974 	/*
975 	 * now adjust reference counts in range.  merge the first
976 	 * changed entry with the last unchanged entry if possible.
977 	 */
978 
979 	if (lcv != curslot)
980 		panic("amap_pp_adjref: overshot target");
981 
982 	for (/* lcv already set */; lcv < stopslot ; lcv += len) {
983 		pp_getreflen(ppref, lcv, &ref, &len);
984 		if (lcv + len > stopslot) {     /* goes past end? */
985 			pp_setreflen(ppref, lcv, ref, stopslot - lcv);
986 			pp_setreflen(ppref, stopslot, ref,
987 			    len - (stopslot - lcv));
988 			len = stopslot - lcv;
989 		}
990 		ref += adjval;
991 		if (ref < 0)
992 			panic("amap_pp_adjref: negative reference count");
993 		if (lcv == prevlcv + prevlen && ref == prevref) {
994 			pp_setreflen(ppref, prevlcv, ref, prevlen + len);
995 		} else {
996 			pp_setreflen(ppref, lcv, ref, len);
997 		}
998 		if (ref == 0)
999 			amap_wiperange(amap, lcv, len);
1000 	}
1001 
1002 }
1003 
1004 /*
1005  * amap_wiperange: wipe out a range of an amap
1006  * [different from amap_wipeout because the amap is kept intact]
1007  *
1008  * => both map and amap must be locked by caller.
1009  */
1010 void
1011 amap_wiperange(amap, slotoff, slots)
1012 	struct vm_amap *amap;
1013 	int slotoff, slots;
1014 {
1015 	int byanon, lcv, stop, curslot, ptr, slotend;
1016 	struct vm_anon *anon;
1017 
1018 	/*
1019 	 * we can either traverse the amap by am_anon or by am_slots depending
1020 	 * on which is cheaper.    decide now.
1021 	 */
1022 
1023 	if (slots < amap->am_nused) {
1024 		byanon = TRUE;
1025 		lcv = slotoff;
1026 		stop = slotoff + slots;
1027 	} else {
1028 		byanon = FALSE;
1029 		lcv = 0;
1030 		stop = amap->am_nused;
1031 		slotend = slotoff + slots;
1032 	}
1033 
1034 	while (lcv < stop) {
1035 		int refs;
1036 
1037 		if (byanon) {
1038 			curslot = lcv++;	/* lcv advances here */
1039 			if (amap->am_anon[curslot] == NULL)
1040 				continue;
1041 		} else {
1042 			curslot = amap->am_slots[lcv];
1043 			if (curslot < slotoff || curslot >= slotend) {
1044 				lcv++;		/* lcv advances here */
1045 				continue;
1046 			}
1047 			stop--;	/* drop stop, since anon will be removed */
1048 		}
1049 		anon = amap->am_anon[curslot];
1050 
1051 		/*
1052 		 * remove it from the amap
1053 		 */
1054 
1055 		amap->am_anon[curslot] = NULL;
1056 		ptr = amap->am_bckptr[curslot];
1057 		if (ptr != (amap->am_nused - 1)) {
1058 			amap->am_slots[ptr] =
1059 			    amap->am_slots[amap->am_nused - 1];
1060 			amap->am_bckptr[amap->am_slots[ptr]] =
1061 			    ptr;    /* back ptr. */
1062 		}
1063 		amap->am_nused--;
1064 
1065 		/*
1066 		 * drop anon reference count
1067 		 */
1068 
1069 		simple_lock(&anon->an_lock);
1070 		refs = --anon->an_ref;
1071 		simple_unlock(&anon->an_lock);
1072 		if (refs == 0) {
1073 
1074 			/*
1075 			 * we just eliminated the last reference to an anon.
1076 			 * free it.
1077 			 */
1078 
1079 			uvm_anfree(anon);
1080 		}
1081 	}
1082 }
1083 
1084 #endif
1085