suricata
util-thash.c
Go to the documentation of this file.
1 /* Copyright (C) 2007-2024 Open Information Security Foundation
2  *
3  * You can copy, redistribute or modify this Program under the terms of
4  * the GNU General Public License version 2 as published by the Free
5  * Software Foundation.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * version 2 along with this program; if not, write to the Free Software
14  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
15  * 02110-1301, USA.
16  */
17 
18 /**
19  * \file
20  *
21  * \author Victor Julien <victor@inliniac.net>
22  *
23  */
24 
25 #include "suricata-common.h"
26 #include "conf.h"
27 
28 #include "util-debug.h"
29 #include "util-thash.h"
30 
31 #include "util-random.h"
32 #include "util-misc.h"
33 #include "util-byte.h"
34 
35 #include "util-hash-lookup3.h"
36 #include "util-validate.h"
37 
38 static THashData *THashGetUsed(THashTableContext *ctx, uint32_t data_size);
39 static void THashDataEnqueue (THashDataQueue *q, THashData *h);
40 
42 {
43  THashDataEnqueue(&ctx->spare_q, h);
44  (void) SC_ATOMIC_SUB(ctx->counter, 1);
45 }
46 
47 static THashDataQueue *THashDataQueueInit (THashDataQueue *q)
48 {
49  if (q != NULL) {
50  memset(q, 0, sizeof(THashDataQueue));
51  HQLOCK_INIT(q);
52  }
53  return q;
54 }
55 
57 {
59  if (q == NULL) {
60  SCLogError("Fatal error encountered in THashDataQueueNew. Exiting...");
61  exit(EXIT_SUCCESS);
62  }
63  q = THashDataQueueInit(q);
64  return q;
65 }
66 
67 /**
68  * \brief Destroy a queue
69  *
70  * \param q the queue to destroy
71  */
72 static void THashDataQueueDestroy (THashDataQueue *q)
73 {
74  HQLOCK_DESTROY(q);
75 }
76 
77 /**
78  * \brief add to queue
79  *
80  * \param q queue
81  * \param h data
82  */
83 static void THashDataEnqueue (THashDataQueue *q, THashData *h)
84 {
85 #ifdef DEBUG
86  BUG_ON(q == NULL || h == NULL);
87 #endif
88 
89  HQLOCK_LOCK(q);
90 
91  /* more data in queue */
92  if (q->top != NULL) {
93  h->next = q->top;
94  q->top->prev = h;
95  q->top = h;
96  /* only data */
97  } else {
98  q->top = h;
99  q->bot = h;
100  }
101  q->len++;
102 #ifdef DBG_PERF
103  if (q->len > q->dbg_maxlen)
104  q->dbg_maxlen = q->len;
105 #endif /* DBG_PERF */
106  HQLOCK_UNLOCK(q);
107 }
108 
109 /**
110  * \brief remove data from the queue
111  *
112  * \param q queue
113  *
114  * \retval h data or NULL if empty list.
115  */
116 static THashData *THashDataDequeue (THashDataQueue *q)
117 {
118  HQLOCK_LOCK(q);
119 
120  THashData *h = q->bot;
121  if (h == NULL) {
122  HQLOCK_UNLOCK(q);
123  return NULL;
124  }
125 
126  /* more packets in queue */
127  if (q->bot->prev != NULL) {
128  q->bot = q->bot->prev;
129  q->bot->next = NULL;
130  /* just the one we remove, so now empty */
131  } else {
132  q->top = NULL;
133  q->bot = NULL;
134  }
135 
136 #ifdef DEBUG
137  BUG_ON(q->len == 0);
138 #endif
139  if (q->len > 0)
140  q->len--;
141 
142  h->next = NULL;
143  h->prev = NULL;
144 
145  HQLOCK_UNLOCK(q);
146  return h;
147 }
148 
149 #if 0
150 static uint32_t THashDataQueueLen(THashDataQueue *q)
151 {
152  uint32_t len;
153  HQLOCK_LOCK(q);
154  len = q->len;
155  HQLOCK_UNLOCK(q);
156  return len;
157 }
158 #endif
159 
160 static THashData *THashDataAlloc(THashTableContext *ctx, uint32_t data_size)
161 {
162  const size_t thash_data_size = THASH_DATA_SIZE(ctx);
163 
164  if (!(THASH_CHECK_MEMCAP(ctx, thash_data_size + data_size))) {
165  return NULL;
166  }
167 
168  size_t total_data_size = thash_data_size + data_size;
169 
170  (void)SC_ATOMIC_ADD(ctx->memuse, total_data_size);
171 
172  THashData *h = SCCalloc(1, thash_data_size);
173  if (unlikely(h == NULL))
174  goto error;
175 
176  /* points to data right after THashData block */
177  h->data = (uint8_t *)h + sizeof(THashData);
178 
179 // memset(h, 0x00, data_size);
180 
181  SCMutexInit(&h->m, NULL);
182  SC_ATOMIC_INIT(h->use_cnt);
183  return h;
184 
185 error:
186  (void)SC_ATOMIC_SUB(ctx->memuse, total_data_size);
187  return NULL;
188 }
189 
190 static void THashDataFree(THashTableContext *ctx, THashData *h)
191 {
192  if (h != NULL) {
193  DEBUG_VALIDATE_BUG_ON(SC_ATOMIC_GET(h->use_cnt) != 0);
194 
195  uint32_t data_size = 0;
196  if (h->data != NULL) {
197  if (ctx->config.DataSize) {
198  data_size = ctx->config.DataSize(h->data);
199  }
200  ctx->config.DataFree(h->data);
201  }
202  SCMutexDestroy(&h->m);
203  SCFree(h);
204  (void)SC_ATOMIC_SUB(ctx->memuse, THASH_DATA_SIZE(ctx) + (uint64_t)data_size);
205  }
206 }
207 
208 #define THASH_DEFAULT_HASHSIZE 4096
209 #define THASH_DEFAULT_MEMCAP 16777216
210 #define THASH_DEFAULT_PREALLOC 1000
211 
212 #define GET_VAR(prefix,name) \
213  snprintf(varname, sizeof(varname), "%s.%s", (prefix), (name))
214 
215 /** \brief initialize the configuration
216  * \warning Not thread safe */
217 static int THashInitConfig(THashTableContext *ctx, const char *cnf_prefix)
218 {
219  char varname[256];
220 
221  SCLogDebug("initializing thash engine...");
222 
223  /* Check if we have memcap and hash_size defined at config */
224  const char *conf_val;
225  uint32_t configval = 0;
226 
227  /** set config values for memcap, prealloc and hash_size */
228  GET_VAR(cnf_prefix, "memcap");
229  if ((ConfGet(varname, &conf_val)) == 1)
230  {
231  uint64_t memcap;
232  if (ParseSizeStringU64(conf_val, &memcap) < 0) {
233  SCLogError("Error parsing %s "
234  "from conf file - %s. Killing engine",
235  varname, conf_val);
236  return -1;
237  }
238  SC_ATOMIC_INIT(ctx->config.memcap);
239  SC_ATOMIC_SET(ctx->config.memcap, memcap);
240  }
241  GET_VAR(cnf_prefix, "hash-size");
242  if ((ConfGet(varname, &conf_val)) == 1)
243  {
244  if (StringParseUint32(&configval, 10, (uint16_t)strlen(conf_val), conf_val) > 0) {
245  ctx->config.hash_size = configval;
246  }
247  }
248 
249  GET_VAR(cnf_prefix, "prealloc");
250  if ((ConfGet(varname, &conf_val)) == 1)
251  {
252  if (StringParseUint32(&configval, 10, (uint16_t)strlen(conf_val), conf_val) > 0) {
253  ctx->config.prealloc = configval;
254  } else {
255  WarnInvalidConfEntry(varname, "%"PRIu32, ctx->config.prealloc);
256  }
257  }
258 
259  /* alloc hash memory */
260  uint64_t hash_size = ctx->config.hash_size * sizeof(THashHashRow);
261  if (!(THASH_CHECK_MEMCAP(ctx, hash_size))) {
262  SCLogError("allocating hash failed: "
263  "max hash memcap is smaller than projected hash size. "
264  "Memcap: %" PRIu64 ", Hash table size %" PRIu64 ". Calculate "
265  "total hash size by multiplying \"hash-size\" with %" PRIuMAX ", "
266  "which is the hash bucket size.",
267  SC_ATOMIC_GET(ctx->config.memcap), hash_size, (uintmax_t)sizeof(THashHashRow));
268  return -1;
269  }
270  ctx->array = SCMallocAligned(ctx->config.hash_size * sizeof(THashHashRow), CLS);
271  if (unlikely(ctx->array == NULL)) {
272  SCLogError("Fatal error encountered in THashInitConfig. Exiting...");
273  return -1;
274  }
275  memset(ctx->array, 0, ctx->config.hash_size * sizeof(THashHashRow));
276 
277  uint32_t i = 0;
278  for (i = 0; i < ctx->config.hash_size; i++) {
279  HRLOCK_INIT(&ctx->array[i]);
280  }
281  (void)SC_ATOMIC_ADD(ctx->memuse, (ctx->config.hash_size * sizeof(THashHashRow)));
282 
283  /* pre allocate prealloc */
284  for (i = 0; i < ctx->config.prealloc; i++) {
286  SCLogError("preallocating data failed: "
287  "max thash memcap reached. Memcap %" PRIu64 ", "
288  "Memuse %" PRIu64 ".",
289  SC_ATOMIC_GET(ctx->config.memcap),
290  ((uint64_t)SC_ATOMIC_GET(ctx->memuse) + THASH_DATA_SIZE(ctx)));
291  return -1;
292  }
293 
294  THashData *h = THashDataAlloc(ctx, 0 /* as we don't have string data here */);
295  if (h == NULL) {
296  SCLogError("preallocating data failed: %s", strerror(errno));
297  return -1;
298  }
299  THashDataEnqueue(&ctx->spare_q,h);
300  }
301 
302  return 0;
303 }
304 
305 THashTableContext *THashInit(const char *cnf_prefix, size_t data_size,
306  int (*DataSet)(void *, void *), void (*DataFree)(void *),
307  uint32_t (*DataHash)(uint32_t, void *), bool (*DataCompare)(void *, void *),
308  bool (*DataExpired)(void *, SCTime_t), uint32_t (*DataSize)(void *), bool reset_memcap,
309  uint64_t memcap, uint32_t hashsize)
310 {
311  THashTableContext *ctx = SCCalloc(1, sizeof(*ctx));
312  BUG_ON(!ctx);
313 
314  ctx->config.data_size = data_size;
315  ctx->config.DataSet = DataSet;
316  ctx->config.DataFree = DataFree;
317  ctx->config.DataHash = DataHash;
318  ctx->config.DataCompare = DataCompare;
319  ctx->config.DataExpired = DataExpired;
320  ctx->config.DataSize = DataSize;
321 
322  /* set defaults */
323  ctx->config.hash_rand = (uint32_t)RandomGet();
324  ctx->config.hash_size = hashsize > 0 ? hashsize : THASH_DEFAULT_HASHSIZE;
325  /* Reset memcap in case of loading from file to the highest possible value
326  unless defined by the rule keyword */
327 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
328  // limit memcap size to default when fuzzing
329  SC_ATOMIC_SET(ctx->config.memcap, THASH_DEFAULT_MEMCAP);
330 #else
331  if (memcap > 0) {
332  SC_ATOMIC_SET(ctx->config.memcap, memcap);
333  } else {
334  SC_ATOMIC_SET(ctx->config.memcap, reset_memcap ? UINT64_MAX : THASH_DEFAULT_MEMCAP);
335  }
336 #endif
337  ctx->config.prealloc = THASH_DEFAULT_PREALLOC;
338 
339  SC_ATOMIC_INIT(ctx->counter);
340  SC_ATOMIC_INIT(ctx->memuse);
341  SC_ATOMIC_INIT(ctx->prune_idx);
342  THashDataQueueInit(&ctx->spare_q);
343 
344  if (THashInitConfig(ctx, cnf_prefix) < 0) {
346  ctx = NULL;
347  }
348  return ctx;
349 }
350 
351 /* \brief Set memcap to current memuse
352  * */
354 {
356  ctx->config.memcap, MAX(SC_ATOMIC_GET(ctx->memuse), SC_ATOMIC_GET(ctx->config.memcap)));
357  SCLogDebug("memcap after load set to: %" PRIu64, SC_ATOMIC_GET(ctx->config.memcap));
358 }
359 
360 /** \brief shutdown the flow engine
361  * \warning Not thread safe */
363 {
364  THashData *h;
365 
366  /* free spare queue */
367  while ((h = THashDataDequeue(&ctx->spare_q))) {
368  BUG_ON(SC_ATOMIC_GET(h->use_cnt) > 0);
369  THashDataFree(ctx, h);
370  }
371 
372  /* clear and free the hash */
373  if (ctx->array != NULL) {
374  for (uint32_t u = 0; u < ctx->config.hash_size; u++) {
375  h = ctx->array[u].head;
376  while (h) {
377  THashData *n = h->next;
378  THashDataFree(ctx, h);
379  h = n;
380  }
381 
382  HRLOCK_DESTROY(&ctx->array[u]);
383  }
384  SCFreeAligned(ctx->array);
385  ctx->array = NULL;
386  (void)SC_ATOMIC_SUB(ctx->memuse, ctx->config.hash_size * sizeof(THashHashRow));
387  }
388  THashDataQueueDestroy(&ctx->spare_q);
389  DEBUG_VALIDATE_BUG_ON(SC_ATOMIC_GET(ctx->memuse) != 0);
390  SCFree(ctx);
391 }
392 
393 /** \brief Walk the hash
394  *
395  */
396 int THashWalk(THashTableContext *ctx, THashFormatFunc FormatterFunc, THashOutputFunc OutputterFunc, void *output_ctx)
397 {
398  uint32_t u;
399 
400  if (ctx->array == NULL)
401  return -1;
402 
403  bool err = false;
404  for (u = 0; u < ctx->config.hash_size; u++) {
405  THashHashRow *hb = &ctx->array[u];
406  HRLOCK_LOCK(hb);
407  THashData *h = hb->head;
408  while (h) {
409  char output_string[1024] = "";
410  int size = FormatterFunc(h->data, output_string, sizeof(output_string));
411  if (size > 0) {
412  if (OutputterFunc(output_ctx, (const uint8_t *)output_string, size) < 0) {
413  err = true;
414  break;
415  }
416  }
417  h = h->next;
418  }
419  HRLOCK_UNLOCK(hb);
420  if (err == true)
421  return -1;
422  }
423  return 0;
424 }
425 
426 /** \brief expire data from the hash
427  * Walk the hash table and remove data that is exprired according to the
428  * DataExpired callback.
429  * \retval cnt number of items successfully expired/removed
430  */
432 {
433  if (ctx->config.DataExpired == NULL)
434  return 0;
435 
436  SCLogDebug("timeout: starting");
437  uint32_t cnt = 0;
438 
439  for (uint32_t i = 0; i < ctx->config.hash_size; i++) {
440  THashHashRow *hb = &ctx->array[i];
441  if (HRLOCK_TRYLOCK(hb) != 0)
442  continue;
443  /* hash bucket is now locked */
444  THashData *h = hb->head;
445  while (h) {
446  THashData *next = h->next;
447  THashDataLock(h);
448  DEBUG_VALIDATE_BUG_ON(SC_ATOMIC_GET(h->use_cnt) > (uint32_t)INT_MAX);
449  /* only consider items with no references to it */
450  if (SC_ATOMIC_GET(h->use_cnt) == 0 && ctx->config.DataExpired(h->data, ts)) {
451  /* remove from the hash */
452  if (h->prev != NULL)
453  h->prev->next = h->next;
454  if (h->next != NULL)
455  h->next->prev = h->prev;
456  if (hb->head == h)
457  hb->head = h->next;
458  if (hb->tail == h)
459  hb->tail = h->prev;
460  h->next = NULL;
461  h->prev = NULL;
462  SCLogDebug("timeout: removing data %p", h);
463  if (ctx->config.DataSize) {
464  uint32_t data_size = ctx->config.DataSize(h->data);
465  if (data_size > 0)
466  (void)SC_ATOMIC_SUB(ctx->memuse, (uint64_t)data_size);
467  }
468  ctx->config.DataFree(h->data);
469  THashDataUnlock(h);
471  cnt++;
472  } else {
473  THashDataUnlock(h);
474  }
475  h = next;
476  }
477  HRLOCK_UNLOCK(hb);
478  }
479 
480  SCLogDebug("timeout: ending: %u entries expired", cnt);
481  return cnt;
482 }
483 
484 /** \brief Cleanup the thash engine
485  *
486  * Cleanup the thash engine from tag and threshold.
487  *
488  */
490 {
491  uint32_t u;
492 
493  if (ctx->array == NULL)
494  return;
495 
496  for (u = 0; u < ctx->config.hash_size; u++) {
497  THashHashRow *hb = &ctx->array[u];
498  HRLOCK_LOCK(hb);
499  THashData *h = hb->head;
500  while (h) {
501  if ((SC_ATOMIC_GET(h->use_cnt) > 0)) {
502  h = h->next;
503  } else {
504  THashData *n = h->next;
505  /* remove from the hash */
506  if (h->prev != NULL)
507  h->prev->next = h->next;
508  if (h->next != NULL)
509  h->next->prev = h->prev;
510  if (hb->head == h)
511  hb->head = h->next;
512  if (hb->tail == h)
513  hb->tail = h->prev;
514  h->next = NULL;
515  h->prev = NULL;
516  if (ctx->config.DataSize) {
517  uint32_t data_size = ctx->config.DataSize(h->data);
518  if (data_size > 0)
519  (void)SC_ATOMIC_SUB(ctx->memuse, (uint64_t)data_size);
520  }
522  h = n;
523  }
524  }
525  HRLOCK_UNLOCK(hb);
526  }
527 }
528 
529 /* calculate the hash key for this packet
530  *
531  * we're using:
532  * hash_rand -- set at init time
533  * source address
534  */
535 static uint32_t THashGetKey(const THashConfig *cnf, void *data)
536 {
537  uint32_t key;
538 
539  key = cnf->DataHash(cnf->hash_rand, data);
540  key %= cnf->hash_size;
541 
542  return key;
543 }
544 
545 static inline int THashCompare(const THashConfig *cnf, void *a, void *b)
546 {
547  if (cnf->DataCompare(a, b))
548  return 1;
549  return 0;
550 }
551 
552 /**
553  * \brief Get new data
554  *
555  * Get new data. We're checking memcap first and will try to make room
556  * if the memcap is reached.
557  *
558  * \retval h *LOCKED* data on succes, NULL on error.
559  */
560 static THashData *THashDataGetNew(THashTableContext *ctx, void *data)
561 {
562  THashData *h = NULL;
563  uint32_t data_size = 0;
564  if (ctx->config.DataSize) {
565  data_size = ctx->config.DataSize(data);
566  }
567 
568  /* get data from the spare queue */
569  h = THashDataDequeue(&ctx->spare_q);
570  if (h == NULL) {
571  /* If we reached the max memcap, we get used data */
572  if (!(THASH_CHECK_MEMCAP(ctx, THASH_DATA_SIZE(ctx) + data_size))) {
573  h = THashGetUsed(ctx, data_size);
574  if (h == NULL) {
575  return NULL;
576  }
577 
578  if (!SC_ATOMIC_GET(ctx->memcap_reached)) {
579  SC_ATOMIC_SET(ctx->memcap_reached, true);
580  }
581 
582  /* freed data, but it's unlocked */
583  } else {
584  /* now see if we can alloc a new data */
585  h = THashDataAlloc(ctx, data_size);
586  if (h == NULL) {
587  return NULL;
588  }
589 
590  /* data is initialized but *unlocked* */
591  }
592  } else {
593  /* data has been recycled before it went into the spare queue */
594  /* data is initialized (recycled) but *unlocked* */
595  /* the recycled data was THashData and again does not include
596  * the size of current data to be added */
597  if (data_size > 0) {
598  /* Since it is prealloc'd data, it already has THashData in its memuse */
599  (void)SC_ATOMIC_ADD(ctx->memuse, data_size);
600  if (!(THASH_CHECK_MEMCAP(ctx, data_size))) {
601  if (!SC_ATOMIC_GET(ctx->memcap_reached)) {
602  SC_ATOMIC_SET(ctx->memcap_reached, true);
603  }
604  SCLogError("Adding data will exceed memcap: %" PRIu64 ", current memuse: %" PRIu64,
605  SC_ATOMIC_GET((ctx)->config.memcap), SC_ATOMIC_GET(ctx->memuse));
606  }
607  }
608  }
609 
610  // setup the data
611  BUG_ON(ctx->config.DataSet(h->data, data) != 0);
612  (void) SC_ATOMIC_ADD(ctx->counter, 1);
613  SCMutexLock(&h->m);
614  return h;
615 }
616 
617 /*
618  * returns a *LOCKED* data or NULL
619  */
620 
621 struct THashDataGetResult
623 {
624  struct THashDataGetResult res = { .data = NULL, .is_new = false, };
625  THashData *h = NULL;
626 
627  /* get the key to our bucket */
628  uint32_t key = THashGetKey(&ctx->config, data);
629  /* get our hash bucket and lock it */
630  THashHashRow *hb = &ctx->array[key];
631  HRLOCK_LOCK(hb);
632 
633  /* see if the bucket already has data */
634  if (hb->head == NULL) {
635  h = THashDataGetNew(ctx, data);
636  if (h == NULL) {
637  HRLOCK_UNLOCK(hb);
638  return res;
639  }
640 
641  /* data is locked */
642  hb->head = h;
643  hb->tail = h;
644 
645  /* initialize and return */
646  (void) THashIncrUsecnt(h);
647 
648  HRLOCK_UNLOCK(hb);
649  res.data = h;
650  res.is_new = true;
651  return res;
652  }
653 
654  /* ok, we have data in the bucket. Let's find out if it is our data */
655  h = hb->head;
656 
657  /* see if this is the data we are looking for */
658  if (THashCompare(&ctx->config, h->data, data) == 0) {
659  THashData *ph = NULL; /* previous data */
660 
661  while (h) {
662  ph = h;
663  h = h->next;
664 
665  if (h == NULL) {
666  h = ph->next = THashDataGetNew(ctx, data);
667  if (h == NULL) {
668  HRLOCK_UNLOCK(hb);
669  return res;
670  }
671  hb->tail = h;
672 
673  /* data is locked */
674 
675  h->prev = ph;
676 
677  /* initialize and return */
678  (void) THashIncrUsecnt(h);
679 
680  HRLOCK_UNLOCK(hb);
681  res.data = h;
682  res.is_new = true;
683  return res;
684  }
685 
686  if (THashCompare(&ctx->config, h->data, data) != 0) {
687  /* we found our data, lets put it on top of the
688  * hash list -- this rewards active data */
689  if (h->next) {
690  h->next->prev = h->prev;
691  }
692  if (h->prev) {
693  h->prev->next = h->next;
694  }
695  if (h == hb->tail) {
696  hb->tail = h->prev;
697  }
698 
699  h->next = hb->head;
700  h->prev = NULL;
701  hb->head->prev = h;
702  hb->head = h;
703 
704  /* found our data, lock & return */
705  SCMutexLock(&h->m);
706  (void) THashIncrUsecnt(h);
707  HRLOCK_UNLOCK(hb);
708  res.data = h;
709  res.is_new = false;
710  /* coverity[missing_unlock : FALSE] */
711  return res;
712  }
713  }
714  }
715 
716  /* lock & return */
717  SCMutexLock(&h->m);
718  (void) THashIncrUsecnt(h);
719  HRLOCK_UNLOCK(hb);
720  res.data = h;
721  res.is_new = false;
722  /* coverity[missing_unlock : FALSE] */
723  return res;
724 }
725 
726 /** \brief look up data in the hash
727  *
728  * \param data data to look up
729  *
730  * \retval h *LOCKED* data or NULL
731  */
733 {
734  THashData *h = NULL;
735 
736  /* get the key to our bucket */
737  uint32_t key = THashGetKey(&ctx->config, data);
738  /* get our hash bucket and lock it */
739  THashHashRow *hb = &ctx->array[key];
740  HRLOCK_LOCK(hb);
741 
742  if (hb->head == NULL) {
743  HRLOCK_UNLOCK(hb);
744  return h;
745  }
746 
747  /* ok, we have data in the bucket. Let's find out if it is our data */
748  h = hb->head;
749 
750  /* see if this is the data we are looking for */
751  if (THashCompare(&ctx->config, h->data, data) == 0) {
752  while (h) {
753  h = h->next;
754  if (h == NULL) {
755  HRLOCK_UNLOCK(hb);
756  return h;
757  }
758 
759  if (THashCompare(&ctx->config, h->data, data) != 0) {
760  /* we found our data, lets put it on top of the
761  * hash list -- this rewards active data */
762  if (h->next) {
763  h->next->prev = h->prev;
764  }
765  if (h->prev) {
766  h->prev->next = h->next;
767  }
768  if (h == hb->tail) {
769  hb->tail = h->prev;
770  }
771 
772  h->next = hb->head;
773  h->prev = NULL;
774  hb->head->prev = h;
775  hb->head = h;
776 
777  /* found our data, lock & return */
778  SCMutexLock(&h->m);
779  (void) THashIncrUsecnt(h);
780  HRLOCK_UNLOCK(hb);
781  return h;
782  }
783  }
784  }
785 
786  /* lock & return */
787  SCMutexLock(&h->m);
788  (void) THashIncrUsecnt(h);
789  HRLOCK_UNLOCK(hb);
790  return h;
791 }
792 
793 /** \internal
794  * \brief Get data from the hash directly.
795  *
796  * Called in conditions where the spare queue is empty and memcap is
797  * reached.
798  *
799  * Walks the hash until data can be freed. "prune_idx" atomic int makes
800  * sure we don't start at the top each time since that would clear the top
801  * of the hash leading to longer and longer search times under high
802  * pressure (observed).
803  *
804  * \retval h data or NULL
805  */
806 static THashData *THashGetUsed(THashTableContext *ctx, uint32_t data_size)
807 {
808  uint32_t idx = SC_ATOMIC_GET(ctx->prune_idx) % ctx->config.hash_size;
809  uint32_t cnt = ctx->config.hash_size;
810 
811  while (cnt--) {
812  if (++idx >= ctx->config.hash_size)
813  idx = 0;
814 
815  THashHashRow *hb = &ctx->array[idx];
816 
817  if (HRLOCK_TRYLOCK(hb) != 0)
818  continue;
819 
820  THashData *h = hb->tail;
821  if (h == NULL) {
822  HRLOCK_UNLOCK(hb);
823  continue;
824  }
825 
826  if (SCMutexTrylock(&h->m) != 0) {
827  HRLOCK_UNLOCK(hb);
828  continue;
829  }
830 
831  if (SC_ATOMIC_GET(h->use_cnt) > 0) {
832  HRLOCK_UNLOCK(hb);
833  SCMutexUnlock(&h->m);
834  continue;
835  }
836 
837  /* remove from the hash */
838  if (h->prev != NULL)
839  h->prev->next = h->next;
840  if (h->next != NULL)
841  h->next->prev = h->prev;
842  if (hb->head == h)
843  hb->head = h->next;
844  if (hb->tail == h)
845  hb->tail = h->prev;
846 
847  h->next = NULL;
848  h->prev = NULL;
849  HRLOCK_UNLOCK(hb);
850 
851  if (h->data != NULL) {
852  if (ctx->config.DataSize) {
853  uint32_t h_data_size = ctx->config.DataSize(h->data);
854  if (h_data_size > 0) {
855  (void)SC_ATOMIC_SUB(ctx->memuse, (uint64_t)h_data_size);
856  }
857  }
858  ctx->config.DataFree(h->data);
859  }
860  SCMutexUnlock(&h->m);
861 
862  (void) SC_ATOMIC_ADD(ctx->prune_idx, (ctx->config.hash_size - cnt));
863  if (data_size > 0)
864  (void)SC_ATOMIC_ADD(ctx->memuse, data_size);
865  return h;
866  }
867 
868  return NULL;
869 }
870 
871 /**
872  * \retval int -1 not found
873  * \retval int 0 found, but it was busy (ref cnt)
874  * \retval int 1 found and removed */
876 {
877  /* get the key to our bucket */
878  uint32_t key = THashGetKey(&ctx->config, data);
879  /* get our hash bucket and lock it */
880  THashHashRow *hb = &ctx->array[key];
881 
882  HRLOCK_LOCK(hb);
883  THashData *h = hb->head;
884  while (h != NULL) {
885  /* see if this is the data we are looking for */
886  if (THashCompare(&ctx->config, h->data, data) == 0) {
887  h = h->next;
888  continue;
889  }
890 
891  SCMutexLock(&h->m);
892  if (SC_ATOMIC_GET(h->use_cnt) > 0) {
893  SCMutexUnlock(&h->m);
894  HRLOCK_UNLOCK(hb);
895  return 0;
896  }
897 
898  /* remove from the hash */
899  if (h->prev != NULL)
900  h->prev->next = h->next;
901  if (h->next != NULL)
902  h->next->prev = h->prev;
903  if (hb->head == h)
904  hb->head = h->next;
905  if (hb->tail == h)
906  hb->tail = h->prev;
907 
908  h->next = NULL;
909  h->prev = NULL;
910  SCMutexUnlock(&h->m);
911  HRLOCK_UNLOCK(hb);
912  THashDataFree(ctx, h);
913  SCLogDebug("found and removed");
914  return 1;
915  }
916 
917  HRLOCK_UNLOCK(hb);
918  SCLogDebug("data not found");
919  return -1;
920 }
HRLOCK_DESTROY
#define HRLOCK_DESTROY(fb)
Definition: host.h:50
util-byte.h
HQLOCK_LOCK
#define HQLOCK_LOCK(q)
Definition: host-queue.h:67
len
uint8_t len
Definition: app-layer-dnp3.h:2
ts
uint64_t ts
Definition: source-erf-file.c:55
THashCleanup
void THashCleanup(THashTableContext *ctx)
Cleanup the thash engine.
Definition: util-thash.c:489
THashDataGetResult::data
THashData * data
Definition: util-thash.h:192
SC_ATOMIC_INIT
#define SC_ATOMIC_INIT(name)
wrapper for initializing an atomic variable.
Definition: util-atomic.h:314
CLS
#define CLS
Definition: suricata-common.h:56
unlikely
#define unlikely(expr)
Definition: util-optimize.h:35
SC_ATOMIC_SET
#define SC_ATOMIC_SET(name, val)
Set the value for the atomic variable.
Definition: util-atomic.h:386
HQLOCK_DESTROY
#define HQLOCK_DESTROY(q)
Definition: host-queue.h:66
THashOutputFunc
int(* THashOutputFunc)(void *output_ctx, const uint8_t *data, const uint32_t data_len)
Definition: util-thash.h:121
SCLogDebug
#define SCLogDebug(...)
Definition: util-debug.h:269
ParseSizeStringU64
int ParseSizeStringU64(const char *size, uint64_t *res)
Definition: util-misc.c:190
next
struct HtpBodyChunk_ * next
Definition: app-layer-htp.h:0
THashData_::prev
struct THashData_ * prev
Definition: util-thash.h:95
THashRemoveFromHash
int THashRemoveFromHash(THashTableContext *ctx, void *data)
Definition: util-thash.c:875
ctx
struct Thresholds ctx
SC_ATOMIC_ADD
#define SC_ATOMIC_ADD(name, val)
add a value to our atomic variable
Definition: util-atomic.h:332
THashData_::next
struct THashData_ * next
Definition: util-thash.h:94
THashConsolidateMemcap
void THashConsolidateMemcap(THashTableContext *ctx)
Definition: util-thash.c:353
SCMutexLock
#define SCMutexLock(mut)
Definition: threads-debug.h:117
THashDataQueue_
Definition: util-thash.h:105
RandomGet
long int RandomGet(void)
Definition: util-random.c:130
THashDataConfig_::DataCompare
bool(* DataCompare)(void *, void *)
Definition: util-thash.h:134
MAX
#define MAX(x, y)
Definition: suricata-common.h:395
HRLOCK_LOCK
#define HRLOCK_LOCK(fb)
Definition: host.h:51
ConfGet
int ConfGet(const char *name, const char **vptr)
Retrieve the value of a configuration node.
Definition: conf.c:335
HRLOCK_UNLOCK
#define HRLOCK_UNLOCK(fb)
Definition: host.h:53
THashDataConfig_::hash_size
uint32_t hash_size
Definition: util-thash.h:127
util-debug.h
THASH_DEFAULT_HASHSIZE
#define THASH_DEFAULT_HASHSIZE
Definition: util-thash.c:208
SCMutexUnlock
#define SCMutexUnlock(mut)
Definition: threads-debug.h:119
THashTableContext_
Definition: util-thash.h:141
THASH_DATA_SIZE
#define THASH_DATA_SIZE(ctx)
Definition: util-thash.h:139
THashDataQueue_::bot
THashData * bot
Definition: util-thash.h:107
StringParseUint32
int StringParseUint32(uint32_t *res, int base, size_t len, const char *str)
Definition: util-byte.c:313
THashData_::m
SCMutex m
Definition: util-thash.h:87
BUG_ON
#define BUG_ON(x)
Definition: suricata-common.h:300
SC_ATOMIC_SUB
#define SC_ATOMIC_SUB(name, val)
sub a value from our atomic variable
Definition: util-atomic.h:341
THashDataGetResult
Definition: util-thash.h:191
SCFreeAligned
#define SCFreeAligned(p)
Definition: util-mem.h:77
GET_VAR
#define GET_VAR(prefix, name)
Definition: util-thash.c:212
conf.h
SCTime_t
Definition: util-time.h:40
HRLOCK_INIT
#define HRLOCK_INIT(fb)
Definition: host.h:49
THashDataMoveToSpare
void THashDataMoveToSpare(THashTableContext *ctx, THashData *h)
Definition: util-thash.c:41
SCMutexInit
#define SCMutexInit(mut, mutattrs)
Definition: threads-debug.h:116
WarnInvalidConfEntry
#define WarnInvalidConfEntry(param_name, format, value)
Generic API that can be used by all to log an invalid conf entry.
Definition: util-misc.h:35
THashShutdown
void THashShutdown(THashTableContext *ctx)
shutdown the flow engine
Definition: util-thash.c:362
HQLOCK_UNLOCK
#define HQLOCK_UNLOCK(q)
Definition: host-queue.h:69
THashData_::data
void * data
Definition: util-thash.h:92
cnt
uint32_t cnt
Definition: tmqh-packetpool.h:7
THashData_
Definition: util-thash.h:85
THashDataQueue_::len
uint32_t len
Definition: util-thash.h:108
suricata-common.h
THASH_DEFAULT_MEMCAP
#define THASH_DEFAULT_MEMCAP
Definition: util-thash.c:209
SCMallocAligned
#define SCMallocAligned(size, align)
Definition: util-mem.h:68
HQLOCK_INIT
#define HQLOCK_INIT(q)
Definition: host-queue.h:65
THashGetFromHash
struct THashDataGetResult THashGetFromHash(THashTableContext *ctx, void *data)
Definition: util-thash.c:622
hashsize
#define hashsize(n)
Definition: util-hash-lookup3.h:40
THashLookupFromHash
THashData * THashLookupFromHash(THashTableContext *ctx, void *data)
look up data in the hash
Definition: util-thash.c:732
util-hash-lookup3.h
THASH_DEFAULT_PREALLOC
#define THASH_DEFAULT_PREALLOC
Definition: util-thash.c:210
util-validate.h
SCMalloc
#define SCMalloc(sz)
Definition: util-mem.h:47
THashDataConfig_
Definition: util-thash.h:124
SCLogError
#define SCLogError(...)
Macro used to log ERROR messages.
Definition: util-debug.h:261
THashWalk
int THashWalk(THashTableContext *ctx, THashFormatFunc FormatterFunc, THashOutputFunc OutputterFunc, void *output_ctx)
Walk the hash.
Definition: util-thash.c:396
SCFree
#define SCFree(p)
Definition: util-mem.h:61
THashFormatFunc
int(* THashFormatFunc)(const void *in_data, char *output, size_t output_size)
Definition: util-thash.h:122
THashDataConfig_::DataHash
uint32_t(* DataHash)(uint32_t, void *)
Definition: util-thash.h:133
util-random.h
HRLOCK_TRYLOCK
#define HRLOCK_TRYLOCK(fb)
Definition: host.h:52
THashDataGetResult::is_new
bool is_new
Definition: util-thash.h:193
THashDataConfig_::hash_rand
uint32_t hash_rand
Definition: util-thash.h:126
THashExpire
uint32_t THashExpire(THashTableContext *ctx, const SCTime_t ts)
expire data from the hash Walk the hash table and remove data that is exprired according to the DataE...
Definition: util-thash.c:431
THashInit
THashTableContext * THashInit(const char *cnf_prefix, size_t data_size, int(*DataSet)(void *, void *), void(*DataFree)(void *), uint32_t(*DataHash)(uint32_t, void *), bool(*DataCompare)(void *, void *), bool(*DataExpired)(void *, SCTime_t), uint32_t(*DataSize)(void *), bool reset_memcap, uint64_t memcap, uint32_t hashsize)
Definition: util-thash.c:305
THashIncrUsecnt
#define THashIncrUsecnt(h)
Definition: util-thash.h:168
SC_ATOMIC_GET
#define SC_ATOMIC_GET(name)
Get the value from the atomic variable.
Definition: util-atomic.h:375
util-misc.h
util-thash.h
SCCalloc
#define SCCalloc(nm, sz)
Definition: util-mem.h:53
SCMutexDestroy
#define SCMutexDestroy
Definition: threads-debug.h:120
THASH_CHECK_MEMCAP
#define THASH_CHECK_MEMCAP(ctx, size)
check if a memory alloc would fit in the memcap
Definition: util-thash.h:164
DEBUG_VALIDATE_BUG_ON
#define DEBUG_VALIDATE_BUG_ON(exp)
Definition: util-validate.h:102
THashDataQueueNew
THashDataQueue * THashDataQueueNew(void)
Definition: util-thash.c:56
SCMutexTrylock
#define SCMutexTrylock(mut)
Definition: threads-debug.h:118
THashDataQueue_::top
THashData * top
Definition: util-thash.h:106