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