first public release
[dpdk.git] / lib / librte_hash / rte_fbk_hash.h
1 /*-
2  *   BSD LICENSE
3  * 
4  *   Copyright(c) 2010-2012 Intel Corporation. All rights reserved.
5  *   All rights reserved.
6  * 
7  *   Redistribution and use in source and binary forms, with or without 
8  *   modification, are permitted provided that the following conditions 
9  *   are met:
10  * 
11  *     * Redistributions of source code must retain the above copyright 
12  *       notice, this list of conditions and the following disclaimer.
13  *     * Redistributions in binary form must reproduce the above copyright 
14  *       notice, this list of conditions and the following disclaimer in 
15  *       the documentation and/or other materials provided with the 
16  *       distribution.
17  *     * Neither the name of Intel Corporation nor the names of its 
18  *       contributors may be used to endorse or promote products derived 
19  *       from this software without specific prior written permission.
20  * 
21  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
22  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
23  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 
24  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
25  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
26  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 
27  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
28  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 
29  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
30  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 
31  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  * 
33  *  version: DPDK.L.1.2.3-3
34  */
35
36 #ifndef _RTE_FBK_HASH_H_
37 #define _RTE_FBK_HASH_H_
38
39 /**
40  * @file
41  *
42  * This is a hash table implementation for four byte keys (fbk).
43  *
44  * Note that the return value of the add function should always be checked as,
45  * if a bucket is full, the key is not added even if there is space in other
46  * buckets. This keeps the lookup function very simple and therefore fast.
47  */
48
49 #include <stdint.h>
50 #include <errno.h>
51 #include <sys/queue.h>
52 #include <rte_hash_crc.h>
53
54 #ifdef __cplusplus
55 extern "C" {
56 #endif
57
58 #include <string.h>
59
60 #ifndef RTE_FBK_HASH_FUNC_DEFAULT
61 /** Default four-byte key hash function if none is specified. */
62 #define RTE_FBK_HASH_FUNC_DEFAULT               rte_hash_crc_4byte
63 #endif
64
65 #ifndef RTE_FBK_HASH_INIT_VAL_DEFAULT
66 /** Initialising value used when calculating hash. */
67 #define RTE_FBK_HASH_INIT_VAL_DEFAULT           0xFFFFFFFF
68 #endif
69
70 /** The maximum number of entries in the hash table that is supported. */
71 #define RTE_FBK_HASH_ENTRIES_MAX                (1 << 20)
72
73 /** The maximum number of entries in each bucket that is supported. */
74 #define RTE_FBK_HASH_ENTRIES_PER_BUCKET_MAX     256
75
76 /** Maximum size of string for naming the hash. */
77 #define RTE_FBK_HASH_NAMESIZE                   32
78
79 /** Type of function that can be used for calculating the hash value. */
80 typedef uint32_t (*rte_fbk_hash_fn)(uint32_t key, uint32_t init_val);
81
82 /** Parameters used when creating four-byte key hash table. */
83 struct rte_fbk_hash_params {
84         const char *name;               /**< Name of the hash table. */
85         uint32_t entries;               /**< Total number of entries. */
86         uint32_t entries_per_bucket;    /**< Number of entries in a bucket. */
87         int socket_id;                  /**< Socket to allocate memory on. */
88         rte_fbk_hash_fn hash_func;      /**< The hash function. */
89         uint32_t init_val;              /**< For initialising hash function. */
90 };
91
92 /** Individual entry in the four-byte key hash table. */
93 union rte_fbk_hash_entry {
94         uint64_t whole_entry;           /**< For accessing entire entry. */
95         struct {
96                 uint16_t is_entry;      /**< Non-zero if entry is active. */
97                 uint16_t value;         /**< Value returned by lookup. */
98                 uint32_t key;           /**< Key used to find value. */
99         } entry;                        /**< For accessing each entry part. */
100 } ;
101
102
103
104 /** The four-byte key hash table structure. */
105 struct rte_fbk_hash_table {
106         TAILQ_ENTRY(rte_fbk_hash_table) next;   /**< Linked list. */
107
108         char name[RTE_FBK_HASH_NAMESIZE];       /**< Name of the hash. */
109         uint32_t entries;               /**< Total number of entries. */
110         uint32_t entries_per_bucket;    /**< Number of entries in a bucket. */
111         uint32_t used_entries;          /**< How many entries are used. */
112         uint32_t bucket_mask;           /**< To find which bucket the key is in. */
113         uint32_t bucket_shift;          /**< Convert bucket to table offset. */
114         rte_fbk_hash_fn hash_func;      /**< The hash function. */
115         uint32_t init_val;              /**< For initialising hash function. */
116
117         /** A flat table of all buckets. */
118         union rte_fbk_hash_entry t[0];
119 };
120
121 /**
122  * Find the offset into hash table of the bucket containing a particular key.
123  *
124  * @param ht
125  *   Pointer to hash table.
126  * @param key
127  *   Key to calculate bucket for.
128  * @return
129  *   Offset into hash table.
130  */
131 static inline uint32_t
132 rte_fbk_hash_get_bucket(const struct rte_fbk_hash_table *ht, uint32_t key)
133 {
134         return (ht->hash_func(key, ht->init_val) & ht->bucket_mask) <<
135                         ht->bucket_shift;
136 }
137
138
139 /**
140  * Add a key to an existing hash table. This operation is not multi-thread safe
141  * and should only be called from one thread.
142  *
143  * @param ht
144  *   Hash table to add the key to.
145  * @param key
146  *   Key to add to the hash table.
147  * @param value
148  *   Value to associate with key.
149  * @return
150  *   0 if ok, or negative value on error.
151  */
152 static inline int
153 rte_fbk_hash_add_key(struct rte_fbk_hash_table *ht,
154                         uint32_t key, uint16_t value)
155 {
156         /*
157          * The writing of a new value to the hash table is done as a single
158          * 64bit operation. This should help prevent individual entries being
159          * corrupted due to race conditions, but it's still possible to
160          * overwrite entries that have just been made valid.
161          */
162         const uint64_t new_entry = ((uint64_t)(key) << 32) |
163                         ((uint64_t)(value) << 16) |
164                         1;  /* 1 = is_entry bit. */
165         const uint32_t bucket = rte_fbk_hash_get_bucket(ht, key);
166         uint32_t i;
167
168         for (i = 0; i < ht->entries_per_bucket; i++) {
169                 /* Set entry if unused. */
170                 if (! ht->t[bucket + i].entry.is_entry) {
171                         ht->t[bucket + i].whole_entry = new_entry;
172                         ht->used_entries++;
173                         return 0;
174                 }
175                 /* Change value if key already exists. */
176                 if (ht->t[bucket + i].entry.key == key) {
177                         ht->t[bucket + i].entry.value = value;
178                         return 0;
179                 }
180         }
181
182         return -ENOSPC; /* No space in bucket. */
183 }
184
185 /**
186  * Remove a key from an existing hash table. This operation is not multi-thread
187  * safe and should only be called from one thread.
188  *
189  * @param ht
190  *   Hash table to remove the key from.
191  * @param key
192  *   Key to remove from the hash table.
193  * @return
194  *   0 if ok, or negative value on error.
195  */
196 static inline int
197 rte_fbk_hash_delete_key(struct rte_fbk_hash_table *ht, uint32_t key)
198 {
199         const uint32_t bucket = rte_fbk_hash_get_bucket(ht, key);
200         uint32_t last_entry = ht->entries_per_bucket - 1;
201         uint32_t i, j;
202
203         for (i = 0; i < ht->entries_per_bucket; i++) {
204                 if (ht->t[bucket + i].entry.key == key) {
205                         /* Find last key in bucket. */
206                         for (j = ht->entries_per_bucket - 1; j > i; j-- ) {
207                                 if (! ht->t[bucket + j].entry.is_entry) {
208                                         last_entry = j - 1;
209                                 }
210                         }
211                         /*
212                          * Move the last key to the deleted key's position, and
213                          * delete the last key. lastEntry and i may be same but
214                          * it doesn't matter.
215                          */
216                         ht->t[bucket + i].whole_entry =
217                                         ht->t[bucket + last_entry].whole_entry;
218                         ht->t[bucket + last_entry].whole_entry = 0;
219
220                         ht->used_entries--;
221                         return 0;
222                 }
223         }
224
225         return -ENOENT; /* Key didn't exist. */
226 }
227
228 /**
229  * Find a key in the hash table. This operation is multi-thread safe.
230  *
231  * @param ht
232  *   Hash table to look in.
233  * @param key
234  *   Key to find.
235  * @return
236  *   The value that was associated with the key, or negative value on error.
237  */
238 static inline int
239 rte_fbk_hash_lookup(const struct rte_fbk_hash_table *ht, uint32_t key)
240 {
241         const uint32_t bucket = rte_fbk_hash_get_bucket(ht, key);
242         union rte_fbk_hash_entry current_entry;
243         uint32_t i;
244
245         for (i = 0; i < ht->entries_per_bucket; i++) {
246                 /* Single read of entry, which should be atomic. */
247                 current_entry.whole_entry = ht->t[bucket + i].whole_entry;
248                 if (! current_entry.entry.is_entry) {
249                         return -ENOENT; /* Error once we hit an empty field. */
250                 }
251                 if (current_entry.entry.key == key) {
252                         return current_entry.entry.value;
253                 }
254         }
255         return -ENOENT; /* Key didn't exist. */
256 }
257
258 /**
259  * Delete all entries in a hash table. This operation is not multi-thread
260  * safe and should only be called from one thread.
261  *
262  * @param ht
263  *   Hash table to delete entries in.
264  */
265 static inline void
266 rte_fbk_hash_clear_all(struct rte_fbk_hash_table *ht)
267 {
268         memset(ht->t, 0, sizeof(ht->t[0]) * ht->entries);
269         ht->used_entries = 0;
270 }
271
272 /**
273  * Find what fraction of entries are being used.
274  *
275  * @param ht
276  *   Hash table to find how many entries are being used in.
277  * @return
278  *   Load factor of the hash table, or negative value on error.
279  */
280 static inline double
281 rte_fbk_hash_get_load_factor(struct rte_fbk_hash_table *ht)
282 {
283         return (double)ht->used_entries / (double)ht->entries;
284 }
285
286 /**
287  * Performs a lookup for an existing hash table, and returns a pointer to
288  * the table if found.
289  *
290  * @param name
291  *   Name of the hash table to find
292  *
293  * @return
294  *   pointer to hash table structure or NULL on error with rte_errno
295  *   set appropriately. Possible rte_errno values include:
296  *    - ENOENT - required entry not available to return.
297  */
298 struct rte_fbk_hash_table *rte_fbk_hash_find_existing(const char *name);
299
300 /**
301  * Create a new hash table for use with four byte keys.
302  *
303  * @param params
304  *   Parameters used in creation of hash table.
305  *
306  * @return
307  *   Pointer to hash table structure that is used in future hash table
308  *   operations, or NULL on error with rte_errno set appropriately.
309  *   Possible rte_errno error values include:
310  *    - E_RTE_NO_CONFIG - function could not get pointer to rte_config structure
311  *    - E_RTE_SECONDARY - function was called from a secondary process instance
312  *    - E_RTE_NO_TAILQ - no tailq list could be got for the fbk hash table list
313  *    - EINVAL - invalid parameter value passed to function
314  *    - ENOSPC - the maximum number of memzones has already been allocated
315  *    - EEXIST - a memzone with the same name already exists
316  *    - ENOMEM - no appropriate memory area found in which to create memzone
317  */
318 struct rte_fbk_hash_table * \
319 rte_fbk_hash_create(const struct rte_fbk_hash_params *params);
320
321 /**
322  * Free all memory used by a hash table.
323  * Has no effect on hash tables allocated in memory zones
324  *
325  * @param ht
326  *   Hash table to deallocate.
327  */
328 void rte_fbk_hash_free(struct rte_fbk_hash_table *ht);
329
330 #ifdef __cplusplus
331 }
332 #endif
333
334 #endif /* _RTE_FBK_HASH_H_ */