xref: /original-bsd/sys/kern/subr_rmap.c (revision 552e81d8)
1 /*	subr_rmap.c	3.3	06/24/80	*/
2 
3 #include "../h/param.h"
4 #include "../h/systm.h"
5 #include "../h/map.h"
6 #include "../h/dir.h"
7 #include "../h/user.h"
8 #include "../h/proc.h"
9 #include "../h/mtpr.h"
10 #include "../h/text.h"
11 
12 /*
13  * Allocate 'size' units from the given
14  * map. Return the base of the allocated
15  * space.
16  * In a map, the addresses are increasing and the
17  * list is terminated by a 0 size.
18  * The swap map unit is 512 bytes.
19  * Algorithm is first-fit.
20  */
21 malloc(mp, size)
22 struct map *mp;
23 {
24 	register int a;
25 	register struct map *bp;
26 	swblk_t first, rest;
27 
28 	if (size <= 0 || mp == swapmap && size > DMMAX)
29 		panic("malloc");
30 	for (bp=mp; bp->m_size; bp++) {
31 		if (bp->m_size >= size) {
32 			if (mp == swapmap &&
33 			    (first = DMMAX - bp->m_addr%DMMAX) < bp->m_size) {
34 				if (bp->m_size - first < size)
35 					continue;
36 				a = bp->m_addr + first;
37 				rest = bp->m_size - first - size;
38 				bp->m_size = first;
39 				if (rest)
40 					mfree(swapmap, rest, a+size);
41 				return (a);
42 			}
43 			a = bp->m_addr;
44 			bp->m_addr += size;
45 			if ((bp->m_size -= size) == 0) {
46 				do {
47 					bp++;
48 					(bp-1)->m_addr = bp->m_addr;
49 				} while ((bp-1)->m_size = bp->m_size);
50 			}
51 			if (mp == swapmap && a % CLSIZE)
52 				panic("malloc swapmap");
53 			return(a);
54 		}
55 	}
56 	return(0);
57 }
58 
59 /*
60  * Free the previously allocated space aa
61  * of size units into the specified map.
62  * Sort aa into map and combine on
63  * one or both ends if possible.
64  */
65 mfree(mp, size, a)
66 struct map *mp;
67 register int size, a;
68 {
69 	register struct map *bp;
70 	register int t;
71 
72 	if (a <= 0)
73 		panic("mfree addr");
74 	if (size <= 0)
75 		panic("mfree size");
76 	bp = mp;
77 	for (; bp->m_addr<=a && bp->m_size!=0; bp++)
78 		continue;
79 	if (bp>mp && (bp-1)->m_addr+(bp-1)->m_size > a)
80 		panic("mfree begov");
81 	if (a+size > bp->m_addr && bp->m_size)
82 		panic("mfree endov");
83 	if (bp>mp && (bp-1)->m_addr+(bp-1)->m_size == a) {
84 		(bp-1)->m_size += size;
85 		if (a+size == bp->m_addr) {
86 			(bp-1)->m_size += bp->m_size;
87 			while (bp->m_size) {
88 				bp++;
89 				(bp-1)->m_addr = bp->m_addr;
90 				(bp-1)->m_size = bp->m_size;
91 			}
92 		}
93 	} else {
94 		if (a+size == bp->m_addr && bp->m_size) {
95 			bp->m_addr -= size;
96 			bp->m_size += size;
97 		} else if (size) {
98 			do {
99 				t = bp->m_addr;
100 				bp->m_addr = a;
101 				a = t;
102 				t = bp->m_size;
103 				bp->m_size = size;
104 				bp++;
105 			} while (size = t);
106 		}
107 	}
108 	if ((mp == kernelmap) && kmapwnt) {
109 		kmapwnt = 0;
110 		wakeup((caddr_t)kernelmap);
111 	}
112 }
113