pull-prototypes-to-head-20020821
[openafs.git] / src / afs / LINUX / osi_alloc.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  * 
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 /*
11  * osi_alloc.c - Linux memory allocation routines.
12  *
13  */
14 #include <afsconfig.h>
15 #include "../afs/param.h"
16
17 RCSID("$Header$");
18
19 #include "../afs/sysincludes.h"
20 #include "../afs/afsincludes.h"
21 #include "../h/mm.h"
22 #include "../h/slab.h"
23
24 #include "../afs/afs_atomlist.h"
25 #include "../afs/afs_lhash.h"
26
27 #define MAX_KMALLOC_SIZE PAGE_SIZE /* Max we should alloc with kmalloc */
28 #define MAX_BUCKET_LEN 30 /* max. no. of entries per buckets we expect to see */
29 #define STAT_INTERVAL 8192 /* we collect stats once every STAT_INTERVAL allocs*/
30
31 /* types of alloc */
32 #define KM_TYPE 1        /* kmalloc */
33 #define VM_TYPE 2        /* vmalloc */
34
35 struct osi_linux_mem {
36     void *chunk;
37 };
38
39 /* These assume 32-bit pointers */
40 #define MEMTYPE(A) (((unsigned long)A) & 0x3)
41 #define MEMADDR(A) (void *)((unsigned long)(A) & (~0x3))
42
43 /* globals */
44 afs_atomlist *al_mem_pool; /* pool of osi_linux_mem structures */
45 afs_lhash    *lh_mem_htab; /* mem hash table */
46 unsigned int allocator_init = 0; /* has the allocator been initialized? */
47 unsigned int afs_linux_cur_allocs = 0;
48 unsigned int afs_linux_total_allocs = 0;
49 unsigned int afs_linux_hash_verify_count = 0; /* used by hash_verify */
50 struct afs_lhash_stat afs_linux_lsb; /* hash table statistics */
51 unsigned int afs_linux_hash_bucket_dist[MAX_BUCKET_LEN]; /* bucket population distribution in our hash table */
52
53 #if defined(AFS_LINUX24_ENV)
54 #include "../h/vmalloc.h"
55 #else
56 /* externs : can we do this in a better way. Including vmalloc.h causes other
57  * problems.*/
58 extern void vfree(void * addr);
59 extern void *vmalloc(unsigned long size);
60 #endif
61
62 /* Allocator support functions (static) */
63
64 static int hash_equal(const void *a, const void *b) 
65 {
66     return ( MEMADDR(((struct osi_linux_mem *)a)->chunk) == 
67             MEMADDR(((struct osi_linux_mem *)b)->chunk) );
68
69 }
70
71 /* linux_alloc : Allocates memory from the linux kernel. It uses 
72  *               kmalloc if possible. Otherwise, we use vmalloc. 
73  * Input:
74  *  asize - size of memory required in bytes
75  * Return Values:
76  *  returns NULL if we failed to allocate memory.
77  *  or pointer to memory if we succeeded.
78  */
79 static void *linux_alloc(unsigned int asize, int drop_glock)
80 {
81     void *new = NULL;
82     int max_retry = 10;
83     int haveGlock = ISAFS_GLOCK();
84
85     /*  if we can use kmalloc use it to allocate the required memory. */
86     while(!new && max_retry)
87     {
88         if (asize <=  MAX_KMALLOC_SIZE) {
89         new = (void *)(unsigned long)kmalloc(asize, 
90 #ifdef GFP_NOFS
91                                              GFP_NOFS
92 #else
93                                              GFP_KERNEL
94 #endif
95                                              );
96         if (new) /* piggy back alloc type */
97             (unsigned long)new |= KM_TYPE;
98         } else {
99             new = (void *)vmalloc(asize);
100             if (new) /* piggy back alloc type */
101                 (unsigned long)new |= VM_TYPE;
102             }
103
104         if (!new) {
105 #ifdef set_current_state
106             set_current_state(TASK_INTERRUPTIBLE);
107 #else
108             current->state = TASK_INTERRUPTIBLE;
109 #endif
110             if (drop_glock && haveGlock) AFS_GUNLOCK();
111             schedule_timeout(HZ);
112             if (drop_glock && haveGlock) AFS_GLOCK();
113 #ifdef set_current_state
114             set_current_state(TASK_RUNNING);
115 #else
116             current->state = TASK_RUNNING;
117 #endif
118             --max_retry;
119         }
120     }
121     if (new)
122         memset(MEMADDR(new), 0, asize);
123
124     return new;
125 }
126
127 static void linux_free(void *p)
128 {
129     
130     /* mask out the type information from the pointer and
131      *  use the appropriate free routine to free the chunk.
132      */
133     switch(MEMTYPE(p)) {
134       case KM_TYPE:
135         kfree(MEMADDR(p));
136         break;
137       case VM_TYPE:
138         vfree(MEMADDR(p));
139         break;
140       default:
141         printf("afs_osi_Free: Asked to free unknown type %d at 0x%x\n",
142                MEMTYPE(p), MEMADDR(p));
143         break;
144     }
145
146 }
147
148 /* hash_chunk() receives a pointer to a chunk and hashes it to produce a
149  *            key that the hashtable can use. The key is obtained by 
150  *            right shifting out the 2 LSBs and then multiplying the
151  *            result by a constant no. and dividing it with a large prime.
152  */
153 #define HASH_CONST   32786
154 #define HASH_PRIME   79367
155 static unsigned hash_chunk(void *p)
156 {
157     unsigned int key;
158
159     key = (unsigned int)(long)p >> 2;
160     key = (key * HASH_CONST)%HASH_PRIME;
161
162     return key;
163 }
164
165 /* hash_free() : Invoked by osi_linux_free_afs_memory(), thru 
166  *          afs_lhash_iter(), this function is called by the lhash
167  *          module for every entry in the hash table. hash_free
168  *          frees the memory associated with the entry as well
169  *          as returning the osi_linux_mem struct to its pool.
170  */
171 static void
172 hash_free(size_t index, unsigned key, void *data)
173 {
174     linux_free(((struct osi_linux_mem *)data)->chunk);
175     afs_atomlist_put(al_mem_pool, data);
176 }
177
178 /* hash_verify() is invoked by osi_linux_verify_alloced_memory() thru
179  *   afs_lhash_iter() and is called by the lhash module for every element
180  *   in the hash table. 
181  *  hash_verify() verifies (within limits) that the memory passed to it is
182  *  valid.
183  */
184 static void
185 hash_verify(size_t index, unsigned key, void *data)
186 {
187     struct osi_linux_mem *lmp = (struct osi_linux_mem *)data;
188     int memtype;
189
190     memtype = MEMTYPE(lmp->chunk);
191 #ifdef AFS_SPARC64_LINUX24_ENV
192     if ((memtype == KM_TYPE) && (!VALID_PAGE(virt_to_page(lmp->chunk)))) {
193         printf("osi_linux_verify_alloced_memory: address 0x%x outside range, index=%d, key=%d\n", lmp->chunk, index, key);
194     }
195 #else
196     if ((memtype == KM_TYPE) && (AFS_LINUX_MAP_NR(lmp->chunk) > max_mapnr)) {
197         printf("osi_linux_verify_alloced_memory: address 0x%x outside range, index=%d, key=%d\n", lmp->chunk, index, key);
198     }
199 #endif
200     
201     if (memtype != KM_TYPE && memtype != VM_TYPE) {
202         printf("osi_linux_verify_alloced_memory: unknown type %d at 0x%x, index=%d\n",    memtype, lmp->chunk, index);
203     }
204     afs_linux_hash_verify_count++;
205 }
206
207
208 /* local_free() : wrapper for vfree(), to deal with incompatible protoypes */
209 static void local_free(void *p, size_t n)
210 {
211     vfree(p);
212 }
213
214 /* linux_alloc_init(): Initializes the kernel memory allocator. As part
215  *    of this process, it also initializes a pool of osi_linux_mem
216  *    structures as well as the hash table itself.
217  *  Return values:
218  *    0 - failure
219  *    1 - success
220  */
221 static int linux_alloc_init()
222 {
223     /* initiate our pool of osi_linux_mem structs */
224     al_mem_pool = afs_atomlist_create(sizeof(struct osi_linux_mem),
225                                       sizeof(long)*1024, (void *)vmalloc, 
226                                       local_free);
227     if (!al_mem_pool) {
228         printf("afs_osi_Alloc: Error in initialization(atomlist_create)\n");
229         return 0;
230     }
231
232     /* initialize the hash table to hold references to alloc'ed chunks */
233     lh_mem_htab = afs_lhash_create(hash_equal, (void *)vmalloc, local_free);
234     if (!lh_mem_htab) {
235         printf("afs_osi_Alloc: Error in initialization(lhash_create)\n");
236         return 0;
237     }
238     
239     return 1;
240     
241 }
242
243 /* hash_bucket_stat() : Counts the no. of elements in each bucket and
244  *   stores results in our bucket stats vector.
245  */
246 static unsigned int cur_bucket, cur_bucket_len;
247 static void hash_bucket_stat(size_t index, unsigned key, void *data)
248 {
249     if (index == cur_bucket) { 
250         /* while still on the same bucket, inc len & return */
251         cur_bucket_len++;
252         return;
253     }
254     else { /* if we're on the next bucket, store the distribution */
255         if (cur_bucket_len < MAX_BUCKET_LEN)
256             afs_linux_hash_bucket_dist[cur_bucket_len]++;
257         else
258             printf("afs_get_hash_stats: Warning! exceeded max bucket len %d\n", cur_bucket_len);
259         cur_bucket = index;
260         cur_bucket_len = 1;
261     }
262 }
263 /* get_hash_stats() : get hash table statistics */
264 static void get_hash_stats()
265 {
266     int i;
267
268     afs_lhash_stat(lh_mem_htab, &afs_linux_lsb);
269
270     /* clear out the bucket stat vector */
271     for(i=0;i<MAX_BUCKET_LEN;i++, afs_linux_hash_bucket_dist[i]=0);
272     cur_bucket = cur_bucket_len = 00;
273
274     /* populate the bucket stat vector */
275     afs_lhash_iter(lh_mem_htab, hash_bucket_stat);
276 }
277
278 /************** Linux memory allocator interface functions **********/
279
280 #if defined(AFS_LINUX24_ENV)
281 DECLARE_MUTEX(afs_linux_alloc_sem);
282 #else
283 struct semaphore afs_linux_alloc_sem = MUTEX;
284 #endif
285
286 void *osi_linux_alloc(unsigned int asize, int drop_glock)
287 {
288     void *new = NULL;
289     struct osi_linux_mem *lmem;
290
291     new = linux_alloc(asize, drop_glock); /* get a chunk of memory of size asize */
292
293     if (!new) {
294         printf("afs_osi_Alloc: Can't vmalloc %d bytes.\n", asize);
295         return new;
296     }
297
298     down(&afs_linux_alloc_sem);
299
300     /* allocator hasn't been initialized yet */
301     if (allocator_init == 0) {
302         if (linux_alloc_init() == 0) {
303             goto error;
304          }
305         allocator_init = 1; /* initialization complete */
306     }
307     
308     /* get an atom to store the pointer to the chunk */
309     lmem = (struct osi_linux_mem *)afs_atomlist_get(al_mem_pool);
310     if (!lmem) {
311         printf("afs_osi_Alloc: atomlist_get() failed.");
312         goto free_error;
313     }
314     /* store the chunk reference */
315     lmem->chunk = new;
316
317     /* hash in the chunk */
318     if (afs_lhash_enter(lh_mem_htab, hash_chunk(new), lmem) != 0) {
319         printf("afs_osi_Alloc: lhash_enter failed\n");
320         goto free_error;
321     }
322     afs_linux_cur_allocs++;   /* no. of current allocations */
323     afs_linux_total_allocs++; /* total no. of allocations done so far */
324     if ((afs_linux_cur_allocs % STAT_INTERVAL) == 0) {
325         get_hash_stats();
326     }
327   error:
328     up(&afs_linux_alloc_sem);
329     return MEMADDR(new);
330
331   free_error:
332     if (new) {
333         up(&afs_linux_alloc_sem);
334         linux_free(new);
335         down(&afs_linux_alloc_sem);
336     }
337     new = NULL;
338     goto error;
339
340     
341 }
342
343 /* osi_linux_free() - free chunk of memory passed to us.
344  */
345 void osi_linux_free(void *addr)
346 {
347     struct osi_linux_mem lmem, *lmp;
348
349     down(&afs_linux_alloc_sem);
350     
351     lmem.chunk = addr;
352     /* remove this chunk from our hash table */
353     if ((lmp = (struct osi_linux_mem *)afs_lhash_remove(lh_mem_htab, hash_chunk(addr), &lmem))) {
354         linux_free(lmp->chunk); /* this contains the piggybacked type info*/
355         afs_atomlist_put(al_mem_pool, lmp); /* return osi_linux_mem struct to pool*/
356         afs_linux_cur_allocs--;
357     }
358     else   {
359         printf("osi_linux_free: failed to remove chunk from hashtable\n");
360     }
361
362     up(&afs_linux_alloc_sem);
363 }
364
365 /* osi_linux_free_afs_memory() - free all chunks of memory allocated.
366  */
367 void osi_linux_free_afs_memory(void)
368 {
369     down(&afs_linux_alloc_sem);
370
371     if (allocator_init) {
372         /* iterate through all elements in the hash table and free both 
373          * the chunk and the atom associated with it.
374          */
375         afs_lhash_iter(lh_mem_htab, hash_free);
376
377         /*  free the atomlist. */
378         afs_atomlist_destroy(al_mem_pool);
379
380         /* free the hashlist. */
381         afs_lhash_destroy(lh_mem_htab);
382         
383         /* change the state so that the allocator is now uninitialized. */
384         allocator_init = 0;
385     }
386     up(&afs_linux_alloc_sem);    
387 }
388
389 /* osi_linux_verify_alloced_memory(): verify all chunks of alloced memory in
390  *          our hash table.
391  */
392 void osi_linux_verify_alloced_memory()
393 {
394     down(&afs_linux_alloc_sem);
395     
396     /* count of times hash_verify was called. reset it to 0 before iteration */
397     afs_linux_hash_verify_count = 0;
398
399     /* iterate thru elements in the hash table */
400     afs_lhash_iter(lh_mem_htab, hash_verify);
401
402     if (afs_linux_hash_verify_count != afs_linux_cur_allocs) {
403         /* hmm, some pieces of memory are missing. */
404         printf("osi_linux_verify_alloced_memory: %d chunks of memory are not accounted for during verify!\n", afs_linux_hash_verify_count - afs_linux_cur_allocs);
405     }
406
407     up(&afs_linux_alloc_sem);
408     return;
409 }
410