// SPDX-License-Identifier: GPL-3.0-or-later

#include "ebpf.h"
#include "ebpf_process.h"
#include "libbpf_api/ebpf_library.h"

/*****************************************************************
 *
 *  GLOBAL VARIABLES
 *
 *****************************************************************/

static char *process_dimension_names[NETDATA_KEY_PUBLISH_PROCESS_END] = {"process", "task", "process", "thread"};
static char *process_id_names[NETDATA_KEY_PUBLISH_PROCESS_END] = {"do_exit", "release_task", "_do_fork", "sys_clone"};
static char *status[] = {"process", "zombie"};

netdata_ebpf_targets_t process_targets[] = {
    {.name = "release_task", .mode = EBPF_LOAD_TRAMPOLINE},
    {.name = "__x64_sys_clone", .mode = EBPF_LOAD_TRAMPOLINE},
    {.name = "__x64_sys_clone3", .mode = EBPF_LOAD_TRAMPOLINE},
    {.name = "_do_fork", .mode = EBPF_LOAD_TRAMPOLINE},
    {.name = NULL, .mode = EBPF_LOAD_TRAMPOLINE}};

static ebpf_local_maps_t process_maps[] = {
    {.name = "tbl_pid_stats",
     .internal_input = ND_EBPF_DEFAULT_PID_SIZE,
     .user_input = 0,
     .type = NETDATA_EBPF_MAP_RESIZABLE | NETDATA_EBPF_MAP_PID,
     .map_fd = ND_EBPF_MAP_FD_NOT_INITIALIZED,
#ifdef LIBBPF_MAJOR_VERSION
     .map_type = BPF_MAP_TYPE_PERCPU_HASH
#endif
    },
    {.name = "tbl_total_stats",
     .internal_input = NETDATA_KEY_END_VECTOR,
     .user_input = 0,
     .type = NETDATA_EBPF_MAP_STATIC,
     .map_fd = ND_EBPF_MAP_FD_NOT_INITIALIZED,
#ifdef LIBBPF_MAJOR_VERSION
     .map_type = BPF_MAP_TYPE_PERCPU_ARRAY
#endif
    },
    {.name = "process_ctrl",
     .internal_input = NETDATA_CONTROLLER_END,
     .user_input = 0,
     .type = NETDATA_EBPF_MAP_CONTROLLER,
     .map_fd = ND_EBPF_MAP_FD_NOT_INITIALIZED,
#ifdef LIBBPF_MAJOR_VERSION
     .map_type = BPF_MAP_TYPE_PERCPU_ARRAY
#endif
    },
    {.name = NULL,
     .internal_input = 0,
     .user_input = 0,
     .type = NETDATA_EBPF_MAP_CONTROLLER,
     .map_fd = ND_EBPF_MAP_FD_NOT_INITIALIZED,
#ifdef LIBBPF_MAJOR_VERSION
     .map_type = BPF_MAP_TYPE_PERCPU_ARRAY
#endif
    }};

char *tracepoint_sched_type = "sched";
char *tracepoint_sched_process_exit = "sched_process_exit";
char *tracepoint_sched_process_exec = "sched_process_exec";
char *tracepoint_sched_process_fork = "sched_process_fork";
static int was_sched_process_exit_enabled = 0;
static int was_sched_process_exec_enabled = 0;
static int was_sched_process_fork_enabled = 0;

static netdata_idx_t *process_hash_values = NULL;
ebpf_process_stat_t *process_stat_vector = NULL;
static bool process_safe_clean = false;
static netdata_syscall_stat_t process_aggregated_data[NETDATA_KEY_PUBLISH_PROCESS_END];
static netdata_publish_syscall_t process_publish_aggregated[NETDATA_KEY_PUBLISH_PROCESS_END];

struct config process_config = APPCONFIG_INITIALIZER;

#ifdef LIBBPF_MAJOR_VERSION
/**
 * Disable probe
 *
 * Disable all probes to use exclusively another method.
 *
 * @param obj is the main structure for bpf objects
 */
static void ebpf_process_disable_probe(struct process_bpf *obj)
{
    bpf_program__set_autoload(obj->progs.netdata_release_task_probe, false);
    bpf_program__set_autoload(obj->progs.netdata_do_fork_probe, false);
    bpf_program__set_autoload(obj->progs.netdata_kernel_clone_probe, false);
}

static void ebpf_disable_tracepoints(struct process_bpf *obj)
{
    bpf_program__set_autoload(obj->progs.netdata_clone_exit, false);
    bpf_program__set_autoload(obj->progs.netdata_clone3_exit, false);
    bpf_program__set_autoload(obj->progs.netdata_fork_exit, false);
    bpf_program__set_autoload(obj->progs.netdata_vfork_exit, false);
}

static void ebpf_set_trampoline_target(struct process_bpf *obj)
{
    bpf_program__set_attach_target(
        obj->progs.netdata_release_task_fentry, 0, process_targets[PROCESS_RELEASE_TASK_NAME].name);

    bpf_program__set_attach_target(obj->progs.netdata_clone_fexit, 0, process_targets[PROCESS_SYS_CLONE].name);

    bpf_program__set_attach_target(obj->progs.netdata_clone3_fexit, 0, process_targets[PROCESS_SYS_CLONE3].name);
}

/*
 * Disable trampoline
 *
 * Disable all trampoline to use exclusively another method.
 *
 * @param obj is the main structure for bpf objects.
 */
static void ebpf_disable_trampoline(struct process_bpf *obj)
{
    bpf_program__set_autoload(obj->progs.netdata_release_task_fentry, false);
    bpf_program__set_autoload(obj->progs.netdata_clone_fexit, false);
    bpf_program__set_autoload(obj->progs.netdata_clone3_fexit, false);
}

static inline void ebpf_disable_clone3(struct process_bpf *obj)
{
    bpf_program__set_autoload(obj->progs.netdata_clone3_exit, false);
    bpf_program__set_autoload(obj->progs.netdata_clone3_fexit, false);
}

static inline void ebpf_adjust_process_fork(struct process_bpf *obj)
{
    if (running_on_kernel <= NETDATA_EBPF_KERNEL_6_16) {
        bpf_program__set_autoload(obj->progs.netdata_tracepoint_sched_process_fork, true);
        bpf_program__set_autoload(obj->progs.netdata_tracepoint_sched_process_fork_v2, false);
    } else {
        bpf_program__set_autoload(obj->progs.netdata_tracepoint_sched_process_fork_v2, true);
        bpf_program__set_autoload(obj->progs.netdata_tracepoint_sched_process_fork, false);
    }
}

/**
 * Mount Attach Probe
 *
 * Attach probes to target
 *
 * @param obj is the main structure for bpf objects.
 *
 * @return It returns 0 on success and -1 otherwise.
 */
static inline int process_attach_kprobe_target(struct process_bpf *obj)
{
    obj->links.netdata_release_task_probe = bpf_program__attach_kprobe(
        obj->progs.netdata_release_task_probe, false, process_targets[PROCESS_RELEASE_TASK_NAME].name);
    int ret = libbpf_get_error(obj->links.netdata_release_task_probe);
    if (ret)
        goto endakt;

    if (running_on_kernel < NETDATA_EBPF_KERNEL_5_9_16) {
        obj->links.netdata_do_fork_probe =
            bpf_program__attach_kprobe(obj->progs.netdata_do_fork_probe, false, process_targets[PROCESS_SYS_FORK].name);
        ret = libbpf_get_error(obj->links.netdata_do_fork_probe);
    } else {
        obj->links.netdata_kernel_clone_probe = bpf_program__attach_kprobe(
            obj->progs.netdata_kernel_clone_probe, false, process_targets[PROCESS_KERNEL_CLONE].name);
        ret = libbpf_get_error(obj->links.netdata_kernel_clone_probe);
    }
endakt:
    return ret;
}

/**
 * Set hash tables
 *
 * Set the values for maps according the value given by kernel.
 *
 * @param obj is the main structure for bpf objects.
 */
static void ebpf_process_set_hash_tables(struct process_bpf *obj)
{
    process_maps[NETDATA_PROCESS_GLOBAL_TABLE].map_fd = bpf_map__fd(obj->maps.tbl_total_stats);
    process_maps[NETDATA_PROCESS_PID_TABLE].map_fd = bpf_map__fd(obj->maps.tbl_pid_stats);
    process_maps[NETDATA_PROCESS_CTRL_TABLE].map_fd = bpf_map__fd(obj->maps.process_ctrl);
}

/**
 * Load and attach
 *
 * Load and attach the eBPF code in kernel.
 *
 * @param obj is the main structure for bpf objects.
 * @param em  structure with configuration
 *
 * @return it returns 0 on success and -1 otherwise
 */
static inline int ebpf_process_load_and_attach(struct process_bpf *obj, ebpf_module_t *em)
{
    netdata_ebpf_program_loaded_t mode = em->targets[PROCESS_RELEASE_TASK_NAME].mode;
    if (mode == EBPF_LOAD_TRAMPOLINE) {
        ebpf_process_disable_probe(obj);
        ebpf_disable_tracepoints(obj);

        ebpf_set_trampoline_target(obj);
    } else if (mode == EBPF_LOAD_PROBE || mode == EBPF_LOAD_RETPROBE) {
        ebpf_disable_tracepoints(obj);
        ebpf_disable_trampoline(obj);

        bpf_program__set_autoload(
            (running_on_kernel <= NETDATA_EBPF_KERNEL_5_9_16) ? obj->progs.netdata_kernel_clone_probe :
                                                                obj->progs.netdata_do_fork_probe,
            false);
    } else { // Tracepoint
        ebpf_process_disable_probe(obj);
        ebpf_disable_trampoline(obj);
    }

    if (running_on_kernel < NETDATA_EBPF_KERNEL_5_3) {
        ebpf_disable_clone3(obj);
    }

    ebpf_adjust_process_fork(obj);

    int ret = process_bpf__load(obj);
    if (ret) {
        return ret;
    }

    ret = (mode == EBPF_LOAD_TRAMPOLINE) ? process_bpf__attach(obj) : process_attach_kprobe_target(obj);
    if (!ret) {
        ebpf_process_set_hash_tables(obj);

        ebpf_update_controller(cachestat_maps[NETDATA_PROCESS_CTRL_TABLE].map_fd, em);
    }

    return ret;
}
#endif

/*
 * Load BPF
 *
 * Load BPF files.
 *
 * @param em the structure with configuration
 */
static int ebpf_process_load_bpf(ebpf_module_t *em)
{
#ifdef LIBBPF_MAJOR_VERSION
    ebpf_define_map_type(process_maps, em->maps_per_core, running_on_kernel);
#endif

    int ret = 0;
    // ebpf_adjust_apps_cgroup(em, em->targets[NETDATA_KEY_CALLS_ADD_TO_PAGE_CACHE_LRU].mode);
    if (em->load & EBPF_LOAD_LEGACY) {
        em->probe_links = ebpf_load_program(ebpf_plugin_dir, em, running_on_kernel, isrh, &em->objects);
        if (!em->probe_links) {
            ret = -1;
        }
    }
#ifdef LIBBPF_MAJOR_VERSION
    else {
        process_bpf_obj = process_bpf__open();
        if (!process_bpf_obj)
            ret = -1;
        else {
            ret = ebpf_process_load_and_attach(process_bpf_obj, em);
            if (ret) {
                process_bpf__destroy(process_bpf_obj);
                process_bpf_obj = NULL;
            }
        }
    }
#endif

    if (ret)
        netdata_log_error("%s %s", EBPF_DEFAULT_ERROR_MSG, em->info.thread_name);

    return ret;
}

/*****************************************************************
 *
 *  PROCESS DATA AND SEND TO NETDATA
 *
 *****************************************************************/

/**
 * Update publish structure before to send data to Netdata.
 *
 * @param publish  the first output structure with independent dimensions
 * @param pvc      the second output structure with correlated dimensions
 * @param input    the structure with the input data.
 */
static void ebpf_update_global_publish(
    netdata_publish_syscall_t *publish,
    netdata_publish_vfs_common_t *pvc,
    netdata_syscall_stat_t *input)
{
    netdata_publish_syscall_t *move = publish;
    int selector = NETDATA_KEY_PUBLISH_PROCESS_EXIT;
    while (move) {
        move->ncall = (input->call > move->pcall) ? input->call - move->pcall : move->pcall - input->call;
        move->nbyte = (input->bytes > move->pbyte) ? input->bytes - move->pbyte : move->pbyte - input->bytes;
        move->nerr = (input->ecall > move->nerr) ? input->ecall - move->perr : move->perr - input->ecall;

        move->pcall = input->call;
        move->pbyte = input->bytes;
        move->perr = input->ecall;

        input = input->next;
        move = move->next;
        selector++;
    }

    pvc->running =
        (long)publish[NETDATA_KEY_PUBLISH_PROCESS_FORK].ncall - (long)publish[NETDATA_KEY_PUBLISH_PROCESS_CLONE].ncall;
    publish[NETDATA_KEY_PUBLISH_PROCESS_RELEASE_TASK].ncall = -publish[NETDATA_KEY_PUBLISH_PROCESS_RELEASE_TASK].ncall;
    pvc->zombie = (long)publish[NETDATA_KEY_PUBLISH_PROCESS_EXIT].ncall +
                  (long)publish[NETDATA_KEY_PUBLISH_PROCESS_RELEASE_TASK].ncall;
}

/**
 * Call the necessary functions to create a chart.
 *
 * @param family  the chart family
 * @param move    the pointer with the values that will be published
 */
static void write_status_chart(char *family, netdata_publish_vfs_common_t *pvc)
{
    ebpf_write_begin_chart(family, NETDATA_PROCESS_STATUS_NAME, "");

    write_chart_dimension(status[0], (long long)pvc->running);
    write_chart_dimension(status[1], (long long)pvc->zombie);

    ebpf_write_end_chart();
}

/**
 * Send data to Netdata calling auxiliary functions.
 *
 * @param em the structure with thread information
 */
static void ebpf_process_send_data(ebpf_module_t *em)
{
    netdata_publish_vfs_common_t pvc;
    ebpf_update_global_publish(process_publish_aggregated, &pvc, process_aggregated_data);

    write_count_chart(
        NETDATA_EXIT_SYSCALL,
        NETDATA_EBPF_SYSTEM_GROUP,
        &process_publish_aggregated[NETDATA_KEY_PUBLISH_PROCESS_EXIT],
        2);
    write_count_chart(
        NETDATA_PROCESS_SYSCALL,
        NETDATA_EBPF_SYSTEM_GROUP,
        &process_publish_aggregated[NETDATA_KEY_PUBLISH_PROCESS_FORK],
        2);

    write_status_chart(NETDATA_EBPF_SYSTEM_GROUP, &pvc);
    if (em->mode < MODE_ENTRY) {
        write_err_chart(
            NETDATA_PROCESS_ERROR_NAME,
            NETDATA_EBPF_SYSTEM_GROUP,
            &process_publish_aggregated[NETDATA_KEY_PUBLISH_PROCESS_FORK],
            2);
    }
}

/**
 * Send data to Netdata calling auxiliary functions.
 *
 * @param root the target list.
 */
void ebpf_process_send_apps_data(struct ebpf_target *root, ebpf_module_t *em)
{
    struct ebpf_target *w;

    for (w = root; w; w = w->next) {
        if (ebpf_plugin_stop())
            break;

        if (unlikely(!(w->charts_created & (1 << EBPF_MODULE_PROCESS_IDX))))
            continue;

        ebpf_write_begin_chart(NETDATA_APP_FAMILY, w->clean_name, "_ebpf_process_start");
        write_chart_dimension("calls", w->process.create_process);
        ebpf_write_end_chart();

        ebpf_write_begin_chart(NETDATA_APP_FAMILY, w->clean_name, "_ebpf_thread_start");
        write_chart_dimension("calls", w->process.create_thread);
        ebpf_write_end_chart();

        ebpf_write_begin_chart(NETDATA_APP_FAMILY, w->clean_name, "_ebpf_task_exit");
        write_chart_dimension("calls", w->process.exit_call);
        ebpf_write_end_chart();

        ebpf_write_begin_chart(NETDATA_APP_FAMILY, w->clean_name, "_ebpf_task_released");
        write_chart_dimension("calls", w->process.release_call);
        ebpf_write_end_chart();

        if (em->mode < MODE_ENTRY) {
            ebpf_write_begin_chart(NETDATA_APP_FAMILY, w->clean_name, "_ebpf_task_error");
            write_chart_dimension("calls", w->process.task_err);
            ebpf_write_end_chart();
        }
    }
}

/*****************************************************************
 *
 *  READ INFORMATION FROM KERNEL RING
 *
 *****************************************************************/

/**
 * Read the hash table and store data to allocated vectors.
 *
 * @param maps_per_core do I need to read all cores?
 */
static void ebpf_read_process_hash_global_tables(netdata_idx_t *stats, int maps_per_core)
{
    netdata_idx_t res[NETDATA_KEY_END_VECTOR];
    ebpf_read_global_table_stats(
        res,
        process_hash_values,
        process_maps[NETDATA_PROCESS_GLOBAL_TABLE].map_fd,
        maps_per_core,
        0,
        NETDATA_KEY_END_VECTOR);

    ebpf_read_global_table_stats(
        stats,
        process_hash_values,
        process_maps[NETDATA_PROCESS_CTRL_TABLE].map_fd,
        maps_per_core,
        NETDATA_CONTROLLER_PID_TABLE_ADD,
        NETDATA_CONTROLLER_END);

    process_aggregated_data[NETDATA_KEY_PUBLISH_PROCESS_EXIT].call = res[NETDATA_KEY_CALLS_DO_EXIT];
    process_aggregated_data[NETDATA_KEY_PUBLISH_PROCESS_RELEASE_TASK].call = res[NETDATA_KEY_CALLS_RELEASE_TASK];
    process_aggregated_data[NETDATA_KEY_PUBLISH_PROCESS_FORK].call = res[NETDATA_KEY_CALLS_DO_FORK];
    process_aggregated_data[NETDATA_KEY_PUBLISH_PROCESS_CLONE].call = res[NETDATA_KEY_CALLS_SYS_CLONE];

    process_aggregated_data[NETDATA_KEY_PUBLISH_PROCESS_FORK].ecall = res[NETDATA_KEY_ERROR_DO_FORK];
    process_aggregated_data[NETDATA_KEY_PUBLISH_PROCESS_CLONE].ecall = res[NETDATA_KEY_ERROR_SYS_CLONE];
}

/**
 * Update cgroup
 *
 * Update cgroup data based in PID running.
 *
 * @param maps_per_core do I need to read all cores?
 */
static void ebpf_update_process_cgroup()
{
    ebpf_cgroup_target_t *ect;
    netdata_mutex_lock(&mutex_cgroup_shm);
    for (ect = ebpf_cgroup_pids; ect; ect = ect->next) {
        if (ebpf_plugin_stop())
            break;

        struct pid_on_target2 *pids;
        for (pids = ect->pids; pids; pids = pids->next) {
            uint32_t pid = pids->pid;
            ebpf_publish_process_t *out = &pids->ps;
            netdata_ebpf_pid_stats_t *local_pid = netdata_ebpf_lookup_shm_pointer_unsafe(pid);
            if (!local_pid || !(local_pid->threads & (1U << (NETDATA_EBPF_PIDS_PROCESS_IDX << 1))))
                continue;

            ebpf_publish_process_t *in = &local_pid->process;

            memcpy(out, in, sizeof(ebpf_publish_process_t));
        }
    }
    netdata_mutex_unlock(&mutex_cgroup_shm);
}

/*****************************************************************
 *
 *  FUNCTIONS TO CREATE CHARTS
 *
 *****************************************************************/

/**
 * Create process status chart
 *
 * @param family the chart family
 * @param name   the chart name
 * @param axis   the axis label
 * @param web    the group name used to attach the chart on dashboard
 * @param order  the order number of the specified chart
 * @param update_every value to overwrite the update frequency set by the server.
 */
static void
ebpf_process_status_chart(char *family, char *name, char *axis, char *web, char *algorithm, int order, int update_every)
{
    printf(
        "CHART %s.%s '' 'Process not closed' '%s' '%s' 'system.process_status' line %d %d '' 'ebpf.plugin' 'process'\n",
        family,
        name,
        axis,
        web,
        order,
        update_every);

    printf("DIMENSION %s '' %s 1 1\n", status[0], algorithm);
    printf("DIMENSION %s '' %s 1 1\n", status[1], algorithm);
}

/**
 * Create global charts
 *
 * Call ebpf_create_chart to create the charts for the collector.
 *
 * @param em a pointer to the structure with the default values.
 */
static void ebpf_create_global_charts(ebpf_module_t *em)
{
    ebpf_create_chart(
        NETDATA_EBPF_SYSTEM_GROUP,
        NETDATA_PROCESS_SYSCALL,
        "Start process",
        EBPF_COMMON_UNITS_CALLS_PER_SEC,
        NETDATA_PROCESS_GROUP,
        "system.process_thread",
        NETDATA_EBPF_CHART_TYPE_LINE,
        21002,
        ebpf_create_global_dimension,
        &process_publish_aggregated[NETDATA_KEY_PUBLISH_PROCESS_FORK],
        2,
        em->update_every,
        NETDATA_EBPF_MODULE_NAME_PROCESS);

    ebpf_create_chart(
        NETDATA_EBPF_SYSTEM_GROUP,
        NETDATA_EXIT_SYSCALL,
        "Exit process",
        EBPF_COMMON_UNITS_CALLS_PER_SEC,
        NETDATA_PROCESS_GROUP,
        "system.exit",
        NETDATA_EBPF_CHART_TYPE_LINE,
        21003,
        ebpf_create_global_dimension,
        &process_publish_aggregated[NETDATA_KEY_PUBLISH_PROCESS_EXIT],
        2,
        em->update_every,
        NETDATA_EBPF_MODULE_NAME_PROCESS);

    ebpf_process_status_chart(
        NETDATA_EBPF_SYSTEM_GROUP,
        NETDATA_PROCESS_STATUS_NAME,
        EBPF_COMMON_UNITS_CALLS,
        NETDATA_PROCESS_GROUP,
        ebpf_algorithms[NETDATA_EBPF_ABSOLUTE_IDX],
        21004,
        em->update_every);

    if (em->mode < MODE_ENTRY) {
        ebpf_create_chart(
            NETDATA_EBPF_SYSTEM_GROUP,
            NETDATA_PROCESS_ERROR_NAME,
            "Fails to create process",
            EBPF_COMMON_UNITS_CALLS_PER_SEC,
            NETDATA_PROCESS_GROUP,
            "system.task_error",
            NETDATA_EBPF_CHART_TYPE_LINE,
            21005,
            ebpf_create_global_dimension,
            &process_publish_aggregated[NETDATA_KEY_PUBLISH_PROCESS_FORK],
            2,
            em->update_every,
            NETDATA_EBPF_MODULE_NAME_PROCESS);
    }

    fflush(stdout);
}

/**
 * Create process apps charts
 *
 * Call ebpf_create_chart to create the charts on apps submenu.
 *
 * @param em   a pointer to the structure with the default values.
 * @param ptr  a pointer for the targets.
 */
void ebpf_process_create_apps_charts(struct ebpf_module *em, void *ptr)
{
    struct ebpf_target *root = ptr;
    struct ebpf_target *w;
    int update_every = em->update_every;
    for (w = root; w; w = w->next) {
        if (ebpf_plugin_stop())
            break;

        if (unlikely(!w->exposed))
            continue;

        ebpf_write_chart_cmd(
            NETDATA_APP_FAMILY,
            w->clean_name,
            "_ebpf_process_start",
            "Process started.",
            EBPF_COMMON_UNITS_CALLS_PER_SEC,
            NETDATA_PROCESS_GROUP,
            NETDATA_EBPF_CHART_TYPE_STACKED,
            "app.ebpf_process_start",
            20161,
            update_every,
            NETDATA_EBPF_MODULE_NAME_PROCESS);
        ebpf_create_chart_labels("app_group", w->name, RRDLABEL_SRC_AUTO);
        ebpf_commit_label();
        fprintf(stdout, "DIMENSION calls '' %s 1 1\n", ebpf_algorithms[NETDATA_EBPF_INCREMENTAL_IDX]);

        ebpf_write_chart_cmd(
            NETDATA_APP_FAMILY,
            w->clean_name,
            "_ebpf_thread_start",
            "Threads started.",
            EBPF_COMMON_UNITS_CALLS_PER_SEC,
            NETDATA_PROCESS_GROUP,
            NETDATA_EBPF_CHART_TYPE_STACKED,
            "app.ebpf_thread_start",
            20162,
            update_every,
            NETDATA_EBPF_MODULE_NAME_PROCESS);
        ebpf_create_chart_labels("app_group", w->name, RRDLABEL_SRC_AUTO);
        ebpf_commit_label();
        fprintf(stdout, "DIMENSION calls '' %s 1 1\n", ebpf_algorithms[NETDATA_EBPF_INCREMENTAL_IDX]);

        ebpf_write_chart_cmd(
            NETDATA_APP_FAMILY,
            w->clean_name,
            "_ebpf_task_exit",
            "Tasks starts exit process.",
            EBPF_COMMON_UNITS_CALLS_PER_SEC,
            NETDATA_PROCESS_GROUP,
            NETDATA_EBPF_CHART_TYPE_STACKED,
            "app.ebpf_task_exit",
            20163,
            update_every,
            NETDATA_EBPF_MODULE_NAME_PROCESS);
        ebpf_create_chart_labels("app_group", w->name, RRDLABEL_SRC_AUTO);
        ebpf_commit_label();
        fprintf(stdout, "DIMENSION calls '' %s 1 1\n", ebpf_algorithms[NETDATA_EBPF_INCREMENTAL_IDX]);

        ebpf_write_chart_cmd(
            NETDATA_APP_FAMILY,
            w->clean_name,
            "_ebpf_task_released",
            "Tasks released.",
            EBPF_COMMON_UNITS_CALLS_PER_SEC,
            NETDATA_PROCESS_GROUP,
            NETDATA_EBPF_CHART_TYPE_STACKED,
            "app.ebpf_task_released",
            20164,
            update_every,
            NETDATA_EBPF_MODULE_NAME_PROCESS);
        ebpf_create_chart_labels("app_group", w->name, RRDLABEL_SRC_AUTO);
        ebpf_commit_label();
        fprintf(stdout, "DIMENSION calls '' %s 1 1\n", ebpf_algorithms[NETDATA_EBPF_INCREMENTAL_IDX]);

        if (em->mode < MODE_ENTRY) {
            ebpf_write_chart_cmd(
                NETDATA_APP_FAMILY,
                w->clean_name,
                "_ebpf_task_error",
                "Errors to create process or threads.",
                EBPF_COMMON_UNITS_CALLS_PER_SEC,
                NETDATA_PROCESS_GROUP,
                NETDATA_EBPF_CHART_TYPE_STACKED,
                "app.ebpf_task_error",
                20165,
                update_every,
                NETDATA_EBPF_MODULE_NAME_PROCESS);
            ebpf_create_chart_labels("app_group", w->name, RRDLABEL_SRC_AUTO);
            ebpf_commit_label();
            fprintf(stdout, "DIMENSION calls '' %s 1 1\n", ebpf_algorithms[NETDATA_EBPF_INCREMENTAL_IDX]);
        }
        w->charts_created |= 1 << EBPF_MODULE_PROCESS_IDX;
    }

    em->apps_charts |= NETDATA_EBPF_APPS_FLAG_CHART_CREATED;
}

/*****************************************************************
 *
 *  FUNCTIONS TO CLOSE THE THREAD
 *
 *****************************************************************/

static void ebpf_obsolete_specific_process_charts(char *type, ebpf_module_t *em);

/**
 * Obsolete services
 *
 * Obsolete all service charts created
 *
 * @param em a pointer to `struct ebpf_module`
 */
static void ebpf_obsolete_process_services(ebpf_module_t *em, char *id)
{
    ebpf_write_chart_obsolete(
        id,
        NETDATA_SYSCALL_APPS_TASK_PROCESS,
        "",
        "Process started",
        EBPF_COMMON_UNITS_CALLS_PER_SEC,
        NETDATA_APPS_PROCESS_GROUP,
        NETDATA_EBPF_CHART_TYPE_STACKED,
        NETDATA_SYSTEMD_PROCESS_CREATE_CONTEXT,
        20065,
        em->update_every);

    ebpf_write_chart_obsolete(
        id,
        NETDATA_SYSCALL_APPS_TASK_THREAD,
        "",
        "Threads started",
        EBPF_COMMON_UNITS_CALLS_PER_SEC,
        NETDATA_APPS_PROCESS_GROUP,
        NETDATA_EBPF_CHART_TYPE_STACKED,
        NETDATA_SYSTEMD_THREAD_CREATE_CONTEXT,
        20066,
        em->update_every);

    ebpf_write_chart_obsolete(
        id,
        NETDATA_SYSCALL_APPS_TASK_CLOSE,
        "",
        "Tasks starts exit process.",
        EBPF_COMMON_UNITS_CALLS_PER_SEC,
        NETDATA_APPS_PROCESS_GROUP,
        NETDATA_EBPF_CHART_TYPE_STACKED,
        NETDATA_SYSTEMD_PROCESS_EXIT_CONTEXT,
        20067,
        em->update_every);

    ebpf_write_chart_obsolete(
        id,
        NETDATA_SYSCALL_APPS_TASK_EXIT,
        "",
        "Tasks closed",
        EBPF_COMMON_UNITS_CALLS_PER_SEC,
        NETDATA_APPS_PROCESS_GROUP,
        NETDATA_EBPF_CHART_TYPE_STACKED,
        NETDATA_SYSTEMD_PROCESS_CLOSE_CONTEXT,
        20068,
        em->update_every);

    if (em->mode < MODE_ENTRY) {
        ebpf_write_chart_obsolete(
            id,
            NETDATA_SYSCALL_APPS_TASK_ERROR,
            "",
            "Errors to create process or threads.",
            EBPF_COMMON_UNITS_CALLS_PER_SEC,
            NETDATA_APPS_PROCESS_GROUP,
            NETDATA_EBPF_CHART_TYPE_STACKED,
            NETDATA_SYSTEMD_PROCESS_ERROR_CONTEXT,
            20069,
            em->update_every);
    }
}

/**
 * Obsolete cgroup chart
 *
 * Send obsolete for all charts created before to close.
 *
 * @param em a pointer to `struct ebpf_module`
 */
static inline void ebpf_obsolete_process_cgroup_charts(ebpf_module_t *em)
{
    netdata_mutex_lock(&mutex_cgroup_shm);

    ebpf_cgroup_target_t *ect;
    for (ect = ebpf_cgroup_pids; ect; ect = ect->next) {
        if (ect->systemd) {
            ebpf_obsolete_process_services(em, ect->name);

            continue;
        }

        ebpf_obsolete_specific_process_charts(ect->name, em);
    }
    netdata_mutex_unlock(&mutex_cgroup_shm);
}

/**
 * Obsolette apps charts
 *
 * Obsolete apps charts.
 *
 * @param em a pointer to the structure with the default values.
 */
void ebpf_obsolete_process_apps_charts(struct ebpf_module *em)
{
    struct ebpf_target *w;
    int update_every = em->update_every;
    for (w = apps_groups_root_target; w; w = w->next) {
        if (unlikely(!(w->charts_created & (1 << EBPF_MODULE_PROCESS_IDX))))
            continue;

        ebpf_write_chart_obsolete(
            NETDATA_APP_FAMILY,
            w->clean_name,
            "_ebpf_process_start",
            "Process started.",
            EBPF_COMMON_UNITS_CALLS_PER_SEC,
            NETDATA_PROCESS_GROUP,
            NETDATA_EBPF_CHART_TYPE_STACKED,
            "app.ebpf_process_start",
            20161,
            update_every);

        ebpf_write_chart_obsolete(
            NETDATA_APP_FAMILY,
            w->clean_name,
            "_ebpf_thread_start",
            "Threads started.",
            EBPF_COMMON_UNITS_CALLS_PER_SEC,
            NETDATA_PROCESS_GROUP,
            NETDATA_EBPF_CHART_TYPE_STACKED,
            "app.ebpf_thread_start",
            20162,
            update_every);

        ebpf_write_chart_obsolete(
            NETDATA_APP_FAMILY,
            w->clean_name,
            "_ebpf_task_exit",
            "Tasks starts exit process.",
            EBPF_COMMON_UNITS_CALLS_PER_SEC,
            NETDATA_PROCESS_GROUP,
            NETDATA_EBPF_CHART_TYPE_STACKED,
            "app.ebpf_task_exit",
            20163,
            update_every);

        ebpf_write_chart_obsolete(
            NETDATA_APP_FAMILY,
            w->clean_name,
            "_ebpf_task_released",
            "Tasks released.",
            EBPF_COMMON_UNITS_CALLS_PER_SEC,
            NETDATA_PROCESS_GROUP,
            NETDATA_EBPF_CHART_TYPE_STACKED,
            "app.ebpf_task_released",
            20164,
            update_every);

        if (em->mode < MODE_ENTRY) {
            ebpf_write_chart_obsolete(
                NETDATA_APP_FAMILY,
                w->clean_name,
                "_ebpf_task_error",
                "Errors to create process or threads.",
                EBPF_COMMON_UNITS_CALLS_PER_SEC,
                NETDATA_PROCESS_GROUP,
                NETDATA_EBPF_CHART_TYPE_STACKED,
                "app.ebpf_task_error",
                20165,
                update_every);
        }

        w->charts_created &= ~(1 << EBPF_MODULE_PROCESS_IDX);
    }
}

/**
 * Obsolete global
 *
 * Obsolete global charts created by thread.
 *
 * @param em a pointer to `struct ebpf_module`
 */
static void ebpf_obsolete_process_global(ebpf_module_t *em)
{
    ebpf_write_chart_obsolete(
        NETDATA_EBPF_SYSTEM_GROUP,
        NETDATA_PROCESS_SYSCALL,
        "",
        "Start process",
        EBPF_COMMON_UNITS_CALLS_PER_SEC,
        NETDATA_PROCESS_GROUP,
        NETDATA_EBPF_CHART_TYPE_LINE,
        "system.process_thread",
        21002,
        em->update_every);

    ebpf_write_chart_obsolete(
        NETDATA_EBPF_SYSTEM_GROUP,
        NETDATA_EXIT_SYSCALL,
        "",
        "Exit process",
        EBPF_COMMON_UNITS_CALLS_PER_SEC,
        NETDATA_PROCESS_GROUP,
        NETDATA_EBPF_CHART_TYPE_LINE,
        "system.exit",
        21003,
        em->update_every);

    ebpf_write_chart_obsolete(
        NETDATA_EBPF_SYSTEM_GROUP,
        NETDATA_PROCESS_STATUS_NAME,
        "",
        "Process not closed",
        EBPF_COMMON_UNITS_CALLS,
        NETDATA_PROCESS_GROUP,
        NETDATA_EBPF_CHART_TYPE_LINE,
        "system.process_status",
        21004,
        em->update_every);

    if (em->mode < MODE_ENTRY) {
        ebpf_write_chart_obsolete(
            NETDATA_EBPF_SYSTEM_GROUP,
            NETDATA_PROCESS_ERROR_NAME,
            "",
            "Fails to create process",
            EBPF_COMMON_UNITS_CALLS_PER_SEC,
            NETDATA_PROCESS_GROUP,
            NETDATA_EBPF_CHART_TYPE_LINE,
            "system.task_error",
            21005,
            em->update_every);
    }
}

/**
 * Process disable tracepoints
 *
 * Disable tracepoints when the plugin was responsible to enable it.
 */
static void ebpf_process_disable_tracepoints()
{
    char *default_message = "Cannot disable the tracepoint";
    if (!was_sched_process_exit_enabled) {
        if (ebpf_disable_tracing_values(tracepoint_sched_type, tracepoint_sched_process_exit))
            netdata_log_error("%s %s/%s.", default_message, tracepoint_sched_type, tracepoint_sched_process_exit);
    }

    if (!was_sched_process_exec_enabled) {
        if (ebpf_disable_tracing_values(tracepoint_sched_type, tracepoint_sched_process_exec))
            netdata_log_error("%s %s/%s.", default_message, tracepoint_sched_type, tracepoint_sched_process_exec);
    }

    if (!was_sched_process_fork_enabled) {
        if (ebpf_disable_tracing_values(tracepoint_sched_type, tracepoint_sched_process_fork))
            netdata_log_error("%s %s/%s.", default_message, tracepoint_sched_type, tracepoint_sched_process_fork);
    }
}

static void ebpf_process_exit(void *pptr)
{
    ebpf_set_pid_map_fd(NETDATA_EBPF_PIDS_PROCESS_IDX, -1);
    ebpf_module_t *em = CLEANUP_FUNCTION_GET_PTR(pptr);
    if (!em)
        return;

    if (!process_safe_clean) {
        netdata_mutex_lock(&ebpf_exit_cleanup);
        em->enabled = NETDATA_THREAD_EBPF_STOPPED;
        netdata_mutex_unlock(&ebpf_exit_cleanup);
        return;
    }

    netdata_mutex_lock(&lock);
    collect_pids &= ~(1 << EBPF_MODULE_PROCESS_IDX);
    netdata_mutex_unlock(&lock);

    // Drop this module's bits from the shared PID pool so its slots don't
    // stay pinned if the plugin keeps running after the module stops.
    if (integration_shm && ebpf_shm_sem_wait_or_stop(shm_mutex_ebpf_integration)) {
        netdata_ebpf_sweep_shm_for_module_unsafe(NETDATA_EBPF_PIDS_PROCESS_IDX);
        sem_post(shm_mutex_ebpf_integration);
    }

    if (em->enabled == NETDATA_THREAD_EBPF_FUNCTION_RUNNING && !ebpf_plugin_stop()) {
        netdata_mutex_lock(&lock);
        if (em->cgroup_charts) {
            ebpf_obsolete_process_cgroup_charts(em);
            fflush(stdout);
        }

        if (em->apps_charts & NETDATA_EBPF_APPS_FLAG_CHART_CREATED) {
            ebpf_obsolete_process_apps_charts(em);
        }

        ebpf_obsolete_process_global(em);

        fflush(stdout);
        netdata_mutex_unlock(&lock);
    }

    freez(process_hash_values);
    freez(process_stat_vector);

    ebpf_process_disable_tracepoints();

    if (!ebpf_plugin_stop() && em->functions.bpf_unload)
        em->functions.bpf_unload(em);

    netdata_mutex_lock(&ebpf_exit_cleanup);
    process_pid_fd = -1;
    em->enabled = NETDATA_THREAD_EBPF_STOPPED;
    netdata_mutex_unlock(&ebpf_exit_cleanup);
}

/*****************************************************************
 *
 *  FUNCTIONS WITH THE MAIN LOOP
 *
 *****************************************************************/

/**
 * Sum PIDs
 *
 * Sum values for all targets.
 *
 * @param ps  structure used to store data
 * @param pids input data
 */
static void ebpf_process_sum_cgroup_pids(ebpf_publish_process_t *ps, struct pid_on_target2 *pids)
{
    ebpf_publish_process_t accumulator;
    memset(&accumulator, 0, sizeof(accumulator));

    while (pids) {
        ebpf_publish_process_t *pps = &pids->ps;

        accumulator.exit_call += pps->exit_call;
        accumulator.release_call += pps->release_call;
        accumulator.create_process += pps->create_process;
        accumulator.create_thread += pps->create_thread;

        accumulator.task_err += pps->task_err;

        pids = pids->next;
    }

    ps->exit_call = (accumulator.exit_call >= ps->exit_call) ? accumulator.exit_call : ps->exit_call;
    ps->release_call = (accumulator.release_call >= ps->release_call) ? accumulator.release_call : ps->release_call;
    ps->create_process =
        (accumulator.create_process >= ps->create_process) ? accumulator.create_process : ps->create_process;
    ps->create_thread =
        (accumulator.create_thread >= ps->create_thread) ? accumulator.create_thread : ps->create_thread;

    ps->task_err = (accumulator.task_err >= ps->task_err) ? accumulator.task_err : ps->task_err;
}

/*
 * Send Specific Process data
 *
 * Send data for specific cgroup/apps.
 *
 * @param type   chart type
 * @param values structure with values that will be sent to netdata
 * @param em   the structure with thread information
 */
static void ebpf_send_specific_process_data(char *type, ebpf_publish_process_t *values, ebpf_module_t *em)
{
    ebpf_write_begin_chart(type, NETDATA_SYSCALL_APPS_TASK_PROCESS, "");
    write_chart_dimension(
        process_publish_aggregated[NETDATA_KEY_PUBLISH_PROCESS_FORK].name, (long long)values->create_process);
    ebpf_write_end_chart();

    ebpf_write_begin_chart(type, NETDATA_SYSCALL_APPS_TASK_THREAD, "");
    write_chart_dimension(
        process_publish_aggregated[NETDATA_KEY_PUBLISH_PROCESS_CLONE].name, (long long)values->create_thread);
    ebpf_write_end_chart();

    ebpf_write_begin_chart(type, NETDATA_SYSCALL_APPS_TASK_EXIT, "");
    write_chart_dimension(
        process_publish_aggregated[NETDATA_KEY_PUBLISH_PROCESS_EXIT].name, (long long)values->release_call);
    ebpf_write_end_chart();

    ebpf_write_begin_chart(type, NETDATA_SYSCALL_APPS_TASK_CLOSE, "");
    write_chart_dimension(
        process_publish_aggregated[NETDATA_KEY_PUBLISH_PROCESS_RELEASE_TASK].name, (long long)values->release_call);
    ebpf_write_end_chart();

    if (em->mode < MODE_ENTRY) {
        ebpf_write_begin_chart(type, NETDATA_SYSCALL_APPS_TASK_ERROR, "");
        write_chart_dimension(
            process_publish_aggregated[NETDATA_KEY_PUBLISH_PROCESS_EXIT].name, (long long)values->task_err);
        ebpf_write_end_chart();
    }
}

/**
 * Create specific process charts
 *
 * Create charts for cgroup/application
 *
 * @param type the chart type.
 * @param em   the structure with thread information
 */
static void ebpf_create_specific_process_charts(char *type, ebpf_module_t *em)
{
    char *label = (!strncmp(type, "cgroup_", 7)) ? &type[7] : type;
    ebpf_create_chart(
        type,
        NETDATA_SYSCALL_APPS_TASK_PROCESS,
        "Process started",
        EBPF_COMMON_UNITS_CALLS_PER_SEC,
        NETDATA_PROCESS_GROUP,
        NETDATA_CGROUP_PROCESS_CREATE_CONTEXT,
        NETDATA_EBPF_CHART_TYPE_LINE,
        NETDATA_CHART_PRIO_CGROUPS_CONTAINERS + 5000,
        ebpf_create_global_dimension,
        &process_publish_aggregated[NETDATA_KEY_PUBLISH_PROCESS_FORK],
        1,
        em->update_every,
        NETDATA_EBPF_MODULE_NAME_PROCESS);
    ebpf_create_chart_labels("cgroup_name", label, RRDLABEL_SRC_AUTO);
    ebpf_commit_label();

    ebpf_create_chart(
        type,
        NETDATA_SYSCALL_APPS_TASK_THREAD,
        "Threads started",
        EBPF_COMMON_UNITS_CALLS_PER_SEC,
        NETDATA_PROCESS_GROUP,
        NETDATA_CGROUP_THREAD_CREATE_CONTEXT,
        NETDATA_EBPF_CHART_TYPE_LINE,
        NETDATA_CHART_PRIO_CGROUPS_CONTAINERS + 5001,
        ebpf_create_global_dimension,
        &process_publish_aggregated[NETDATA_KEY_PUBLISH_PROCESS_CLONE],
        1,
        em->update_every,
        NETDATA_EBPF_MODULE_NAME_PROCESS);
    ebpf_create_chart_labels("cgroup_name", label, RRDLABEL_SRC_AUTO);
    ebpf_commit_label();

    ebpf_create_chart(
        type,
        NETDATA_SYSCALL_APPS_TASK_EXIT,
        "Tasks starts exit process.",
        EBPF_COMMON_UNITS_CALLS_PER_SEC,
        NETDATA_PROCESS_GROUP,
        NETDATA_CGROUP_PROCESS_EXIT_CONTEXT,
        NETDATA_EBPF_CHART_TYPE_LINE,
        NETDATA_CHART_PRIO_CGROUPS_CONTAINERS + 5002,
        ebpf_create_global_dimension,
        &process_publish_aggregated[NETDATA_KEY_PUBLISH_PROCESS_EXIT],
        1,
        em->update_every,
        NETDATA_EBPF_MODULE_NAME_PROCESS);
    ebpf_create_chart_labels("cgroup_name", label, RRDLABEL_SRC_AUTO);
    ebpf_commit_label();

    ebpf_create_chart(
        type,
        NETDATA_SYSCALL_APPS_TASK_CLOSE,
        "Tasks closed",
        EBPF_COMMON_UNITS_CALLS_PER_SEC,
        NETDATA_PROCESS_GROUP,
        NETDATA_CGROUP_PROCESS_CLOSE_CONTEXT,
        NETDATA_EBPF_CHART_TYPE_LINE,
        NETDATA_CHART_PRIO_CGROUPS_CONTAINERS + 5003,
        ebpf_create_global_dimension,
        &process_publish_aggregated[NETDATA_KEY_PUBLISH_PROCESS_RELEASE_TASK],
        1,
        em->update_every,
        NETDATA_EBPF_MODULE_NAME_PROCESS);
    ebpf_create_chart_labels("cgroup_name", label, RRDLABEL_SRC_AUTO);
    ebpf_commit_label();

    if (em->mode < MODE_ENTRY) {
        ebpf_create_chart(
            type,
            NETDATA_SYSCALL_APPS_TASK_ERROR,
            "Errors to create process or threads.",
            EBPF_COMMON_UNITS_CALLS_PER_SEC,
            NETDATA_PROCESS_GROUP,
            NETDATA_CGROUP_PROCESS_ERROR_CONTEXT,
            NETDATA_EBPF_CHART_TYPE_LINE,
            NETDATA_CHART_PRIO_CGROUPS_CONTAINERS + 5004,
            ebpf_create_global_dimension,
            &process_publish_aggregated[NETDATA_KEY_PUBLISH_PROCESS_EXIT],
            1,
            em->update_every,
            NETDATA_EBPF_MODULE_NAME_PROCESS);
        ebpf_create_chart_labels("cgroup_name", label, RRDLABEL_SRC_AUTO);
        ebpf_commit_label();
    }
}

/**
 * Obsolete specific process charts
 *
 * Obsolete charts for cgroup/application
 *
 * @param type the chart type.
 * @param em   the structure with thread information
 */
static void ebpf_obsolete_specific_process_charts(char *type, ebpf_module_t *em)
{
    ebpf_write_chart_obsolete(
        type,
        NETDATA_SYSCALL_APPS_TASK_PROCESS,
        "",
        "Process started",
        EBPF_COMMON_UNITS_CALLS_PER_SEC,
        NETDATA_PROCESS_GROUP,
        NETDATA_EBPF_CHART_TYPE_LINE,
        NETDATA_CGROUP_PROCESS_CREATE_CONTEXT,
        NETDATA_CHART_PRIO_CGROUPS_CONTAINERS + 5000,
        em->update_every);

    ebpf_write_chart_obsolete(
        type,
        NETDATA_SYSCALL_APPS_TASK_THREAD,
        "",
        "Threads started",
        EBPF_COMMON_UNITS_CALLS_PER_SEC,
        NETDATA_PROCESS_GROUP,
        NETDATA_EBPF_CHART_TYPE_LINE,
        NETDATA_CGROUP_THREAD_CREATE_CONTEXT,
        NETDATA_CHART_PRIO_CGROUPS_CONTAINERS + 5001,
        em->update_every);

    ebpf_write_chart_obsolete(
        type,
        NETDATA_SYSCALL_APPS_TASK_EXIT,
        "",
        "Tasks starts exit process.",
        EBPF_COMMON_UNITS_CALLS_PER_SEC,
        NETDATA_PROCESS_GROUP,
        NETDATA_EBPF_CHART_TYPE_LINE,
        NETDATA_CGROUP_PROCESS_EXIT_CONTEXT,
        NETDATA_CHART_PRIO_CGROUPS_CONTAINERS + 5002,
        em->update_every);

    ebpf_write_chart_obsolete(
        type,
        NETDATA_SYSCALL_APPS_TASK_CLOSE,
        "",
        "Tasks closed",
        EBPF_COMMON_UNITS_CALLS_PER_SEC,
        NETDATA_PROCESS_GROUP,
        NETDATA_EBPF_CHART_TYPE_LINE,
        NETDATA_CGROUP_PROCESS_CLOSE_CONTEXT,
        NETDATA_CHART_PRIO_CGROUPS_CONTAINERS + 5003,
        em->update_every);

    if (em->mode < MODE_ENTRY) {
        ebpf_write_chart_obsolete(
            type,
            NETDATA_SYSCALL_APPS_TASK_ERROR,
            "",
            "Errors to create process or threads.",
            EBPF_COMMON_UNITS_CALLS_PER_SEC,
            NETDATA_PROCESS_GROUP,
            NETDATA_EBPF_CHART_TYPE_LINE,
            NETDATA_CGROUP_PROCESS_ERROR_CONTEXT,
            NETDATA_CHART_PRIO_CGROUPS_CONTAINERS + 5004,
            em->update_every);
    }
}

/**
 *  Create Systemd process Charts
 *
 *  Create charts when systemd is enabled
 *
 *  @param em   the structure with thread information
 **/
static void ebpf_create_systemd_process_charts(ebpf_module_t *em)
{
    static ebpf_systemd_args_t data_process = {
        .title = "Process started",
        .units = EBPF_COMMON_UNITS_CALLS_PER_SEC,
        .family = NETDATA_APPS_PROCESS_GROUP,
        .charttype = NETDATA_EBPF_CHART_TYPE_STACKED,
        .order = 20065,
        .algorithm = EBPF_CHART_ALGORITHM_INCREMENTAL,
        .context = NETDATA_SYSTEMD_PROCESS_CREATE_CONTEXT,
        .module = NETDATA_EBPF_MODULE_NAME_PROCESS,
        .update_every = 0,
        .suffix = NETDATA_SYSCALL_APPS_TASK_PROCESS,
        .dimension = "calls"};

    static ebpf_systemd_args_t data_thread = {
        .title = "Threads started",
        .units = EBPF_COMMON_UNITS_CALLS_PER_SEC,
        .family = NETDATA_APPS_PROCESS_GROUP,
        .charttype = NETDATA_EBPF_CHART_TYPE_STACKED,
        .order = 20066,
        .algorithm = EBPF_CHART_ALGORITHM_INCREMENTAL,
        .context = NETDATA_SYSTEMD_THREAD_CREATE_CONTEXT,
        .module = NETDATA_EBPF_MODULE_NAME_PROCESS,
        .update_every = 0,
        .suffix = NETDATA_SYSCALL_APPS_TASK_THREAD,
        .dimension = "calls"};

    static ebpf_systemd_args_t task_exit = {
        .title = "Tasks starts exit process.",
        .units = EBPF_COMMON_UNITS_CALLS_PER_SEC,
        .family = NETDATA_APPS_PROCESS_GROUP,
        .charttype = NETDATA_EBPF_CHART_TYPE_STACKED,
        .order = 20067,
        .algorithm = EBPF_CHART_ALGORITHM_INCREMENTAL,
        .context = NETDATA_SYSTEMD_PROCESS_EXIT_CONTEXT,
        .module = NETDATA_EBPF_MODULE_NAME_PROCESS,
        .update_every = 0,
        .suffix = NETDATA_SYSCALL_APPS_TASK_CLOSE,
        .dimension = "calls"};

    static ebpf_systemd_args_t task_closed = {
        .title = "Tasks closed",
        .units = EBPF_COMMON_UNITS_CALLS_PER_SEC,
        .family = NETDATA_APPS_PROCESS_GROUP,
        .charttype = NETDATA_EBPF_CHART_TYPE_STACKED,
        .order = 20068,
        .algorithm = EBPF_CHART_ALGORITHM_INCREMENTAL,
        .context = NETDATA_SYSTEMD_PROCESS_CLOSE_CONTEXT,
        .module = NETDATA_EBPF_MODULE_NAME_PROCESS,
        .update_every = 0,
        .suffix = NETDATA_SYSCALL_APPS_TASK_EXIT,
        .dimension = "calls"};

    static ebpf_systemd_args_t task_error = {
        .title = "Errors to create process or threads.",
        .units = EBPF_COMMON_UNITS_CALLS_PER_SEC,
        .family = NETDATA_APPS_PROCESS_GROUP,
        .charttype = NETDATA_EBPF_CHART_TYPE_STACKED,
        .order = 20069,
        .algorithm = EBPF_CHART_ALGORITHM_INCREMENTAL,
        .context = NETDATA_SYSTEMD_PROCESS_ERROR_CONTEXT,
        .module = NETDATA_EBPF_MODULE_NAME_PROCESS,
        .update_every = 0,
        .suffix = NETDATA_SYSCALL_APPS_TASK_ERROR,
        .dimension = "calls"};

    ebpf_cgroup_target_t *w;
    netdata_run_mode_t mode = em->mode;
    if (!task_exit.update_every)
        data_process.update_every = data_thread.update_every = task_exit.update_every = task_closed.update_every =
            task_error.update_every = em->update_every;

    for (w = ebpf_cgroup_pids; w; w = w->next) {
        if (ebpf_plugin_stop())
            break;

        if (unlikely(!w->systemd || w->flags & NETDATA_EBPF_SERVICES_HAS_PROCESS_CHART))
            continue;

        data_process.id = data_thread.id = task_exit.id = task_closed.id = task_error.id = w->name;
        ebpf_create_charts_on_systemd(&data_process);

        ebpf_create_charts_on_systemd(&data_thread);

        ebpf_create_charts_on_systemd(&task_exit);

        ebpf_create_charts_on_systemd(&task_closed);
        if (mode < MODE_ENTRY) {
            ebpf_create_charts_on_systemd(&task_error);
        }
        w->flags |= NETDATA_EBPF_SERVICES_HAS_PROCESS_CHART;
    }
}

/**
 * Send Systemd charts
 *
 * Send collected data to Netdata.
 *
 *  @param em   the structure with thread information
 */
static void ebpf_send_systemd_process_charts(ebpf_module_t *em)
{
    ebpf_cgroup_target_t *ect;
    for (ect = ebpf_cgroup_pids; ect; ect = ect->next) {
        if (ebpf_plugin_stop())
            break;

        if (unlikely(!(ect->flags & NETDATA_EBPF_SERVICES_HAS_PROCESS_CHART))) {
            continue;
        }

        ebpf_write_begin_chart(ect->name, NETDATA_SYSCALL_APPS_TASK_PROCESS, "");
        write_chart_dimension("calls", ect->publish_systemd_ps.create_process);
        ebpf_write_end_chart();

        ebpf_write_begin_chart(ect->name, NETDATA_SYSCALL_APPS_TASK_THREAD, "");
        write_chart_dimension("calls", ect->publish_systemd_ps.create_thread);
        ebpf_write_end_chart();

        ebpf_write_begin_chart(ect->name, NETDATA_SYSCALL_APPS_TASK_EXIT, "");
        write_chart_dimension("calls", ect->publish_systemd_ps.exit_call);
        ebpf_write_end_chart();

        ebpf_write_begin_chart(ect->name, NETDATA_SYSCALL_APPS_TASK_CLOSE, "");
        write_chart_dimension("calls", ect->publish_systemd_ps.release_call);
        ebpf_write_end_chart();

        if (em->mode < MODE_ENTRY) {
            ebpf_write_begin_chart(ect->name, NETDATA_SYSCALL_APPS_TASK_ERROR, "");
            write_chart_dimension("calls", ect->publish_systemd_ps.task_err);
            ebpf_write_end_chart();
        }
    }
}

/**
 * Send data to Netdata calling auxiliary functions.
 *
 * @param em   the structure with thread information
*/
static void ebpf_process_send_cgroup_data(ebpf_module_t *em)
{
    netdata_mutex_lock(&mutex_cgroup_shm);
    ebpf_cgroup_target_t *ect;
    for (ect = ebpf_cgroup_pids; ect; ect = ect->next) {
        ebpf_process_sum_cgroup_pids(&ect->publish_systemd_ps, ect->pids);
    }

    if (ebpf_plugin_stop()) {
        netdata_mutex_unlock(&mutex_cgroup_shm);
        return;
    }

    if (shm_ebpf_cgroup.header->systemd_enabled) {
        if (send_cgroup_chart) {
            ebpf_create_systemd_process_charts(em);
        }

        ebpf_send_systemd_process_charts(em);
    }

    for (ect = ebpf_cgroup_pids; ect; ect = ect->next) {
        if (ebpf_plugin_stop())
            break;

        if (ect->systemd)
            continue;

        if (!(ect->flags & NETDATA_EBPF_CGROUP_HAS_PROCESS_CHART) && ect->updated) {
            ebpf_create_specific_process_charts(ect->name, em);
            ect->flags |= NETDATA_EBPF_CGROUP_HAS_PROCESS_CHART;
        }

        if (ect->flags & NETDATA_EBPF_CGROUP_HAS_PROCESS_CHART) {
            if (ect->updated) {
                ebpf_send_specific_process_data(ect->name, &ect->publish_systemd_ps, em);
            } else {
                ebpf_obsolete_specific_process_charts(ect->name, em);
                ect->flags &= ~NETDATA_EBPF_CGROUP_HAS_PROCESS_CHART;
            }
        }
    }

    netdata_mutex_unlock(&mutex_cgroup_shm);
}

/**
 * Update Cgroup algorithm
 *
 * Change algorithm from absolute to incremental
 */
void ebpf_process_update_cgroup_algorithm()
{
    int i;
    for (i = 0; i < NETDATA_KEY_PUBLISH_PROCESS_END; i++) {
        netdata_publish_syscall_t *ptr = &process_publish_aggregated[i];
        ptr->algorithm = ebpf_algorithms[NETDATA_EBPF_INCREMENTAL_IDX];
    }
}

/**
 * Process Accumulator
 *
 * Sum all values read from kernel and store in the first address.
 *
 * @param out the vector with read values.
 * @param maps_per_core do I need to read all cores?
 */
void ebpf_process_apps_accumulator(ebpf_process_stat_t *out, int maps_per_core)
{
    int i, end = (maps_per_core) ? ebpf_nprocs : 1;
    ebpf_process_stat_t *total = &out[0];
    uint64_t ct = total->ct;
    for (i = 1; i < end; i++) {
        if (ebpf_plugin_stop())
            break;

        ebpf_process_stat_t *w = &out[i];
        total->exit_call += w->exit_call;
        total->task_err += w->task_err;
        total->create_thread += w->create_thread;
        total->create_process += w->create_process;
        total->release_call += w->release_call;

        if (w->ct > ct)
            ct = w->ct;
    }
    total->ct = ct;
}

/**
 * Sum values for pid
 *
 * @param structure to store result.
 * @param root the structure with all available PIDs
 */
void ebpf_process_sum_values_for_pids(ebpf_process_stat_t *process, struct ebpf_pid_on_target *root)
{
    memset(process, 0, sizeof(ebpf_process_stat_t));
    for (; root; root = root->next) {
        if (ebpf_plugin_stop())
            break;

        uint32_t pid = root->pid;
        netdata_ebpf_pid_stats_t *local_pid = netdata_ebpf_lookup_shm_pointer_unsafe(pid);
        if (!local_pid || !(local_pid->threads & (1U << (NETDATA_EBPF_PIDS_PROCESS_IDX << 1))))
            continue;

        ebpf_publish_process_t *in = &local_pid->process;

        process->task_err += in->task_err;
        process->release_call += in->release_call;
        process->exit_call += in->exit_call;
        process->create_thread += in->create_thread;
        process->create_process += in->create_process;
    }
}

/**
 * Collect data for all process
 *
 * Read data from hash table and store it in appropriate vectors.
 * It also creates the link between targets and PIDs.
 *
 * @param tbl_pid_stats_fd      The mapped file descriptor for the hash table.
 * @param maps_per_core         do I have hash maps per core?
 */
void collect_data_for_all_processes(int tbl_pid_stats_fd, int maps_per_core)
{
    if (tbl_pid_stats_fd == -1)
        return;

    ebpf_set_pid_map_fd(NETDATA_EBPF_PIDS_PROCESS_IDX, tbl_pid_stats_fd);
    size_t length = sizeof(ebpf_process_stat_t);
    if (maps_per_core)
        length *= ebpf_nprocs;

    if (tbl_pid_stats_fd != -1) {
        uint32_t key = 0, next_key = 0;
        while (bpf_map_get_next_key(tbl_pid_stats_fd, &key, &next_key) == 0) {
            if (ebpf_plugin_stop())
                break;

            if (bpf_map_lookup_elem(tbl_pid_stats_fd, &key, process_stat_vector)) {
                goto end_process_loop;
            }

            ebpf_process_apps_accumulator(process_stat_vector, maps_per_core);

            netdata_ebpf_pid_stats_t *local_pid =
                netdata_ebpf_get_shm_pointer_unsafe(key, NETDATA_EBPF_PIDS_PROCESS_IDX);
            if (!local_pid)
                goto end_process_loop;

            ebpf_publish_process_t *w = &local_pid->process;

            if (!w->ct || w->ct != process_stat_vector[0].ct) {
                w->ct = process_stat_vector[0].ct;
                w->create_thread = process_stat_vector[0].create_thread;
                w->exit_call = process_stat_vector[0].exit_call;
                w->create_process = process_stat_vector[0].create_process;
                w->release_call = process_stat_vector[0].release_call;
                w->task_err = process_stat_vector[0].task_err;
            } else {
                if (kill((pid_t)key, 0) == -1 && errno == ESRCH) {
                    if (netdata_ebpf_reset_shm_pointer_unsafe(tbl_pid_stats_fd, key, NETDATA_EBPF_PIDS_PROCESS_IDX))
                        memset(w, 0, sizeof(*w));
                }
            }

        end_process_loop:
            memset(process_stat_vector, 0, length);
            key = next_key;
        }
    }

    struct ebpf_target *w;
    for (w = apps_groups_root_target; w; w = w->next) {
        if (ebpf_plugin_stop())
            break;

        if (unlikely(!(w->processes)))
            continue;

        ebpf_process_sum_values_for_pids(&w->process, w->root_pid);
    }
}

/**
 * Main loop for this collector.
 *
 * @param em   the structure with thread information
 */
static void process_collector(ebpf_module_t *em)
{
    int publish_global = em->global_charts;
    int cgroups = em->cgroup_charts;
    netdata_mutex_lock(&ebpf_exit_cleanup);
    process_pid_fd = process_maps[NETDATA_PROCESS_PID_TABLE].map_fd;
    netdata_mutex_unlock(&ebpf_exit_cleanup);
    if (cgroups)
        ebpf_process_update_cgroup_algorithm();

    int update_every = em->update_every;
    int counter = update_every - 1;
    int maps_per_core = em->maps_per_core;
    uint32_t running_time = 0;
    uint32_t lifetime = em->lifetime;
    netdata_idx_t *stats = em->hash_table_stats;
    memset(stats, 0, sizeof(netdata_idx_t) * NETDATA_EBPF_GLOBAL_TABLE_STATUS_END);
    heartbeat_t hb;
    heartbeat_init(&hb, USEC_PER_SEC);
    int process_maps_per_core = ebpf_modules[EBPF_MODULE_PROCESS_IDX].maps_per_core;
    while (!ebpf_plugin_stop() && running_time < lifetime) {
        if (ebpf_plugin_stop())
            break;

        heartbeat_next(&hb);

        if (ebpf_plugin_stop())
            break;

        if (++counter == update_every) {
            counter = 0;

            ebpf_read_process_hash_global_tables(stats, maps_per_core);

            netdata_apps_integration_flags_t apps_enabled = em->apps_charts;

            if (ebpf_all_pids_count > 0) {
                if (!ebpf_shm_sem_wait_or_stop(shm_mutex_ebpf_integration)) {
                    if (errno != ECANCELED)
                        netdata_log_error("PROCESS: Failed to wait on semaphore.");
                    break;
                }
                netdata_mutex_lock(&collect_data_mutex);
                collect_data_for_all_processes(process_pid_fd, process_maps_per_core);

                if (cgroups && shm_ebpf_cgroup.header) {
                    ebpf_update_process_cgroup();
                }
                netdata_mutex_unlock(&collect_data_mutex);
                if (sem_post(shm_mutex_ebpf_integration)) {
                    netdata_log_error("PROCESS: Failed to post semaphore.");
                    break;
                }
            }

            // Avoid acquiring lock for data-send when shutdown is in progress;
            // the main thread may be holding lock for apps-parsing at this point,
            // which would delay this thread's join and compound the shutdown time.
            if (ebpf_plugin_stop())
                break;

            netdata_mutex_lock(&lock);

            if (publish_global) {
                ebpf_process_send_data(em);
            }

            netdata_mutex_lock(&collect_data_mutex);
            if (apps_enabled & NETDATA_EBPF_APPS_FLAG_CHART_CREATED) {
                ebpf_process_send_apps_data(apps_groups_root_target, em);
            }

            if (cgroups && shm_ebpf_cgroup.header) {
                if (!ebpf_plugin_stop())
                    ebpf_process_send_cgroup_data(em);
            }

            netdata_mutex_unlock(&collect_data_mutex);
            netdata_mutex_unlock(&lock);

            fflush(stdout);

            if (ebpf_plugin_stop())
                break;

            netdata_mutex_lock(&ebpf_exit_cleanup);
            running_time += update_every;
            em->running_time = running_time;
            netdata_mutex_unlock(&ebpf_exit_cleanup);
        }
    }
}

/*****************************************************************
 *
 *  FUNCTIONS TO START THREAD
 *
 *****************************************************************/

/**
 * Allocate vectors used with this thread.
 * We are not testing the return, because callocz does this and shutdown the software
 * case it was not possible to allocate.
 *
 *  @param length is the length for the vectors used inside the collector.
 */
static void ebpf_process_allocate_global_vectors(size_t length)
{
    memset(process_aggregated_data, 0, length * sizeof(netdata_syscall_stat_t));
    memset(process_publish_aggregated, 0, length * sizeof(netdata_publish_syscall_t));
    process_hash_values = callocz(ebpf_nprocs, sizeof(netdata_idx_t));
    process_stat_vector = callocz(ebpf_nprocs, sizeof(ebpf_process_stat_t));
}

static void change_syscalls()
{
    static char *lfork = "do_fork";
    process_id_names[NETDATA_KEY_PUBLISH_PROCESS_FORK] = lfork;
}

/**
 * Set local variables
 *
 */
static void set_local_pointers()
{
    if (isrh >= NETDATA_MINIMUM_RH_VERSION && isrh < NETDATA_RH_8)
        change_syscalls();
}

/*****************************************************************
 *
 *  EBPF PROCESS THREAD
 *
 *****************************************************************/

/**
 * Enable a single tracepoint
 *
 * Enable a tracepoint and store whether it was already enabled.
 *
 * @param event    the tracepoint event name
 * @param was_enabled  pointer to store the previous state
 *
 * @return 0 on success, -1 on error
 */
static int ebpf_enable_single_tracepoint(const char *event, int *was_enabled)
{
    int enabled = ebpf_is_tracepoint_enabled(tracepoint_sched_type, event);
    if (enabled == -1)
        return -1;
    if (!enabled) {
        if (ebpf_enable_tracing_values(tracepoint_sched_type, event))
            return -1;
    }
    *was_enabled = enabled;
    return 0;
}

/**
 * Enable tracepoints
 *
 * Enable necessary tracepoints for thread.
 *
 * @return  It returns 0 on success and -1 otherwise
 */
static int ebpf_process_enable_tracepoints()
{
    if (ebpf_enable_single_tracepoint(tracepoint_sched_process_exit, &was_sched_process_exit_enabled))
        return -1;

    if (ebpf_enable_single_tracepoint(tracepoint_sched_process_exec, &was_sched_process_exec_enabled))
        return -1;

    if (ebpf_enable_single_tracepoint(tracepoint_sched_process_fork, &was_sched_process_fork_enabled))
        return -1;

    return 0;
}

/**
 * Process thread
 *
 * Thread used to generate process charts.
 *
 * @param ptr a pointer to `struct ebpf_module`
 *
 * @return It always return NULL
 */
void ebpf_process_thread(void *ptr)
{
    ebpf_module_t *em = (ebpf_module_t *)ptr;

    process_safe_clean = false;

    CLEANUP_FUNCTION_REGISTER(ebpf_process_exit) cleanup_ptr = em;

    if (!ebpf_module_thread_has_valid_state(em)) {
        em->enabled = em->global_charts = em->apps_charts = em->cgroup_charts = NETDATA_THREAD_EBPF_STOPPING;
        netdata_mutex_lock(&ebpf_exit_cleanup);
        ebpf_update_disabled_plugin_stats(em);
        netdata_mutex_unlock(&ebpf_exit_cleanup);
        return;
    }

    em->maps = process_maps;

    netdata_mutex_lock(&ebpf_exit_cleanup);
    if (ebpf_process_enable_tracepoints()) {
        em->enabled = em->global_charts = em->apps_charts = em->cgroup_charts = NETDATA_THREAD_EBPF_STOPPING;
    }
    netdata_mutex_unlock(&ebpf_exit_cleanup);

    ebpf_process_allocate_global_vectors(NETDATA_KEY_PUBLISH_PROCESS_END);
    netdata_mutex_lock(&lock);
    ebpf_update_pid_table(&process_maps[0], em);

    set_local_pointers();
    if (ebpf_process_load_bpf(em)) {
        em->enabled = em->global_charts = em->apps_charts = em->cgroup_charts = NETDATA_THREAD_EBPF_STOPPING;
    }

    int algorithms[NETDATA_KEY_PUBLISH_PROCESS_END] = {
        NETDATA_EBPF_ABSOLUTE_IDX, NETDATA_EBPF_ABSOLUTE_IDX, NETDATA_EBPF_ABSOLUTE_IDX, NETDATA_EBPF_ABSOLUTE_IDX};

    ebpf_global_labels(
        process_aggregated_data,
        process_publish_aggregated,
        process_dimension_names,
        process_id_names,
        algorithms,
        NETDATA_KEY_PUBLISH_PROCESS_END);

    ebpf_create_global_charts(em);

    ebpf_update_stats(&plugin_statistics, em);
    ebpf_update_kernel_memory_with_vector(&plugin_statistics, em->maps, EBPF_ACTION_STAT_ADD);

    netdata_mutex_unlock(&lock);

    process_safe_clean = true;
    process_collector(em);

    netdata_mutex_lock(&ebpf_exit_cleanup);
    ebpf_update_disabled_plugin_stats(em);
    netdata_mutex_unlock(&ebpf_exit_cleanup);
}
