af2fe7b78d8aff5321cf122079be8d9a6a713625
[samba.git] / source3 / ubiqx / ubi_Cache.c
1 /* ========================================================================== **
2  *                                 ubi_Cache.c
3  *
4  *  Copyright (C) 1997 by Christopher R. Hertel
5  *
6  *  Email: crh@ubiqx.mn.org
7  * -------------------------------------------------------------------------- **
8  *
9  *  This module implements a generic cache.
10  *
11  * -------------------------------------------------------------------------- **
12  *
13  *  This library is free software; you can redistribute it and/or
14  *  modify it under the terms of the GNU Library General Public
15  *  License as published by the Free Software Foundation; either
16  *  version 2 of the License, or (at your option) any later version.
17  *
18  *  This library is distributed in the hope that it will be useful,
19  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
20  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21  *  Library General Public License for more details.
22  *
23  *  You should have received a copy of the GNU Library General Public
24  *  License along with this library; if not, write to the Free
25  *  Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
26  *
27  * -------------------------------------------------------------------------- **
28  *
29  *  This module uses a splay tree to implement a simple cache.  The cache
30  *  module adds a thin layer of functionality to the splay tree.  In
31  *  particular:
32  *
33  *    - The tree (cache) may be limited in size by the number of
34  *      entries permitted or the amount of memory used.  When either
35  *      limit is exceeded cache entries are removed until the cache
36  *      conforms.
37  *    - Some statistical information is kept so that an approximate
38  *      "hit ratio" can be calculated.
39  *    - There are several functions available that provide access to
40  *      and management of cache size limits, hit ratio, and tree
41  *      trimming.
42  *
43  *  The splay tree is used because recently accessed items tend toward the
44  *  top of the tree and less recently accessed items tend toward the bottom.
45  *  This makes it easy to purge less recently used items should the cache
46  *  exceed its limits.
47  *
48  *  To use this module, you will need to supply a comparison function of
49  *  type ubi_trCompFunc and a node-freeing function of type
50  *  ubi_trKillNodeTrn.  See ubi_BinTree.h for more information on
51  *  these.  (This is all basic ubiqx tree management stuff.)
52  *
53  *  Notes:
54  *
55  *  - Cache performance will start to suffer dramatically if the
56  *    cache becomes large enough to force the OS to start swapping
57  *    memory to disk.  This is because the nodes of the underlying tree
58  *    will be scattered across memory in an order that is completely
59  *    unrelated to their traversal order.  As more and more of the
60  *    cache is placed into swap space, more and more swaps will be
61  *    required for a simple traversal (...and then there's the splay
62  *    operation).
63  *
64  *    In one simple test under Linux, the load and dump of a cache of
65  *    400,000 entries took only 1min, 40sec of real time.  The same
66  *    test with 450,000 records took 2 *hours* and eight minutes.
67  *
68  *  - In an effort to save memory, I considered using an unsigned
69  *    short to save the per-entry entry size.  I would have tucked this
70  *    value into some unused space in the tree node structure.  On
71  *    32-bit word aligned systems this would have saved an additional
72  *    four bytes per entry.  I may revisit this issue, but for now I've
73  *    decided against it.
74  *
75  *    Using an unsigned short would limit the size of an entry to 64K
76  *    bytes.  That's probably more than enough for most applications.
77  *    The key word in that last sentence, however, is "probably".  I
78  *    really dislike imposing such limits on things.
79  *
80  *  - Each entry keeps track of the amount of memory it used and the
81  *    cache header keeps the total.  This information is provided via
82  *    the EntrySize parameter in ubi_cachePut(), so it is up to you to
83  *    make sure that the numbers are accurate.  (The numbers don't even
84  *    have to represent bytes used.)
85  *
86  *    As you consider this, note that the strdup() function--as an
87  *    example--will call malloc().  The latter generally allocates a
88  *    multiple of the system word size, which may be more than the
89  *    number of bytes needed to store the string.
90  *
91  * -------------------------------------------------------------------------- **
92  *
93  *  Log: ubi_Cache.c,v 
94  *  Revision 0.1  1998/05/20 04:36:02  crh
95  *  The C file now includes ubi_null.h.  See ubi_null.h for more info.
96  *
97  *  Revision 0.0  1997/12/18 06:24:33  crh
98  *  Initial Revision.
99  *
100  * ========================================================================== **
101  */
102
103 #include "ubi_null.h"     /* ubiqx NULL source.       */
104 #include "ubi_Cache.h"    /* Header for *this* module. */
105
106 /* -------------------------------------------------------------------------- **
107  * Static data...
108  */
109
110 /*  commented out until I make use of it...
111 static char ModuleID[] = 
112 "ubi_Cache\n\
113 \tRevision: 0.1 \n\
114 \tDate: 1998/05/20 04:36:02 \n\
115 \tAuthor: crh \n";
116 */
117
118 /* -------------------------------------------------------------------------- **
119  * Internal functions...
120  */
121
122 static void free_entry( ubi_cacheRootPtr CachePtr, ubi_cacheEntryPtr EntryPtr )
123   /* ------------------------------------------------------------------------ **
124    * Free a ubi_cacheEntry, and adjust the mem_used counter accordingly.
125    *
126    *  Input:  CachePtr  - A pointer to the cache from which the entry has
127    *                      been removed.
128    *          EntryPtr  - A pointer to the already removed entry.
129    *
130    *  Output: none.
131    *
132    *  Notes:  The entry must be removed from the cache *before* this function
133    *          is called!!!!
134    * ------------------------------------------------------------------------ **
135    */
136   {
137   CachePtr->mem_used -= EntryPtr->entry_size;
138   (*CachePtr->free_func)( (void *)EntryPtr );
139   } /* free_entry */
140
141 static void cachetrim( ubi_cacheRootPtr crptr )
142   /* ------------------------------------------------------------------------ **
143    * Remove entries from the cache until the number of entries and the amount
144    * of memory used are *both* below or at the maximum.
145    *
146    *  Input:  crptr - pointer to the cache to be trimmed.
147    *
148    *  Output: None.
149    *
150    * ------------------------------------------------------------------------ **
151    */
152   {
153   while( ( crptr->max_entries && (crptr->max_entries < crptr->root.count) )
154       || ( crptr->max_memory  && (crptr->max_memory  < crptr->mem_used)   ) )
155     {
156     if( !ubi_cacheReduce( crptr, 1 ) )
157       return;
158     }
159   } /* cachetrim */
160
161
162 /* -------------------------------------------------------------------------- **
163  * Exported functions...
164  */
165
166 ubi_cacheRootPtr ubi_cacheInit( ubi_cacheRootPtr  CachePtr,
167                                 ubi_trCompFunc    CompFunc,
168                                 ubi_trKillNodeRtn FreeFunc,
169                                 unsigned long     MaxEntries,
170                                 unsigned long     MaxMemory )
171   /* ------------------------------------------------------------------------ **
172    * Initialize a cache header structure.
173    *
174    *  Input:  CachePtr    - A pointer to a ubi_cacheRoot structure that is
175    *                        to be initialized.
176    *          CompFunc    - A pointer to the function that will be called
177    *                        to compare two cache values.  See the module
178    *                        comments, above, for more information.
179    *          FreeFunc    - A pointer to a function that will be called
180    *                        to free a cache entry.  If you allocated
181    *                        the cache entry using malloc(), then this
182    *                        will likely be free().  If you are allocating
183    *                        cache entries from a free list, then this will
184    *                        likely be a function that returns memory to the
185    *                        free list, etc.
186    *          MaxEntries  - The maximum number of entries that will be
187    *                        allowed to exist in the cache.  If this limit
188    *                        is exceeded, then existing entries will be
189    *                        removed from the cache.  A value of zero
190    *                        indicates that there is no limit on the number
191    *                        of cache entries.  See ubi_cachePut().
192    *          MaxMemory   - The maximum amount of memory, in bytes, to be
193    *                        allocated to the cache (excluding the cache
194    *                        header).  If this is exceeded, existing entries
195    *                        in the cache will be removed until enough memory
196    *                        has been freed to meet the condition.  See
197    *                        ubi_cachePut().
198    *
199    *  Output: A pointer to the initialized cache (i.e., the same as CachePtr).
200    *
201    *  Notes:  Both MaxEntries and MaxMemory may be changed after the cache
202    *          has been created.  See
203    *            ubi_cacheSetMaxEntries() 
204    *            ubi_cacheSetMaxMemory()
205    *            ubi_cacheGetMaxEntries()
206    *            ubi_cacheGetMaxMemory()    (the latter two are macros).
207    *
208    *        - Memory is allocated in multiples of the word size.  The
209    *          return value of the strlen() function does not reflect
210    *          this; it will allways be less than or equal to the amount
211    *          of memory actually allocated.  Keep this in mind when
212    *          choosing a value for MaxMemory.
213    *
214    * ------------------------------------------------------------------------ **
215    */
216   {
217   if( CachePtr )
218     {
219     (void)ubi_trInitTree( CachePtr, CompFunc, ubi_trOVERWRITE );
220     CachePtr->free_func   = FreeFunc;
221     CachePtr->max_entries = MaxEntries;
222     CachePtr->max_memory  = MaxMemory;
223     CachePtr->mem_used    = 0;
224     CachePtr->cache_hits  = 0;
225     CachePtr->cache_trys  = 0;
226     }
227   return( CachePtr );
228   } /* ubi_cacheInit */
229
230 ubi_cacheRootPtr ubi_cacheClear( ubi_cacheRootPtr CachePtr )
231   /* ------------------------------------------------------------------------ **
232    * Remove and free all entries in an existing cache.
233    *
234    *  Input:  CachePtr  - A pointer to the cache that is to be cleared.
235    *
236    *  Output: A pointer to the cache header (i.e., the same as CachePtr).
237    *          This function re-initializes the cache header.
238    *
239    * ------------------------------------------------------------------------ **
240    */
241   {
242   if( CachePtr )
243     {
244     (void)ubi_trKillTree( CachePtr, CachePtr->free_func );
245     CachePtr->mem_used    = 0;
246     CachePtr->cache_hits  = 0;
247     CachePtr->cache_trys  = 0;
248     }
249   return( CachePtr );
250   } /* ubi_cacheClear */
251
252 void ubi_cachePut( ubi_cacheRootPtr  CachePtr,
253                    unsigned long     EntrySize,
254                    ubi_cacheEntryPtr EntryPtr,
255                    ubi_trItemPtr     Key )
256   /* ------------------------------------------------------------------------ **
257    * Add an entry to the cache.
258    *
259    *  Input:  CachePtr  - A pointer to the cache into which the entry
260    *                      will be added.
261    *          EntrySize - The size, in bytes, of the memory block indicated
262    *                      by EntryPtr.  This will be copied into the
263    *                      EntryPtr->entry_size field.
264    *          EntryPtr  - A pointer to a memory block that begins with a
265    *                      ubi_cacheEntry structure.  The entry structure
266    *                      should be followed immediately by the data to be
267    *                      cached (even if that is a pointer to yet more data).
268    *          Key       - Pointer used to identify the lookup key within the
269    *                      Entry.
270    *
271    *  Output: None.
272    *
273    *  Notes:  After adding the new node, the cache is "trimmed".  This
274    *          removes extra nodes if the tree has exceeded it's memory or
275    *          entry count limits.  It is unlikely that the newly added node
276    *          will be purged from the cache (assuming a reasonably large
277    *          cache), since new nodes in a splay tree (which is what this
278    *          module was designed to use) are moved to the top of the tree
279    *          and the cache purge process removes nodes from the bottom of
280    *          the tree.
281    *        - The underlying splay tree is opened in OVERWRITE mode.  If
282    *          the input key matches an existing key, the existing entry will
283    *          be politely removed from the tree and freed.
284    *        - Memory is allocated in multiples of the word size.  The
285    *          return value of the strlen() function does not reflect
286    *          this; it will allways be less than or equal to the amount
287    *          of memory actually allocated.
288    *
289    * ------------------------------------------------------------------------ **
290    */
291   {
292   ubi_trNodePtr OldNode;
293
294   EntryPtr->entry_size = EntrySize;
295   CachePtr->mem_used  += EntrySize;
296   (void)ubi_trInsert( CachePtr, EntryPtr, Key, &OldNode );
297   if( OldNode )
298     free_entry( CachePtr, (ubi_cacheEntryPtr)OldNode );
299
300   cachetrim( CachePtr );
301   } /* ubi_cachePut */
302
303 ubi_cacheEntryPtr ubi_cacheGet( ubi_cacheRootPtr CachePtr,
304                                 ubi_trItemPtr    FindMe )
305   /* ------------------------------------------------------------------------ **
306    * Attempt to retrieve an entry from the cache.
307    *
308    *  Input:  CachePtr  - A ponter to the cache that is to be searched.
309    *          FindMe    - A ubi_trItemPtr that indicates the key for which
310    *                      to search.
311    *
312    *  Output: A pointer to the cache entry that was found, or NULL if no
313    *          matching entry was found.
314    *
315    *  Notes:  This function also updates the hit ratio counters.
316    *          The counters are unsigned short.  If the number of cache tries
317    *          reaches 32768, then both the number of tries and the number of
318    *          hits are divided by two.  This prevents the counters from
319    *          overflowing.  See the comments in ubi_cacheHitRatio() for
320    *          additional notes.
321    *
322    * ------------------------------------------------------------------------ **
323    */
324   {
325   ubi_trNodePtr FoundPtr;
326
327   FoundPtr = ubi_trFind( CachePtr, FindMe );
328
329   if( FoundPtr )
330     CachePtr->cache_hits++;
331   CachePtr->cache_trys++;
332
333   if( CachePtr->cache_trys & 0x8000 )
334     {
335     CachePtr->cache_hits = CachePtr->cache_hits / 2;
336     CachePtr->cache_trys = CachePtr->cache_trys / 2;
337     }
338
339   return( (ubi_cacheEntryPtr)FoundPtr );
340   } /* ubi_cacheGet */
341
342 ubi_trBool ubi_cacheDelete( ubi_cacheRootPtr CachePtr, ubi_trItemPtr DeleteMe )
343   /* ------------------------------------------------------------------------ **
344    * Find and delete the specified cache entry.
345    *
346    *  Input:  CachePtr  - A pointer to the cache.
347    *          DeleteMe  - The key of the entry to be deleted.
348    *
349    *  Output: TRUE if the entry was found & freed, else FALSE.
350    *
351    * ------------------------------------------------------------------------ **
352    */
353   {
354   ubi_trNodePtr FoundPtr;
355
356   FoundPtr = ubi_trFind( CachePtr, DeleteMe );
357   if( FoundPtr )
358     {
359     (void)ubi_trRemove( CachePtr, FoundPtr );
360     free_entry( CachePtr, (ubi_cacheEntryPtr)FoundPtr );
361     return( ubi_trTRUE );
362     }
363   return( ubi_trFALSE );
364   } /* ubi_cacheDelete */
365
366 ubi_trBool ubi_cacheReduce( ubi_cacheRootPtr CachePtr, unsigned long count )
367   /* ------------------------------------------------------------------------ **
368    * Remove <count> entries from the bottom of the cache.
369    *
370    *  Input:  CachePtr  - A pointer to the cache which is to be reduced in
371    *                      size.
372    *          count     - The number of entries to remove.
373    *
374    *  Output: The function will return TRUE if <count> entries were removed,
375    *          else FALSE.  A return value of FALSE should indicate that
376    *          there were less than <count> entries in the cache, and that the
377    *          cache is now empty.
378    *
379    *  Notes:  This function forces a reduction in the number of cache entries
380    *          without requiring that the MaxMemory or MaxEntries values be
381    *          changed.
382    *
383    * ------------------------------------------------------------------------ **
384    */
385   {
386   ubi_trNodePtr NodePtr;
387
388   while( count )
389     {
390     NodePtr = ubi_trLeafNode( CachePtr->root.root );
391     if( NULL == NodePtr )
392       return( ubi_trFALSE );
393     else
394       {
395       (void)ubi_trRemove( CachePtr, NodePtr );
396       free_entry( CachePtr, (ubi_cacheEntryPtr)NodePtr );
397       }
398     count--;
399     }
400   return( ubi_trTRUE );
401   } /* ubi_cacheReduce */
402
403 unsigned long ubi_cacheSetMaxEntries( ubi_cacheRootPtr CachePtr,
404                                       unsigned long    NewSize )
405   /* ------------------------------------------------------------------------ **
406    * Change the maximum number of entries allowed to exist in the cache.
407    *
408    *  Input:  CachePtr  - A pointer to the cache to be modified.
409    *          NewSize   - The new maximum number of cache entries.
410    *
411    *  Output: The maximum number of entries previously allowed to exist in
412    *          the cache.
413    *
414    *  Notes:  If the new size is less than the old size, this function will
415    *          trim the cache (remove excess entries).
416    *        - A value of zero indicates an unlimited number of entries.
417    *
418    * ------------------------------------------------------------------------ **
419    */
420   {
421   unsigned long oldsize = CachePtr->max_entries;      /* Save the old value.  */
422
423   CachePtr->max_entries = NewSize;                    /* Apply the new value. */
424   if( (NewSize < oldsize) || (NewSize && !oldsize) )  /* If size is smaller,  */
425     cachetrim( CachePtr );                            /*   remove excess.     */
426   return( oldsize );
427   } /* ubi_cacheSetMaxEntries */
428
429 unsigned long ubi_cacheSetMaxMemory( ubi_cacheRootPtr CachePtr,
430                                      unsigned long    NewSize )
431   /* ------------------------------------------------------------------------ **
432    * Change the maximum amount of memory to be used for storing cache
433    * entries.
434    *
435    *  Input:  CachePtr  - A pointer to the cache to be modified.
436    *          NewSize   - The new cache memory size.
437    *
438    *  Output: The previous maximum memory size.
439    *
440    *  Notes:  If the new size is less than the old size, this function will
441    *          trim the cache (remove excess entries).
442    *        - A value of zero indicates that the cache has no memory limit.
443    *
444    * ------------------------------------------------------------------------ **
445    */
446   {
447   unsigned long oldsize = CachePtr->max_memory;       /* Save the old value.  */
448
449   CachePtr->max_memory = NewSize;                     /* Apply the new value. */
450   if( (NewSize < oldsize) || (NewSize && !oldsize) )  /* If size is smaller,  */
451     cachetrim( CachePtr );                            /*   remove excess.     */
452   return( oldsize );
453   } /* ubi_cacheSetMaxMemory */
454
455 int ubi_cacheHitRatio( ubi_cacheRootPtr CachePtr )
456   /* ------------------------------------------------------------------------ **
457    * Returns a value that is 10,000 times the slightly weighted average hit
458    * ratio for the cache.
459    *
460    *  Input:  CachePtr  - Pointer to the cache to be queried.
461    *
462    *  Output: An integer that is 10,000 times the number of successful
463    *          cache hits divided by the number of cache lookups, or:
464    *            (10000 * hits) / trys
465    *          You can easily convert this to a float, or do something
466    *          like this (where i is the return value of this function):
467    *
468    *            printf( "Hit rate   : %d.%02d%%\n", (i/100), (i%100) );
469    *
470    *  Notes:  I say "slightly-weighted", because the numerator and
471    *          denominator are both accumulated in locations of type
472    *          'unsigned short'.  If the number of cache trys becomes
473    *          large enough, both are divided  by two.  (See function
474    *          ubi_cacheGet().) 
475    *          Dividing both numerator and denominator by two does not
476    *          change the ratio (much...it is an integer divide), but it
477    *          does mean that subsequent increments to either counter will
478    *          have twice as much significance as previous ones.
479    *
480    *        - The value returned by this function will be in the range
481    *          [0..10000] because ( 0 <= cache_hits <= cache_trys ) will
482    *          always be true.
483    *
484    * ------------------------------------------------------------------------ **
485    */
486   {
487   int tmp = 0;
488
489   if( CachePtr->cache_trys )
490     tmp = (int)( (10000 * (long)(CachePtr->cache_hits) )
491                         / (long)(CachePtr->cache_trys) );
492   return( tmp );
493   } /* ubi_cacheHitRatio */
494
495 /* -------------------------------------------------------------------------- */