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