varnish-cache/bin/varnishd/cache/cache_main.c
0
/*-
1
 * Copyright (c) 2006 Verdens Gang AS
2
 * Copyright (c) 2006-2011 Varnish Software AS
3
 * All rights reserved.
4
 *
5
 * Author: Poul-Henning Kamp <phk@phk.freebsd.dk>
6
 *
7
 * SPDX-License-Identifier: BSD-2-Clause
8
 *
9
 * Redistribution and use in source and binary forms, with or without
10
 * modification, are permitted provided that the following conditions
11
 * are met:
12
 * 1. Redistributions of source code must retain the above copyright
13
 *    notice, this list of conditions and the following disclaimer.
14
 * 2. Redistributions in binary form must reproduce the above copyright
15
 *    notice, this list of conditions and the following disclaimer in the
16
 *    documentation and/or other materials provided with the distribution.
17
 *
18
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21
 * ARE DISCLAIMED.  IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
22
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28
 * SUCH DAMAGE.
29
 */
30
31
#include "config.h"
32
33
#include "cache_varnishd.h"
34
#include "acceptor/cache_acceptor.h"
35
36
#include <signal.h>
37
#include <stdio.h>
38
#include <stdlib.h>
39
40
#include <sys/mman.h>
41
42
#ifdef HAVE_PTHREAD_NP_H
43
#  include <pthread_np.h>
44
#endif
45
46
#include "common/heritage.h"
47
48
#include "vcli_serve.h"
49
#include "vnum.h"
50
#include "vtim.h"
51
#include "vrnd.h"
52
53
#include "hash/hash_slinger.h"
54
55
volatile struct params          *cache_param;
56
static pthread_mutex_t          cache_vrnd_mtx;
57
static vtim_dur                 shutdown_delay = 0;
58
59
pthread_mutexattr_t mtxattr_errorcheck;
60
61
static void
62 53453
cache_vrnd_lock(void)
63
{
64 53453
        PTOK(pthread_mutex_lock(&cache_vrnd_mtx));
65 53453
}
66
67
static void
68 53453
cache_vrnd_unlock(void)
69
{
70 53453
        PTOK(pthread_mutex_unlock(&cache_vrnd_mtx));
71 53453
}
72
73
/*--------------------------------------------------------------------
74
 * Per thread storage for the session currently being processed by
75
 * the thread.  This is used for panic messages.
76
 */
77
78
static pthread_key_t req_key;
79
static pthread_key_t bo_key;
80
static pthread_key_t wrk_key;
81
pthread_key_t witness_key;
82
pthread_key_t panic_key;
83
84
void
85 9039
THR_SetBusyobj(const struct busyobj *bo)
86
{
87
88 9039
        PTOK(pthread_setspecific(bo_key, bo));
89 9039
}
90
91
struct busyobj *
92 13
THR_GetBusyobj(void)
93
{
94
95 13
        return (pthread_getspecific(bo_key));
96
}
97
98
void
99 5880
THR_SetRequest(const struct req *req)
100
{
101
102 5880
        PTOK(pthread_setspecific(req_key, req));
103 5880
}
104
105
struct req *
106 15
THR_GetRequest(void)
107
{
108
109 15
        return (pthread_getspecific(req_key));
110
}
111
112
void
113 18970
THR_SetWorker(const struct worker *wrk)
114
{
115
116 18970
        PTOK(pthread_setspecific(wrk_key, wrk));
117 18970
}
118
119
struct worker *
120 4341
THR_GetWorker(void)
121
{
122
123 4341
        return (pthread_getspecific(wrk_key));
124
}
125
126
/*--------------------------------------------------------------------
127
 * Name threads if our pthreads implementation supports it.
128
 */
129
130
static pthread_key_t name_key;
131
132
#if defined(HAVE_PTHREAD_SETNAME_NP) && !defined(__APPLE__) &&  \
133
    !defined(__NetBSD__)
134
static void
135 33879
thr_setname_generic(const char *name)
136
{
137
        char buf[16];
138
139
        /* The Linux kernel enforces a strict limitation of 15 bytes name,
140
         * truncate the name if we would overflow it.
141
         */
142 33879
        if (strlen(name) > 15) {
143 935
                bprintf(buf, "%.14s~", name);
144 935
                name = buf;
145 935
        }
146
147
        //lint --e{438} Last value assigned not used
148 33879
        PTOK(pthread_setname_np(pthread_self(), name));
149 33879
}
150
#endif
151
152
void
153 33879
THR_SetName(const char *name)
154
{
155
156 33879
        PTOK(pthread_setspecific(name_key, name));
157
#if defined(HAVE_PTHREAD_SETNAME_NP)
158
#  if defined(__APPLE__)
159
        (void)pthread_setname_np(name);
160
#  elif defined(__NetBSD__)
161
        (void)pthread_setname_np(pthread_self(), "%s", (char *)(uintptr_t)name);
162
#  else
163 33879
        thr_setname_generic(name);
164
#  endif
165
#elif defined(HAVE_PTHREAD_SET_NAME_NP)
166
        (void)pthread_set_name_np(pthread_self(), name);
167
#endif
168 33879
}
169
170
const char *
171 13
THR_GetName(void)
172
{
173
174 13
        return (pthread_getspecific(name_key));
175
}
176
177
/*--------------------------------------------------------------------
178
 * Generic setup all our threads should call
179
 */
180
static stack_t altstack;
181
182
void
183 33876
THR_Init(void)
184
{
185 33876
        if (altstack.ss_sp != NULL)
186 33842
                AZ(sigaltstack(&altstack, NULL));
187 33876
}
188
189
/*--------------------------------------------------------------------
190
 * VXID's are unique transaction numbers allocated with a minimum of
191
 * locking overhead via pools in the worker threads.
192
 *
193
 * VXID's are mostly for use in VSL and for that reason we never return
194
 * zero vxid, in order to reserve that for "unassociated" VSL records.
195
 */
196
197
static uint64_t vxid_base = 1;
198
static uint32_t vxid_chunk = 32768;
199
static struct lock vxid_lock;
200
201
vxid_t
202 8299
VXID_Get(const struct worker *wrk, uint64_t mask)
203
{
204
        struct vxid_pool *v;
205
        vxid_t retval;
206
207 8299
        CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC);
208 8299
        CHECK_OBJ_NOTNULL(wrk->wpriv, WORKER_PRIV_MAGIC);
209 8299
        v = wrk->wpriv->vxid_pool;
210 8299
        AZ(mask & VSL_IDENTMASK);
211 16588
        while (v->count == 0 || v->next >= VRT_INTEGER_MAX) {
212 8289
                Lck_Lock(&vxid_lock);
213 8289
                v->next = vxid_base;
214 8289
                v->count = vxid_chunk;
215 8289
                vxid_base += v->count;
216 8289
                if (vxid_base >= VRT_INTEGER_MAX)
217 2
                        vxid_base = 1;
218 8289
                Lck_Unlock(&vxid_lock);
219
        }
220 8299
        v->count--;
221 8299
        assert(v->next > 0);
222 8299
        assert(v->next < VSL_CLIENTMARKER);
223 8299
        retval.vxid = v->next | mask;
224 8299
        v->next++;
225 8299
        return (retval);
226
}
227
228
/*--------------------------------------------------------------------
229
 * Debugging aids
230
 */
231
232
/*
233
 * Dumb down the VXID allocation to make it predictable for
234
 * varnishtest cases
235
 */
236
static void v_matchproto_(cli_func_t)
237 927
cli_debug_xid(struct cli *cli, const char * const *av, void *priv)
238
{
239 927
        (void)priv;
240 927
        if (av[2] != NULL) {
241 927
                vxid_base = strtoull(av[2], NULL, 0);
242 927
                vxid_chunk = 0;
243 927
                if (av[3] != NULL)
244 0
                        vxid_chunk = strtoul(av[3], NULL, 0);
245 927
                if (vxid_chunk == 0)
246 927
                        vxid_chunk = 1;
247 927
        }
248 927
        VCLI_Out(cli, "XID is %ju chunk %u", (uintmax_t)vxid_base, vxid_chunk);
249 927
}
250
251
/*
252
 * Artificially slow down the process shutdown.
253
 */
254
static void v_matchproto_(cli_func_t)
255 0
cli_debug_shutdown_delay(struct cli *cli, const char * const *av, void *priv)
256
{
257
258 0
        (void)cli;
259 0
        (void)priv;
260 0
        shutdown_delay = VNUM_duration(av[2]);
261 0
}
262
263
/*
264
 * Default to seed=1, this is the only seed value POSIX guarantees will
265
 * result in a reproducible random number sequence.
266
 */
267
static void v_matchproto_(cli_func_t)
268 3
cli_debug_srandom(struct cli *cli, const char * const *av, void *priv)
269
{
270 3
        unsigned seed = 1;
271
272 3
        (void)priv;
273 3
        (void)cli;
274 3
        if (av[2] != NULL)
275 0
                seed = strtoul(av[2], NULL, 0);
276 3
        VRND_SeedTestable(seed);
277 3
}
278
279
static struct cli_proto debug_cmds[] = {
280
        { CLICMD_DEBUG_XID,             "d", cli_debug_xid },
281
        { CLICMD_DEBUG_SHUTDOWN_DELAY,  "d", cli_debug_shutdown_delay },
282
        { CLICMD_DEBUG_SRANDOM,         "d", cli_debug_srandom },
283
        { NULL }
284
};
285
286
/*--------------------------------------------------------------------
287
 * XXX: Think more about which order we start things
288
 */
289
290
#if defined(__FreeBSD__) && __FreeBSD_version >= 1000000
291
static void
292 0
child_malloc_fail(void *p, const char *s)
293
{
294 0
        VSL(SLT_Error, NO_VXID, "MALLOC ERROR: %s (%p)", s, p);
295 0
        fprintf(stderr, "MALLOC ERROR: %s (%p)\n", s, p);
296 0
        WRONG("Malloc Error");
297 0
}
298
#endif
299
300
/*=====================================================================
301
 * signal handler for child process
302
 */
303
304
static void v_noreturn_ v_matchproto_()
305 2
child_signal_handler(int s, siginfo_t *si, void *c)
306
{
307
        char buf[1024];
308
        struct sigaction sa;
309
        struct req *req;
310 2
        const char *a, *p, *info = NULL;
311
312 2
        (void)c;
313
        /* Don't come back */
314 2
        memset(&sa, 0, sizeof sa);
315 2
        sa.sa_handler = SIG_DFL;
316 2
        (void)sigaction(SIGSEGV, &sa, NULL);
317 2
        (void)sigaction(SIGBUS, &sa, NULL);
318 2
        (void)sigaction(SIGABRT, &sa, NULL);
319
320 2
        while (s == SIGSEGV || s == SIGBUS) {
321 2
                req = THR_GetRequest();
322 2
                if (req == NULL || req->wrk == NULL)
323 0
                        break;
324 2
                a = TRUST_ME(si->si_addr);
325 2
                p = TRUST_ME(req->wrk);
326 2
                p += sizeof *req->wrk;
327
                // rough safe estimate - top of stack
328 2
                if (a > p + cache_param->wthread_stacksize)
329 0
                        break;
330 2
                if (a < p - 2 * cache_param->wthread_stacksize)
331 1
                        break;
332 1
                info = "\nTHIS PROBABLY IS A STACK OVERFLOW - "
333
                        "check thread_pool_stack parameter";
334 1
                break;
335
        }
336 2
        bprintf(buf, "Signal %d (%s) received at %p si_code %d%s",
337
                s, strsignal(s), si->si_addr, si->si_code,
338
                info ? info : "");
339
340 2
        VAS_Fail(__func__,
341
                 __FILE__,
342
                 __LINE__,
343 2
                 buf,
344
                 VAS_WRONG);
345
}
346
347
/*=====================================================================
348
 * Magic for panicking properly on signals
349
 */
350
351
static void
352 934
child_sigmagic(size_t altstksz)
353
{
354
        struct sigaction sa;
355
356 934
        memset(&sa, 0, sizeof sa);
357
358 934
        size_t sz = vmax_t(size_t, SIGSTKSZ + 4096, altstksz);
359 934
        altstack.ss_sp = mmap(NULL, sz,  PROT_READ | PROT_WRITE,
360
                              MAP_PRIVATE | MAP_ANONYMOUS,
361
                              -1, 0);
362 934
        AN(altstack.ss_sp != MAP_FAILED);
363 934
        AN(altstack.ss_sp);
364 934
        altstack.ss_size = sz;
365 934
        altstack.ss_flags = 0;
366 934
        sa.sa_flags |= SA_ONSTACK;
367
368 934
        THR_Init();
369
370 934
        sa.sa_sigaction = child_signal_handler;
371 934
        sa.sa_flags |= SA_SIGINFO;
372 934
        (void)sigaction(SIGBUS, &sa, NULL);
373 934
        (void)sigaction(SIGABRT, &sa, NULL);
374 934
        (void)sigaction(SIGSEGV, &sa, NULL);
375 934
}
376
377
static void
378 2
cli_quit(int sig)
379
{
380
381 2
        if (!IS_CLI()) {
382 0
                PTOK(pthread_kill(cli_thread, sig));
383 0
                return;
384
        }
385
386 2
        WRONG("It's time for the big quit");
387 0
}
388
389
/*=====================================================================
390
 * Run the child process
391
 */
392
393
static void v_matchproto_(cli_func_t)
394 930
ccf_child_start(struct cli *cli, const char * const *av, void *priv)
395
{
396 930
        (void)av;
397 930
        (void)priv;
398
399 930
        VCA_Start(cli);
400 930
}
401
402
static struct cli_proto child_cmds[] = {
403
        { CLICMD_SERVER_START,          "", ccf_child_start },
404
        { NULL }
405
};
406
407
void
408 935
child_main(int sigmagic, size_t altstksz)
409
{
410
411 935
        if (sigmagic)
412 934
                child_sigmagic(altstksz);
413 935
        (void)signal(SIGINT, SIG_DFL);
414 935
        (void)signal(SIGTERM, SIG_DFL);
415 935
        (void)signal(SIGQUIT, cli_quit);
416
417
#if defined(__FreeBSD__) && __FreeBSD_version >= 1000000
418 935
        malloc_message = child_malloc_fail;
419
#endif
420
421
        /* Before anything uses pthreads in anger */
422 935
        PTOK(pthread_mutexattr_init(&mtxattr_errorcheck));
423 935
        PTOK(pthread_mutexattr_settype(&mtxattr_errorcheck, PTHREAD_MUTEX_ERRORCHECK));
424
425 935
        cache_param = heritage.param;
426
427 935
        PTOK(pthread_key_create(&req_key, NULL));
428 935
        PTOK(pthread_key_create(&bo_key, NULL));
429 935
        PTOK(pthread_key_create(&wrk_key, NULL));
430 935
        PTOK(pthread_key_create(&witness_key, free));
431 935
        PTOK(pthread_key_create(&name_key, NULL));
432 935
        PTOK(pthread_key_create(&panic_key, NULL));
433
434 935
        THR_SetName("cache-main");
435
436 935
        PTOK(pthread_mutex_init(&cache_vrnd_mtx, &mtxattr_errorcheck));
437 935
        VRND_Lock = cache_vrnd_lock;
438 935
        VRND_Unlock = cache_vrnd_unlock;
439
440 935
        VSM_Init();     /* First, LCK needs it. */
441
442 935
        LCK_Init();     /* Second, locking */
443
444 935
        Lck_New(&vxid_lock, lck_vxid);
445
446 935
        CLI_Init();
447 935
        PAN_Init();
448 935
        VFP_Init();
449
450 935
        ObjInit();
451
452 935
        WRK_Init();
453
454 935
        VCL_Init();
455 935
        VCL_VRT_Init();
456
457 935
        HTTP_Init();
458
459 935
        VBO_Init();
460 935
        VCP_Init();
461 935
        VBP_Init();
462 935
        VDI_Init();
463 935
        VBE_InitCfg();
464 935
        Pool_Init();
465 935
        V1P_Init();
466 935
        V2D_Init();
467
468 935
        EXP_Init();
469 935
        HSH_Init(heritage.hash);
470 935
        BAN_Init();
471
472 935
        VCA_Init();
473
474 935
        STV_open();
475
476 935
        VMOD_Init();
477
478 935
        BAN_Compile();
479
480 935
        VRND_SeedAll();
481
482
483 935
        CLI_AddFuncs(debug_cmds);
484 935
        CLI_AddFuncs(child_cmds);
485
486
#ifdef WITH_PERSISTENT_STORAGE
487
        /* Wait for persistent storage to load if asked to */
488 935
        if (FEATURE(FEATURE_WAIT_SILO))
489 24
                SMP_Ready();
490
#endif
491
492 935
        CLI_Run();
493
494 935
        if (shutdown_delay > 0)
495 0
                VTIM_sleep(shutdown_delay);
496
497 935
        VCA_Shutdown();
498 935
        BAN_Shutdown();
499 935
        EXP_Shutdown();
500 935
        STV_close();
501
502 935
        printf("Child dies\n");
503 935
}