HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/libsystemd/sd-event/sd-event.c

181,814 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 231ed955b540a6e71c82e47bc4d98bc301ac14ac

Lines 1001–2000 of 5,529

                        source_child_pidfd_unregister(s);
                else
                        event_gc_signal_data(s->event, &s->priority, SIGCHLD);
 
                break;
 
        case SOURCE_DEFER:
                /* nothing */
                break;
 
        case SOURCE_POST:
                set_remove(s->event->post_sources, s);
                break;
 
        case SOURCE_EXIT:
                prioq_remove(s->event->exit, s, &s->exit.prioq_index);
                break;
 
        case SOURCE_INOTIFY: {
                InodeData *inode_data;
 
                inode_data = s->inotify.inode_data;
                if (inode_data) {
                        InotifyData *inotify_data;
                        assert_se(inotify_data = inode_data->inotify_data);
 
                        /* Detach this event source from the inode object */
                        LIST_REMOVE(inotify.by_inode_data, inode_data->event_sources, s);
                        s->inotify.inode_data = NULL;
 
                        if (s->pending) {
                                assert(inotify_data->n_pending > 0);
                                inotify_data->n_pending--;
                        }
 
                        /* Note that we don't reduce the inotify mask for the watch descriptor here if the inode is
                         * continued to being watched. That's because inotify doesn't really have an API for that: we
                         * can only change watch masks with access to the original inode either by fd or by path. But
                         * paths aren't stable, and keeping an O_PATH fd open all the time would mean wasting an fd
                         * continuously and keeping the mount busy which we can't really do. We could reconstruct the
                         * original inode from /proc/self/fdinfo/$INOTIFY_FD (as all watch descriptors are listed
                         * there), but given the need for open_by_handle_at() which is privileged and not universally
                         * available this would be quite an incomplete solution. Hence we go the other way, leave the
                         * mask set, even if it is not minimized now, and ignore all events we aren't interested in
                         * anymore after reception. Yes, this sucks, but … Linux … */
 
                        /* Maybe release the inode data (and its inotify) */
                        event_gc_inode_data(s->event, inode_data);
                }
 
                break;
        }
 
        case SOURCE_MEMORY_PRESSURE:
        case SOURCE_CPU_PRESSURE:
        case SOURCE_IO_PRESSURE:
                source_pressure_remove_from_write_list(s);
                source_pressure_unregister(s);
                break;
 
        default:
                assert_not_reached();
        }
 
        if (s->pending)
                prioq_remove(s->event->pending, s, &s->pending_index);
 
        if (s->prepare)
                prioq_remove(s->event->prepare, s, &s->prepare_index);
 
        if (s->ratelimited)
                event_source_time_prioq_remove(s, &s->event->boottime);
 
        event = TAKE_PTR(s->event);
        LIST_REMOVE(sources, event->sources, s);
        event->n_sources--;
 
        /* Note that we don't invalidate the type here, since we still need it in order to close the fd or
         * pidfd associated with this event source, which we'll do only on source_free(). */
 
        if (!s->floating)
                sd_event_unref(event);
}
 
static sd_event_source* source_free(sd_event_source *s) {
        int r;
 
        assert(s);
 
        source_disconnect(s);
 
        if (s->type == SOURCE_IO && s->io.owned)
                s->io.fd = safe_close(s->io.fd);
 
        if (s->type == SOURCE_CHILD) {
                /* Eventually the kernel will do this automatically for us, but for now let's emulate this (unreliably) in userspace. */
 
                if (s->child.process_owned) {
                        assert(s->child.pid > 0);
                        assert(s->child.pidfd >= 0);
 
                        if (!s->child.exited) {
                                r = RET_NERRNO(pidfd_send_signal(s->child.pidfd, SIGKILL, NULL, 0));
                                if (r < 0 && r != -ESRCH)
                                        log_debug_errno(r, "Failed to kill process " PID_FMT ", ignoring: %m",
                                                        s->child.pid);
                        }
 
                        if (!s->child.waited) {
                                siginfo_t si = {};
 
                                /* Reap the child if we can */
                                (void) waitid(P_PIDFD, s->child.pidfd, &si, WEXITED);
                        }
                }
 
                if (s->child.pidfd_owned)
                        s->child.pidfd = safe_close(s->child.pidfd);
        }
 
        if (EVENT_SOURCE_IS_PRESSURE(s)) {
                s->pressure.fd = safe_close(s->pressure.fd);
                s->pressure.write_buffer = mfree(s->pressure.write_buffer);
        }
 
        if (s->destroy_callback)
                s->destroy_callback(s->userdata);
 
        free(s->description);
        return mfree(s);
}
DEFINE_TRIVIAL_CLEANUP_FUNC(sd_event_source*, source_free);
 
static int source_set_pending(sd_event_source *s, bool b) {
        int r;
 
        assert(s);
        assert(s->type != SOURCE_EXIT);
 
        if (s->pending == b)
                return 0;
 
        s->pending = b;
 
        if (b) {
                s->pending_iteration = s->event->iteration;
 
                r = prioq_put(s->event->pending, s, &s->pending_index);
                if (r < 0) {
                        s->pending = false;
                        return r;
                }
        } else
                assert_se(prioq_remove(s->event->pending, s, &s->pending_index));
 
        if (EVENT_SOURCE_IS_TIME(s->type))
                event_source_time_prioq_reshuffle(s);
 
        if (s->type == SOURCE_SIGNAL && !b) {
                struct signal_data *d;
 
                d = hashmap_get(s->event->signal_data, &s->priority);
                if (d && d->current == s)
                        d->current = NULL;
        }
 
        if (s->type == SOURCE_INOTIFY) {
 
                assert(s->inotify.inode_data);
                assert(s->inotify.inode_data->inotify_data);
 
                if (b)
                        s->inotify.inode_data->inotify_data->n_pending++;
                else {
                        assert(s->inotify.inode_data->inotify_data->n_pending > 0);
                        s->inotify.inode_data->inotify_data->n_pending--;
                }
        }
 
        return 1;
}
 
static sd_event_source* source_new(sd_event *e, bool floating, EventSourceType type) {
 
        /* Let's allocate exactly what we need. Note that the difference of the smallest event source
         * structure to the largest is 144 bytes on x86-64 at the time of writing, i.e. more than two cache
         * lines. */
        static const size_t size_table[_SOURCE_EVENT_SOURCE_TYPE_MAX] = {
                [SOURCE_IO]                  = endoffsetof_field(sd_event_source, io),
                [SOURCE_TIME_REALTIME]       = endoffsetof_field(sd_event_source, time),
                [SOURCE_TIME_BOOTTIME]       = endoffsetof_field(sd_event_source, time),
                [SOURCE_TIME_MONOTONIC]      = endoffsetof_field(sd_event_source, time),
                [SOURCE_TIME_REALTIME_ALARM] = endoffsetof_field(sd_event_source, time),
                [SOURCE_TIME_BOOTTIME_ALARM] = endoffsetof_field(sd_event_source, time),
                [SOURCE_SIGNAL]              = endoffsetof_field(sd_event_source, signal),
                [SOURCE_CHILD]               = endoffsetof_field(sd_event_source, child),
                [SOURCE_DEFER]               = endoffsetof_field(sd_event_source, defer),
                [SOURCE_POST]                = endoffsetof_field(sd_event_source, post),
                [SOURCE_EXIT]                = endoffsetof_field(sd_event_source, exit),
                [SOURCE_INOTIFY]             = endoffsetof_field(sd_event_source, inotify),
                [SOURCE_MEMORY_PRESSURE]     = endoffsetof_field(sd_event_source, pressure),
                [SOURCE_CPU_PRESSURE]        = endoffsetof_field(sd_event_source, pressure),
                [SOURCE_IO_PRESSURE]         = endoffsetof_field(sd_event_source, pressure),
        };
 
        sd_event_source *s;
 
        assert(e);
        assert(type >= 0);
        assert(type < _SOURCE_EVENT_SOURCE_TYPE_MAX);
        assert(size_table[type] > 0);
 
        s = malloc0(size_table[type]);
        if (!s)
                return NULL;
        /* We use expand_to_usable() here to tell gcc that it should consider this an object of the full
         * size, even if we only allocate the initial part we need. */
        s = expand_to_usable(s, sizeof(sd_event_source));
 
        /* Note: we cannot use compound initialization here, because sizeof(sd_event_source) is likely larger
         * than what we allocated here. */
        s->n_ref = 1;
        s->event = e;
        s->floating = floating;
        s->type = type;
        s->pending_index = PRIOQ_IDX_NULL;
        s->prepare_index = PRIOQ_IDX_NULL;
 
        if (!floating)
                sd_event_ref(e);
 
        LIST_PREPEND(sources, e->sources, s);
        e->n_sources++;
 
        return s;
}
 
static int io_exit_callback(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
        assert(s);
 
        return sd_event_exit(sd_event_source_get_event(s), PTR_TO_INT(userdata));
}
 
_public_ int sd_event_add_io(
                sd_event *e,
                sd_event_source **ret,
                int fd,
                uint32_t events,
                sd_event_io_handler_t callback,
                void *userdata) {
 
        _cleanup_(source_freep) sd_event_source *s = NULL;
        int r;
 
        assert_return(e, -EINVAL);
        assert_return(e = event_resolve(e), -ENOPKG);
        assert_return(fd >= 0, -EBADF);
        assert_return(!(events & ~(EPOLLIN|EPOLLOUT|EPOLLRDHUP|EPOLLPRI|EPOLLERR|EPOLLHUP|EPOLLET)), -EINVAL);
        assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
        assert_return(!event_origin_changed(e), -ECHILD);
 
        if (!callback)
                callback = io_exit_callback;
 
        s = source_new(e, !ret, SOURCE_IO);
        if (!s)
                return -ENOMEM;
 
        s->wakeup = WAKEUP_EVENT_SOURCE;
        s->io.fd = fd;
        s->io.events = events;
        s->io.callback = callback;
        s->userdata = userdata;
        s->enabled = SD_EVENT_ON;
 
        r = source_io_register(s, s->enabled, events);
        if (r < 0)
                return r;
 
        if (ret)
                *ret = s;
        TAKE_PTR(s);
 
        return 0;
}
 
static void initialize_perturb(sd_event *e) {
        sd_id128_t id = {};
 
        /* When we sleep for longer, we try to realign the wakeup to the same time within each
         * minute/second/250ms, so that events all across the system can be coalesced into a single CPU
         * wakeup. However, let's take some system-specific randomness for this value, so that in a network
         * of systems with synced clocks timer events are distributed a bit. Here, we calculate a
         * perturbation usec offset from the boot ID (or machine ID if failed, e.g. /proc is not mounted). */
 
        if (_likely_(e->perturb != USEC_INFINITY))
                return;
 
        if (sd_id128_get_boot(&id) >= 0 || sd_id128_get_machine(&id) >= 0)
                e->perturb = (id.qwords[0] ^ id.qwords[1]) % USEC_PER_MINUTE;
        else
                e->perturb = 0; /* This is a super early process without /proc and /etc ?? */
}
 
static int event_setup_timer_fd(
                sd_event *e,
                struct clock_data *d,
                clockid_t clock) {
 
        assert(e);
        assert(d);
 
        if (_likely_(d->fd >= 0))
                return 0;
 
        _cleanup_close_ int fd = -EBADF;
 
        fd = timerfd_create(clock, TFD_NONBLOCK|TFD_CLOEXEC);
        if (fd < 0)
                return -errno;
 
        fd = fd_move_above_stdio(fd);
 
        struct epoll_event ev = {
                .events = EPOLLIN,
                .data.ptr = d,
        };
 
        if (epoll_ctl(e->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0)
                return -errno;
 
        d->fd = TAKE_FD(fd);
        return 0;
}
 
static int time_exit_callback(sd_event_source *s, uint64_t usec, void *userdata) {
        assert(s);
 
        return sd_event_exit(sd_event_source_get_event(s), PTR_TO_INT(userdata));
}
 
static int setup_clock_data(sd_event *e, struct clock_data *d, clockid_t clock) {
        int r;
 
        assert(d);
 
        if (d->fd < 0) {
                r = event_setup_timer_fd(e, d, clock);
                if (r < 0)
                        return r;
        }
 
        r = prioq_ensure_allocated(&d->earliest, earliest_time_prioq_compare);
        if (r < 0)
                return r;
 
        r = prioq_ensure_allocated(&d->latest, latest_time_prioq_compare);
        if (r < 0)
                return r;
 
        return 0;
}
 
static int event_source_time_prioq_put(
                sd_event_source *s,
                struct clock_data *d) {
 
        int r;
 
        assert(s);
        assert(d);
        assert(EVENT_SOURCE_USES_TIME_PRIOQ(s->type));
 
        r = prioq_put(d->earliest, s, &s->earliest_index);
        if (r < 0)
                return r;
 
        r = prioq_put(d->latest, s, &s->latest_index);
        if (r < 0) {
                assert_se(prioq_remove(d->earliest, s, &s->earliest_index) > 0);
                s->earliest_index = PRIOQ_IDX_NULL;
                return r;
        }
 
        d->needs_rearm = true;
        return 0;
}
 
_public_ int sd_event_add_time(
                sd_event *e,
                sd_event_source **ret,
                clockid_t clock,
                uint64_t usec,
                uint64_t accuracy,
                sd_event_time_handler_t callback,
                void *userdata) {
 
        EventSourceType type;
        _cleanup_(source_freep) sd_event_source *s = NULL;
        struct clock_data *d;
        int r;
 
        assert_return(e, -EINVAL);
        assert_return(e = event_resolve(e), -ENOPKG);
        assert_return(accuracy != UINT64_MAX, -EINVAL);
        assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
        assert_return(!event_origin_changed(e), -ECHILD);
 
        if (!clock_supported(clock)) /* Checks whether the kernel supports the clock */
                return -EOPNOTSUPP;
 
        type = clock_to_event_source_type(clock); /* checks whether sd-event supports this clock */
        if (type < 0)
                return -EOPNOTSUPP;
 
        if (!callback)
                callback = time_exit_callback;
 
        assert_se(d = event_get_clock_data(e, type));
 
        r = setup_clock_data(e, d, clock);
        if (r < 0)
                return r;
 
        s = source_new(e, !ret, type);
        if (!s)
                return -ENOMEM;
 
        s->time.next = usec;
        s->time.accuracy = accuracy == 0 ? EVENT_DEFAULT_ACCURACY_USEC : accuracy;
        s->time.callback = callback;
        s->earliest_index = s->latest_index = PRIOQ_IDX_NULL;
        s->userdata = userdata;
        s->enabled = SD_EVENT_ONESHOT;
 
        r = event_source_time_prioq_put(s, d);
        if (r < 0)
                return r;
 
        if (ret)
                *ret = s;
        TAKE_PTR(s);
 
        return 0;
}
 
_public_ int sd_event_add_time_relative(
                sd_event *e,
                sd_event_source **ret,
                clockid_t clock,
                uint64_t usec,
                uint64_t accuracy,
                sd_event_time_handler_t callback,
                void *userdata) {
 
        usec_t t;
        int r;
 
        /* Same as sd_event_add_time() but operates relative to the event loop's current point in time, and
         * checks for overflow. */
 
        r = sd_event_now(e, clock, &t);
        if (r < 0)
                return r;
 
        if (usec >= USEC_INFINITY - t)
                return -EOVERFLOW;
 
        return sd_event_add_time(e, ret, clock, t + usec, accuracy, callback, userdata);
}
 
static int signal_exit_callback(sd_event_source *s, const struct signalfd_siginfo *si, void *userdata) {
        assert(s);
 
        return sd_event_exit(sd_event_source_get_event(s), PTR_TO_INT(userdata));
}
 
_public_ int sd_event_add_signal(
                sd_event *e,
                sd_event_source **ret,
                int sig,
                sd_event_signal_handler_t callback,
                void *userdata) {
 
        _cleanup_(source_freep) sd_event_source *s = NULL;
        struct signal_data *d;
        sigset_t new_ss;
        bool block_it;
        int r;
 
        assert_return(e, -EINVAL);
        assert_return(e = event_resolve(e), -ENOPKG);
        assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
        assert_return(!event_origin_changed(e), -ECHILD);
 
        /* Let's make sure our special flag stays outside of the valid signal range */
        assert_cc(_NSIG < SD_EVENT_SIGNAL_PROCMASK);
 
        if (sig & SD_EVENT_SIGNAL_PROCMASK) {
                sig &= ~SD_EVENT_SIGNAL_PROCMASK;
                assert_return(SIGNAL_VALID(sig), -EINVAL);
 
                block_it = true;
        } else {
                assert_return(SIGNAL_VALID(sig), -EINVAL);
 
                r = signal_is_blocked(sig);
                if (r < 0)
                        return r;
                if (r == 0)
                        return -EBUSY;
 
                block_it = false;
        }
 
        if (!callback)
                callback = signal_exit_callback;
 
        if (!e->signal_sources) {
                e->signal_sources = new0(sd_event_source*, _NSIG);
                if (!e->signal_sources)
                        return -ENOMEM;
        } else if (e->signal_sources[sig])
                return -EBUSY;
 
        s = source_new(e, !ret, SOURCE_SIGNAL);
        if (!s)
                return -ENOMEM;
 
        s->signal.sig = sig;
        s->signal.callback = callback;
        s->userdata = userdata;
        s->enabled = SD_EVENT_ON;
 
        e->signal_sources[sig] = s;
 
        if (block_it) {
                sigset_t old_ss;
 
                if (sigemptyset(&new_ss) < 0)
                        return -errno;
 
                if (sigaddset(&new_ss, sig) < 0)
                        return -errno;
 
                r = pthread_sigmask(SIG_BLOCK, &new_ss, &old_ss);
                if (r != 0)
                        return -r;
 
                r = sigismember(&old_ss, sig);
                if (r < 0)
                        return -errno;
 
                s->signal.unblock = !r;
        } else
                s->signal.unblock = false;
 
        r = event_make_signal_data(e, sig, &d);
        if (r < 0) {
                if (s->signal.unblock)
                        (void) pthread_sigmask(SIG_UNBLOCK, &new_ss, NULL);
 
                return r;
        }
 
        /* Use the signal name as description for the event source by default */
        (void) sd_event_source_set_description(s, signal_to_string(sig));
 
        if (ret)
                *ret = s;
        TAKE_PTR(s);
 
        return 0;
}
 
static int child_exit_callback(sd_event_source *s, const siginfo_t *si, void *userdata) {
        assert(s);
 
        return sd_event_exit(sd_event_source_get_event(s), PTR_TO_INT(userdata));
}
 
static int verify_sigchld(int options) {
        int r;
 
        if ((options & (WSTOPPED|WCONTINUED)) != 0) {
                /* Caller must block SIGCHLD before using us to watch for WSTOPPED or WCONTINUED. */
 
                r = signal_is_blocked(SIGCHLD);
                if (r < 0)
                        return r;
                if (r == 0)
                        return -EBUSY;
        }
 
        /* We don't want the Linux autoreaping logic to take effect when we're watching for process exit, so
         * check if it is enabled. */
 
        if (options & WEXITED) {
                r = autoreaping_enabled();
                if (r < 0)
                        return r;
                if (r > 0)
                        return -EBUSY;
        }
 
        return 0;
}
 
_public_ int sd_event_add_child(
                sd_event *e,
                sd_event_source **ret,
                pid_t pid,
                int options,
                sd_event_child_handler_t callback,
                void *userdata) {
 
        _cleanup_(source_freep) sd_event_source *s = NULL;
        int r;
 
        assert_return(e, -EINVAL);
        assert_return(e = event_resolve(e), -ENOPKG);
        assert_return(pid > 1, -EINVAL);
        assert_return(!(options & ~(WEXITED|WSTOPPED|WCONTINUED|WNOWAIT)), -EINVAL);
        assert_return(options != 0, -EINVAL);
        assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
        assert_return(!event_origin_changed(e), -ECHILD);
 
        if (!callback)
                callback = child_exit_callback;
 
        r = verify_sigchld(options);
        if (r < 0)
                return r;
 
        r = hashmap_ensure_allocated(&e->child_sources, NULL);
        if (r < 0)
                return r;
 
        if (hashmap_contains(e->child_sources, PID_TO_PTR(pid)))
                return -EBUSY;
 
        s = source_new(e, !ret, SOURCE_CHILD);
        if (!s)
                return -ENOMEM;
 
        /* We always take a pidfd here, even if we wait for anything else than WEXITED, so that we pin the
         * PID, and make regular waitid() handling race-free. */
 
        s->child.pidfd = pidfd_open(pid, 0);
        if (s->child.pidfd < 0)
                return -errno;
 
        s->child.pidfd_owned = true; /* If we allocate the pidfd we own it by default */
 
        s->wakeup = WAKEUP_EVENT_SOURCE;
        s->child.options = options;
        s->child.callback = callback;
        s->userdata = userdata;
        s->enabled = SD_EVENT_ONESHOT;
 
        if (EVENT_SOURCE_WATCH_PIDFD(s)) {
                /* We only want to watch for exit */
                r = source_child_pidfd_register(s, s->enabled);
                if (r < 0)
                        return r;
 
        } else {
                /* We shall wait for some other event than WEXITED */
                r = event_make_signal_data(e, SIGCHLD, NULL);
                if (r < 0)
                        return r;
 
                e->need_process_child = true;
        }
 
        r = hashmap_put(e->child_sources, PID_TO_PTR(pid), s);
        if (r < 0)
                return r;
 
        /* These must be done after everything succeeds. */
        s->child.pid = pid;
        e->n_online_child_sources++;
 
        if (ret)
                *ret = s;
        TAKE_PTR(s);
        return 0;
}
 
_public_ int sd_event_add_child_pidfd(
                sd_event *e,
                sd_event_source **ret,
                int pidfd,
                int options,
                sd_event_child_handler_t callback,
                void *userdata) {
 
        _cleanup_(source_freep) sd_event_source *s = NULL;
        pid_t pid;
        int r;
 
        assert_return(e, -EINVAL);
        assert_return(e = event_resolve(e), -ENOPKG);
        assert_return(pidfd >= 0, -EBADF);
        assert_return(!(options & ~(WEXITED|WSTOPPED|WCONTINUED|WNOWAIT)), -EINVAL);
        assert_return(options != 0, -EINVAL);
        assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
        assert_return(!event_origin_changed(e), -ECHILD);
 
        if (!callback)
                callback = child_exit_callback;
 
        r = verify_sigchld(options);
        if (r < 0)
                return r;
 
        r = hashmap_ensure_allocated(&e->child_sources, NULL);
        if (r < 0)
                return r;
 
        r = pidfd_get_pid(pidfd, &pid);
        if (r < 0)
                return r;
 
        if (hashmap_contains(e->child_sources, PID_TO_PTR(pid)))
                return -EBUSY;
 
        s = source_new(e, !ret, SOURCE_CHILD);
        if (!s)
                return -ENOMEM;
 
        s->wakeup = WAKEUP_EVENT_SOURCE;
        s->child.pidfd = pidfd;
        s->child.options = options;
        s->child.callback = callback;
        s->child.pidfd_owned = false; /* If we got the pidfd passed in we don't own it by default (similar to the IO fd case) */
        s->userdata = userdata;
        s->enabled = SD_EVENT_ONESHOT;
 
        if (EVENT_SOURCE_WATCH_PIDFD(s)) {
                /* We only want to watch for WEXITED */
                r = source_child_pidfd_register(s, s->enabled);
                if (r < 0)
                        return r;
        } else {
                /* We shall wait for some other event than WEXITED */
                r = event_make_signal_data(e, SIGCHLD, NULL);
                if (r < 0)
                        return r;
 
                e->need_process_child = true;
        }
 
        r = hashmap_put(e->child_sources, PID_TO_PTR(pid), s);
        if (r < 0)
                return r;
 
        s->child.pid = pid;
        e->n_online_child_sources++;
 
        if (ret)
                *ret = s;
        TAKE_PTR(s);
        return 0;
}
 
static int generic_exit_callback(sd_event_source *s, void *userdata) {
        assert(s);
 
        return sd_event_exit(sd_event_source_get_event(s), PTR_TO_INT(userdata));
}
 
_public_ int sd_event_add_defer(
                sd_event *e,
                sd_event_source **ret,
                sd_event_handler_t callback,
                void *userdata) {
 
        _cleanup_(source_freep) sd_event_source *s = NULL;
        int r;
 
        assert_return(e, -EINVAL);
        assert_return(e = event_resolve(e), -ENOPKG);
        assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
        assert_return(!event_origin_changed(e), -ECHILD);
 
        if (!callback)
                callback = generic_exit_callback;
 
        s = source_new(e, !ret, SOURCE_DEFER);
        if (!s)
                return -ENOMEM;
 
        s->defer.callback = callback;
        s->userdata = userdata;
        s->enabled = SD_EVENT_ONESHOT;
 
        r = source_set_pending(s, true);
        if (r < 0)
                return r;
 
        if (ret)
                *ret = s;
        TAKE_PTR(s);
 
        return 0;
}
 
_public_ int sd_event_add_post(
                sd_event *e,
                sd_event_source **ret,
                sd_event_handler_t callback,
                void *userdata) {
 
        _cleanup_(source_freep) sd_event_source *s = NULL;
        int r;
 
        assert_return(e, -EINVAL);
        assert_return(e = event_resolve(e), -ENOPKG);
        assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
        assert_return(!event_origin_changed(e), -ECHILD);
 
        if (!callback)
                callback = generic_exit_callback;
 
        s = source_new(e, !ret, SOURCE_POST);
        if (!s)
                return -ENOMEM;
 
        s->post.callback = callback;
        s->userdata = userdata;
        s->enabled = SD_EVENT_ON;
 
        r = set_ensure_put(&e->post_sources, NULL, s);
        if (r < 0)
                return r;
        assert(r > 0);
 
        if (ret)
                *ret = s;
        TAKE_PTR(s);
 
        return 0;
}
 
_public_ int sd_event_add_exit(
                sd_event *e,
                sd_event_source **ret,
                sd_event_handler_t callback,
                void *userdata) {
 
        _cleanup_(source_freep) sd_event_source *s = NULL;
        int r;
 
        assert_return(e, -EINVAL);
        assert_return(e = event_resolve(e), -ENOPKG);
        assert_return(callback, -EINVAL);
        assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
        assert_return(!event_origin_changed(e), -ECHILD);
 
        r = prioq_ensure_allocated(&e->exit, exit_prioq_compare);
        if (r < 0)
                return r;
 
        s = source_new(e, !ret, SOURCE_EXIT);
        if (!s)
                return -ENOMEM;
 
        s->exit.callback = callback;
        s->userdata = userdata;
        s->exit.prioq_index = PRIOQ_IDX_NULL;
        s->enabled = SD_EVENT_ONESHOT;
 
        r = prioq_put(s->event->exit, s, &s->exit.prioq_index);
        if (r < 0)
                return r;
 
        if (ret)
                *ret = s;
        TAKE_PTR(s);
 
        return 0;
}
 
_public_ int sd_event_trim_memory(void) {
        int r;
 
        /* A default implementation of a memory pressure callback. Simply releases our own allocation caches
         * and glibc's. This is automatically used when people call sd_event_add_memory_pressure() with a
         * NULL callback parameter. */
 
        log_debug("Memory pressure event, trimming malloc() memory.");
 
        struct mallinfo2 before_mallinfo = mallinfo2();
 
        usec_t before_timestamp = now(CLOCK_MONOTONIC);
        hashmap_trim_pools();
        r = malloc_trim(0);
        usec_t after_timestamp = now(CLOCK_MONOTONIC);
 
        if (r > 0)
                log_debug("Successfully trimmed some memory.");
        else
                log_debug("Couldn't trim any memory.");
 
        usec_t period = after_timestamp - before_timestamp;
 
        struct mallinfo2 after_mallinfo = mallinfo2();
        size_t l = LESS_BY(before_mallinfo.hblkhd, after_mallinfo.hblkhd) +
                LESS_BY(before_mallinfo.arena, after_mallinfo.arena);
        log_struct(LOG_DEBUG,
                   LOG_MESSAGE("Memory trimming took %s, returned %s to OS.",
                               FORMAT_TIMESPAN(period, 0),
                               FORMAT_BYTES(l)),
                   LOG_MESSAGE_ID(SD_MESSAGE_MEMORY_TRIM_STR),
                   LOG_ITEM("TRIMMED_BYTES=%zu", l),
                   LOG_ITEM("TRIMMED_USEC=" USEC_FMT, period));
 
        return 0;
}
 
static int memory_pressure_callback(sd_event_source *s, void *userdata) {
        assert(s);
 
        sd_event_trim_memory();
        return 0;
}
 
static int event_add_pressure(
                sd_event *e,
                sd_event_source **ret,
                sd_event_handler_t callback,
                void *userdata,
                EventSourceType type,
                sd_event_handler_t default_callback,
                PressureResource resource) {
 
        _cleanup_free_ char *w = NULL;
        _cleanup_(source_freep) sd_event_source *s = NULL;
        _cleanup_close_ int path_fd = -EBADF, fd = -EBADF;
        _cleanup_free_ void *write_buffer = NULL;
        _cleanup_free_ char *watch_fallback = NULL;
        const char *watch, *env;
        size_t write_buffer_size = 0;
        struct stat st;
        uint32_t events;
        bool locked;
        int r;
 
        assert_return(e, -EINVAL);
        assert_return(e = event_resolve(e), -ENOPKG);
        assert_return(e->state != SD_EVENT_FINISHED, -ESTALE);
        assert_return(!event_origin_changed(e), -ECHILD);
 
        const PressureResourceInfo *info = pressure_resource_get_info(resource);
 
        if (!callback)
                callback = default_callback;
 
        s = source_new(e, !ret, type);
        if (!s)
                return -ENOMEM;
 
        s->wakeup = WAKEUP_EVENT_SOURCE;
        s->pressure.callback = callback;
        s->userdata = userdata;
        s->enabled = SD_EVENT_ON;
        s->pressure.fd = -EBADF;
 
        env = secure_getenv(info->env_watch);
        if (env) {
                if (isempty(env) || path_equal(env, "/dev/null"))
                        return log_debug_errno(SYNTHETIC_ERRNO(EHOSTDOWN),
                                               "Pressure logic is explicitly disabled via $%s.", info->env_watch);
 
                if (!path_is_absolute(env) || !path_is_normalized(env))
                        return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG),
                                               "$%s set to invalid path: %s", info->env_watch, env);
 
                watch = env;
 
                env = secure_getenv(info->env_write);
                if (env) {
                        r = unbase64mem(env, &write_buffer, &write_buffer_size);
                        if (r < 0)
                                return r;
                }
 
                locked = true;
        } else {
 
                r = is_pressure_supported();
                if (r < 0)
                        return r;
                if (r == 0)
                        return -EOPNOTSUPP;
 
                /* By default we want to watch pressure on the local cgroup, but we'll fall back on
                 * the system wide pressure if for some reason we cannot (which could be: controller
                 * not delegated to us, or PSI simply not available in the kernel). */