• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

OISF / suricata / 22522913668

28 Feb 2026 02:48PM UTC coverage: 73.705% (+0.02%) from 73.687%
22522913668

Pull #14916

github

web-flow
Merge d18a4d509 into 90823fa90
Pull Request #14916: output/ipv6: Add per-output configuration option to compress IPv6 IP addresses

38322 of 77382 branches covered (49.52%)

Branch coverage included in aggregate %.

203 of 216 new or added lines in 15 files covered. (93.98%)

48 existing lines in 16 files now uncovered.

265573 of 334933 relevant lines covered (79.29%)

4563575.4 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

69.54
/src/tm-threads.c
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
 * \author Anoop Saldanha <anoopsaldanha@gmail.com>
23
 * \author Eric Leblond <eric@regit.org>
24
 *
25
 * Thread management functions.
26
 */
27

28
#include "suricata-common.h"
29
#include "suricata.h"
30
#include "stream.h"
31
#include "runmodes.h"
32
#include "thread-callbacks.h"
33
#include "threadvars.h"
34
#include "thread-storage.h"
35
#include "tm-queues.h"
36
#include "tm-queuehandlers.h"
37
#include "tm-threads.h"
38
#include "capture-hooks.h"
39
#include "tmqh-packetpool.h"
40
#include "threads.h"
41
#include "util-affinity.h"
42
#include "util-debug.h"
43
#include "util-privs.h"
44
#include "util-cpu.h"
45
#include "util-optimize.h"
46
#include "util-profiling.h"
47
#include "util-signal.h"
48
#include "queue.h"
49
#include "util-validate.h"
50
#include "source-pcap-file-helper.h"
51

52
#ifdef PROFILE_LOCKING
53
thread_local uint64_t mutex_lock_contention;
54
thread_local uint64_t mutex_lock_wait_ticks;
55
thread_local uint64_t mutex_lock_cnt;
56

57
thread_local uint64_t spin_lock_contention;
58
thread_local uint64_t spin_lock_wait_ticks;
59
thread_local uint64_t spin_lock_cnt;
60

61
thread_local uint64_t rww_lock_contention;
62
thread_local uint64_t rww_lock_wait_ticks;
63
thread_local uint64_t rww_lock_cnt;
64

65
thread_local uint64_t rwr_lock_contention;
66
thread_local uint64_t rwr_lock_wait_ticks;
67
thread_local uint64_t rwr_lock_cnt;
68
#endif
69

70
#ifdef OS_FREEBSD
71
#include <sched.h>
72
#include <sys/param.h>
73
#include <sys/resource.h>
74
#include <sys/cpuset.h>
75
#include <sys/thr.h>
76
#define cpu_set_t cpuset_t
77
#endif /* OS_FREEBSD */
78

79
/* prototypes */
80
static int SetCPUAffinity(uint16_t cpu);
81
static void TmThreadDeinitMC(ThreadVars *tv);
82

83
/* root of the threadvars list */
84
ThreadVars *tv_root[TVT_MAX] = { NULL };
85

86
/* lock to protect tv_root */
87
SCMutex tv_root_lock = SCMUTEX_INITIALIZER;
88

89
/**
90
 * \brief Check if a thread flag is set.
91
 *
92
 * \retval 1 flag is set.
93
 * \retval 0 flag is not set.
94
 */
95
int TmThreadsCheckFlag(ThreadVars *tv, uint32_t flag)
96
{
3,078,311,308✔
97
    return (SC_ATOMIC_GET(tv->flags) & flag) ? 1 : 0;
3,078,311,308✔
98
}
3,078,311,308✔
99

100
/**
101
 * \brief Set a thread flag.
102
 */
103
void TmThreadsSetFlag(ThreadVars *tv, uint32_t flag)
104
{
628,622✔
105
    SC_ATOMIC_OR(tv->flags, flag);
628,622✔
106
}
628,622✔
107

108
/**
109
 * \brief Unset a thread flag.
110
 */
111
void TmThreadsUnsetFlag(ThreadVars *tv, uint32_t flag)
112
{
58,282✔
113
    SC_ATOMIC_AND(tv->flags, ~flag);
58,282✔
114
}
58,282✔
115

116
TmEcode TmThreadsProcessDecodePseudoPackets(
117
        ThreadVars *tv, PacketQueueNoLock *decode_pq, TmSlot *slot)
118
{
121,791,653✔
119
    while (decode_pq->top != NULL) {
121,826,026✔
120
        Packet *extra_p = PacketDequeueNoLock(decode_pq);
34,373✔
121
        if (unlikely(extra_p == NULL))
34,373!
122
            continue;
×
123
        DEBUG_VALIDATE_BUG_ON(extra_p->flow != NULL);
34,373✔
124

125
        if (TmThreadsSlotProcessPkt(tv, slot, extra_p) != TM_ECODE_OK) {
34,373!
126
            SCReturnInt(TM_ECODE_FAILED);
×
127
        }
×
128
    }
34,373✔
129
    SCReturnInt(TM_ECODE_OK);
121,791,653✔
130
}
121,791,653✔
131

132
/**
133
 * \brief Separate run function so we can call it recursively.
134
 */
135
TmEcode TmThreadsSlotVarRun(ThreadVars *tv, Packet *p, TmSlot *slot)
136
{
129,274,827✔
137
    for (TmSlot *s = slot; s != NULL; s = s->slot_next) {
489,098,513✔
138
        PACKET_PROFILING_TMM_START(p, s->tm_id);
359,823,686✔
139
        TmEcode r = s->SlotFunc(tv, p, SC_ATOMIC_GET(s->slot_data));
359,823,686✔
140
        PACKET_PROFILING_TMM_END(p, s->tm_id);
359,823,686✔
141
        DEBUG_VALIDATE_BUG_ON(p->flow != NULL);
359,823,686✔
142

143
        /* handle error */
144
        if (unlikely(r == TM_ECODE_FAILED)) {
359,823,686!
145
            /* Encountered error.  Return packets to packetpool and return */
146
            TmThreadsSlotProcessPktFail(tv, NULL);
×
147
            return TM_ECODE_FAILED;
×
148
        }
×
149
        if (s->tm_flags & TM_FLAG_DECODE_TM) {
359,823,686✔
150
            if (TmThreadsProcessDecodePseudoPackets(tv, &tv->decode_pq, s->slot_next) !=
121,613,910!
151
                    TM_ECODE_OK) {
121,613,910✔
152
                return TM_ECODE_FAILED;
×
153
            }
×
154
        }
121,613,910✔
155
    }
359,823,686✔
156

157
    return TM_ECODE_OK;
129,274,827✔
158
}
129,274,827✔
159

160
/** \internal
161
 *
162
 *  \brief Process flow timeout packets
163
 *
164
 *  Process flow timeout pseudo packets. During shutdown this loop
165
 *  is run until the flow engine kills the thread and the queue is
166
 *  empty.
167
 */
168
int TmThreadTimeoutLoop(ThreadVars *tv, TmSlot *s)
169
{
16,812✔
170
    TmSlot *fw_slot = tv->tm_flowworker;
16,812✔
171
    int r = TM_ECODE_OK;
16,812✔
172

173
    if (tv->stream_pq == NULL || fw_slot == NULL) {
16,812!
174
        SCLogDebug("not running TmThreadTimeoutLoop %p/%p", tv->stream_pq, fw_slot);
3,347!
175
        return r;
3,347✔
176
    }
3,347✔
177

178
    SCLogDebug("flow end loop starting");
13,465!
179
    while (1) {
1,634,144!
180
        SCMutexLock(&tv->stream_pq->mutex_q);
1,634,144✔
181
        uint32_t len = tv->stream_pq->len;
1,634,144✔
182
        SCMutexUnlock(&tv->stream_pq->mutex_q);
1,634,144✔
183
        if (len > 0) {
1,634,144✔
184
            while (len--) {
2,806✔
185
                SCMutexLock(&tv->stream_pq->mutex_q);
1,403✔
186
                Packet *p = PacketDequeue(tv->stream_pq);
1,403✔
187
                SCMutexUnlock(&tv->stream_pq->mutex_q);
1,403✔
188
                if (likely(p)) {
1,403!
189
                    DEBUG_VALIDATE_BUG_ON(p->flow != NULL);
1,403✔
190
                    r = TmThreadsSlotProcessPkt(tv, fw_slot, p);
1,403✔
191
                    if (r == TM_ECODE_FAILED) {
1,403!
192
                        break;
×
193
                    }
×
194
                }
1,403✔
195
            }
1,403✔
196
        } else {
1,632,741✔
197
            if (TmThreadsCheckFlag(tv, THV_KILL)) {
1,632,741✔
198
                break;
13,465✔
199
            }
13,465✔
200
            SleepUsec(1);
1,619,276✔
201
        }
1,619,276✔
202
    }
1,634,144✔
203
    SCLogDebug("flow end loop complete");
13,465!
204
    StatsSyncCounters(&tv->stats);
13,465✔
205

206
    return r;
13,465✔
207
}
16,812✔
208

209
static bool TmThreadsSlotPktAcqLoopInit(ThreadVars *tv)
210
{
3,439✔
211
    TmSlot *s = tv->tm_slots;
3,439✔
212

213
    SCSetThreadName(tv->name);
3,439!
214

215
    if (tv->thread_setup_flags != 0)
3,439!
216
        TmThreadSetupOptions(tv);
24✔
217

218
    CaptureStatsSetup(tv);
3,439✔
219
    PacketPoolInit();
3,439✔
220

221
    for (TmSlot *slot = s; slot != NULL; slot = slot->slot_next) {
10,465✔
222
        if (slot->SlotThreadInit != NULL) {
7,026!
223
            void *slot_data = NULL;
6,972✔
224
            TmEcode r = slot->SlotThreadInit(tv, slot->slot_initdata, &slot_data);
6,972✔
225
            if (r != TM_ECODE_OK) {
6,972!
226
                if (r == TM_ECODE_DONE) {
×
227
                    EngineDone();
×
228
                    TmThreadsSetFlag(tv, THV_CLOSED | THV_INIT_DONE | THV_RUNNING_DONE);
×
229
                    goto error;
×
230
                } else {
×
231
                    TmThreadsSetFlag(tv, THV_CLOSED | THV_RUNNING_DONE);
×
232
                    goto error;
×
233
                }
×
234
            }
×
235
            (void)SC_ATOMIC_SET(slot->slot_data, slot_data);
6,972✔
236
        }
6,972✔
237

238
        /* if the flowworker module is the first, get the threads input queue */
239
        if (slot == (TmSlot *)tv->tm_slots && (slot->tm_id == TMM_FLOWWORKER)) {
7,026!
240
            tv->stream_pq = tv->inq->pq;
×
241
            tv->tm_flowworker = slot;
×
242
            SCLogDebug("pre-stream packetqueue %p (inq)", tv->stream_pq);
×
243
            tv->flow_queue = FlowQueueNew();
×
244
            if (tv->flow_queue == NULL) {
×
245
                TmThreadsSetFlag(tv, THV_CLOSED | THV_RUNNING_DONE);
×
246
                goto error;
×
247
            }
×
248
        /* setup a queue */
249
        } else if (slot->tm_id == TMM_FLOWWORKER) {
7,026✔
250
            tv->stream_pq_local = SCCalloc(1, sizeof(PacketQueue));
93✔
251
            if (tv->stream_pq_local == NULL)
93!
252
                FatalError("failed to alloc PacketQueue");
×
253
            SCMutexInit(&tv->stream_pq_local->mutex_q, NULL);
93✔
254
            tv->stream_pq = tv->stream_pq_local;
93✔
255
            tv->tm_flowworker = slot;
93✔
256
            SCLogDebug("pre-stream packetqueue %p (local)", tv->stream_pq);
93!
257
            tv->flow_queue = FlowQueueNew();
93✔
258
            if (tv->flow_queue == NULL) {
93!
259
                TmThreadsSetFlag(tv, THV_CLOSED | THV_RUNNING_DONE);
×
260
                goto error;
×
261
            }
×
262
        }
93✔
263
    }
7,026✔
264

265
    StatsSetupPrivate(&tv->stats, tv->printable_name ? tv->printable_name : tv->name);
3,439!
266

267
    TmThreadsSetFlag(tv, THV_INIT_DONE);
3,439✔
268

269
    return true;
3,439✔
270

271
error:
×
272
    return false;
×
273
}
3,439✔
274

275
bool SCTmThreadsSlotPacketLoopFinish(ThreadVars *tv)
276
{
16,812✔
277
    TmSlot *s = tv->tm_slots;
16,812✔
278
    bool rc = true;
16,812✔
279

280
    StatsSyncCounters(&tv->stats);
16,812✔
281

282
    TmThreadsSetFlag(tv, THV_FLOW_LOOP);
16,812✔
283

284
    /* process all pseudo packets the flow timeout may throw at us */
285
    TmThreadTimeoutLoop(tv, s);
16,812✔
286

287
    TmThreadsSetFlag(tv, THV_RUNNING_DONE);
16,812✔
288
    TmThreadWaitForFlag(tv, THV_DEINIT);
16,812✔
289

290
    PacketPoolDestroy();
16,812✔
291

292
    for (TmSlot *slot = s; slot != NULL; slot = slot->slot_next) {
37,232✔
293
        if (slot->SlotThreadExitPrintStats != NULL) {
20,420✔
294
            slot->SlotThreadExitPrintStats(tv, SC_ATOMIC_GET(slot->slot_data));
3,415✔
295
        }
3,415✔
296

297
        if (slot->SlotThreadDeinit != NULL) {
20,420!
298
            TmEcode r = slot->SlotThreadDeinit(tv, SC_ATOMIC_GET(slot->slot_data));
20,420✔
299
            if (r != TM_ECODE_OK) {
20,420!
300
                TmThreadsSetFlag(tv, THV_CLOSED);
×
301
                rc = false;
×
302
                break;
×
303
            }
×
304
        }
20,420✔
305
    }
20,420✔
306

307
    tv->stream_pq = NULL;
16,812✔
308
    TmThreadsSetFlag(tv, THV_CLOSED);
16,812✔
309
    return rc;
16,812✔
310
}
16,812✔
311

312
static void *TmThreadsSlotPktAcqLoop(void *td)
313
{
3,439✔
314
    ThreadVars *tv = (ThreadVars *)td;
3,439✔
315
    TmSlot *s = tv->tm_slots;
3,439✔
316
    TmEcode r = TM_ECODE_OK;
3,439✔
317

318
    /* check if we are setup properly */
319
    if (s == NULL || s->PktAcqLoop == NULL || tv->tmqh_in == NULL || tv->tmqh_out == NULL) {
3,439!
320
        SCLogError("TmSlot or ThreadVars badly setup: s=%p,"
×
321
                   " PktAcqLoop=%p, tmqh_in=%p,"
×
322
                   " tmqh_out=%p",
×
323
                s, s ? s->PktAcqLoop : NULL, tv->tmqh_in, tv->tmqh_out);
×
324
        TmThreadsSetFlag(tv, THV_CLOSED | THV_RUNNING_DONE);
×
325
        pthread_exit(NULL);
×
326
        return NULL;
×
327
    }
×
328

329
    if (!TmThreadsSlotPktAcqLoopInit(td)) {
3,439!
330
        goto error;
×
331
    }
×
332

333
    bool run = TmThreadsWaitForUnpause(tv);
3,439✔
334

335
    while (run) {
6,877✔
336
        r = s->PktAcqLoop(tv, SC_ATOMIC_GET(s->slot_data), s);
3,438✔
337

338
        if (r == TM_ECODE_FAILED) {
3,438!
339
            TmThreadsSetFlag(tv, THV_FAILED);
×
340
            run = false;
×
341
        }
×
342
        if (TmThreadsCheckFlag(tv, THV_REQ_FLOW_LOOP) || suricata_ctl_flags) {
3,439!
343
            run = false;
2,048✔
344
        }
2,048✔
345
        if (r == TM_ECODE_DONE) {
3,438✔
346
            run = false;
3,341✔
347
        }
3,341✔
348
    }
3,438✔
349
    if (!SCTmThreadsSlotPacketLoopFinish(tv)) {
3,439!
350
        goto error;
×
351
    }
×
352

353
    SCLogDebug("%s ending", tv->name);
3,439!
354
    pthread_exit((void *) 0);
3,439✔
355
    return NULL;
×
356

357
error:
×
358
    pthread_exit(NULL);
×
359
    return NULL;
×
360
}
3,439✔
361

362
/**
363
 * Also returns if the kill flag is set.
364
 */
365
bool TmThreadsWaitForUnpause(ThreadVars *tv)
366
{
29,443✔
367
    if (TmThreadsCheckFlag(tv, THV_PAUSE)) {
29,443✔
368
        TmThreadsSetFlag(tv, THV_PAUSED);
27,493✔
369

370
        while (TmThreadsCheckFlag(tv, THV_PAUSE)) {
1,550,066✔
371
            SleepUsec(100);
1,522,576✔
372

373
            if (TmThreadsCheckFlag(tv, THV_KILL))
1,522,576!
374
                return false;
3✔
375
        }
1,522,576✔
376

377
        TmThreadsUnsetFlag(tv, THV_PAUSED);
27,490✔
378
    }
27,490✔
379

380
    return true;
29,440✔
381
}
29,443✔
382

383
static void *TmThreadsLib(void *td)
384
{
×
385
    ThreadVars *tv = (ThreadVars *)td;
×
386
    TmSlot *s = tv->tm_slots;
×
387

388
    /* check if we are setup properly */
389
    if (s == NULL || tv->tmqh_in == NULL || tv->tmqh_out == NULL) {
×
390
        SCLogError("TmSlot or ThreadVars badly setup: s=%p, tmqh_in=%p,"
×
391
                   " tmqh_out=%p",
×
392
                s, tv->tmqh_in, tv->tmqh_out);
×
393
        TmThreadsSetFlag(tv, THV_CLOSED | THV_RUNNING_DONE);
×
394
        return NULL;
×
395
    }
×
396

397
    if (!TmThreadsSlotPktAcqLoopInit(tv)) {
×
398
        goto error;
×
399
    }
×
400

401
    if (!TmThreadsWaitForUnpause(tv)) {
×
402
        goto error;
×
403
    }
×
404

405
    return NULL;
×
406

407
error:
×
408
    tv->stream_pq = NULL;
×
409
    return (void *)-1;
×
410
}
×
411

412
static void *TmThreadsSlotVar(void *td)
413
{
13,373✔
414
    ThreadVars *tv = (ThreadVars *)td;
13,373✔
415
    TmSlot *s = (TmSlot *)tv->tm_slots;
13,373✔
416
    Packet *p = NULL;
13,373✔
417
    TmEcode r = TM_ECODE_OK;
13,373✔
418

419
    CaptureStatsSetup(tv);
13,373✔
420
    PacketPoolInit();//Empty();
13,373✔
421

422
    SCSetThreadName(tv->name);
13,373!
423

424
    if (tv->thread_setup_flags != 0)
13,373!
425
        TmThreadSetupOptions(tv);
×
426

427
    /* Drop the capabilities for this thread */
428
    SCDropCaps(tv);
13,373✔
429

430
    /* check if we are setup properly */
431
    if (s == NULL || tv->tmqh_in == NULL || tv->tmqh_out == NULL) {
13,373!
432
        TmThreadsSetFlag(tv, THV_CLOSED | THV_RUNNING_DONE);
×
433
        pthread_exit(NULL);
×
434
        return NULL;
×
435
    }
×
436

437
    for (; s != NULL; s = s->slot_next) {
26,767✔
438
        if (s->SlotThreadInit != NULL) {
13,394!
439
            void *slot_data = NULL;
13,373✔
440
            r = s->SlotThreadInit(tv, s->slot_initdata, &slot_data);
13,373✔
441
            if (r != TM_ECODE_OK) {
13,373!
442
                TmThreadsSetFlag(tv, THV_CLOSED | THV_RUNNING_DONE);
×
443
                goto error;
×
444
            }
×
445
            (void)SC_ATOMIC_SET(s->slot_data, slot_data);
13,373✔
446
        }
13,373✔
447

448
        /* special case: we need to access the stream queue
449
         * from the flow timeout code */
450

451
        /* if the flowworker module is the first, get the threads input queue */
452
        if (s == (TmSlot *)tv->tm_slots && (s->tm_id == TMM_FLOWWORKER)) {
13,394!
453
            tv->stream_pq = tv->inq->pq;
13,372✔
454
            tv->tm_flowworker = s;
13,372✔
455
            SCLogDebug("pre-stream packetqueue %p (inq)", tv->stream_pq);
13,372!
456
            tv->flow_queue = FlowQueueNew();
13,372✔
457
            if (tv->flow_queue == NULL) {
13,372!
458
                TmThreadsSetFlag(tv, THV_CLOSED | THV_RUNNING_DONE);
×
459
                pthread_exit(NULL);
×
460
                return NULL;
×
461
            }
×
462
        /* setup a queue */
463
        } else if (s->tm_id == TMM_FLOWWORKER) {
13,372!
464
            tv->stream_pq_local = SCCalloc(1, sizeof(PacketQueue));
×
465
            if (tv->stream_pq_local == NULL)
×
466
                FatalError("failed to alloc PacketQueue");
×
467
            SCMutexInit(&tv->stream_pq_local->mutex_q, NULL);
×
468
            tv->stream_pq = tv->stream_pq_local;
×
469
            tv->tm_flowworker = s;
×
470
            SCLogDebug("pre-stream packetqueue %p (local)", tv->stream_pq);
×
471
            tv->flow_queue = FlowQueueNew();
×
472
            if (tv->flow_queue == NULL) {
×
473
                TmThreadsSetFlag(tv, THV_CLOSED | THV_RUNNING_DONE);
×
474
                pthread_exit(NULL);
×
475
                return NULL;
×
476
            }
×
477
        }
×
478
    }
13,394✔
479

480
    StatsSetupPrivate(&tv->stats, tv->printable_name ? tv->printable_name : tv->name);
13,373!
481

482
    // Each 'worker' thread uses this func to process/decode the packet read.
483
    // Each decode method is different to receive methods in that they do not
484
    // enter infinite loops. They use this as the core loop. As a result, at this
485
    // point the worker threads can be considered both initialized and running.
486
    TmThreadsSetFlag(tv, THV_INIT_DONE | THV_RUNNING);
13,373✔
487
    bool run = TmThreadsWaitForUnpause(tv);
13,373✔
488

489
    s = (TmSlot *)tv->tm_slots;
13,373✔
490

491
    while (run) {
2,736,569✔
492
        /* input a packet */
493
        p = tv->tmqh_in(tv);
2,723,196✔
494

495
        /* if we didn't get a packet see if we need to do some housekeeping */
496
        if (unlikely(p == NULL)) {
2,723,196✔
497
            if (tv->flow_queue && SC_ATOMIC_GET(tv->flow_queue->non_empty)) {
13,750!
498
                p = PacketGetFromQueueOrAlloc();
3✔
499
                if (p != NULL) {
3!
500
                    p->flags |= PKT_PSEUDO_STREAM_END;
3✔
501
                    PKT_SET_SRC(p, PKT_SRC_CAPTURE_TIMEOUT);
3✔
502
                }
3✔
503
            }
3✔
504
        }
13,750✔
505

506
        if (p != NULL) {
2,723,196✔
507
            /* run the thread module(s) */
508
            r = TmThreadsSlotVarRun(tv, p, s);
2,709,446✔
509
            if (r == TM_ECODE_FAILED) {
2,709,446!
510
                TmqhOutputPacketpool(tv, p);
×
511
                TmThreadsSetFlag(tv, THV_FAILED);
×
512
                break;
×
513
            }
×
514

515
            /* output the packet */
516
            tv->tmqh_out(tv, p);
2,709,446✔
517

518
            /* now handle the stream pq packets */
519
            TmThreadsHandleInjectedPackets(tv);
2,709,446✔
520
        }
2,709,446✔
521

522
        if (TmThreadsCheckFlag(tv, (THV_KILL | THV_REQ_FLOW_LOOP))) {
2,723,196✔
523
            run = false;
13,373✔
524
        }
13,373✔
525
    }
2,723,196✔
526
    if (!SCTmThreadsSlotPacketLoopFinish(tv)) {
13,373!
527
        goto error;
×
528
    }
×
529
    StatsSyncCounters(&tv->stats);
13,373✔
530

531
    pthread_exit(NULL);
13,373✔
532
    return NULL;
×
533

534
error:
×
535
    tv->stream_pq = NULL;
×
536
    pthread_exit(NULL);
×
537
    return NULL;
×
538
}
13,373✔
539

540
static void *TmThreadsManagement(void *td)
541
{
6,846✔
542
    ThreadVars *tv = (ThreadVars *)td;
6,846✔
543
    TmSlot *s = (TmSlot *)tv->tm_slots;
6,846✔
544
    TmEcode r = TM_ECODE_OK;
6,846✔
545

546
    BUG_ON(s == NULL);
6,846!
547

548
    SCSetThreadName(tv->name);
6,846!
549

550
    if (tv->thread_setup_flags != 0)
6,846!
551
        TmThreadSetupOptions(tv);
50✔
552

553
    /* Drop the capabilities for this thread */
554
    SCDropCaps(tv);
6,846✔
555

556
    SCLogDebug("%s starting", tv->name);
6,846!
557

558
    if (s->SlotThreadInit != NULL) {
6,846!
559
        void *slot_data = NULL;
6,846✔
560
        r = s->SlotThreadInit(tv, s->slot_initdata, &slot_data);
6,846✔
561
        if (r != TM_ECODE_OK) {
6,846!
562
            TmThreadsSetFlag(tv, THV_CLOSED | THV_RUNNING_DONE);
×
563
            pthread_exit(NULL);
×
564
            return NULL;
×
565
        }
×
566
        (void)SC_ATOMIC_SET(s->slot_data, slot_data);
6,846✔
567
    }
6,846✔
568

569
    StatsSetupPrivate(&tv->stats, tv->printable_name ? tv->printable_name : tv->name);
6,846!
570

571
    TmThreadsSetFlag(tv, THV_INIT_DONE);
6,846✔
572

573
    r = s->Management(tv, SC_ATOMIC_GET(s->slot_data));
6,846✔
574
    /* handle error */
575
    if (r == TM_ECODE_FAILED) {
6,846!
576
        TmThreadsSetFlag(tv, THV_FAILED);
×
577
    }
×
578

579
    if (TmThreadsCheckFlag(tv, THV_KILL)) {
6,846✔
580
        StatsSyncCounters(&tv->stats);
6,806✔
581
    }
6,806✔
582

583
    TmThreadsSetFlag(tv, THV_RUNNING_DONE);
6,846✔
584
    TmThreadWaitForFlag(tv, THV_DEINIT);
6,846✔
585

586
    if (s->SlotThreadExitPrintStats != NULL) {
6,846!
587
        s->SlotThreadExitPrintStats(tv, SC_ATOMIC_GET(s->slot_data));
×
588
    }
×
589

590
    if (s->SlotThreadDeinit != NULL) {
6,846✔
591
        r = s->SlotThreadDeinit(tv, SC_ATOMIC_GET(s->slot_data));
6,833✔
592
        if (r != TM_ECODE_OK) {
6,833!
593
            TmThreadsSetFlag(tv, THV_CLOSED);
×
594
            pthread_exit(NULL);
×
595
            return NULL;
×
596
        }
×
597
    }
6,833✔
598

599
    TmThreadsSetFlag(tv, THV_CLOSED);
6,846✔
600
    pthread_exit((void *) 0);
6,846✔
601
    return NULL;
×
602
}
6,846✔
603

604
/**
605
 * \brief We set the slot functions.
606
 *
607
 * \param tv   Pointer to the TV to set the slot function for.
608
 * \param name Name of the slot variant.
609
 * \param fn_p Pointer to a custom slot function.  Used only if slot variant
610
 *             "name" is "custom".
611
 *
612
 * \retval TmEcode TM_ECODE_OK on success; TM_ECODE_FAILED on failure.
613
 */
614
static TmEcode TmThreadSetSlots(ThreadVars *tv, const char *name, void *(*fn_p)(void *))
615
{
29,509✔
616
    if (name == NULL) {
29,509!
617
        if (fn_p == NULL) {
×
618
            printf("Both slot name and function pointer can't be NULL inside "
×
619
                   "TmThreadSetSlots\n");
×
620
            goto error;
×
621
        } else {
×
622
            name = "custom";
×
623
        }
×
624
    }
×
625

626
    if (strcmp(name, "varslot") == 0) {
29,509✔
627
        tv->tm_func = TmThreadsSlotVar;
13,373✔
628
    } else if (strcmp(name, "pktacqloop") == 0) {
16,136✔
629
        tv->tm_func = TmThreadsSlotPktAcqLoop;
3,440✔
630
    } else if (strcmp(name, "management") == 0) {
12,697✔
631
        tv->tm_func = TmThreadsManagement;
6,796✔
632
    } else if (strcmp(name, "command") == 0) {
6,833✔
633
        tv->tm_func = TmThreadsManagement;
50✔
634
    } else if (strcmp(name, "lib") == 0) {
5,850!
635
        tv->tm_func = TmThreadsLib;
×
636
    } else if (strcmp(name, "custom") == 0) {
5,850!
637
        if (fn_p == NULL)
5,850!
638
            goto error;
×
639
        tv->tm_func = fn_p;
5,850✔
640
    } else {
5,850✔
641
        printf("Error: Slot \"%s\" not supported\n", name);
×
642
        goto error;
×
643
    }
×
644

645
    return TM_ECODE_OK;
29,509✔
646

647
error:
×
648
    return TM_ECODE_FAILED;
×
649
}
29,509✔
650

651
/**
652
 * \brief Appends a new entry to the slots.
653
 *
654
 * \param tv   TV the slot is attached to.
655
 * \param tm   TM to append.
656
 * \param data Data to be passed on to the slot init function.
657
 *
658
 * \retval The allocated TmSlot or NULL if there is an error
659
 */
660
void TmSlotSetFuncAppend(ThreadVars *tv, TmModule *tm, const void *data)
661
{
27,268✔
662
    TmSlot *slot = SCCalloc(1, sizeof(TmSlot));
27,268✔
663
    if (unlikely(slot == NULL))
27,268!
664
        return;
×
665
    SC_ATOMIC_INITPTR(slot->slot_data);
27,268✔
666
    slot->SlotThreadInit = tm->ThreadInit;
27,268✔
667
    slot->slot_initdata = data;
27,268✔
668
    if (tm->Func) {
27,268✔
669
        slot->SlotFunc = tm->Func;
16,982✔
670
    } else if (tm->PktAcqLoop) {
16,982✔
671
        slot->PktAcqLoop = tm->PktAcqLoop;
3,440✔
672
        if (tm->PktAcqBreakLoop) {
3,440!
673
            tv->break_loop = true;
3✔
674
        }
3✔
675
    } else if (tm->Management) {
6,855!
676
        slot->Management = tm->Management;
6,846✔
677
    }
6,846✔
678
    slot->SlotThreadExitPrintStats = tm->ThreadExitPrintStats;
27,268✔
679
    slot->SlotThreadDeinit = tm->ThreadDeinit;
27,268✔
680
    /* we don't have to check for the return value "-1".  We wouldn't have
681
     * received a TM as arg, if it didn't exist */
682
    slot->tm_id = TmModuleGetIDForTM(tm);
27,268✔
683
    slot->tm_flags |= tm->flags;
27,268✔
684

685
    tv->tmm_flags |= tm->flags;
27,268✔
686
    tv->cap_flags |= tm->cap_flags;
27,268✔
687

688
    if (tv->tm_slots == NULL) {
27,268✔
689
        tv->tm_slots = slot;
23,659✔
690
    } else {
23,680✔
691
        TmSlot *a = (TmSlot *)tv->tm_slots, *b = NULL;
3,609✔
692

693
        /* get the last slot */
694
        for ( ; a != NULL; a = a->slot_next) {
7,422✔
695
             b = a;
3,813✔
696
        }
3,813✔
697
        /* append the new slot */
698
        if (b != NULL) {
3,609!
699
            b->slot_next = slot;
3,609✔
700
        }
3,609✔
701
    }
3,609✔
702
}
27,268✔
703

704
#if !defined __CYGWIN__ && !defined OS_WIN32 && !defined __OpenBSD__ && !defined sun
705
static int SetCPUAffinitySet(cpu_set_t *cs)
706
{
104✔
707
#if defined OS_FREEBSD
708
    int r = cpuset_setaffinity(CPU_LEVEL_WHICH, CPU_WHICH_TID,
709
                               SCGetThreadIdLong(), sizeof(cpu_set_t),cs);
710
#elif OS_DARWIN
711
    int r = thread_policy_set(mach_thread_self(), THREAD_AFFINITY_POLICY,
712
                              (void*)cs, THREAD_AFFINITY_POLICY_COUNT);
713
#else
714
    pid_t tid = (pid_t)syscall(SYS_gettid);
104✔
715
    int r = sched_setaffinity(tid, sizeof(cpu_set_t), cs);
104✔
716
#endif /* OS_FREEBSD */
104✔
717

718
    if (r != 0) {
104!
719
        printf("Warning: sched_setaffinity failed (%" PRId32 "): %s\n", r,
×
720
               strerror(errno));
×
721
        return -1;
×
722
    }
×
723

724
    return 0;
104✔
725
}
104✔
726
#endif
727

728

729
/**
730
 * \brief Set the thread affinity on the calling thread.
731
 *
732
 * \param cpuid Id of the core/cpu to setup the affinity.
733
 *
734
 * \retval 0 If all goes well; -1 if something is wrong.
735
 */
736
static int SetCPUAffinity(uint16_t cpuid)
737
{
24✔
738
#if defined __OpenBSD__ || defined sun
739
    return 0;
740
#else
741
    int cpu = (int)cpuid;
24✔
742

743
#if defined OS_WIN32 || defined __CYGWIN__
744
    DWORD cs = 1 << cpu;
745

746
    int r = (0 == SetThreadAffinityMask(GetCurrentThread(), cs));
747
    if (r != 0) {
748
        printf("Warning: sched_setaffinity failed (%" PRId32 "): %s\n", r,
749
               strerror(errno));
750
        return -1;
751
    }
752
    SCLogDebug("CPU Affinity for thread %lu set to CPU %" PRId32,
753
               SCGetThreadIdLong(), cpu);
754

755
    return 0;
756

757
#else
758
    cpu_set_t cs;
24✔
759
    memset(&cs, 0, sizeof(cs));
24✔
760

761
    CPU_ZERO(&cs);
24!
762
    CPU_SET(cpu, &cs);
24!
763
    return SetCPUAffinitySet(&cs);
24✔
764
#endif /* windows */
24✔
765
#endif /* not supported */
24✔
766
}
24✔
767

768

769
/**
770
 * \brief Set the thread options (thread priority).
771
 *
772
 * \param tv Pointer to the ThreadVars to setup the thread priority.
773
 *
774
 * \retval TM_ECODE_OK.
775
 */
776
TmEcode TmThreadSetThreadPriority(ThreadVars *tv, int prio)
777
{
×
778
    tv->thread_setup_flags |= THREAD_SET_PRIORITY;
×
779
    tv->thread_priority = prio;
×
780

781
    return TM_ECODE_OK;
×
782
}
×
783

784
/**
785
 * \brief Adjusting nice value for threads.
786
 */
787
void TmThreadSetPrio(ThreadVars *tv)
788
{
104✔
789
    SCEnter();
104✔
790
#ifndef __CYGWIN__
104✔
791
#ifdef OS_WIN32
792
        if (0 == SetThreadPriority(GetCurrentThread(), tv->thread_priority)) {
793
            SCLogError("Error setting priority for "
794
                       "thread %s: %s",
795
                    tv->name, strerror(errno));
796
    } else {
797
        SCLogDebug("Priority set to %"PRId32" for thread %s",
798
                   tv->thread_priority, tv->name);
799
    }
800
#else
801
    int ret = nice(tv->thread_priority);
104✔
802
    if (ret == -1) {
104!
803
        SCLogError("Error setting nice value %d "
×
804
                   "for thread %s: %s",
×
805
                tv->thread_priority, tv->name, strerror(errno));
×
806
    } else {
104✔
807
        SCLogDebug("Nice value set to %"PRId32" for thread %s",
104!
808
                   tv->thread_priority, tv->name);
104✔
809
    }
104✔
810
#endif /* OS_WIN32 */
104✔
811
#endif
104✔
812
    SCReturn;
104✔
813
}
104✔
814

815

816
/**
817
 * \brief Set the thread options (cpu affinity).
818
 *
819
 * \param tv pointer to the ThreadVars to setup the affinity.
820
 * \param cpu cpu on which affinity is set.
821
 *
822
 * \retval TM_ECODE_OK
823
 */
824
TmEcode TmThreadSetCPUAffinity(ThreadVars *tv, uint16_t cpu)
825
{
×
826
    tv->thread_setup_flags |= THREAD_SET_AFFINITY;
×
827
    tv->cpu_affinity = cpu;
×
828

829
    return TM_ECODE_OK;
×
830
}
×
831

832

833
TmEcode TmThreadSetCPU(ThreadVars *tv, uint8_t type)
834
{
29,508✔
835
    if (!threading_set_cpu_affinity)
29,508!
836
        return TM_ECODE_OK;
29,404✔
837

838
    if (type > MAX_CPU_SET) {
104!
839
        SCLogError("invalid cpu type family");
×
840
        return TM_ECODE_FAILED;
×
841
    }
×
842

843
    tv->thread_setup_flags |= THREAD_SET_AFFTYPE;
104✔
844
    tv->cpu_affinity = type;
104✔
845

846
    return TM_ECODE_OK;
104✔
847
}
104✔
848

849
int TmThreadGetNbThreads(uint8_t type)
850
{
3,364✔
851
    if (type >= MAX_CPU_SET) {
3,364!
852
        SCLogError("invalid cpu type family");
×
853
        return 0;
×
854
    }
×
855

856
    return thread_affinity[type].nb_threads;
3,364✔
857
}
3,364✔
858

859
/**
860
 * \brief Set the thread options (cpu affinitythread).
861
 *        Priority should be already set by pthread_create.
862
 *
863
 * \param tv pointer to the ThreadVars of the calling thread.
864
 */
865
TmEcode TmThreadSetupOptions(ThreadVars *tv)
866
{
104✔
867
    if (tv->thread_setup_flags & THREAD_SET_AFFINITY) {
104!
868
        SCLogPerf("Setting affinity for thread \"%s\"to cpu/core "
×
869
                  "%"PRIu16", thread id %lu", tv->name, tv->cpu_affinity,
×
870
                  SCGetThreadIdLong());
×
871
        SetCPUAffinity(tv->cpu_affinity);
×
872
    }
×
873

874
#if !defined __CYGWIN__ && !defined OS_WIN32 && !defined __OpenBSD__ && !defined sun
104✔
875
    if (tv->thread_setup_flags & THREAD_SET_PRIORITY)
104!
876
        TmThreadSetPrio(tv);
×
877
    if (tv->thread_setup_flags & THREAD_SET_AFFTYPE) {
104!
878
        ThreadsAffinityType *taf = &thread_affinity[tv->cpu_affinity];
104✔
879
        bool use_iface_affinity = RunmodeIsAutofp() && tv->cpu_affinity == RECEIVE_CPU_SET &&
104!
880
                                  FindAffinityByInterface(taf, tv->iface_name) != NULL;
104!
881
        use_iface_affinity |= RunmodeIsWorkers() && tv->cpu_affinity == WORKER_CPU_SET &&
104!
882
                              FindAffinityByInterface(taf, tv->iface_name) != NULL;
104!
883

884
        if (use_iface_affinity) {
104!
885
            taf = FindAffinityByInterface(taf, tv->iface_name);
×
886
        }
×
887

888
        if (UtilAffinityGetAffinedCPUNum(taf) == 0) {
104!
889
            if (!taf->nocpu_warned) {
×
890
                SCLogWarning("No CPU affinity set for %s", AffinityGetYamlPath(taf));
×
891
                taf->nocpu_warned = true;
×
892
            }
×
893
        }
×
894

895
        if (taf->mode_flag == EXCLUSIVE_AFFINITY) {
104!
896
            uint16_t cpu = AffinityGetNextCPU(tv, taf);
24✔
897
            SetCPUAffinity(cpu);
24✔
898
            /* If CPU is in a set overwrite the default thread prio */
899
            if (CPU_ISSET(cpu, &taf->lowprio_cpu)) {
24!
900
                tv->thread_priority = PRIO_LOW;
×
901
            } else if (CPU_ISSET(cpu, &taf->medprio_cpu)) {
24!
902
                tv->thread_priority = PRIO_MEDIUM;
×
903
            } else if (CPU_ISSET(cpu, &taf->hiprio_cpu)) {
24!
904
                tv->thread_priority = PRIO_HIGH;
×
905
            } else {
24✔
906
                tv->thread_priority = taf->prio;
24✔
907
            }
24✔
908
            SCLogPerf("Setting prio %d for thread \"%s\" to cpu/core "
24✔
909
                      "%d, thread id %lu", tv->thread_priority,
24✔
910
                      tv->name, cpu, SCGetThreadIdLong());
24✔
911
        } else {
80✔
912
            SetCPUAffinitySet(&taf->cpu_set);
80✔
913
            tv->thread_priority = taf->prio;
80✔
914
            SCLogPerf("Setting prio %d for thread \"%s\", "
80✔
915
                      "thread id %lu", tv->thread_priority,
80✔
916
                      tv->name, SCGetThreadIdLong());
80✔
917
        }
80✔
918
        TmThreadSetPrio(tv);
104✔
919
    }
104✔
920
#endif
104✔
921

922
    return TM_ECODE_OK;
104✔
923
}
104✔
924

925
/**
926
 * \brief Creates and returns the TV instance for a new thread.
927
 *
928
 * \param name       Name of this TV instance
929
 * \param inq_name   Incoming queue name
930
 * \param inqh_name  Incoming queue handler name as set by TmqhSetup()
931
 * \param outq_name  Outgoing queue name
932
 * \param outqh_name Outgoing queue handler as set by TmqhSetup()
933
 * \param slots      String representation for the slot function to be used
934
 * \param fn_p       Pointer to function when \"slots\" is of type \"custom\"
935
 * \param mucond     Flag to indicate whether to initialize the condition
936
 *                   and the mutex variables for this newly created TV.
937
 *
938
 * \retval the newly created TV instance, or NULL on error
939
 */
940
ThreadVars *TmThreadCreate(const char *name, const char *inq_name, const char *inqh_name,
941
                           const char *outq_name, const char *outqh_name, const char *slots,
942
                           void * (*fn_p)(void *), int mucond)
943
{
29,509✔
944
    ThreadVars *tv = NULL;
29,509✔
945
    Tmq *tmq = NULL;
29,509✔
946
    Tmqh *tmqh = NULL;
29,509✔
947

948
    SCLogDebug("creating thread \"%s\"...", name);
29,509!
949

950
    /* XXX create separate function for this: allocate a thread container */
951
    tv = SCCalloc(1, sizeof(ThreadVars) + ThreadStorageSize());
29,509✔
952
    if (unlikely(tv == NULL))
29,509!
953
        goto error;
×
954

955
    SC_ATOMIC_INIT(tv->flags);
29,509✔
956
    StatsThreadInit(&tv->stats);
29,509✔
957

958
    strlcpy(tv->name, name, sizeof(tv->name));
29,509✔
959

960
    /* default state for every newly created thread */
961
    TmThreadsSetFlag(tv, THV_PAUSE);
29,509✔
962

963
    /* set the incoming queue */
964
    if (inq_name != NULL && strcmp(inq_name, "packetpool") != 0) {
29,509✔
965
        SCLogDebug("inq_name \"%s\"", inq_name);
13,373!
966

967
        tmq = TmqGetQueueByName(inq_name);
13,373✔
968
        if (tmq == NULL) {
13,373!
969
            tmq = TmqCreateQueue(inq_name);
×
970
            if (tmq == NULL)
×
971
                goto error;
×
972
        }
×
973
        SCLogDebug("tmq %p", tmq);
13,373!
974

975
        tv->inq = tmq;
13,373✔
976
        tv->inq->reader_cnt++;
13,373✔
977
        SCLogDebug("tv->inq %p", tv->inq);
13,373!
978
    }
13,373✔
979
    if (inqh_name != NULL) {
29,509✔
980
        SCLogDebug("inqh_name \"%s\"", inqh_name);
16,813!
981

982
        int id = TmqhNameToID(inqh_name);
16,813✔
983
        if (id <= 0) {
16,813!
984
            goto error;
×
985
        }
×
986
        tmqh = TmqhGetQueueHandlerByName(inqh_name);
16,813✔
987
        if (tmqh == NULL)
16,813!
988
            goto error;
×
989

990
        tv->tmqh_in = tmqh->InHandler;
16,813✔
991
        tv->inq_id = (uint8_t)id;
16,813✔
992
        SCLogDebug("tv->tmqh_in %p", tv->tmqh_in);
16,813!
993
    }
16,813✔
994

995
    /* set the outgoing queue */
996
    if (outqh_name != NULL) {
29,509✔
997
        SCLogDebug("outqh_name \"%s\"", outqh_name);
16,813!
998

999
        int id = TmqhNameToID(outqh_name);
16,813✔
1000
        if (id <= 0) {
16,813!
1001
            goto error;
×
1002
        }
×
1003

1004
        tmqh = TmqhGetQueueHandlerByName(outqh_name);
16,813✔
1005
        if (tmqh == NULL)
16,813!
1006
            goto error;
×
1007

1008
        tv->tmqh_out = tmqh->OutHandler;
16,813✔
1009
        tv->outq_id = (uint8_t)id;
16,813✔
1010

1011
        if (outq_name != NULL && strcmp(outq_name, "packetpool") != 0) {
16,813!
1012
            SCLogDebug("outq_name \"%s\"", outq_name);
3,350!
1013

1014
            if (tmqh->OutHandlerCtxSetup != NULL) {
3,350!
1015
                tv->outctx = tmqh->OutHandlerCtxSetup(outq_name);
3,346✔
1016
                if (tv->outctx == NULL)
3,346!
1017
                    goto error;
×
1018
                tv->outq = NULL;
3,346✔
1019
            } else {
3,346✔
1020
                tmq = TmqGetQueueByName(outq_name);
4✔
1021
                if (tmq == NULL) {
4!
1022
                    tmq = TmqCreateQueue(outq_name);
1✔
1023
                    if (tmq == NULL)
1!
1024
                        goto error;
×
1025
                }
1✔
1026
                SCLogDebug("tmq %p", tmq);
4!
1027

1028
                tv->outq = tmq;
4✔
1029
                tv->outctx = NULL;
4✔
1030
                tv->outq->writer_cnt++;
4✔
1031
            }
4✔
1032
        }
3,350✔
1033
    }
16,813✔
1034

1035
    if (TmThreadSetSlots(tv, slots, fn_p) != TM_ECODE_OK) {
29,509!
1036
        goto error;
×
1037
    }
×
1038

1039
    if (mucond != 0)
29,509✔
1040
        TmThreadInitMC(tv);
5,865✔
1041

1042
    SCThreadRunInitCallbacks(tv);
29,509✔
1043

1044
    return tv;
29,509✔
1045

1046
error:
×
1047
    SCLogError("failed to setup a thread");
×
1048

1049
    if (tv != NULL)
×
1050
        SCFree(tv);
×
1051
    return NULL;
×
1052
}
29,509✔
1053

1054
/**
1055
 * \brief Creates and returns a TV instance for a Packet Processing Thread.
1056
 *        This function doesn't support custom slots, and hence shouldn't be
1057
 *        supplied \"custom\" as its slot type.  All PPT threads are created
1058
 *        with a mucond(see TmThreadCreate declaration) of 0. Hence the tv
1059
 *        conditional variables are not used to kill the thread.
1060
 *
1061
 * \param name       Name of this TV instance
1062
 * \param inq_name   Incoming queue name
1063
 * \param inqh_name  Incoming queue handler name as set by TmqhSetup()
1064
 * \param outq_name  Outgoing queue name
1065
 * \param outqh_name Outgoing queue handler as set by TmqhSetup()
1066
 * \param slots      String representation for the slot function to be used
1067
 *
1068
 * \retval the newly created TV instance, or NULL on error
1069
 */
1070
ThreadVars *TmThreadCreatePacketHandler(const char *name, const char *inq_name,
1071
                                        const char *inqh_name, const char *outq_name,
1072
                                        const char *outqh_name, const char *slots)
1073
{
16,813✔
1074
    ThreadVars *tv = NULL;
16,813✔
1075

1076
    tv = TmThreadCreate(name, inq_name, inqh_name, outq_name, outqh_name,
16,813✔
1077
                        slots, NULL, 0);
16,813✔
1078

1079
    if (tv != NULL) {
16,813!
1080
        tv->type = TVT_PPT;
16,813✔
1081
        tv->id = TmThreadsRegisterThread(tv, tv->type);
16,813✔
1082
    }
16,813✔
1083

1084
    return tv;
16,813✔
1085
}
16,813✔
1086

1087
/**
1088
 * \brief Creates and returns the TV instance for a Management thread(MGMT).
1089
 *        This function supports only custom slot functions and hence a
1090
 *        function pointer should be sent as an argument.
1091
 *
1092
 * \param name       Name of this TV instance
1093
 * \param fn_p       Pointer to function when \"slots\" is of type \"custom\"
1094
 * \param mucond     Flag to indicate whether to initialize the condition
1095
 *                   and the mutex variables for this newly created TV.
1096
 *
1097
 * \retval the newly created TV instance, or NULL on error
1098
 */
1099
ThreadVars *TmThreadCreateMgmtThread(const char *name, void *(fn_p)(void *),
1100
                                     int mucond)
1101
{
5,850✔
1102
    ThreadVars *tv = NULL;
5,850✔
1103

1104
    tv = TmThreadCreate(name, NULL, NULL, NULL, NULL, "custom", fn_p, mucond);
5,850✔
1105

1106
    if (tv != NULL) {
5,850!
1107
        tv->type = TVT_MGMT;
5,850✔
1108
        tv->id = TmThreadsRegisterThread(tv, tv->type);
5,850✔
1109
        TmThreadSetCPU(tv, MANAGEMENT_CPU_SET);
5,850✔
1110
    }
5,850✔
1111

1112
    return tv;
5,850✔
1113
}
5,850✔
1114

1115
/**
1116
 * \brief Creates and returns the TV instance for a Management thread(MGMT).
1117
 *        This function supports only custom slot functions and hence a
1118
 *        function pointer should be sent as an argument.
1119
 *
1120
 * \param name       Name of this TV instance
1121
 * \param module     Name of TmModule with MANAGEMENT flag set.
1122
 * \param mucond     Flag to indicate whether to initialize the condition
1123
 *                   and the mutex variables for this newly created TV.
1124
 *
1125
 * \retval the newly created TV instance, or NULL on error
1126
 */
1127
ThreadVars *TmThreadCreateMgmtThreadByName(const char *name, const char *module,
1128
                                     int mucond)
1129
{
6,796✔
1130
    ThreadVars *tv = NULL;
6,796✔
1131

1132
    tv = TmThreadCreate(name, NULL, NULL, NULL, NULL, "management", NULL, mucond);
6,796✔
1133

1134
    if (tv != NULL) {
6,796!
1135
        tv->type = TVT_MGMT;
6,796✔
1136
        tv->id = TmThreadsRegisterThread(tv, tv->type);
6,796✔
1137
        TmThreadSetCPU(tv, MANAGEMENT_CPU_SET);
6,796✔
1138

1139
        TmModule *m = TmModuleGetByName(module);
6,796✔
1140
        if (m) {
6,796!
1141
            TmSlotSetFuncAppend(tv, m, NULL);
6,796✔
1142
        }
6,796✔
1143
    }
6,796✔
1144

1145
    return tv;
6,796✔
1146
}
6,796✔
1147

1148
/**
1149
 * \brief Creates and returns the TV instance for a Command thread (CMD).
1150
 *        This function supports only custom slot functions and hence a
1151
 *        function pointer should be sent as an argument.
1152
 *
1153
 * \param name       Name of this TV instance
1154
 * \param module     Name of TmModule with COMMAND flag set.
1155
 * \param mucond     Flag to indicate whether to initialize the condition
1156
 *                   and the mutex variables for this newly created TV.
1157
 *
1158
 * \retval the newly created TV instance, or NULL on error
1159
 */
1160
ThreadVars *TmThreadCreateCmdThreadByName(const char *name, const char *module,
1161
                                     int mucond)
1162
{
50✔
1163
    ThreadVars *tv = NULL;
50✔
1164

1165
    tv = TmThreadCreate(name, NULL, NULL, NULL, NULL, "command", NULL, mucond);
50✔
1166

1167
    if (tv != NULL) {
50!
1168
        tv->type = TVT_CMD;
50✔
1169
        tv->id = TmThreadsRegisterThread(tv, tv->type);
50✔
1170
        TmThreadSetCPU(tv, MANAGEMENT_CPU_SET);
50✔
1171

1172
        TmModule *m = TmModuleGetByName(module);
50✔
1173
        if (m) {
50!
1174
            TmSlotSetFuncAppend(tv, m, NULL);
50✔
1175
        }
50✔
1176
    }
50✔
1177

1178
    return tv;
50✔
1179
}
50✔
1180

1181
/**
1182
 * \brief Appends this TV to tv_root based on its type
1183
 *
1184
 * \param type holds the type this TV belongs to.
1185
 */
1186
void TmThreadAppend(ThreadVars *tv, int type)
1187
{
29,508✔
1188
    SCMutexLock(&tv_root_lock);
29,508✔
1189

1190
    if (tv_root[type] == NULL) {
29,508✔
1191
        tv_root[type] = tv;
6,834✔
1192
        tv->next = NULL;
6,834✔
1193

1194
        SCMutexUnlock(&tv_root_lock);
6,834✔
1195

1196
        return;
6,834✔
1197
    }
6,834✔
1198

1199
    ThreadVars *t = tv_root[type];
22,674✔
1200

1201
    while (t) {
51,708!
1202
        if (t->next == NULL) {
51,708✔
1203
            t->next = tv;
22,674✔
1204
            tv->next = NULL;
22,674✔
1205
            break;
22,674✔
1206
        }
22,674✔
1207

1208
        t = t->next;
29,034✔
1209
    }
29,034✔
1210

1211
    SCMutexUnlock(&tv_root_lock);
22,674✔
1212
}
22,674✔
1213

1214
static bool ThreadStillHasPackets(ThreadVars *tv)
1215
{
139,494✔
1216
    if (tv->inq != NULL && !tv->inq->is_packet_pool) {
139,494!
1217
        /* we wait till we dry out all the inq packets, before we
1218
         * kill this thread.  Do note that you should have disabled
1219
         * packet acquire by now using TmThreadDisableReceiveThreads()*/
1220
        PacketQueue *q = tv->inq->pq;
104,535✔
1221
        SCMutexLock(&q->mutex_q);
104,535✔
1222
        uint32_t len = q->len;
104,535✔
1223
        SCMutexUnlock(&q->mutex_q);
104,535✔
1224
        if (len != 0) {
104,535✔
1225
            return true;
19,328✔
1226
        }
19,328✔
1227
    }
104,535✔
1228

1229
    if (tv->stream_pq != NULL) {
120,166✔
1230
        SCMutexLock(&tv->stream_pq->mutex_q);
85,854✔
1231
        uint32_t len = tv->stream_pq->len;
85,854✔
1232
        SCMutexUnlock(&tv->stream_pq->mutex_q);
85,854✔
1233

1234
        if (len != 0) {
85,854!
UNCOV
1235
            return true;
×
UNCOV
1236
        }
×
1237
    }
85,854✔
1238
    return false;
120,166✔
1239
}
120,166✔
1240

1241
/**
1242
 * \brief Kill a thread.
1243
 *
1244
 * \param tv A ThreadVars instance corresponding to the thread that has to be
1245
 *           killed.
1246
 *
1247
 * \retval r 1 killed successfully
1248
 *           0 not yet ready, needs another look
1249
 */
1250
static int TmThreadKillThread(ThreadVars *tv)
1251
{
371,907✔
1252
    BUG_ON(tv == NULL);
371,907!
1253

1254
    /* kill only once :) */
1255
    if (TmThreadsCheckFlag(tv, THV_DEAD)) {
371,907✔
1256
        return 1;
228,309✔
1257
    }
228,309✔
1258

1259
    /* set the thread flag informing the thread that it needs to be
1260
     * terminated */
1261
    TmThreadsSetFlag(tv, THV_KILL);
143,598✔
1262
    TmThreadsSetFlag(tv, THV_DEINIT);
143,598✔
1263

1264
    /* to be sure, signal more */
1265
    if (!(TmThreadsCheckFlag(tv, THV_CLOSED))) {
143,598✔
1266
        if (tv->inq_id != TMQH_NOT_SET) {
114,103✔
1267
            Tmqh *qh = TmqhGetQueueHandlerByID(tv->inq_id);
83,093✔
1268
            if (qh != NULL && qh->InShutdownHandler != NULL) {
83,093!
1269
                qh->InShutdownHandler(tv);
4✔
1270
            }
4✔
1271
        }
83,093✔
1272
        if (tv->inq != NULL) {
114,103✔
1273
            for (int i = 0; i < (tv->inq->reader_cnt + tv->inq->writer_cnt); i++) {
219,651✔
1274
                SCMutexLock(&tv->inq->pq->mutex_q);
146,486✔
1275
                SCCondSignal(&tv->inq->pq->cond_q);
146,486✔
1276
                SCMutexUnlock(&tv->inq->pq->mutex_q);
146,486✔
1277
            }
146,486✔
1278
            SCLogDebug("signalled tv->inq->id %" PRIu32 "", tv->inq->id);
73,165!
1279
        }
73,165✔
1280

1281
        if (tv->ctrl_cond != NULL ) {
114,103✔
1282
            SCCtrlMutexLock(tv->ctrl_mutex);
17,626✔
1283
            pthread_cond_broadcast(tv->ctrl_cond);
17,626✔
1284
            SCCtrlMutexUnlock(tv->ctrl_mutex);
17,626✔
1285
        }
17,626✔
1286
        return 0;
114,103✔
1287
    }
114,103✔
1288

1289
    if (tv->outctx != NULL) {
29,495✔
1290
        if (tv->outq_id != TMQH_NOT_SET) {
3,346!
1291
            Tmqh *qh = TmqhGetQueueHandlerByID(tv->outq_id);
3,346✔
1292
            if (qh != NULL && qh->OutHandlerCtxFree != NULL) {
3,346!
1293
                qh->OutHandlerCtxFree(tv->outctx);
3,346✔
1294
                tv->outctx = NULL;
3,346✔
1295
            }
3,346✔
1296
        }
3,346✔
1297
    }
3,346✔
1298

1299
    /* Join the thread and flag as dead, unless the thread ID is 0 as
1300
     * its not a thread created by Suricata. */
1301
    if (tv->t) {
29,495!
1302
        pthread_join(tv->t, NULL);
29,495✔
1303
        SCLogDebug("thread %s stopped", tv->name);
29,495!
1304
    }
29,495✔
1305
    TmThreadsSetFlag(tv, THV_DEAD);
29,495✔
1306
    return 1;
29,495✔
1307
}
143,598✔
1308

1309
static bool ThreadBusy(ThreadVars *tv)
1310
{
120,166✔
1311
    for (TmSlot *s = tv->tm_slots; s != NULL; s = s->slot_next) {
275,317✔
1312
        TmModule *tm = TmModuleGetById(s->tm_id);
156,556✔
1313
        if (tm && tm->ThreadBusy != NULL) {
156,556!
1314
            if (tm->ThreadBusy(tv, SC_ATOMIC_GET(s->slot_data)))
85,854✔
1315
                return true;
1,405✔
1316
        }
85,854✔
1317
    }
156,556✔
1318
    return false;
118,761✔
1319
}
120,166✔
1320

1321
/** \internal
1322
 *
1323
 *  \brief make sure that all packet threads are done processing their
1324
 *         in-flight packets, including 'injected' flow packets.
1325
 */
1326
static void TmThreadDrainPacketThreads(void)
1327
{
10,194✔
1328
    ThreadVars *tv = NULL;
10,194✔
1329
    struct timeval start_ts;
10,194✔
1330
    struct timeval cur_ts;
10,194✔
1331
    gettimeofday(&start_ts, NULL);
10,194✔
1332

1333
again:
30,926✔
1334
    gettimeofday(&cur_ts, NULL);
30,926✔
1335
    if ((cur_ts.tv_sec - start_ts.tv_sec) > 60) {
30,926!
1336
        SCLogWarning("unable to get all packet threads "
×
1337
                     "to process their packets in time");
×
1338
        return;
×
1339
    }
×
1340

1341
    SCMutexLock(&tv_root_lock);
30,926✔
1342

1343
    /* all receive threads are part of packet processing threads */
1344
    tv = tv_root[TVT_PPT];
30,926✔
1345
    while (tv) {
145,778✔
1346
        if (ThreadStillHasPackets(tv)) {
135,584✔
1347
            /* we wait till we dry out all the inq packets, before we
1348
             * kill this thread.  Do note that you should have disabled
1349
             * packet acquire by now using TmThreadDisableReceiveThreads()*/
1350
            SCMutexUnlock(&tv_root_lock);
19,328✔
1351

1352
            /* sleep outside lock */
1353
            SleepMsec(1);
19,328✔
1354
            goto again;
19,328✔
1355
        }
19,328✔
1356
        if (ThreadBusy(tv)) {
116,256✔
1357
            SCMutexUnlock(&tv_root_lock);
1,404✔
1358

1359
            Packet *p = PacketGetFromAlloc();
1,404✔
1360
            if (p != NULL) {
1,404!
1361
                p->flags |= PKT_PSEUDO_STREAM_END;
1,404✔
1362
                PKT_SET_SRC(p, PKT_SRC_SHUTDOWN_FLUSH);
1,404✔
1363
                CaptureHooksOnPseudoPacketCreated(p);
1,404✔
1364
                PacketQueue *q = tv->stream_pq;
1,404✔
1365
                SCMutexLock(&q->mutex_q);
1,404✔
1366
                PacketEnqueue(q, p);
1,404✔
1367
                SCCondSignal(&q->cond_q);
1,404✔
1368
                SCMutexUnlock(&q->mutex_q);
1,404✔
1369
            }
1,404✔
1370

1371
            /* don't sleep while holding a lock */
1372
            SleepMsec(1);
1,404✔
1373
            goto again;
1,404✔
1374
        }
1,404✔
1375
        tv = tv->next;
114,852✔
1376
    }
114,852✔
1377

1378
    SCMutexUnlock(&tv_root_lock);
10,194✔
1379
}
10,194✔
1380

1381
/**
1382
 *  \brief Disable all threads having the specified TMs.
1383
 *
1384
 *  Breaks out of the packet acquisition loop, and bumps
1385
 *  into the 'flow loop', where it will process packets
1386
 *  from the flow engine's shutdown handling.
1387
 */
1388
void TmThreadDisableReceiveThreads(void)
1389
{
3,398✔
1390
    ThreadVars *tv = NULL;
3,398✔
1391
    struct timeval start_ts;
3,398✔
1392
    struct timeval cur_ts;
3,398✔
1393
    gettimeofday(&start_ts, NULL);
3,398✔
1394

1395
again:
3,869✔
1396
    gettimeofday(&cur_ts, NULL);
3,869✔
1397
    if ((cur_ts.tv_sec - start_ts.tv_sec) > 60) {
3,869!
1398
        FatalError("Engine unable to disable detect "
×
1399
                   "thread - \"%s\". Killing engine",
×
1400
                tv->name);
×
1401
    }
×
1402

1403
    SCMutexLock(&tv_root_lock);
3,869✔
1404

1405
    /* all receive threads are part of packet processing threads */
1406
    tv = tv_root[TVT_PPT];
3,869✔
1407

1408
    /* we do have to keep in mind that TVs are arranged in the order
1409
     * right from receive to log.  The moment we fail to find a
1410
     * receive TM amongst the slots in a tv, it indicates we are done
1411
     * with all receive threads */
1412
    while (tv) {
20,681✔
1413
        int disable = 0;
17,283✔
1414
        TmModule *tm = NULL;
17,283✔
1415
        /* obtain the slots for this TV */
1416
        TmSlot *slots = tv->tm_slots;
17,283✔
1417
        while (slots != NULL) {
30,677✔
1418
            tm = TmModuleGetById(slots->tm_id);
17,304✔
1419

1420
            if (tm->flags & TM_FLAG_RECEIVE_TM) {
17,304✔
1421
                disable = 1;
3,910✔
1422
                break;
3,910✔
1423
            }
3,910✔
1424

1425
            slots = slots->slot_next;
13,394✔
1426
            continue;
13,394✔
1427
        }
17,304✔
1428

1429
        if (disable) {
17,283✔
1430
            if (ThreadStillHasPackets(tv)) {
3,910!
1431
                /* we wait till we dry out all the inq packets, before we
1432
                 * kill this thread.  Do note that you should have disabled
1433
                 * packet acquire by now using TmThreadDisableReceiveThreads()*/
1434
                SCMutexUnlock(&tv_root_lock);
×
1435
                /* don't sleep while holding a lock */
1436
                SleepMsec(1);
×
1437
                goto again;
×
1438
            }
×
1439

1440
            if (ThreadBusy(tv)) {
3,910✔
1441
                SCMutexUnlock(&tv_root_lock);
1✔
1442

1443
                Packet *p = PacketGetFromAlloc();
1✔
1444
                if (p != NULL) {
1!
1445
                    p->flags |= PKT_PSEUDO_STREAM_END;
1✔
1446
                    PKT_SET_SRC(p, PKT_SRC_SHUTDOWN_FLUSH);
1✔
1447
                    CaptureHooksOnPseudoPacketCreated(p);
1✔
1448
                    PacketQueue *q = tv->stream_pq;
1✔
1449
                    SCMutexLock(&q->mutex_q);
1✔
1450
                    PacketEnqueue(q, p);
1✔
1451
                    SCCondSignal(&q->cond_q);
1✔
1452
                    SCMutexUnlock(&q->mutex_q);
1✔
1453
                }
1✔
1454

1455
                /* don't sleep while holding a lock */
1456
                SleepMsec(1);
1✔
1457
                goto again;
1✔
1458
            }
1✔
1459

1460
            /* we found a receive TV. Send it a KILL_PKTACQ signal. */
1461
            if (tm && tm->PktAcqBreakLoop != NULL) {
3,909!
1462
                tm->PktAcqBreakLoop(tv, SC_ATOMIC_GET(slots->slot_data));
3✔
1463
            }
3✔
1464
            TmThreadsSetFlag(tv, THV_REQ_FLOW_LOOP);
3,909✔
1465

1466
            if (tv->inq != NULL) {
3,909!
1467
                for (int i = 0; i < (tv->inq->reader_cnt + tv->inq->writer_cnt); i++) {
×
1468
                    SCMutexLock(&tv->inq->pq->mutex_q);
×
1469
                    SCCondSignal(&tv->inq->pq->cond_q);
×
1470
                    SCMutexUnlock(&tv->inq->pq->mutex_q);
×
1471
                }
×
1472
                SCLogDebug("signalled tv->inq->id %" PRIu32 "", tv->inq->id);
×
1473
            }
×
1474

1475
            /* wait for it to enter the 'flow loop' stage */
1476
            while (!TmThreadsCheckFlag(tv, THV_FLOW_LOOP)) {
3,909!
1477
                SCMutexUnlock(&tv_root_lock);
470✔
1478

1479
                SleepMsec(1);
470✔
1480
                goto again;
470✔
1481
            }
470✔
1482
        }
3,909✔
1483

1484
        tv = tv->next;
16,812✔
1485
    }
16,812✔
1486

1487
    SCMutexUnlock(&tv_root_lock);
3,398✔
1488

1489
    /* finally wait for all packet threads to have
1490
     * processed all of their 'live' packets so we
1491
     * don't process the last live packets together
1492
     * with FFR packets */
1493
    TmThreadDrainPacketThreads();
3,398✔
1494
}
3,398✔
1495

1496
#ifdef DEBUG_VALIDATION
1497
static void TmThreadDumpThreads(void);
1498
#endif
1499

1500
static void TmThreadDebugValidateNoMorePackets(void)
1501
{
6,796✔
1502
#ifdef DEBUG_VALIDATION
1503
    SCMutexLock(&tv_root_lock);
1504
    for (ThreadVars *tv = tv_root[TVT_PPT]; tv != NULL; tv = tv->next) {
1505
        if (ThreadStillHasPackets(tv)) {
1506
            SCMutexUnlock(&tv_root_lock);
1507
            TmThreadDumpThreads();
1508
            DEBUG_VALIDATE_BUG_ON(1);
1509
        }
1510
    }
1511
    SCMutexUnlock(&tv_root_lock);
1512
#endif
1513
}
6,796✔
1514

1515
/** \internal
1516
 *  \brief check if a thread has any of the modules indicated by TM_FLAG_*
1517
 *  \param tv thread
1518
 *  \param flags TM_FLAG_*'s
1519
 *  \retval bool true if at least on of the flags is present */
1520
static inline bool CheckModuleFlags(const ThreadVars *tv, const uint8_t flags)
1521
{
118,872✔
1522
    return (tv->tmm_flags & flags) != 0;
118,872✔
1523
}
118,872✔
1524

1525
/**
1526
 * \brief Disable all packet threads
1527
 * \param set flag to set
1528
 * \param check flag to check
1529
 * \param module_flags bitflags of TmModule's to apply the `set` flag to.
1530
 *
1531
 * Support 2 stages in shutting down the packet threads:
1532
 * 1. set THV_REQ_FLOW_LOOP and wait for THV_FLOW_LOOP
1533
 * 2. set THV_KILL and wait for THV_RUNNING_DONE
1534
 *
1535
 * During step 1 the main loop is exited, and the flow loop logic is entered.
1536
 * During step 2, the flow loop logic is done and the thread closes.
1537
 *
1538
 * `module_flags` limits which threads are disabled
1539
 */
1540
void TmThreadDisablePacketThreads(
1541
        const uint16_t set, const uint16_t check, const uint8_t module_flags)
1542
{
6,796✔
1543
    struct timeval start_ts;
6,796✔
1544
    struct timeval cur_ts;
6,796✔
1545

1546
    /* first drain all packet threads of their packets */
1547
    TmThreadDrainPacketThreads();
6,796✔
1548

1549
    /* since all the threads possibly able to produce more packets
1550
     * are now gone or inactive, we should see no packets anywhere
1551
     * anymore. */
1552
    TmThreadDebugValidateNoMorePackets();
6,796✔
1553

1554
    gettimeofday(&start_ts, NULL);
6,796✔
1555
again:
31,099✔
1556
    gettimeofday(&cur_ts, NULL);
31,099✔
1557
    if ((cur_ts.tv_sec - start_ts.tv_sec) > 60) {
31,099!
1558
        FatalError("Engine unable to disable packet  "
×
1559
                   "threads. Killing engine");
×
1560
    }
×
1561

1562
    /* loop through the packet threads and kill them */
1563
    SCMutexLock(&tv_root_lock);
31,099✔
1564
    for (ThreadVars *tv = tv_root[TVT_PPT]; tv != NULL; tv = tv->next) {
125,668✔
1565
        /* only set flow worker threads to THV_REQ_FLOW_LOOP */
1566
        if (!CheckModuleFlags(tv, module_flags)) {
118,872!
1567
            SCLogDebug("%s does not have any of the modules %02x, skip", tv->name, module_flags);
1!
1568
            continue;
1✔
1569
        }
1✔
1570
        TmThreadsSetFlag(tv, set);
118,871✔
1571

1572
        /* separate worker threads (autofp) will still wait at their
1573
         * input queues. So nudge them here so they will observe the
1574
         * THV_KILL flag. */
1575
        if (tv->inq != NULL) {
118,871✔
1576
            for (int i = 0; i < (tv->inq->reader_cnt + tv->inq->writer_cnt); i++) {
262,812✔
1577
                SCMutexLock(&tv->inq->pq->mutex_q);
175,294✔
1578
                SCCondSignal(&tv->inq->pq->cond_q);
175,294✔
1579
                SCMutexUnlock(&tv->inq->pq->mutex_q);
175,294✔
1580
            }
175,294✔
1581
            SCLogDebug("signalled tv->inq->id %" PRIu32 "", tv->inq->id);
87,518!
1582
        }
87,518✔
1583

1584
        /* wait for it to reach the expected state */
1585
        if (!TmThreadsCheckFlag(tv, check)) {
118,871✔
1586
            SCMutexUnlock(&tv_root_lock);
24,303✔
1587
            SCLogDebug("%s did not reach state %u, again", tv->name, check);
24,303!
1588

1589
            SleepMsec(1);
24,303✔
1590
            goto again;
24,303✔
1591
        }
24,303✔
1592
    }
118,871✔
1593
    SCMutexUnlock(&tv_root_lock);
6,796✔
1594
}
6,796✔
1595

1596
#define MIN_WAIT_TIME 100
270,627✔
1597
#define MAX_WAIT_TIME 999999
1598
void TmThreadKillThreadsFamily(int family)
1599
{
12,823✔
1600
    ThreadVars *tv = NULL;
12,823✔
1601
    unsigned int sleep_usec = MIN_WAIT_TIME;
12,823✔
1602

1603
    BUG_ON((family < 0) || (family >= TVT_MAX));
12,823!
1604

1605
again:
126,926✔
1606
    SCMutexLock(&tv_root_lock);
126,926✔
1607
    tv = tv_root[family];
126,926✔
1608

1609
    while (tv) {
384,730✔
1610
        int r = TmThreadKillThread(tv);
371,907✔
1611
        if (r == 0) {
371,907✔
1612
            SCMutexUnlock(&tv_root_lock);
114,103✔
1613
            SleepUsec(sleep_usec);
114,103✔
1614
            sleep_usec *= 2; /* slowly back off */
114,103✔
1615
            sleep_usec = MIN(sleep_usec, MAX_WAIT_TIME);
114,103!
1616
            goto again;
114,103✔
1617
        }
114,103✔
1618
        sleep_usec = MIN_WAIT_TIME; /* reset */
257,804✔
1619

1620
        tv = tv->next;
257,804✔
1621
    }
257,804✔
1622
    SCMutexUnlock(&tv_root_lock);
12,823✔
1623
}
12,823✔
1624
#undef MIN_WAIT_TIME
1625
#undef MAX_WAIT_TIME
1626

1627
void TmThreadKillThreads(void)
1628
{
2,009✔
1629
    int i = 0;
2,009✔
1630

1631
    for (i = 0; i < TVT_MAX; i++) {
8,036✔
1632
        TmThreadKillThreadsFamily(i);
6,027✔
1633
    }
6,027✔
1634
}
2,009✔
1635

1636
static void TmThreadFree(ThreadVars *tv)
1637
{
29,458✔
1638
    TmSlot *s;
29,458✔
1639
    TmSlot *ps;
29,458✔
1640
    if (tv == NULL)
29,458!
1641
        return;
×
1642

1643
    SCLogDebug("Freeing thread '%s'.", tv->name);
29,458!
1644

1645
    ThreadFreeStorage(tv);
29,458✔
1646

1647
    if (tv->flow_queue) {
29,458✔
1648
        BUG_ON(tv->flow_queue->qlen != 0);
13,465!
1649
        SCFree(tv->flow_queue);
13,465✔
1650
    }
13,465✔
1651

1652
    StatsThreadCleanup(&tv->stats);
29,458✔
1653

1654
    TmThreadDeinitMC(tv);
29,458✔
1655

1656
    if (tv->printable_name) {
29,458!
1657
        SCFree(tv->printable_name);
59✔
1658
    }
59✔
1659

1660
    if (tv->iface_name) {
29,458!
1661
        SCFree(tv->iface_name);
59✔
1662
    }
59✔
1663

1664
    if (tv->stream_pq_local) {
29,458✔
1665
        BUG_ON(tv->stream_pq_local->len);
93!
1666
        SCMutexDestroy(&tv->stream_pq_local->mutex_q);
93✔
1667
        SCFree(tv->stream_pq_local);
93✔
1668
    }
93✔
1669

1670
    s = (TmSlot *)tv->tm_slots;
29,458✔
1671
    while (s) {
56,674✔
1672
        ps = s;
27,216✔
1673
        s = s->slot_next;
27,216✔
1674
        SCFree(ps);
27,216✔
1675
    }
27,216✔
1676

1677
    TmThreadsUnregisterThread(tv->id);
29,458✔
1678
    SCFree(tv);
29,458✔
1679
}
29,458✔
1680

1681
void TmThreadClearThreadsFamily(int family)
1682
{
6,796✔
1683
    ThreadVars *tv = NULL;
6,796✔
1684
    ThreadVars *ptv = NULL;
6,796✔
1685

1686
    if ((family < 0) || (family >= TVT_MAX))
6,796!
1687
        return;
×
1688

1689
    SCMutexLock(&tv_root_lock);
6,796✔
1690
    tv = tv_root[family];
6,796✔
1691

1692
    while (tv) {
36,254✔
1693
        ptv = tv;
29,458✔
1694
        tv = tv->next;
29,458✔
1695
        TmThreadFree(ptv);
29,458✔
1696
    }
29,458✔
1697
    tv_root[family] = NULL;
6,796✔
1698
    SCMutexUnlock(&tv_root_lock);
6,796✔
1699
}
6,796✔
1700

1701
/**
1702
 * \brief Spawns a thread associated with the ThreadVars instance tv
1703
 *
1704
 * \retval TM_ECODE_OK on success and TM_ECODE_FAILED on failure
1705
 */
1706
TmEcode TmThreadSpawn(ThreadVars *tv)
1707
{
29,508✔
1708
    pthread_attr_t attr;
29,508✔
1709
    if (tv->tm_func == NULL) {
29,508!
1710
        FatalError("No thread function set");
×
1711
    }
×
1712

1713
    /* Initialize and set thread detached attribute */
1714
    pthread_attr_init(&attr);
29,508✔
1715

1716
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
29,508✔
1717

1718
    /* Adjust thread stack size if configured */
1719
    if (threading_set_stack_size) {
29,508!
1720
        SCLogDebug("Setting per-thread stack size to %" PRIu64, threading_set_stack_size);
×
1721
        if (pthread_attr_setstacksize(&attr, (size_t)threading_set_stack_size)) {
×
1722
            FatalError("Unable to increase stack size to %" PRIu64 " in thread attributes",
×
1723
                    threading_set_stack_size);
×
1724
        }
×
1725
    }
×
1726

1727
    int rc = pthread_create(&tv->t, &attr, tv->tm_func, (void *)tv);
29,508✔
1728
    if (rc) {
29,508!
1729
        FatalError("Unable to create thread %s with pthread_create(): retval %d: %s", tv->name, rc,
×
1730
                strerror(errno));
×
1731
    }
×
1732

1733
#if DEBUG && HAVE_PTHREAD_GETATTR_NP
1734
    if (threading_set_stack_size) {
1735
        if (pthread_getattr_np(tv->t, &attr) == 0) {
1736
            size_t stack_size;
1737
            void *stack_addr;
1738
            pthread_attr_getstack(&attr, &stack_addr, &stack_size);
1739
            SCLogDebug("stack: %p;  size %" PRIu64, stack_addr, (uintmax_t)stack_size);
1740
        } else {
1741
            SCLogDebug("Unable to retrieve current stack-size for display; return code from "
1742
                       "pthread_getattr_np() is %" PRId32,
1743
                    rc);
1744
        }
1745
    }
1746
#endif
1747

1748
    TmThreadWaitForFlag(tv, THV_INIT_DONE | THV_RUNNING_DONE);
29,508✔
1749

1750
    TmThreadAppend(tv, tv->type);
29,508✔
1751
    return TM_ECODE_OK;
29,508✔
1752
}
29,508✔
1753

1754
/**
1755
 * \brief Spawns a "fake" lib thread associated with the ThreadVars instance tv
1756
 *
1757
 * \retval TM_ECODE_OK on success and TM_ECODE_FAILED on failure
1758
 */
1759
TmEcode TmThreadLibSpawn(ThreadVars *tv)
1760
{
×
1761
    if (tv->tm_func == NULL) {
×
1762
        printf("ERROR: no thread function set\n");
×
1763
        return TM_ECODE_FAILED;
×
1764
    }
×
1765

1766
    if (tv->tm_func((void *)tv) == (void *)-1) {
×
1767
        return TM_ECODE_FAILED;
×
1768
    }
×
1769

1770
    TmThreadWaitForFlag(tv, THV_INIT_DONE | THV_RUNNING_DONE);
×
1771

1772
    return TM_ECODE_OK;
×
1773
}
×
1774

1775
/**
1776
 * \brief Initializes the mutex and condition variables for this TV
1777
 *
1778
 * It can be used by a thread to control a wait loop that can also be
1779
 * influenced by other threads.
1780
 *
1781
 * \param tv Pointer to a TV instance
1782
 */
1783
void TmThreadInitMC(ThreadVars *tv)
1784
{
5,865✔
1785
    if ( (tv->ctrl_mutex = SCMalloc(sizeof(*tv->ctrl_mutex))) == NULL) {
5,865!
1786
        FatalError("Fatal error encountered in TmThreadInitMC.  "
×
1787
                   "Exiting...");
×
1788
    }
×
1789

1790
    if (SCCtrlMutexInit(tv->ctrl_mutex, NULL) != 0) {
5,865!
1791
        printf("Error initializing the tv->m mutex\n");
×
1792
        exit(EXIT_FAILURE);
×
1793
    }
×
1794

1795
    if ( (tv->ctrl_cond = SCMalloc(sizeof(*tv->ctrl_cond))) == NULL) {
5,865!
1796
        FatalError("Fatal error encountered in TmThreadInitMC.  "
×
1797
                   "Exiting...");
×
1798
    }
×
1799

1800
    if (SCCtrlCondInit(tv->ctrl_cond, NULL) != 0) {
5,865!
1801
        FatalError("Error initializing the tv->cond condition "
×
1802
                   "variable");
×
1803
    }
×
1804
}
5,865✔
1805

1806
static void TmThreadDeinitMC(ThreadVars *tv)
1807
{
29,458✔
1808
    if (tv->ctrl_mutex) {
29,458✔
1809
        SCCtrlMutexDestroy(tv->ctrl_mutex);
5,850✔
1810
        SCFree(tv->ctrl_mutex);
5,850✔
1811
    }
5,850✔
1812
    if (tv->ctrl_cond) {
29,458✔
1813
        SCCtrlCondDestroy(tv->ctrl_cond);
5,850✔
1814
        SCFree(tv->ctrl_cond);
5,850✔
1815
    }
5,850✔
1816
}
29,458✔
1817

1818
/**
1819
 * \brief Waits till the specified flag(s) is(are) set.  We don't bother if
1820
 *        the kill flag has been set or not on the thread.
1821
 *
1822
 * \param tv Pointer to the TV instance.
1823
 */
1824
void TmThreadWaitForFlag(ThreadVars *tv, uint32_t flags)
1825
{
59,010✔
1826
    while (!TmThreadsCheckFlag(tv, flags)) {
3,262,742✔
1827
        SleepUsec(100);
3,203,732✔
1828
    }
3,203,732✔
1829
}
59,010✔
1830

1831
/**
1832
 * \brief Unpauses a thread
1833
 *
1834
 * \param tv Pointer to a TV instance that has to be unpaused
1835
 */
1836
void TmThreadContinue(ThreadVars *tv)
1837
{
30,901✔
1838
    TmThreadsUnsetFlag(tv, THV_PAUSE);
30,901✔
1839
}
30,901✔
1840

1841
static TmEcode WaitOnThreadsRunningByType(const int t)
1842
{
6,027✔
1843
    struct timeval start_ts;
6,027✔
1844
    struct timeval cur_ts;
6,027✔
1845
    uint32_t thread_cnt = 0;
6,027✔
1846

1847
    /* on retries, this will init to the last thread that started up already */
1848
    ThreadVars *tv_start = tv_root[t];
6,027✔
1849
    SCMutexLock(&tv_root_lock);
6,027✔
1850
    for (ThreadVars *tv = tv_start; tv != NULL; tv = tv->next) {
23,003✔
1851
        thread_cnt++;
16,976✔
1852
    }
16,976✔
1853
    SCMutexUnlock(&tv_root_lock);
6,027✔
1854

1855
    /* give threads a second each to start up, plus a margin of a minute. */
1856
    uint32_t time_budget = 60 + thread_cnt;
6,027✔
1857

1858
    gettimeofday(&start_ts, NULL);
6,027✔
1859
again:
15,967✔
1860
    SCMutexLock(&tv_root_lock);
15,967✔
1861
    ThreadVars *tv = tv_start;
15,967✔
1862
    while (tv != NULL) {
34,770✔
1863
        if (TmThreadsCheckFlag(tv, (THV_FAILED | THV_CLOSED | THV_DEAD))) {
28,743!
1864
            SCMutexUnlock(&tv_root_lock);
×
1865

1866
            SCLogError("thread \"%s\" failed to "
×
1867
                       "start: flags %04x",
×
1868
                    tv->name, SC_ATOMIC_GET(tv->flags));
×
1869
            return TM_ECODE_FAILED;
×
1870
        }
×
1871

1872
        if (!(TmThreadsCheckFlag(tv, THV_RUNNING | THV_RUNNING_DONE))) {
28,743✔
1873
            SCMutexUnlock(&tv_root_lock);
9,940✔
1874

1875
            /* 60 seconds provided for the thread to transition from
1876
             * THV_INIT_DONE to THV_RUNNING */
1877
            gettimeofday(&cur_ts, NULL);
9,940✔
1878
            if (((uint32_t)cur_ts.tv_sec - (uint32_t)start_ts.tv_sec) > time_budget) {
9,940!
1879
                SCLogError("thread \"%s\" failed to "
×
1880
                           "start in time: flags %04x. Total threads: %u. Time budget %us",
×
1881
                        tv->name, SC_ATOMIC_GET(tv->flags), thread_cnt, time_budget);
×
1882
                return TM_ECODE_FAILED;
×
1883
            }
×
1884

1885
            /* sleep a little to give the thread some
1886
             * time to start running */
1887
            SleepUsec(100);
9,940✔
1888
            goto again;
9,940✔
1889
        }
9,940✔
1890
        tv_start = tv;
18,803✔
1891

1892
        tv = tv->next;
18,803✔
1893
    }
18,803✔
1894
    SCMutexUnlock(&tv_root_lock);
6,027✔
1895
    return TM_ECODE_OK;
6,027✔
1896
}
15,967✔
1897

1898
/**
1899
 * \brief Waits for all threads to be in a running state
1900
 *
1901
 * \retval TM_ECODE_OK if all are running or error if a thread failed
1902
 */
1903
TmEcode TmThreadWaitOnThreadRunning(void)
1904
{
2,009✔
1905
    uint16_t RX_num = 0;
2,009✔
1906
    uint16_t W_num = 0;
2,009✔
1907
    uint16_t FM_num = 0;
2,009✔
1908
    uint16_t FR_num = 0;
2,009✔
1909
    uint16_t TX_num = 0;
2,009✔
1910

1911
    for (int i = 0; i < TVT_MAX; i++) {
8,036✔
1912
        if (WaitOnThreadsRunningByType(i) != TM_ECODE_OK)
6,027!
1913
            return TM_ECODE_FAILED;
×
1914
    }
6,027✔
1915

1916
    SCMutexLock(&tv_root_lock);
2,009✔
1917
    for (int i = 0; i < TVT_MAX; i++) {
8,036✔
1918
        for (ThreadVars *tv = tv_root[i]; tv != NULL; tv = tv->next) {
23,003✔
1919
            if (strncmp(thread_name_autofp, tv->name, strlen(thread_name_autofp)) == 0)
16,976✔
1920
                RX_num++;
1,955✔
1921
            else if (strncmp(thread_name_workers, tv->name, strlen(thread_name_workers)) == 0)
15,021✔
1922
                W_num++;
7,901✔
1923
            else if (strncmp(thread_name_verdict, tv->name, strlen(thread_name_verdict)) == 0)
7,120!
1924
                TX_num++;
1✔
1925
            else if (strncmp(thread_name_flow_mgr, tv->name, strlen(thread_name_flow_mgr)) == 0)
7,119✔
1926
                FM_num++;
2,007✔
1927
            else if (strncmp(thread_name_flow_rec, tv->name, strlen(thread_name_flow_rec)) == 0)
5,112✔
1928
                FR_num++;
2,007✔
1929
        }
16,976✔
1930
    }
6,027✔
1931
    SCMutexUnlock(&tv_root_lock);
2,009✔
1932

1933
    /* Construct a welcome string displaying
1934
     * initialized thread types and counts */
1935
    uint16_t app_len = 32;
2,009✔
1936
    uint16_t buf_len = 256;
2,009✔
1937

1938
    char append_str[app_len];
2,009✔
1939
    char thread_counts[buf_len];
2,009✔
1940

1941
    strlcpy(thread_counts, "Threads created -> ", strlen("Threads created -> ") + 1);
2,009✔
1942
    if (RX_num > 0) {
2,009✔
1943
        snprintf(append_str, app_len, "RX: %u ", RX_num);
1,946✔
1944
        strlcat(thread_counts, append_str, buf_len);
1,946✔
1945
    }
1,946✔
1946
    if (W_num > 0) {
2,009✔
1947
        snprintf(append_str, app_len, "W: %u ", W_num);
2,007✔
1948
        strlcat(thread_counts, append_str, buf_len);
2,007✔
1949
    }
2,007✔
1950
    if (TX_num > 0) {
2,009!
1951
        snprintf(append_str, app_len, "TX: %u ", TX_num);
1✔
1952
        strlcat(thread_counts, append_str, buf_len);
1✔
1953
    }
1✔
1954
    if (FM_num > 0) {
2,009✔
1955
        snprintf(append_str, app_len, "FM: %u ", FM_num);
2,007✔
1956
        strlcat(thread_counts, append_str, buf_len);
2,007✔
1957
    }
2,007✔
1958
    if (FR_num > 0) {
2,009✔
1959
        snprintf(append_str, app_len, "FR: %u ", FR_num);
2,007✔
1960
        strlcat(thread_counts, append_str, buf_len);
2,007✔
1961
    }
2,007✔
1962
    snprintf(append_str, app_len, "  Engine started.");
2,009✔
1963
    strlcat(thread_counts, append_str, buf_len);
2,009✔
1964
    SCLogNotice("%s", thread_counts);
2,009✔
1965

1966
    return TM_ECODE_OK;
2,009✔
1967
}
2,009✔
1968

1969
/**
1970
 * \brief Unpauses all threads present in tv_root
1971
 */
1972
void TmThreadContinueThreads(void)
1973
{
3,400✔
1974
    SCMutexLock(&tv_root_lock);
3,400✔
1975
    for (int i = 0; i < TVT_MAX; i++) {
13,600✔
1976
        ThreadVars *tv = tv_root[i];
10,200✔
1977
        while (tv != NULL) {
41,086✔
1978
            TmThreadContinue(tv);
30,886✔
1979
            tv = tv->next;
30,886✔
1980
        }
30,886✔
1981
    }
10,200✔
1982
    SCMutexUnlock(&tv_root_lock);
3,400✔
1983
}
3,400✔
1984

1985
/**
1986
 * \brief Used to check the thread for certain conditions of failure.
1987
 */
1988
void TmThreadCheckThreadState(void)
1989
{
94,726✔
1990
    SCMutexLock(&tv_root_lock);
94,726✔
1991
    for (int i = 0; i < TVT_MAX; i++) {
378,904✔
1992
        ThreadVars *tv = tv_root[i];
284,178✔
1993
        while (tv) {
1,170,462✔
1994
            if (TmThreadsCheckFlag(tv, THV_FAILED)) {
886,284!
1995
                FatalError("thread %s failed", tv->name);
×
1996
            }
×
1997
            tv = tv->next;
886,284✔
1998
        }
886,284✔
1999
    }
284,178✔
2000
    SCMutexUnlock(&tv_root_lock);
94,726✔
2001
}
94,726✔
2002

2003
/**
2004
 *  \brief Used to check if all threads have finished their initialization.  On
2005
 *         finding an un-initialized thread, it waits till that thread completes
2006
 *         its initialization, before proceeding to the next thread.
2007
 *
2008
 *  \retval TM_ECODE_OK all initialized properly
2009
 *  \retval TM_ECODE_FAILED failure
2010
 */
2011
TmEcode TmThreadWaitOnThreadInit(void)
2012
{
3,400✔
2013
    struct timeval start_ts;
3,400✔
2014
    struct timeval cur_ts;
3,400✔
2015
    gettimeofday(&start_ts, NULL);
3,400✔
2016

2017
again:
3,400✔
2018
    SCMutexLock(&tv_root_lock);
3,400✔
2019
    for (int i = 0; i < TVT_MAX; i++) {
13,600✔
2020
        ThreadVars *tv = tv_root[i];
10,200✔
2021
        while (tv != NULL) {
41,086✔
2022
            if (TmThreadsCheckFlag(tv, (THV_CLOSED|THV_DEAD))) {
30,886!
2023
                SCMutexUnlock(&tv_root_lock);
×
2024

2025
                SCLogError("thread \"%s\" failed to "
×
2026
                           "initialize: flags %04x",
×
2027
                        tv->name, SC_ATOMIC_GET(tv->flags));
×
2028
                return TM_ECODE_FAILED;
×
2029
            }
×
2030

2031
            if (!(TmThreadsCheckFlag(tv, THV_INIT_DONE))) {
30,886!
2032
                SCMutexUnlock(&tv_root_lock);
×
2033

2034
                gettimeofday(&cur_ts, NULL);
×
2035
                if ((cur_ts.tv_sec - start_ts.tv_sec) > 120) {
×
2036
                    SCLogError("thread \"%s\" failed to "
×
2037
                               "initialize in time: flags %04x",
×
2038
                            tv->name, SC_ATOMIC_GET(tv->flags));
×
2039
                    return TM_ECODE_FAILED;
×
2040
                }
×
2041

2042
                /* sleep a little to give the thread some
2043
                 * time to finish initialization */
2044
                SleepUsec(100);
×
2045
                goto again;
×
2046
            }
×
2047

2048
            if (TmThreadsCheckFlag(tv, THV_FAILED)) {
30,886!
2049
                SCMutexUnlock(&tv_root_lock);
×
2050
                SCLogError("thread \"%s\" failed to "
×
2051
                           "initialize.",
×
2052
                        tv->name);
×
2053
                return TM_ECODE_FAILED;
×
2054
            }
×
2055
            if (TmThreadsCheckFlag(tv, THV_CLOSED)) {
30,886!
2056
                SCMutexUnlock(&tv_root_lock);
×
2057
                SCLogError("thread \"%s\" closed on "
×
2058
                           "initialization.",
×
2059
                        tv->name);
×
2060
                return TM_ECODE_FAILED;
×
2061
            }
×
2062

2063
            tv = tv->next;
30,886✔
2064
        }
30,886✔
2065
    }
10,200✔
2066
    SCMutexUnlock(&tv_root_lock);
3,400✔
2067

2068
    return TM_ECODE_OK;
3,400✔
2069
}
3,400✔
2070

2071
/**
2072
 * \brief returns a count of all the threads that match the flag
2073
 */
2074
uint32_t TmThreadCountThreadsByTmmFlags(uint8_t flags)
2075
{
38,948✔
2076
    uint32_t cnt = 0;
38,948✔
2077
    SCMutexLock(&tv_root_lock);
38,948✔
2078
    for (int i = 0; i < TVT_MAX; i++) {
155,792✔
2079
        ThreadVars *tv = tv_root[i];
116,844✔
2080
        while (tv != NULL) {
147,896✔
2081
            if ((tv->tmm_flags & flags) == flags)
31,052✔
2082
                cnt++;
13,519✔
2083

2084
            tv = tv->next;
31,052✔
2085
        }
31,052✔
2086
    }
116,844✔
2087
    SCMutexUnlock(&tv_root_lock);
38,948✔
2088
    return cnt;
38,948✔
2089
}
38,948✔
2090

2091
#ifdef DEBUG_VALIDATION
2092
static void TmThreadDoDumpSlots(const ThreadVars *tv)
2093
{
2094
    for (TmSlot *s = tv->tm_slots; s != NULL; s = s->slot_next) {
2095
        TmModule *m = TmModuleGetById(s->tm_id);
2096
        SCLogNotice("tv %p: -> slot %p tm_id %d name %s",
2097
            tv, s, s->tm_id, m->name);
2098
    }
2099
}
2100

2101
static void TmThreadDumpThreads(void)
2102
{
2103
    SCMutexLock(&tv_root_lock);
2104
    for (int i = 0; i < TVT_MAX; i++) {
2105
        ThreadVars *tv = tv_root[i];
2106
        while (tv != NULL) {
2107
            const uint32_t flags = SC_ATOMIC_GET(tv->flags);
2108
            SCLogNotice("tv %p: type %u name %s tmm_flags %02X flags %X stream_pq %p",
2109
                    tv, tv->type, tv->name, tv->tmm_flags, flags, tv->stream_pq);
2110
            if (tv->inq && tv->stream_pq == tv->inq->pq) {
2111
                SCLogNotice("tv %p: stream_pq at tv->inq %u", tv, tv->inq->id);
2112
            } else if (tv->stream_pq_local != NULL) {
2113
                for (Packet *xp = tv->stream_pq_local->top; xp != NULL; xp = xp->next) {
2114
                    SCLogNotice("tv %p: ==> stream_pq_local: pq.len %u packet src %s",
2115
                            tv, tv->stream_pq_local->len, PktSrcToString(xp->pkt_src));
2116
                }
2117
            }
2118
            for (Packet *xp = tv->decode_pq.top; xp != NULL; xp = xp->next) {
2119
                SCLogNotice("tv %p: ==> decode_pq: decode_pq.len %u packet src %s",
2120
                        tv, tv->decode_pq.len, PktSrcToString(xp->pkt_src));
2121
            }
2122
            TmThreadDoDumpSlots(tv);
2123
            tv = tv->next;
2124
        }
2125
    }
2126
    SCMutexUnlock(&tv_root_lock);
2127
    TmThreadsListThreads();
2128
}
2129
#endif
2130

2131
/* Aligned to CLS to avoid false sharing between atomic ops. */
2132
typedef struct Thread_ {
2133
    ThreadVars *tv;     /**< threadvars structure */
2134
    const char *name;
2135
    int type;
2136
    int in_use;         /**< bool to indicate this is in use */
2137

2138
    SC_ATOMIC_DECLARE(SCTime_t, pktts); /**< current packet time of this thread
2139
                                         *   (offline mode) */
2140
    SCTime_t sys_sec_stamp; /**< timestamp in real system
2141
                             *   time when the pktts was last updated. */
2142
    SCSpinlock spin;
2143
} __attribute__((aligned(CLS))) Thread;
2144

2145
typedef struct Threads_ {
2146
    Thread *threads;
2147
    size_t threads_size;
2148
    int threads_cnt;
2149
} Threads;
2150

2151
static bool thread_store_sealed = false;
2152
static Threads thread_store = { NULL, 0, 0 };
2153
static SCMutex thread_store_lock = SCMUTEX_INITIALIZER;
2154

2155
void TmThreadsSealThreads(void)
2156
{
3,398✔
2157
    SCMutexLock(&thread_store_lock);
3,398✔
2158
    DEBUG_VALIDATE_BUG_ON(thread_store_sealed);
3,398✔
2159
    thread_store_sealed = true;
3,398✔
2160
    SCMutexUnlock(&thread_store_lock);
3,398✔
2161
}
3,398✔
2162

2163
void TmThreadsUnsealThreads(void)
2164
{
3,398✔
2165
    SCMutexLock(&thread_store_lock);
3,398✔
2166
    DEBUG_VALIDATE_BUG_ON(!thread_store_sealed);
3,398✔
2167
    thread_store_sealed = false;
3,398✔
2168
    SCMutexUnlock(&thread_store_lock);
3,398✔
2169
}
3,398✔
2170

2171
void TmThreadsListThreads(void)
2172
{
×
2173
    SCMutexLock(&thread_store_lock);
×
2174
    for (size_t s = 0; s < thread_store.threads_size; s++) {
×
2175
        Thread *t = &thread_store.threads[s];
×
2176
        if (t == NULL || t->in_use == 0)
×
2177
            continue;
×
2178

2179
        SCLogNotice("Thread %"PRIuMAX", %s type %d, tv %p in_use %d",
×
2180
                (uintmax_t)s+1, t->name, t->type, t->tv, t->in_use);
×
2181
        if (t->tv) {
×
2182
            ThreadVars *tv = t->tv;
×
2183
            const uint32_t flags = SC_ATOMIC_GET(tv->flags);
×
2184
            SCLogNotice("tv %p type %u name %s tmm_flags %02X flags %X",
×
2185
                    tv, tv->type, tv->name, tv->tmm_flags, flags);
×
2186
        }
×
2187
    }
×
2188
    SCMutexUnlock(&thread_store_lock);
×
2189
}
×
2190

2191
#define STEP 32
2,017✔
2192
/**
2193
 *  \retval id thread id, or 0 if not found
2194
 */
2195
int TmThreadsRegisterThread(ThreadVars *tv, const int type)
2196
{
29,509✔
2197
    SCMutexLock(&thread_store_lock);
29,509✔
2198
    DEBUG_VALIDATE_BUG_ON(thread_store_sealed);
29,509✔
2199
    if (thread_store.threads == NULL) {
29,509✔
2200
        thread_store.threads = SCCalloc(STEP, sizeof(Thread));
2,017✔
2201
        BUG_ON(thread_store.threads == NULL);
2,017!
2202
        thread_store.threads_size = STEP;
2,017✔
2203
    }
2,017✔
2204

2205
    size_t s;
29,509✔
2206
    for (s = 0; s < thread_store.threads_size; s++) {
156,659!
2207
        if (thread_store.threads[s].in_use == 0) {
156,659✔
2208
            Thread *t = &thread_store.threads[s];
29,509✔
2209
            SCSpinInit(&t->spin, 0);
29,509✔
2210
            SCSpinLock(&t->spin);
29,509✔
2211
            t->name = tv->name;
29,509✔
2212
            t->type = type;
29,509✔
2213
            t->tv = tv;
29,509✔
2214
            t->in_use = 1;
29,509✔
2215
            SCSpinUnlock(&t->spin);
29,509✔
2216

2217
            SCMutexUnlock(&thread_store_lock);
29,509✔
2218
            return (int)(s+1);
29,509✔
2219
        }
29,509✔
2220
    }
156,659✔
2221

2222
    /* if we get here the array is completely filled */
2223
    void *newmem = SCRealloc(thread_store.threads, ((thread_store.threads_size + STEP) * sizeof(Thread)));
×
2224
    BUG_ON(newmem == NULL);
×
2225
    thread_store.threads = newmem;
×
2226
    memset((uint8_t *)thread_store.threads + (thread_store.threads_size * sizeof(Thread)), 0x00, STEP * sizeof(Thread));
×
2227

2228
    Thread *t = &thread_store.threads[thread_store.threads_size];
×
2229
    SCSpinInit(&t->spin, 0);
×
2230
    SCSpinLock(&t->spin);
×
2231
    t->name = tv->name;
×
2232
    t->type = type;
×
2233
    t->tv = tv;
×
2234
    t->in_use = 1;
×
2235
    SCSpinUnlock(&t->spin);
×
2236

2237
    s = thread_store.threads_size;
×
2238
    thread_store.threads_size += STEP;
×
2239

2240
    SCMutexUnlock(&thread_store_lock);
×
2241
    return (int)(s+1);
×
2242
}
×
2243
#undef STEP
2244

2245
void TmThreadsUnregisterThread(const int id)
2246
{
29,458✔
2247
    SCMutexLock(&thread_store_lock);
29,458✔
2248
    DEBUG_VALIDATE_BUG_ON(thread_store_sealed);
29,458✔
2249
    if (id <= 0 || id > (int)thread_store.threads_size) {
29,458!
2250
        SCMutexUnlock(&thread_store_lock);
×
2251
        return;
×
2252
    }
×
2253

2254
    /* id is one higher than index */
2255
    int idx = id - 1;
29,458✔
2256

2257
    /* reset thread_id, which serves as clearing the record */
2258
    thread_store.threads[idx].in_use = 0;
29,458✔
2259

2260
    /* check if we have at least one registered thread left */
2261
    size_t s;
29,458✔
2262
    for (s = 0; s < thread_store.threads_size; s++) {
112,276✔
2263
        Thread *t = &thread_store.threads[s];
110,298✔
2264
        if (t->in_use == 1) {
110,298✔
2265
            goto end;
27,480✔
2266
        }
27,480✔
2267
    }
110,298✔
2268

2269
    /* if we get here no threads are registered */
2270
    SCFree(thread_store.threads);
1,978✔
2271
    thread_store.threads = NULL;
1,978✔
2272
    thread_store.threads_size = 0;
1,978✔
2273
    thread_store.threads_cnt = 0;
1,978✔
2274

2275
end:
29,458✔
2276
    SCMutexUnlock(&thread_store_lock);
29,458✔
2277
}
29,458✔
2278

2279
void TmThreadsSetThreadTimestamp(const int id, const SCTime_t ts)
2280
{
2,807,887✔
2281
    SCTime_t now = SCTimeGetTime();
2,807,887✔
2282
    int idx = id - 1;
2,807,887✔
2283
    Thread *t = &thread_store.threads[idx];
2,807,887✔
2284
    SCSpinLock(&t->spin);
2,807,887✔
2285
    SC_ATOMIC_SET(t->pktts, ts);
2,807,887✔
2286

2287
#ifdef DEBUG
2288
    if (t->sys_sec_stamp.secs != 0) {
2289
        SCTime_t tmpts = SCTIME_ADD_SECS(t->sys_sec_stamp, 3);
2290
        if (SCTIME_CMP_LT(tmpts, now)) {
2291
            SCLogDebug("%s: thread slept for %u secs", t->name, (uint32_t)(now.secs - tmpts.secs));
2292
        }
2293
    }
2294
#endif
2295

2296
    t->sys_sec_stamp = now;
2,807,887✔
2297
    SCSpinUnlock(&t->spin);
2,807,887✔
2298
}
2,807,887✔
2299

2300
bool TmThreadsTimeSubsysIsReady(void)
2301
{
27,856✔
2302
    static SCTime_t nullts = SCTIME_INITIALIZER;
27,856✔
2303
    bool ready = true;
27,856✔
2304
    for (size_t s = 0; s < thread_store.threads_size; s++) {
54,150!
2305
        Thread *t = &thread_store.threads[s];
54,150✔
2306
        if (!t->in_use) {
54,150✔
2307
            break;
3,340✔
2308
        }
3,340✔
2309
        SCSpinLock(&t->spin);
50,810✔
2310
        if (t->type != TVT_PPT) {
50,810✔
2311
            SCSpinUnlock(&t->spin);
9,726✔
2312
            continue;
9,726✔
2313
        }
9,726✔
2314
        if (SCTIME_CMP_EQ(t->sys_sec_stamp, nullts)) {
41,084✔
2315
            ready = false;
24,516✔
2316
            SCSpinUnlock(&t->spin);
24,516✔
2317
            break;
24,516✔
2318
        }
24,516✔
2319
        SCSpinUnlock(&t->spin);
16,568✔
2320
    }
16,568✔
2321
    return ready;
27,856✔
2322
}
27,856✔
2323

2324
void TmThreadsInitThreadsTimestamp(const SCTime_t ts)
2325
{
13,076✔
2326
    SCTime_t now = SCTimeGetTime();
13,076✔
2327
    for (size_t s = 0; s < thread_store.threads_size; s++) {
53,238!
2328
        Thread *t = &thread_store.threads[s];
53,238✔
2329
        if (!t->in_use) {
53,238✔
2330
            break;
13,076✔
2331
        }
13,076✔
2332
        SCSpinLock(&t->spin);
40,162✔
2333
        if (t->type != TVT_PPT) {
40,162✔
2334
            SCSpinUnlock(&t->spin);
13,862✔
2335
            continue;
13,862✔
2336
        }
13,862✔
2337
        SC_ATOMIC_SET(t->pktts, ts);
26,300✔
2338
        t->sys_sec_stamp = now;
26,300✔
2339
        SCSpinUnlock(&t->spin);
26,300✔
2340
    }
26,300✔
2341
}
13,076✔
2342

2343
SCTime_t TmThreadsGetThreadTime(const int idx)
2344
{
2,687✔
2345
    DEBUG_VALIDATE_BUG_ON(idx == 0);
2,687✔
2346
    const int i = idx - 1;
2,687✔
2347
    Thread *t = &thread_store.threads[i];
2,687✔
2348
    return SC_ATOMIC_GET(t->pktts);
2,687✔
2349
}
2,687✔
2350

2351
void TmThreadsGetMinimalTimestamp(struct timeval *ts)
2352
{
339,772✔
2353
    struct timeval local = { 0 };
339,772✔
2354
    static SCTime_t nullts = SCTIME_INITIALIZER;
339,772✔
2355
    bool set = false;
339,772✔
2356
    SCTime_t now = SCTimeGetTime();
339,772✔
2357

2358
    for (size_t s = 0; s < thread_store.threads_size; s++) {
3,582,303!
2359
        Thread *t = &thread_store.threads[s];
3,582,303✔
2360
        if (t->in_use == 0) {
3,582,303✔
2361
            break;
339,772✔
2362
        }
339,772✔
2363
        SCSpinLock(&t->spin);
3,242,531✔
2364
        /* only packet threads set timestamps based on packets */
2365
        if (t->type != TVT_PPT) {
3,242,531✔
2366
            SCSpinUnlock(&t->spin);
1,571,931✔
2367
            continue;
1,571,931✔
2368
        }
1,571,931✔
2369
        SCTime_t pktts = SC_ATOMIC_GET(t->pktts);
1,670,600✔
2370
        if (SCTIME_CMP_NEQ(pktts, nullts)) {
1,670,600✔
2371
            SCTime_t sys_sec_stamp = SCTIME_ADD_SECS(t->sys_sec_stamp, 5);
1,654,716✔
2372
            /* ignore sleeping threads */
2373
            if (SCTIME_CMP_LT(sys_sec_stamp, now)) {
1,654,716✔
2374
                SCSpinUnlock(&t->spin);
6,449✔
2375
                continue;
6,449✔
2376
            }
6,449✔
2377
            if (!set) {
1,648,267✔
2378
                SCTIME_TO_TIMEVAL(&local, pktts);
337,600✔
2379
                set = true;
337,600✔
2380
            } else {
1,310,667✔
2381
                if (SCTIME_CMP_LT(pktts, SCTIME_FROM_TIMEVAL(&local))) {
1,310,667✔
2382
                    SCTIME_TO_TIMEVAL(&local, pktts);
2,793✔
2383
                }
2,793✔
2384
            }
1,310,667✔
2385
        }
1,648,267✔
2386
        SCSpinUnlock(&t->spin);
1,664,151✔
2387
    }
1,664,151✔
2388
    *ts = local;
339,772✔
2389
    SCLogDebug("ts->tv_sec %"PRIuMAX, (uintmax_t)ts->tv_sec);
339,772!
2390
}
339,772✔
2391

2392
uint16_t TmThreadsGetWorkerThreadMax(void)
2393
{
33✔
2394
    uint16_t ncpus = UtilCpuGetNumProcessorsOnline();
33✔
2395
    int thread_max = TmThreadGetNbThreads(WORKER_CPU_SET);
33✔
2396
    /* always create at least one thread */
2397
    if (thread_max == 0)
33!
2398
        thread_max = ncpus * threading_detect_ratio;
33✔
2399
    if (thread_max < 1)
33!
2400
        thread_max = 1;
×
2401
    if (thread_max > 1024) {
33!
2402
        SCLogWarning("limited number of 'worker' threads to 1024. Wanted %d", thread_max);
×
2403
        thread_max = 1024;
×
2404
    }
×
2405
    return (uint16_t)thread_max;
33✔
2406
}
33✔
2407

2408
/** \brief inject a flow into a threads flow queue
2409
 */
2410
void TmThreadsInjectFlowById(Flow *f, const int id)
2411
{
4,460✔
2412
    if (id > 0 && id <= (int)thread_store.threads_size) {
4,460!
2413
        int idx = id - 1;
4,460✔
2414
        Thread *t = &thread_store.threads[idx];
4,460✔
2415
        ThreadVars *tv = t->tv;
4,460✔
2416
        if (tv != NULL && tv->flow_queue != NULL) {
4,460!
2417
            FlowEnqueue(tv->flow_queue, f);
4,460✔
2418

2419
            /* wake up listening thread(s) if necessary */
2420
            if (tv->inq != NULL) {
4,460✔
2421
                SCMutexLock(&tv->inq->pq->mutex_q);
3,387✔
2422
                SCCondSignal(&tv->inq->pq->cond_q);
3,387✔
2423
                SCMutexUnlock(&tv->inq->pq->mutex_q);
3,387✔
2424
            } else if (tv->break_loop) {
3,392!
2425
                TmThreadsCaptureBreakLoop(tv);
×
2426
            }
×
2427
            return;
4,460✔
2428
        }
4,460✔
2429
    }
4,460✔
2430
    BUG_ON(1);
×
2431
}
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc