/* SPDX-License-Identifier: BSD-2-Clause */ /* * Copyright (C) 2019, Raspberry Pi (Trading) Limited * * pwl.cpp - piecewise linear functions */ #include #include #include "pwl.hpp" using namespace RPiController; void Pwl::Read(boost::property_tree::ptree const ¶ms) { for (auto it = params.begin(); it != params.end(); it++) { double x = it->second.get_value(); assert(it == params.begin() || x > points_.back().x); it++; double y = it->second.get_value(); points_.push_back(Point(x, y)); } assert(points_.size() >= 2); } void Pwl::Append(double x, double y, const double eps) { if (points_.empty() || points_.back().x + eps < x) points_.push_back(Point(x, y)); } void Pwl::Prepend(double x, double y, const double eps) { if (points_.empty() || points_.front().x - eps > x) points_.insert(points_.begin(), Point(x, y)); } Pwl::Interval Pwl::Domain() const { return Interval(points_[0].x, points_[points_.size() - 1].x); } Pwl::Interval Pwl::Range() const { double lo = points_[0].y, hi = lo; for (auto &p : points_) lo = std::min(lo, p.y), hi = std::max(hi, p.y); return Interval(lo, hi); } bool Pwl::Empty() const { return points_.empty(); } double Pwl::Eval(double x, int *span_ptr, bool update_span) const { int span = findSpan(x, span_ptr && *span_ptr != -1 ? *span_ptr : points_.size() / 2 - 1); if (span_ptr && update_span) *span_ptr = span; return points_[span].y + (x - points_[span].x) * (points_[span + 1].y - points_[span].y) / (points_[span + 1].x - points_[span].x); } int Pwl::findSpan(double x, int span) const { // Pwls are generally small, so linear search may well be faster than // binary, though could review this if large PWls start turning up. int last_span = points_.size() - 2; // some algorithms may call us with span pointing directly at the last // control point span = std::max(0, std::min(last_span, span)); while (span < last_span && x >= points_[span + 1].x) span++; while (span && x < points_[span].x) span--; return span; } Pwl::PerpType Pwl::Invert(Point const &xy, Point &perp, int &span, const double eps) const { assert(span >= -1); bool prev_off_end = false; for (span = span + 1; span < (int)points_.size() - 1; span++) { Point span_vec = points_[span + 1] - points_[span]; double t = ((xy - points_[span]) % span_vec) / span_vec.Len2(); if (t < -eps) // off the start of this span { if (span == 0) { perp = points_[span]; return PerpType::Start; } else if (prev_off_end) { perp = points_[span]; return PerpType::Vertex; } } else if (t > 1 + eps) // off the end of this span { if (span == (int)points_.size() - 2) { perp = points_[span + 1]; return PerpType::End; } prev_off_end = true; } else // a true perpendicular { perp = points_[span] + span_vec * t; return PerpType::Perpendicular; } } return PerpType::None; } Pwl Pwl::Inverse(bool *true_inverse, const double eps) const { bool appended = false, prepended = false, neither = false; Pwl inverse; for (Point const &p : points_) { if (inverse.Empty()) inverse.Append(p.y, p.x, eps); else if (std::abs(inverse.points_.back().x - p.y) <= eps || std::abs(inverse.points_.front().x - p.y) <= eps) /* do nothing */; else if (p.y > inverse.points_.back().x) { inverse.Append(p.y, p.x, eps); appended = true; } else if (p.y < inverse.points_.front().x) { inverse.Prepend(p.y, p.x, eps); prepended = true; } else neither = true; } // This is not a proper inverse if we found ourselves putting points // onto both ends of the inverse, or if there were points that couldn't // go on either. if (true_inverse) *true_inverse = !(neither || (appended && prepended)); return inverse; } Pwl Pwl::Compose(Pwl const &other, const double eps) const { double this_x = points_[0].x, this_y = points_[0].y; int this_span = 0, other_span = other.findSpan(this_y, 0); Pwl result({ { this_x, other.Eval(this_y, &other_span, false) } }); while (this_span != (int)points_.size() - 1) { double dx = points_[this_span + 1].x - points_[this_span].x, dy = points_[this_span + 1].y - points_[this_span].y; if (abs(dy) > eps && other_span + 1 < (int)other.points_.size() && points_[this_span + 1].y >= other.points_[other_span + 1].x + eps) { // next control point in result will be where this // function's y reaches the next span in other this_x = points_[this_span].x + (other.points_[other_span + 1].x - points_[this_span].y) * dx / dy; this_y = other.points_[++other_span].x; } else if (abs(dy) > eps && other_span > 0 && points_[this_span + 1].y <= other.points_[other_span - 1].x - eps) { // next control point in result will be where this // function's y reaches the previous span in other this_x = points_[this_span].x + (other.points_[other_span + 1].x - points_[this_span].y) * dx / dy; this_y = other.points_[--other_span].x; } else { // we stay in the same span in other this_span++; this_x = points_[this_span].x, this_y = points_[this_span].y; } result.Append(this_x, other.Eval(this_y, &other_span, false), eps); } return result; } void Pwl::Map(std::function f) const { for (auto &pt : points_) f(pt.x, pt.y); } void Pwl::Map2(Pwl const &pwl0, Pwl const &pwl1, std::function f) { int span0 = 0, span1 = 0; double x = std::min(pwl0.points_[0].x, pwl1.points_[0].x); f(x, pwl0.Eval(x, &span0, false), pwl1.Eval(x, &span1, false)); while (span0 < (int)pwl0.points_.size() - 1 || span1 < (int)pwl1.points_.size() - 1) { if (span0 == (int)pwl0.points_.size() - 1) x = pwl1.points_[++span1].x; else if (span1 == (int)pwl1.points_.size() - 1) x = pwl0.points_[++span0].x; else if (pwl0.points_[span0 + 1].x > pwl1.points_[span1 + 1].x) x = pwl1.points_[++span1].x; else x = pwl0.points_[++span0].x; f(x, pwl0.Eval(x, &span0, false), pwl1.Eval(x, &span1, false)); } } Pwl Pwl::Combine(Pwl const &pwl0, Pwl const &pwl1, std::function f, const double eps) { Pwl result; Map2(pwl0, pwl1, [&](double x, double y0, double y1) { result.Append(x, f(x, y0, y1), eps); }); return result; } void Pwl::MatchDomain(Interval const &domain, bool clip, const double eps) { int span = 0; Prepend(domain.start, Eval(clip ? points_[0].x : domain.start, &span), eps); span = points_.size() - 2; Append(domain.end, Eval(clip ? points_.back().x : domain.end, &span), eps); } Pwl &Pwl::operator*=(double d) { for (auto &pt : points_) pt.y *= d; return *this; } void Pwl::Debug(FILE *fp) const { fprintf(fp, "Pwl {\n"); for (auto &p : points_) fprintf(fp, "\t(%g, %g)\n", p.x, p.y); fprintf(fp, "}\n"); } '#n52'>52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
/* SPDX-License-Identifier: LGPL-2.1-or-later */
/*
 * Copyright (C) 2019, Google Inc.
 *
 * event_dispatcher_poll.cpp - Poll-based event dispatcher
 */

#include "libcamera/internal/event_dispatcher_poll.h"

#include <algorithm>
#include <chrono>
#include <iomanip>
#include <poll.h>
#include <stdint.h>
#include <string.h>
#include <sys/eventfd.h>
#include <unistd.h>

#include "libcamera/internal/event_notifier.h"
#include "libcamera/internal/log.h"
#include "libcamera/internal/thread.h"
#include "libcamera/internal/timer.h"
#include "libcamera/internal/utils.h"

/**
 * \file event_dispatcher_poll.h
 */

namespace libcamera {

LOG_DECLARE_CATEGORY(Event)

static const char *notifierType(EventNotifier::Type type)
{
	if (type == EventNotifier::Read)
		return "read";
	if (type == EventNotifier::Write)
		return "write";
	if (type == EventNotifier::Exception)
		return "exception";

	return "";
}

/**
 * \class EventDispatcherPoll
 * \brief A poll-based event dispatcher
 */

EventDispatcherPoll::EventDispatcherPoll()
	: processingEvents_(false)
{
	/*
	 * Create the event fd. Failures are fatal as we can't implement an
	 * interruptible dispatcher without the fd.
	 */
	eventfd_ = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
	if (eventfd_ < 0)
		LOG(Event, Fatal) << "Unable to create eventfd";
}

EventDispatcherPoll::~EventDispatcherPoll()
{
	close(eventfd_);
}

void EventDispatcherPoll::registerEventNotifier(EventNotifier *notifier)
{
	EventNotifierSetPoll &set = notifiers_[notifier->fd()];
	EventNotifier::Type type = notifier->type();

	if (set.notifiers[type] && set.notifiers[type] != notifier) {
		LOG(Event, Warning)
			<< "Ignoring duplicate " << notifierType(type)
			<< " notifier for fd " << notifier->fd();
		return;
	}

	set.notifiers[type] = notifier;
}

void EventDispatcherPoll::unregisterEventNotifier(EventNotifier *notifier)
{
	auto iter = notifiers_.find(notifier->fd());
	if (iter == notifiers_.end())
		return;

	EventNotifierSetPoll &set = iter->second;
	EventNotifier::Type type = notifier->type();

	if (!set.notifiers[type])
		return;

	if (set.notifiers[type] != notifier) {
		LOG(Event, Warning)
			<< notifierType(type) << " notifier for fd "
			<< notifier->fd() << " is not registered";
		return;
	}

	set.notifiers[type] = nullptr;

	/*
	 * Don't race with event processing if this method is called from an
	 * event notifier. The notifiers_ entry will be erased by
	 * processEvents().
	 */
	if (processingEvents_)
		return;

	if (!set.notifiers[0] && !set.notifiers[1] && !set.notifiers[2])
		notifiers_.erase(iter);
}

void EventDispatcherPoll::registerTimer(Timer *timer)
{
	for (auto iter = timers_.begin(); iter != timers_.end(); ++iter) {
		if ((*iter)->deadline() > timer->deadline()) {
			timers_.insert(iter, timer);
			return;
		}
	}

	timers_.push_back(timer);
}

void EventDispatcherPoll::unregisterTimer(Timer *timer)
{
	for (auto iter = timers_.begin(); iter != timers_.end(); ++iter) {
		if (*iter == timer) {
			timers_.erase(iter);
			return;
		}

		/*
		 * As the timers list is ordered, we can stop as soon as we go
		 * past the deadline.
		 */
		if ((*iter)->deadline() > timer->deadline())
			break;
	}
}

void EventDispatcherPoll::processEvents()
{
	int ret;

	Thread::current()->dispatchMessages();

	/* Create the pollfd array. */
	std::vector<struct pollfd> pollfds;
	pollfds.reserve(notifiers_.size() + 1);

	for (auto notifier : notifiers_)
		pollfds.push_back({ notifier.first, notifier.second.events(), 0 });

	pollfds.push_back({ eventfd_, POLLIN, 0 });

	/* Wait for events and process notifiers and timers. */
	do {
		ret = poll(&pollfds);
	} while (ret == -1 && errno == EINTR);

	if (ret < 0) {
		ret = -errno;
		LOG(Event, Warning) << "poll() failed with " << strerror(-ret);
	} else if (ret > 0) {
		processInterrupt(pollfds.back());
		pollfds.pop_back();
		processNotifiers(pollfds);
	}

	processTimers();
}

void EventDispatcherPoll::interrupt()
{
	uint64_t value = 1;
	ssize_t ret = write(eventfd_, &value, sizeof(value));
	if (ret != sizeof(value)) {
		if (ret < 0)
			ret = -errno;
		LOG(Event, Error)
			<< "Failed to interrupt event dispatcher ("
			<< ret << ")";
	}
}

short EventDispatcherPoll::EventNotifierSetPoll::events() const
{
	short events = 0;

	if (notifiers[EventNotifier::Read])
		events |= POLLIN;
	if (notifiers[EventNotifier::Write])
		events |= POLLOUT;
	if (notifiers[EventNotifier::Exception])
		events |= POLLPRI;

	return events;
}

int EventDispatcherPoll::poll(std::vector<struct pollfd> *pollfds)
{
	/* Compute the timeout. */
	Timer *nextTimer = !timers_.empty() ? timers_.front() : nullptr;
	struct timespec timeout;

	if (nextTimer) {
		utils::time_point now = utils::clock::now();

		if (nextTimer->deadline() > now)
			timeout = utils::duration_to_timespec(nextTimer->deadline() - now);
		else
			timeout = { 0, 0 };

		LOG(Event, Debug)
			<< "timeout " << timeout.tv_sec << "."
			<< std::setfill('0') << std::setw(9)
			<< timeout.tv_nsec;
	}

	return ppoll(pollfds->data(), pollfds->size(),
		     nextTimer ? &timeout : nullptr, nullptr);
}

void EventDispatcherPoll::processInterrupt(const struct pollfd &pfd)
{
	if (!(pfd.revents & POLLIN))
		return;

	uint64_t value;
	ssize_t ret = read(eventfd_, &value, sizeof(value));
	if (ret != sizeof(value)) {
		if (ret < 0)
			ret = -errno;
		LOG(Event, Error)
			<< "Failed to process interrupt (" << ret << ")";
	}
}

void EventDispatcherPoll::processNotifiers(const std::vector<struct pollfd> &pollfds)
{
	static const struct {
		EventNotifier::Type type;
		short events;
	} events[] = {
		{ EventNotifier::Read, POLLIN },
		{ EventNotifier::Write, POLLOUT },
		{ EventNotifier::Exception, POLLPRI },
	};

	processingEvents_ = true;

	for (const pollfd &pfd : pollfds) {
		auto iter = notifiers_.find(pfd.fd);
		ASSERT(iter != notifiers_.end());

		EventNotifierSetPoll &set = iter->second;

		for (const auto &event : events) {
			EventNotifier *notifier = set.notifiers[event.type];

			if (!notifier)
				continue;

			/*
			 * If the file descriptor is invalid, disable the
			 * notifier immediately.
			 */
			if (pfd.revents & POLLNVAL) {
				LOG(Event, Warning)
					<< "Disabling " << notifierType(event.type)
					<< " due to invalid file descriptor "
					<< pfd.fd;
				unregisterEventNotifier(notifier);
				continue;
			}

			if (pfd.revents & event.events)
				notifier->activated.emit(notifier);
		}

		/* Erase the notifiers_ entry if it is now empty. */
		if (!set.notifiers[0] && !set.notifiers[1] && !set.notifiers[2])