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  if (ParseSizeStringU64(conf_val, &ctx->config.memcap) < 0) {
232  SCLogError("Error parsing %s "
233  "from conf file - %s. Killing engine",
234  varname, conf_val);
235  return -1;
236  }
237  }
238  GET_VAR(cnf_prefix, "hash-size");
239  if ((ConfGet(varname, &conf_val)) == 1)
240  {
241  if (StringParseUint32(&configval, 10, (uint16_t)strlen(conf_val), conf_val) > 0) {
242  ctx->config.hash_size = configval;
243  }
244  }
245 
246  GET_VAR(cnf_prefix, "prealloc");
247  if ((ConfGet(varname, &conf_val)) == 1)
248  {
249  if (StringParseUint32(&configval, 10, (uint16_t)strlen(conf_val), conf_val) > 0) {
250  ctx->config.prealloc = configval;
251  } else {
252  WarnInvalidConfEntry(varname, "%"PRIu32, ctx->config.prealloc);
253  }
254  }
255 
256  /* alloc hash memory */
257  uint64_t hash_size = ctx->config.hash_size * sizeof(THashHashRow);
258  if (!(THASH_CHECK_MEMCAP(ctx, hash_size))) {
259  SCLogError("allocating hash failed: "
260  "max hash memcap is smaller than projected hash size. "
261  "Memcap: %" PRIu64 ", Hash table size %" PRIu64 ". Calculate "
262  "total hash size by multiplying \"hash-size\" with %" PRIuMAX ", "
263  "which is the hash bucket size.",
264  ctx->config.memcap, hash_size, (uintmax_t)sizeof(THashHashRow));
265  return -1;
266  }
267  ctx->array = SCMallocAligned(ctx->config.hash_size * sizeof(THashHashRow), CLS);
268  if (unlikely(ctx->array == NULL)) {
269  SCLogError("Fatal error encountered in THashInitConfig. Exiting...");
270  return -1;
271  }
272  memset(ctx->array, 0, ctx->config.hash_size * sizeof(THashHashRow));
273 
274  uint32_t i = 0;
275  for (i = 0; i < ctx->config.hash_size; i++) {
276  HRLOCK_INIT(&ctx->array[i]);
277  }
278  (void)SC_ATOMIC_ADD(ctx->memuse, (ctx->config.hash_size * sizeof(THashHashRow)));
279 
280  /* pre allocate prealloc */
281  for (i = 0; i < ctx->config.prealloc; i++) {
283  SCLogError("preallocating data failed: "
284  "max thash memcap reached. Memcap %" PRIu64 ", "
285  "Memuse %" PRIu64 ".",
286  ctx->config.memcap,
287  ((uint64_t)SC_ATOMIC_GET(ctx->memuse) + THASH_DATA_SIZE(ctx)));
288  return -1;
289  }
290 
291  THashData *h = THashDataAlloc(ctx, 0 /* as we don't have string data here */);
292  if (h == NULL) {
293  SCLogError("preallocating data failed: %s", strerror(errno));
294  return -1;
295  }
296  THashDataEnqueue(&ctx->spare_q,h);
297  }
298 
299  return 0;
300 }
301 
302 THashTableContext *THashInit(const char *cnf_prefix, size_t data_size,
303  int (*DataSet)(void *, void *), void (*DataFree)(void *), uint32_t (*DataHash)(void *),
304  bool (*DataCompare)(void *, void *), bool (*DataExpired)(void *, SCTime_t),
305  uint32_t (*DataSize)(void *), bool reset_memcap, uint64_t memcap, uint32_t hashsize)
306 {
307  THashTableContext *ctx = SCCalloc(1, sizeof(*ctx));
308  BUG_ON(!ctx);
309 
310  ctx->config.data_size = data_size;
311  ctx->config.DataSet = DataSet;
312  ctx->config.DataFree = DataFree;
313  ctx->config.DataHash = DataHash;
314  ctx->config.DataCompare = DataCompare;
315  ctx->config.DataExpired = DataExpired;
316  ctx->config.DataSize = DataSize;
317 
318  /* set defaults */
319  ctx->config.hash_rand = (uint32_t)RandomGet();
320  ctx->config.hash_size = hashsize > 0 ? hashsize : THASH_DEFAULT_HASHSIZE;
321  /* Reset memcap in case of loading from file to the highest possible value
322  unless defined by the rule keyword */
323 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
324  // limit memcap size to default when fuzzing
325  ctx->config.memcap = THASH_DEFAULT_MEMCAP;
326 #else
327  if (memcap > 0) {
328  ctx->config.memcap = memcap;
329  } else {
330  ctx->config.memcap = reset_memcap ? UINT64_MAX : THASH_DEFAULT_MEMCAP;
331  }
332 #endif
333  ctx->config.prealloc = THASH_DEFAULT_PREALLOC;
334 
335  SC_ATOMIC_INIT(ctx->counter);
336  SC_ATOMIC_INIT(ctx->memuse);
337  SC_ATOMIC_INIT(ctx->prune_idx);
338  THashDataQueueInit(&ctx->spare_q);
339 
340  if (THashInitConfig(ctx, cnf_prefix) < 0) {
342  ctx = NULL;
343  }
344  return ctx;
345 }
346 
347 /* \brief Set memcap to current memuse
348  * */
350 {
351  ctx->config.memcap = MAX(SC_ATOMIC_GET(ctx->memuse), ctx->config.memcap);
352  SCLogDebug("memcap after load set to: %" PRIu64, ctx->config.memcap);
353 }
354 
355 /** \brief shutdown the flow engine
356  * \warning Not thread safe */
358 {
359  THashData *h;
360 
361  /* free spare queue */
362  while ((h = THashDataDequeue(&ctx->spare_q))) {
363  BUG_ON(SC_ATOMIC_GET(h->use_cnt) > 0);
364  THashDataFree(ctx, h);
365  }
366 
367  /* clear and free the hash */
368  if (ctx->array != NULL) {
369  for (uint32_t u = 0; u < ctx->config.hash_size; u++) {
370  h = ctx->array[u].head;
371  while (h) {
372  THashData *n = h->next;
373  THashDataFree(ctx, h);
374  h = n;
375  }
376 
377  HRLOCK_DESTROY(&ctx->array[u]);
378  }
379  SCFreeAligned(ctx->array);
380  ctx->array = NULL;
381  (void)SC_ATOMIC_SUB(ctx->memuse, ctx->config.hash_size * sizeof(THashHashRow));
382  }
383  THashDataQueueDestroy(&ctx->spare_q);
384  DEBUG_VALIDATE_BUG_ON(SC_ATOMIC_GET(ctx->memuse) != 0);
385  SCFree(ctx);
386 }
387 
388 /** \brief Walk the hash
389  *
390  */
391 int THashWalk(THashTableContext *ctx, THashFormatFunc FormatterFunc, THashOutputFunc OutputterFunc, void *output_ctx)
392 {
393  uint32_t u;
394 
395  if (ctx->array == NULL)
396  return -1;
397 
398  bool err = false;
399  for (u = 0; u < ctx->config.hash_size; u++) {
400  THashHashRow *hb = &ctx->array[u];
401  HRLOCK_LOCK(hb);
402  THashData *h = hb->head;
403  while (h) {
404  char output_string[1024] = "";
405  int size = FormatterFunc(h->data, output_string, sizeof(output_string));
406  if (size > 0) {
407  if (OutputterFunc(output_ctx, (const uint8_t *)output_string, size) < 0) {
408  err = true;
409  break;
410  }
411  }
412  h = h->next;
413  }
414  HRLOCK_UNLOCK(hb);
415  if (err == true)
416  return -1;
417  }
418  return 0;
419 }
420 
421 /** \brief expire data from the hash
422  * Walk the hash table and remove data that is exprired according to the
423  * DataExpired callback.
424  * \retval cnt number of items successfully expired/removed
425  */
427 {
428  if (ctx->config.DataExpired == NULL)
429  return 0;
430 
431  SCLogDebug("timeout: starting");
432  uint32_t cnt = 0;
433 
434  for (uint32_t i = 0; i < ctx->config.hash_size; i++) {
435  THashHashRow *hb = &ctx->array[i];
436  if (HRLOCK_TRYLOCK(hb) != 0)
437  continue;
438  /* hash bucket is now locked */
439  THashData *h = hb->head;
440  while (h) {
441  THashData *next = h->next;
442  THashDataLock(h);
443  DEBUG_VALIDATE_BUG_ON(SC_ATOMIC_GET(h->use_cnt) > (uint32_t)INT_MAX);
444  /* only consider items with no references to it */
445  if (SC_ATOMIC_GET(h->use_cnt) == 0 && ctx->config.DataExpired(h->data, ts)) {
446  /* remove from the hash */
447  if (h->prev != NULL)
448  h->prev->next = h->next;
449  if (h->next != NULL)
450  h->next->prev = h->prev;
451  if (hb->head == h)
452  hb->head = h->next;
453  if (hb->tail == h)
454  hb->tail = h->prev;
455  h->next = NULL;
456  h->prev = NULL;
457  SCLogDebug("timeout: removing data %p", h);
458  if (ctx->config.DataSize) {
459  uint32_t data_size = ctx->config.DataSize(h->data);
460  if (data_size > 0)
461  (void)SC_ATOMIC_SUB(ctx->memuse, (uint64_t)data_size);
462  }
463  ctx->config.DataFree(h->data);
464  THashDataUnlock(h);
466  cnt++;
467  } else {
468  THashDataUnlock(h);
469  }
470  h = next;
471  }
472  HRLOCK_UNLOCK(hb);
473  }
474 
475  SCLogDebug("timeout: ending: %u entries expired", cnt);
476  return cnt;
477 }
478 
479 /** \brief Cleanup the thash engine
480  *
481  * Cleanup the thash engine from tag and threshold.
482  *
483  */
485 {
486  uint32_t u;
487 
488  if (ctx->array == NULL)
489  return;
490 
491  for (u = 0; u < ctx->config.hash_size; u++) {
492  THashHashRow *hb = &ctx->array[u];
493  HRLOCK_LOCK(hb);
494  THashData *h = hb->head;
495  while (h) {
496  if ((SC_ATOMIC_GET(h->use_cnt) > 0)) {
497  h = h->next;
498  } else {
499  THashData *n = h->next;
500  /* remove from the hash */
501  if (h->prev != NULL)
502  h->prev->next = h->next;
503  if (h->next != NULL)
504  h->next->prev = h->prev;
505  if (hb->head == h)
506  hb->head = h->next;
507  if (hb->tail == h)
508  hb->tail = h->prev;
509  h->next = NULL;
510  h->prev = NULL;
511  if (ctx->config.DataSize) {
512  uint32_t data_size = ctx->config.DataSize(h->data);
513  if (data_size > 0)
514  (void)SC_ATOMIC_SUB(ctx->memuse, (uint64_t)data_size);
515  }
517  h = n;
518  }
519  }
520  HRLOCK_UNLOCK(hb);
521  }
522 }
523 
524 /* calculate the hash key for this packet
525  *
526  * we're using:
527  * hash_rand -- set at init time
528  * source address
529  */
530 static uint32_t THashGetKey(const THashConfig *cnf, void *data)
531 {
532  uint32_t key;
533 
534  key = cnf->DataHash(data);
535  key %= cnf->hash_size;
536 
537  return key;
538 }
539 
540 static inline int THashCompare(const THashConfig *cnf, void *a, void *b)
541 {
542  if (cnf->DataCompare(a, b))
543  return 1;
544  return 0;
545 }
546 
547 /**
548  * \brief Get new data
549  *
550  * Get new data. We're checking memcap first and will try to make room
551  * if the memcap is reached.
552  *
553  * \retval h *LOCKED* data on succes, NULL on error.
554  */
555 static THashData *THashDataGetNew(THashTableContext *ctx, void *data)
556 {
557  THashData *h = NULL;
558  uint32_t data_size = 0;
559  if (ctx->config.DataSize) {
560  data_size = ctx->config.DataSize(data);
561  }
562 
563  /* get data from the spare queue */
564  h = THashDataDequeue(&ctx->spare_q);
565  if (h == NULL) {
566  /* If we reached the max memcap, we get used data */
567  if (!(THASH_CHECK_MEMCAP(ctx, THASH_DATA_SIZE(ctx) + data_size))) {
568  h = THashGetUsed(ctx, data_size);
569  if (h == NULL) {
570  return NULL;
571  }
572 
573  if (!SC_ATOMIC_GET(ctx->memcap_reached)) {
574  SC_ATOMIC_SET(ctx->memcap_reached, true);
575  }
576 
577  /* freed data, but it's unlocked */
578  } else {
579  /* now see if we can alloc a new data */
580  h = THashDataAlloc(ctx, data_size);
581  if (h == NULL) {
582  return NULL;
583  }
584 
585  /* data is initialized but *unlocked* */
586  }
587  } else {
588  /* data has been recycled before it went into the spare queue */
589  /* data is initialized (recycled) but *unlocked* */
590  /* the recycled data was THashData and again does not include
591  * the size of current data to be added */
592  if (data_size > 0) {
593  /* Since it is prealloc'd data, it already has THashData in its memuse */
594  (void)SC_ATOMIC_ADD(ctx->memuse, data_size);
595  if (!(THASH_CHECK_MEMCAP(ctx, data_size))) {
596  if (!SC_ATOMIC_GET(ctx->memcap_reached)) {
597  SC_ATOMIC_SET(ctx->memcap_reached, true);
598  }
599  SCLogError("Adding data will exceed memcap: %" PRIu64 ", current memuse: %" PRIu64,
600  (ctx)->config.memcap, SC_ATOMIC_GET(ctx->memuse));
601  }
602  }
603  }
604 
605  // setup the data
606  BUG_ON(ctx->config.DataSet(h->data, data) != 0);
607  (void) SC_ATOMIC_ADD(ctx->counter, 1);
608  SCMutexLock(&h->m);
609  return h;
610 }
611 
612 /*
613  * returns a *LOCKED* data or NULL
614  */
615 
616 struct THashDataGetResult
618 {
619  struct THashDataGetResult res = { .data = NULL, .is_new = false, };
620  THashData *h = NULL;
621 
622  /* get the key to our bucket */
623  uint32_t key = THashGetKey(&ctx->config, data);
624  /* get our hash bucket and lock it */
625  THashHashRow *hb = &ctx->array[key];
626  HRLOCK_LOCK(hb);
627 
628  /* see if the bucket already has data */
629  if (hb->head == NULL) {
630  h = THashDataGetNew(ctx, data);
631  if (h == NULL) {
632  HRLOCK_UNLOCK(hb);
633  return res;
634  }
635 
636  /* data is locked */
637  hb->head = h;
638  hb->tail = h;
639 
640  /* initialize and return */
641  (void) THashIncrUsecnt(h);
642 
643  HRLOCK_UNLOCK(hb);
644  res.data = h;
645  res.is_new = true;
646  return res;
647  }
648 
649  /* ok, we have data in the bucket. Let's find out if it is our data */
650  h = hb->head;
651 
652  /* see if this is the data we are looking for */
653  if (THashCompare(&ctx->config, h->data, data) == 0) {
654  THashData *ph = NULL; /* previous data */
655 
656  while (h) {
657  ph = h;
658  h = h->next;
659 
660  if (h == NULL) {
661  h = ph->next = THashDataGetNew(ctx, data);
662  if (h == NULL) {
663  HRLOCK_UNLOCK(hb);
664  return res;
665  }
666  hb->tail = h;
667 
668  /* data is locked */
669 
670  h->prev = ph;
671 
672  /* initialize and return */
673  (void) THashIncrUsecnt(h);
674 
675  HRLOCK_UNLOCK(hb);
676  res.data = h;
677  res.is_new = true;
678  return res;
679  }
680 
681  if (THashCompare(&ctx->config, h->data, data) != 0) {
682  /* we found our data, lets put it on top of the
683  * hash list -- this rewards active data */
684  if (h->next) {
685  h->next->prev = h->prev;
686  }
687  if (h->prev) {
688  h->prev->next = h->next;
689  }
690  if (h == hb->tail) {
691  hb->tail = h->prev;
692  }
693 
694  h->next = hb->head;
695  h->prev = NULL;
696  hb->head->prev = h;
697  hb->head = h;
698 
699  /* found our data, lock & return */
700  SCMutexLock(&h->m);
701  (void) THashIncrUsecnt(h);
702  HRLOCK_UNLOCK(hb);
703  res.data = h;
704  res.is_new = false;
705  /* coverity[missing_unlock : FALSE] */
706  return res;
707  }
708  }
709  }
710 
711  /* lock & return */
712  SCMutexLock(&h->m);
713  (void) THashIncrUsecnt(h);
714  HRLOCK_UNLOCK(hb);
715  res.data = h;
716  res.is_new = false;
717  /* coverity[missing_unlock : FALSE] */
718  return res;
719 }
720 
721 /** \brief look up data in the hash
722  *
723  * \param data data to look up
724  *
725  * \retval h *LOCKED* data or NULL
726  */
728 {
729  THashData *h = NULL;
730 
731  /* get the key to our bucket */
732  uint32_t key = THashGetKey(&ctx->config, data);
733  /* get our hash bucket and lock it */
734  THashHashRow *hb = &ctx->array[key];
735  HRLOCK_LOCK(hb);
736 
737  if (hb->head == NULL) {
738  HRLOCK_UNLOCK(hb);
739  return h;
740  }
741 
742  /* ok, we have data in the bucket. Let's find out if it is our data */
743  h = hb->head;
744 
745  /* see if this is the data we are looking for */
746  if (THashCompare(&ctx->config, h->data, data) == 0) {
747  while (h) {
748  h = h->next;
749  if (h == NULL) {
750  HRLOCK_UNLOCK(hb);
751  return h;
752  }
753 
754  if (THashCompare(&ctx->config, h->data, data) != 0) {
755  /* we found our data, lets put it on top of the
756  * hash list -- this rewards active data */
757  if (h->next) {
758  h->next->prev = h->prev;
759  }
760  if (h->prev) {
761  h->prev->next = h->next;
762  }
763  if (h == hb->tail) {
764  hb->tail = h->prev;
765  }
766 
767  h->next = hb->head;
768  h->prev = NULL;
769  hb->head->prev = h;
770  hb->head = h;
771 
772  /* found our data, lock & return */
773  SCMutexLock(&h->m);
774  (void) THashIncrUsecnt(h);
775  HRLOCK_UNLOCK(hb);
776  return h;
777  }
778  }
779  }
780 
781  /* lock & return */
782  SCMutexLock(&h->m);
783  (void) THashIncrUsecnt(h);
784  HRLOCK_UNLOCK(hb);
785  return h;
786 }
787 
788 /** \internal
789  * \brief Get data from the hash directly.
790  *
791  * Called in conditions where the spare queue is empty and memcap is
792  * reached.
793  *
794  * Walks the hash until data can be freed. "prune_idx" atomic int makes
795  * sure we don't start at the top each time since that would clear the top
796  * of the hash leading to longer and longer search times under high
797  * pressure (observed).
798  *
799  * \retval h data or NULL
800  */
801 static THashData *THashGetUsed(THashTableContext *ctx, uint32_t data_size)
802 {
803  uint32_t idx = SC_ATOMIC_GET(ctx->prune_idx) % ctx->config.hash_size;
804  uint32_t cnt = ctx->config.hash_size;
805 
806  while (cnt--) {
807  if (++idx >= ctx->config.hash_size)
808  idx = 0;
809 
810  THashHashRow *hb = &ctx->array[idx];
811 
812  if (HRLOCK_TRYLOCK(hb) != 0)
813  continue;
814 
815  THashData *h = hb->tail;
816  if (h == NULL) {
817  HRLOCK_UNLOCK(hb);
818  continue;
819  }
820 
821  if (SCMutexTrylock(&h->m) != 0) {
822  HRLOCK_UNLOCK(hb);
823  continue;
824  }
825 
826  if (SC_ATOMIC_GET(h->use_cnt) > 0) {
827  HRLOCK_UNLOCK(hb);
828  SCMutexUnlock(&h->m);
829  continue;
830  }
831 
832  /* remove from the hash */
833  if (h->prev != NULL)
834  h->prev->next = h->next;
835  if (h->next != NULL)
836  h->next->prev = h->prev;
837  if (hb->head == h)
838  hb->head = h->next;
839  if (hb->tail == h)
840  hb->tail = h->prev;
841 
842  h->next = NULL;
843  h->prev = NULL;
844  HRLOCK_UNLOCK(hb);
845 
846  if (h->data != NULL) {
847  if (ctx->config.DataSize) {
848  uint32_t h_data_size = ctx->config.DataSize(h->data);
849  if (h_data_size > 0) {
850  (void)SC_ATOMIC_SUB(ctx->memuse, (uint64_t)h_data_size);
851  }
852  }
853  ctx->config.DataFree(h->data);
854  }
855  SCMutexUnlock(&h->m);
856 
857  (void) SC_ATOMIC_ADD(ctx->prune_idx, (ctx->config.hash_size - cnt));
858  if (data_size > 0)
859  (void)SC_ATOMIC_ADD(ctx->memuse, data_size);
860  return h;
861  }
862 
863  return NULL;
864 }
865 
866 /**
867  * \retval int -1 not found
868  * \retval int 0 found, but it was busy (ref cnt)
869  * \retval int 1 found and removed */
871 {
872  /* get the key to our bucket */
873  uint32_t key = THashGetKey(&ctx->config, data);
874  /* get our hash bucket and lock it */
875  THashHashRow *hb = &ctx->array[key];
876 
877  HRLOCK_LOCK(hb);
878  THashData *h = hb->head;
879  while (h != NULL) {
880  /* see if this is the data we are looking for */
881  if (THashCompare(&ctx->config, h->data, data) == 0) {
882  h = h->next;
883  continue;
884  }
885 
886  SCMutexLock(&h->m);
887  if (SC_ATOMIC_GET(h->use_cnt) > 0) {
888  SCMutexUnlock(&h->m);
889  HRLOCK_UNLOCK(hb);
890  return 0;
891  }
892 
893  /* remove from the hash */
894  if (h->prev != NULL)
895  h->prev->next = h->next;
896  if (h->next != NULL)
897  h->next->prev = h->prev;
898  if (hb->head == h)
899  hb->head = h->next;
900  if (hb->tail == h)
901  hb->tail = h->prev;
902 
903  h->next = NULL;
904  h->prev = NULL;
905  SCMutexUnlock(&h->m);
906  HRLOCK_UNLOCK(hb);
907  THashDataFree(ctx, h);
908  SCLogDebug("found and removed");
909  return 1;
910  }
911 
912  HRLOCK_UNLOCK(hb);
913  SCLogDebug("data not found");
914  return -1;
915 }
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:484
THashDataGetResult::data
THashData * data
Definition: util-thash.h:191
THashInit
THashTableContext * THashInit(const char *cnf_prefix, size_t data_size, int(*DataSet)(void *, void *), void(*DataFree)(void *), uint32_t(*DataHash)(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:302
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:870
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:349
SCMutexLock
#define SCMutexLock(mut)
Definition: threads-debug.h:117
THashDataQueue_
Definition: util-thash.h:105
THashDataConfig_::DataHash
uint32_t(* DataHash)(void *)
Definition: util-thash.h:133
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:190
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:357
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:617
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:727
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:391
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
util-random.h
HRLOCK_TRYLOCK
#define HRLOCK_TRYLOCK(fb)
Definition: host.h:52
THashDataGetResult::is_new
bool is_new
Definition: util-thash.h:192
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:426
THashIncrUsecnt
#define THashIncrUsecnt(h)
Definition: util-thash.h:167
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