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