6cd048e7e9d0fedb51539d3bc61bb8d59bc4f509
[dpdk.git] / lib / librte_hash / rte_fbk_hash.h
1 /*-
2  *   BSD LICENSE
3  * 
4  *   Copyright(c) 2010-2013 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  */
34
35 #ifndef _RTE_FBK_HASH_H_
36 #define _RTE_FBK_HASH_H_
37
38 /**
39  * @file
40  *
41  * This is a hash table implementation for four byte keys (fbk).
42  *
43  * Note that the return value of the add function should always be checked as,
44  * if a bucket is full, the key is not added even if there is space in other
45  * buckets. This keeps the lookup function very simple and therefore fast.
46  */
47
48 #include <stdint.h>
49 #include <errno.h>
50 #include <sys/queue.h>
51
52 #ifdef __cplusplus
53 extern "C" {
54 #endif
55
56 #include <string.h>
57
58 #ifndef RTE_FBK_HASH_FUNC_DEFAULT
59 #ifdef RTE_MACHINE_CPUFLAG_SSE4_2
60 #include <rte_hash_crc.h>
61 /** Default four-byte key hash function if none is specified. */
62 #define RTE_FBK_HASH_FUNC_DEFAULT               rte_hash_crc_4byte
63 #else
64 #include <rte_jhash.h>
65 #define RTE_FBK_HASH_FUNC_DEFAULT               rte_jhash_1word
66 #endif
67 #endif
68
69 #ifndef RTE_FBK_HASH_INIT_VAL_DEFAULT
70 /** Initialising value used when calculating hash. */
71 #define RTE_FBK_HASH_INIT_VAL_DEFAULT           0xFFFFFFFF
72 #endif
73
74 /** The maximum number of entries in the hash table that is supported. */
75 #define RTE_FBK_HASH_ENTRIES_MAX                (1 << 20)
76
77 /** The maximum number of entries in each bucket that is supported. */
78 #define RTE_FBK_HASH_ENTRIES_PER_BUCKET_MAX     256
79
80 /** Maximum size of string for naming the hash. */
81 #define RTE_FBK_HASH_NAMESIZE                   32
82
83 /** Type of function that can be used for calculating the hash value. */
84 typedef uint32_t (*rte_fbk_hash_fn)(uint32_t key, uint32_t init_val);
85
86 /** Parameters used when creating four-byte key hash table. */
87 struct rte_fbk_hash_params {
88         const char *name;               /**< Name of the hash table. */
89         uint32_t entries;               /**< Total number of entries. */
90         uint32_t entries_per_bucket;    /**< Number of entries in a bucket. */
91         int socket_id;                  /**< Socket to allocate memory on. */
92         rte_fbk_hash_fn hash_func;      /**< The hash function. */
93         uint32_t init_val;              /**< For initialising hash function. */
94 };
95
96 /** Individual entry in the four-byte key hash table. */
97 union rte_fbk_hash_entry {
98         uint64_t whole_entry;           /**< For accessing entire entry. */
99         struct {
100                 uint16_t is_entry;      /**< Non-zero if entry is active. */
101                 uint16_t value;         /**< Value returned by lookup. */
102                 uint32_t key;           /**< Key used to find value. */
103         } entry;                        /**< For accessing each entry part. */
104 };
105
106
107
108 /** The four-byte key hash table structure. */
109 struct rte_fbk_hash_table {
110         TAILQ_ENTRY(rte_fbk_hash_table) next;   /**< Linked list. */
111
112         char name[RTE_FBK_HASH_NAMESIZE];       /**< Name of the hash. */
113         uint32_t entries;               /**< Total number of entries. */
114         uint32_t entries_per_bucket;    /**< Number of entries in a bucket. */
115         uint32_t used_entries;          /**< How many entries are used. */
116         uint32_t bucket_mask;           /**< To find which bucket the key is in. */
117         uint32_t bucket_shift;          /**< Convert bucket to table offset. */
118         rte_fbk_hash_fn hash_func;      /**< The hash function. */
119         uint32_t init_val;              /**< For initialising hash function. */
120
121         /** A flat table of all buckets. */
122         union rte_fbk_hash_entry t[0];
123 };
124
125 /**
126  * Find the offset into hash table of the bucket containing a particular key.
127  *
128  * @param ht
129  *   Pointer to hash table.
130  * @param key
131  *   Key to calculate bucket for.
132  * @return
133  *   Offset into hash table.
134  */
135 static inline uint32_t
136 rte_fbk_hash_get_bucket(const struct rte_fbk_hash_table *ht, uint32_t key)
137 {
138         return (ht->hash_func(key, ht->init_val) & ht->bucket_mask) <<
139                         ht->bucket_shift;
140 }
141
142 /**
143  * Add a key to an existing hash table with bucket id. 
144  * This operation is not multi-thread safe
145  * and should only be called from one thread.
146  *
147  * @param ht
148  *   Hash table to add the key to.
149  * @param key
150  *   Key to add to the hash table.
151  * @param value
152  *   Value to associate with key.
153  * @param bucket
154  *   Bucket to associate with key.
155  * @return
156  *   0 if ok, or negative value on error.
157  */
158 static inline int
159 rte_fbk_hash_add_key_with_bucket(struct rte_fbk_hash_table *ht,
160                         uint32_t key, uint16_t value, uint32_t bucket)
161 {
162         /*
163          * The writing of a new value to the hash table is done as a single
164          * 64bit operation. This should help prevent individual entries being
165          * corrupted due to race conditions, but it's still possible to
166          * overwrite entries that have just been made valid.
167          */
168         const uint64_t new_entry = ((uint64_t)(key) << 32) |
169                         ((uint64_t)(value) << 16) |
170                         1;  /* 1 = is_entry bit. */
171         uint32_t i;
172
173         for (i = 0; i < ht->entries_per_bucket; i++) {
174                 /* Set entry if unused. */
175                 if (! ht->t[bucket + i].entry.is_entry) {
176                         ht->t[bucket + i].whole_entry = new_entry;
177                         ht->used_entries++;
178                         return 0;
179                 }
180                 /* Change value if key already exists. */
181                 if (ht->t[bucket + i].entry.key == key) {
182                         ht->t[bucket + i].entry.value = value;
183                         return 0;
184                 }
185         }
186
187         return -ENOSPC; /* No space in bucket. */       
188 }
189
190 /**
191  * Add a key to an existing hash table. This operation is not multi-thread safe
192  * and should only be called from one thread.
193  *
194  * @param ht
195  *   Hash table to add the key to.
196  * @param key
197  *   Key to add to the hash table.
198  * @param value
199  *   Value to associate with key.
200  * @return
201  *   0 if ok, or negative value on error.
202  */
203 static inline int
204 rte_fbk_hash_add_key(struct rte_fbk_hash_table *ht,
205                         uint32_t key, uint16_t value)
206 {
207         return rte_fbk_hash_add_key_with_bucket(ht, 
208                                 key, value, rte_fbk_hash_get_bucket(ht, key));
209 }
210
211 /**
212  * Remove a key with a given bucket id from an existing hash table. 
213  * This operation is not multi-thread
214  * safe and should only be called from one thread.
215  *
216  * @param ht
217  *   Hash table to remove the key from.
218  * @param key
219  *   Key to remove from the hash table.
220  * @param bucket
221  *   Bucket id associate with key.
222  * @return
223  *   0 if ok, or negative value on error.
224  */
225 static inline int
226 rte_fbk_hash_delete_key_with_bucket(struct rte_fbk_hash_table *ht, 
227                                         uint32_t key, uint32_t bucket)
228 {
229         uint32_t last_entry = ht->entries_per_bucket - 1;
230         uint32_t i, j;
231
232         for (i = 0; i < ht->entries_per_bucket; i++) {
233                 if (ht->t[bucket + i].entry.key == key) {
234                         /* Find last key in bucket. */
235                         for (j = ht->entries_per_bucket - 1; j > i; j-- ) {
236                                 if (! ht->t[bucket + j].entry.is_entry) {
237                                         last_entry = j - 1;
238                                 }
239                         }
240                         /*
241                          * Move the last key to the deleted key's position, and
242                          * delete the last key. lastEntry and i may be same but
243                          * it doesn't matter.
244                          */
245                         ht->t[bucket + i].whole_entry =
246                                         ht->t[bucket + last_entry].whole_entry;
247                         ht->t[bucket + last_entry].whole_entry = 0;
248
249                         ht->used_entries--;
250                         return 0;
251                 }
252         }
253
254         return -ENOENT; /* Key didn't exist. */
255 }
256
257 /**
258  * Remove a key from an existing hash table. This operation is not multi-thread
259  * safe and should only be called from one thread.
260  *
261  * @param ht
262  *   Hash table to remove the key from.
263  * @param key
264  *   Key to remove from the hash table.
265  * @return
266  *   0 if ok, or negative value on error.
267  */
268 static inline int
269 rte_fbk_hash_delete_key(struct rte_fbk_hash_table *ht, uint32_t key)
270 {
271         return rte_fbk_hash_delete_key_with_bucket(ht, 
272                                 key, rte_fbk_hash_get_bucket(ht, key));
273 }
274
275 /**
276  * Find a key in the hash table with a given bucketid. 
277  * This operation is multi-thread safe.
278  *
279  * @param ht
280  *   Hash table to look in.
281  * @param key
282  *   Key to find.
283  * @param bucket
284  *   Bucket associate to the key.
285  * @return
286  *   The value that was associated with the key, or negative value on error.
287  */
288 static inline int
289 rte_fbk_hash_lookup_with_bucket(const struct rte_fbk_hash_table *ht, 
290                                 uint32_t key, uint32_t bucket)
291 {
292         union rte_fbk_hash_entry current_entry;
293         uint32_t i;
294
295         for (i = 0; i < ht->entries_per_bucket; i++) {
296                 /* Single read of entry, which should be atomic. */
297                 current_entry.whole_entry = ht->t[bucket + i].whole_entry;
298                 if (! current_entry.entry.is_entry) {
299                         return -ENOENT; /* Error once we hit an empty field. */
300                 }
301                 if (current_entry.entry.key == key) {
302                         return current_entry.entry.value;
303                 }
304         }
305         return -ENOENT; /* Key didn't exist. */
306 }
307
308 /**
309  * Find a key in the hash table. This operation is multi-thread safe.
310  *
311  * @param ht
312  *   Hash table to look in.
313  * @param key
314  *   Key to find.
315  * @return
316  *   The value that was associated with the key, or negative value on error.
317  */
318 static inline int
319 rte_fbk_hash_lookup(const struct rte_fbk_hash_table *ht, uint32_t key)
320 {
321         return rte_fbk_hash_lookup_with_bucket(ht,
322                                 key, rte_fbk_hash_get_bucket(ht, key));
323 }
324
325 /**
326  * Delete all entries in a hash table. This operation is not multi-thread
327  * safe and should only be called from one thread.
328  *
329  * @param ht
330  *   Hash table to delete entries in.
331  */
332 static inline void
333 rte_fbk_hash_clear_all(struct rte_fbk_hash_table *ht)
334 {
335         memset(ht->t, 0, sizeof(ht->t[0]) * ht->entries);
336         ht->used_entries = 0;
337 }
338
339 /**
340  * Find what fraction of entries are being used.
341  *
342  * @param ht
343  *   Hash table to find how many entries are being used in.
344  * @return
345  *   Load factor of the hash table, or negative value on error.
346  */
347 static inline double
348 rte_fbk_hash_get_load_factor(struct rte_fbk_hash_table *ht)
349 {
350         return (double)ht->used_entries / (double)ht->entries;
351 }
352
353 /**
354  * Performs a lookup for an existing hash table, and returns a pointer to
355  * the table if found.
356  *
357  * @param name
358  *   Name of the hash table to find
359  *
360  * @return
361  *   pointer to hash table structure or NULL on error with rte_errno
362  *   set appropriately. Possible rte_errno values include:
363  *    - ENOENT - required entry not available to return.
364  */
365 struct rte_fbk_hash_table *rte_fbk_hash_find_existing(const char *name);
366
367 /**
368  * Create a new hash table for use with four byte keys.
369  *
370  * @param params
371  *   Parameters used in creation of hash table.
372  *
373  * @return
374  *   Pointer to hash table structure that is used in future hash table
375  *   operations, or NULL on error with rte_errno set appropriately.
376  *   Possible rte_errno error values include:
377  *    - E_RTE_NO_CONFIG - function could not get pointer to rte_config structure
378  *    - E_RTE_SECONDARY - function was called from a secondary process instance
379  *    - E_RTE_NO_TAILQ - no tailq list could be got for the fbk hash table list
380  *    - EINVAL - invalid parameter value passed to function
381  *    - ENOSPC - the maximum number of memzones has already been allocated
382  *    - EEXIST - a memzone with the same name already exists
383  *    - ENOMEM - no appropriate memory area found in which to create memzone
384  */
385 struct rte_fbk_hash_table * \
386 rte_fbk_hash_create(const struct rte_fbk_hash_params *params);
387
388 /**
389  * Free all memory used by a hash table.
390  * Has no effect on hash tables allocated in memory zones
391  *
392  * @param ht
393  *   Hash table to deallocate.
394  */
395 void rte_fbk_hash_free(struct rte_fbk_hash_table *ht);
396
397 #ifdef __cplusplus
398 }
399 #endif
400
401 #endif /* _RTE_FBK_HASH_H_ */