diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml
index c5b625ee988..42243e574c1 100644
--- a/.github/workflows/linux.yml
+++ b/.github/workflows/linux.yml
@@ -105,6 +105,20 @@ jobs:
TEST_PYTEST=1
TEST_MD=1
# -------------------------------------------------------------------------
+ # The classic pytest suite against the motorz MPM (the other suites
+ # assume event), plus the restart tests: MPM= selects it for those.
+ - name: Python pytest_suite, motorz MPM
+ config: --enable-mods-shared=reallyall --with-mpm=motorz --enable-mpms-shared=all
+ pkgs: nghttp2-client
+ env: |
+ APR_VERSION=1.7.6
+ APU_VERSION=1.6.5
+ APU_CONFIG="--with-crypto"
+ NO_TEST_FRAMEWORK=1
+ TEST_PYTEST=1
+ MPM=motorz
+ PYTEST_ARGS=test_build.py pytest_suite/tests modules/core/test_008_restart.py
+ # -------------------------------------------------------------------------
- name: Default
# -------------------------------------------------------------------------
- name: All-static modules
diff --git a/build/rpm/httpd.spec.in b/build/rpm/httpd.spec.in
index c85881d4845..873207449d2 100644
--- a/build/rpm/httpd.spec.in
+++ b/build/rpm/httpd.spec.in
@@ -360,6 +360,7 @@ rm -rf $RPM_BUILD_ROOT
%{_libdir}/httpd/modules/mod_mime_magic.so
%{_libdir}/httpd/modules/mod_mime.so
%{_libdir}/httpd/modules/mod_mpm_event.so
+%{_libdir}/httpd/modules/mod_mpm_motorz.so
%{_libdir}/httpd/modules/mod_mpm_prefork.so
%{_libdir}/httpd/modules/mod_mpm_worker.so
%{_libdir}/httpd/modules/mod_negotiation.so
diff --git a/changes-entries/mpm_motorz.txt b/changes-entries/mpm_motorz.txt
new file mode 100644
index 00000000000..f94ed79da99
--- /dev/null
+++ b/changes-entries/mpm_motorz.txt
@@ -0,0 +1,3 @@
+ *) mpm_motorz: Add the MotorZ MPM, an event-driven MPM with multi-poller
+ scale-out (new PollersPerChild directive), asynchronous keep-alive and
+ HTTP/2 handling, and graceful drain of connections. [Jim Jagielski]
diff --git a/docs/manual/convenience.map b/docs/manual/convenience.map
index b64c90a8b84..3be6f1427a2 100644
--- a/docs/manual/convenience.map
+++ b/docs/manual/convenience.map
@@ -464,6 +464,7 @@ order mod/mod_access_compat.html#order
outputsed mod/mod_sed.html#outputsed
passenv mod/mod_env.html#passenv
pidfile mod/mpm_common.html#pidfile
+pollersperchild mod/motorz.html#pollersperchild
privilegesmode mod/mod_privileges.html#privilegesmode
protocol mod/core.html#protocol
protocolecho mod/mod_echo.html#protocolecho
diff --git a/docs/manual/mod/allmodules.xml b/docs/manual/mod/allmodules.xml
index 8fdd483eaa5..e7a5517191d 100644
--- a/docs/manual/mod/allmodules.xml
+++ b/docs/manual/mod/allmodules.xml
@@ -129,6 +129,7 @@
mod_xml2enc.xmlmpm_common.xmlevent.xml
+ motorz.xmlmpm_netware.xmlmpmt_os2.xmlprefork.xml
diff --git a/docs/manual/mod/motorz.xml b/docs/manual/mod/motorz.xml
new file mode 100644
index 00000000000..fb1b29f1d04
--- /dev/null
+++ b/docs/manual/mod/motorz.xml
@@ -0,0 +1,375 @@
+
+
+
+
+
+
+
+
+motorz
+A lean, fast, self-contained event-driven Multi-Processing Module
+built on the APR pollset and thread pool especially suited as a reverse proxy
+MPM
+motorz.c
+mpm_motorz_module
+Available in version 2.4.71 and later
+
+
+
The motorz Multi-Processing Module (MPM) is an
+ asynchronous, event-driven implementation. It combines a
+ prefork-style fixed pool of child processes with an event core built on
+ APR's pollset and a shared thread pool. Each child
+ runs one or more dedicated poller threads that watch sockets
+ and timers, dispatching ready I/O events and expired timers to a pool of
+ worker threads. The workers never poll; they only process the
+ connection/request work pushed to them.
+
+
The design goal is a fast, efficient, single, compact MPM that runs on modern
+ Unix platforms by leaning on APR as much as possible, while still supporting
+ the asynchronous connection handling needed for efficient keep-alive and
+ HTTP/2.
+
+
To use the motorz MPM, add
+ --with-mpm=motorz to the configure
+ script's arguments when building the httpd, or build
+ it as a loadable module with
+ --enable-mpms-shared=motorz.
+
+
+
When built as a DSO module, it can be loaded with:
motorz uses prefork as the framework for process
+ management and an event core for connection handling. A single control
+ process (the parent) launches a fixed number of child processes, as set
+ by the StartServers directive.
+ Unlike worker and event, the number of
+ children does not float with load: motorz maintains a
+ static pool, replacing children one-for-one as they exit. Concurrency
+ within a host is scaled by adding worker threads
+ (ThreadsPerChild) and, where
+ the poll/dispatch path is the bottleneck, poller threads
+ (PollersPerChild), rather than by spawning more
+ processes.
+
+
Each child process runs:
+
+
One or more poller threads. Each poller owns its
+ own pollset, timer ring (with a guarding mutex) and lock-free
+ transaction-pool recycle list, so pollers never contend with one
+ another. A poller polls, dispatches ready I/O events and expired
+ timers to the worker pool, and (for the poller that owns the listening
+ sockets) accepts new connections. The number of pollers is controlled
+ by PollersPerChild.
+
+
A shared pool of worker threads
+ (ThreadsPerChild) that run
+ the actual connection and request processing pushed to them. Workers
+ never poll.
+
+
A supervisor (the child's main thread) that
+ watches MaxConnectionsPerChild
+ and the pipe-of-death / generation, signals the pollers to wind down,
+ and then joins them on exit.
+
+
+
A connection is sharded to one poller at accept time (round-robin) and
+ bound to it for its whole lifetime: it re-arms in, and times out on, that
+ poller's pollset and timer ring. Using multiple pollers lifts the
+ single-poll-thread throughput ceiling, so event dispatch and timer expiry
+ scale with PollersPerChild instead of being
+ serialized on one thread. New connections are accepted by the first
+ poller.
+
+
While the parent process is usually started as root under
+ Unix in order to bind to port 80, the child processes and threads are
+ launched by the server as a less-privileged user. The
+ User and
+ Group directives are used to set
+ the privileges of the Apache HTTP Server child processes. The child
+ processes must be able to read all the content that will be served, but
+ should have as few privileges beyond that as possible.
+
+
MaxConnectionsPerChild
+ controls how frequently the server recycles processes by retiring old ones
+ and launching new ones.
+
+
+Asynchronous connection handling
+
motorz reports itself as an asynchronous MPM. When a
+ worker finishes the active phase of a connection (for example, an
+ HTTP keep-alive connection between requests, or a connection waiting on
+ further I/O), it hands the socket back to its poller rather than holding a
+ worker thread idle. The poller waits for the next event on that socket,
+ bounded by the configured Timeout,
+ and re-dispatches the connection to a worker only when there is work to do.
+ This frees worker threads from idle keep-alive connections and is what
+ allows efficient HTTP/2 handling, where the master connection is handed
+ back to the MPM between requests.
+
+
Lingering close is also non-blocking: instead of blocking a worker for
+ the duration of the lingering-close timeout, the draining socket is handed
+ back to the poll loop with a bounded linger timeout, so the worker is
+ returned to the pool immediately.
+
+
Modules that take a connection fully asynchronous by suspending it are
+ supported; the connection is then owned by the module, which drives it
+ itself, as with the event MPM. As in that MPM, a module
+ that registers for the suspend_connection and
+ resume_connection hooks is told on the worker thread that parks
+ a connection (between requests, or while it waits for I/O or for output to
+ drain) and again on the worker thread that continues it, which need not be
+ the same thread. The generic timed callback of the MPM interface
+ (ap_mpm_register_timed_callback()) is not provided: it returns
+ APR_ENOTIMPL, and a module has to cope with that.
+
+
+Graceful stop and restart
+
When a child is asked to stop gracefully (a graceful restart or stop,
+ or reaching MaxConnectionsPerChild)
+ it stops accepting connections, closes idle keep-alive connections, and
+ lets all other connections, including responses still being written,
+ finish before it exits. A previous generation therefore keeps its process
+ slots until its connections are done, which is why
+ ServerLimit must leave room for
+ both generations. GracefulShutdownTimeout
+ bounds how long the parent waits on a graceful stop.
+
+
If every slot is taken by a draining child, the parent cannot start a
+ replacement, and while it has no child of the current generation nothing
+ accepts new connections: they wait until a draining child exits. This
+ needs connections that outlast several restarts in a row, such as long
+ downloads. The parent logs "scoreboard is full" when it happens; raise
+ ServerLimit.
+
+
A child does not enforce a deadline of its own while it drains. A
+ connection that is still writing a response, or is waiting on I/O for a
+ module that handles it asynchronously, is given until it completes or the
+ configured Timeout expires, so a
+ graceful restart can take as long as the longest such connection.
+
+
+Scoreboard and mod_status
+
A connection is not bound to a thread, so the scoreboard's per-thread
+ slots represent the worker threads. A worker reports the connection it is
+ processing through its slot and sets the slot back to ready when it is done
+ with it; a connection parked in a poller (keep-alive, write completion,
+ lingering close, waiting on I/O) does not occupy a slot. The busy and idle
+ worker counts in mod_status therefore reflect the worker
+ threads, as they do for the other threaded MPMs.
+
+
+Platforms and limitations
+
motorz runs on Unix-like platforms whose APR supports
+ threads and which can use a thread-safe pollset (kqueue, event ports or
+ epoll). It is not available on Windows, NetWare or OS/2.
+
+
The ThreadStackSize
+ directive is ignored (a warning is logged): the worker threads come from
+ an APR thread pool, which does not allow their stack size to be set.
+
There is no accept mutex. The listening sockets are non-blocking and
+ polled, so the poller that owns them in every child process wakes for
+ each new connection. A Mutex accept setting is accepted but
+ has no effect.
+
There are no
+ MinSpareThreads,
+ MaxSpareThreads or
+ MaxRequestWorkers controls,
+ as described above.
+
+
+
+Admission control
+
To keep a child safe under overload, motorz applies
+ listener backpressure. The poller that owns the listening sockets removes
+ them from its pollset and stops accepting, and re-adds them once there is
+ room again, in two situations:
+
+
the worker pool is saturated, judged from its idle, pending and
+ active thread counts, with hysteresis to avoid flapping the
+ listeners on and off;
+
the child holds as many connections as
+ AsyncRequestWorkerFactor allows. Connections
+ that are idle in keep-alive, waiting for I/O or writing a response
+ use no worker thread, so the worker pool alone cannot limit
+ them.
+
+
Connections that are not accepted wait in the listen backlog (see
+ ListenBacklog). Other memory use,
+ such as a large request being read, is not limited by this.
+
+ ThreadsPerChild and admission control
+
Because the admission-control low-water mark is a fraction of
+ ThreadsPerChild, very small
+ values (in particular ThreadsPerChild 1) cause the listeners
+ to re-enable only when the work queue is completely empty, which severely
+ degrades throughput. A value of ThreadsPerChild of at least 4
+ is strongly recommended; the server logs a warning for a value of 1.
+
+
+
+Relationship to other MPMs
+
motorz uses prefork for process management and an APR
+ thread pool for workers, with pollers dispatching work to that pool. This
+ is distinct from event's listener/worker/fdqueue design,
+ in which the worker threads themselves re-arm a shared, thread-safe
+ pollset.
+
+
Whether additional pollers help depends on the workload. If the worker
+ threads are the CPU bottleneck—typical for real request
+ processing—the poller threads are not the limiting factor, and a
+ PollersPerChild beyond one or two yields little. The
+ multiple-poller design removes motorz's
+ structural single-thread ceiling, but per-host throughput is still
+ governed by worker CPU.
+
+ No dynamic process scaling
+
Unlike worker and event,
+ motorz does not scale the number of child processes with
+ load. The process pool is fixed at
+ StartServers.
+ ServerLimit only bounds the
+ number of process slots, including those held by old children that are
+ still finishing connections after a graceful restart; it defaults to the
+ larger of 16 and twice
+ StartServers and, like
+ ThreadLimit, cannot be changed
+ during a restart. There are no
+ MinSpareThreads /
+ MaxSpareThreads /
+ MaxRequestWorkers controls.
+ Scale concurrency with
+ ThreadsPerChild (and, if the
+ poll path saturates, PollersPerChild).
This directive has the same meaning as in the event
+ MPM. A process only accepts new connections while the
+ number of connections it holds, not counting those in lingering close, is
+ lower than:
+
+
+ ThreadsPerChild +
+ (AsyncRequestWorkerFactor *
+ number of idle workers)
+
+
+
Most of the connections a child holds are normally idle and use no
+ worker thread, which is why the limit is larger than the number of
+ threads. Values below 1 are raised to 1.
+
+
+
+
+PollersPerChild
+Number of poll threads per child process
+PollersPerChild number
+PollersPerChild 0
+server config
+motorz
+
+
+
The PollersPerChild directive sets the number of
+ poller threads created in each child process. Each poller owns its own
+ pollset, timer ring and connection-recycle list, and handles a shard of
+ the child's connections. Because each poller thread dispatches the ready
+ I/O events and timer expiries of its own connections to the worker pool
+ (the first poller also accepts new connections), adding pollers raises the rate at which a
+ single child process can handle these operations in parallel rather than
+ serializing them on one poll thread.
+
+
A value of 0 (the default) means auto: the number
+ of pollers is derived from the number of online CPUs, capped at a built-in
+ maximum. In all cases the number of pollers is clamped so that it never
+ exceeds ThreadsPerChild and is
+ never less than one.
+
+
Because event dispatch is rarely the bottleneck for real request
+ processing—worker CPU usually is—values beyond one or two
+ seldom improve throughput. Raising PollersPerChild
+ is mainly useful for workloads dominated by very high connection churn or
+ large numbers of idle, event-driven connections, where the poll/accept
+ path itself becomes the limit.
+
+ Example
+
+StartServers 2
+ThreadsPerChild 64
+ThreadLimit 64
+PollersPerChild 2
+
+
+
+
+
+
diff --git a/docs/manual/mod/motorz.xml.meta b/docs/manual/mod/motorz.xml.meta
new file mode 100644
index 00000000000..0d8012243a8
--- /dev/null
+++ b/docs/manual/mod/motorz.xml.meta
@@ -0,0 +1,12 @@
+
+
+
+
+ motorz
+ /mod/
+ ..
+
+
+ en
+
+
diff --git a/docs/manual/mod/mpm_common.xml b/docs/manual/mod/mpm_common.xml
index 564e9a001a3..bd71be9f6ac 100644
--- a/docs/manual/mod/mpm_common.xml
+++ b/docs/manual/mod/mpm_common.xml
@@ -34,7 +34,7 @@ switch before dumping core
CoreDumpDirectory directorySee usage for the default settingserver config
-eventworker
+eventmotorzworkerprefork
@@ -97,7 +97,7 @@ after a crash
EnableExceptionHook Offserver config
-eventworker
+eventmotorzworkerprefork
@@ -122,7 +122,7 @@ will exit.
GracefulShutdownTimeout 0server configeventworker
-prefork
+preforkmotorzAvailable in version 2.2 and later
@@ -142,7 +142,7 @@ of the daemon
PidFile filenamePidFile logs/httpd.pidserver config
-eventworker
+eventmotorzworkerpreforkmpm_winntmpmt_os2
@@ -185,7 +185,7 @@ of the daemon
listens to
Listen [IP-address:]portnumber [protocol]server config
-eventworker
+eventmotorzworkerpreforkmpm_winntmpm_netwarempmt_os2
@@ -270,7 +270,7 @@ listeners' buckets
ListenCoresBucketsRatio ratioListenCoresBucketsRatio 0 (disabled)server config
-eventworker
+eventmotorzworkerpreforkAvailable in Apache HTTP Server 2.4.17, with a kernel supporting
@@ -343,7 +343,7 @@ in *BSDs.ListenBackLog backlogListenBackLog 511server config
-eventworker
+eventmotorzworkerpreforkmpm_winntmpm_netwarempmt_os2
@@ -369,7 +369,7 @@ in *BSDs.
ListenTCPDeferAccept integerListenTCPDeferAccept 30server config
-eventworker
+eventmotorzworkerpreforkAvailable in Apache HTTP Server 2.5.1 and later
@@ -456,7 +456,7 @@ to hold without calling free()MaxMemFree KBytesMaxMemFree 2048server config
-eventworker
+eventmotorzworkerpreforkmpm_winntmpm_netware
@@ -477,7 +477,7 @@ will handle during its life
MaxConnectionsPerChild numberMaxConnectionsPerChild 0server config
-eventworker
+eventmotorzworkerpreforkmpm_winntmpm_netwarempmt_os2
@@ -595,7 +595,7 @@ the child processes
ScoreBoardFile file-pathScoreBoardFile logs/apache_runtime_statusserver config
-eventworker
+eventmotorzworkerpreforkmpm_winnt
@@ -632,7 +632,7 @@ Apache HTTP Server
ReceiveBufferSize bytesReceiveBufferSize 0server config
-eventworker
+eventmotorzworkerpreforkmpm_winntmpm_netwarempmt_os2
@@ -653,7 +653,7 @@ Apache HTTP Server
SendBufferSize bytesSendBufferSize 0server config
-eventworker
+eventmotorzworkerpreforkmpm_winntmpm_netwarempmt_os2
@@ -686,10 +686,17 @@ Apache HTTP Server
See usage for detailsserver configeventworker
-prefork
+preforkmotorz
+
For the motorz MPM, this directive sets the number of
+ process slots, which must cover StartServers plus the old processes still
+ finishing connections after a graceful restart; it defaults to the larger
+ of 16 and twice
+ StartServers.
+
For the prefork MPM, this directive sets the
maximum configured value for MaxRequestWorkers for the lifetime of the
@@ -757,7 +764,7 @@ Apache HTTP Server
StartServers numberSee usage for detailsserver config
-eventworker
+eventmotorzworkerpreforkmpmt_os2
@@ -816,7 +823,7 @@ per child process
ThreadLimit numberSee usage for detailsserver config
-eventworker
+eventmotorzworkermpm_winnt
@@ -866,7 +873,7 @@ per child process
ThreadsPerChild numberSee usage for detailsserver config
-eventworker
+eventmotorzworkermpm_winnt
diff --git a/modules/arch/unix/config5.m4 b/modules/arch/unix/config5.m4
index 7ee06663b60..49343d03a1b 100644
--- a/modules/arch/unix/config5.m4
+++ b/modules/arch/unix/config5.m4
@@ -3,7 +3,8 @@ APACHE_MODPATH_INIT(arch/unix)
if ap_mpm_is_enabled "worker" \
|| ap_mpm_is_enabled "event" \
- || ap_mpm_is_enabled "prefork"; then
+ || ap_mpm_is_enabled "prefork" \
+ || ap_mpm_is_enabled "motorz"; then
unixd_mods_enable=yes
else
unixd_mods_enable=no
diff --git a/server/mpm/config2.m4 b/server/mpm/config2.m4
index d7e73ec05e3..c2f1dad4912 100644
--- a/server/mpm/config2.m4
+++ b/server/mpm/config2.m4
@@ -1,7 +1,7 @@
AC_MSG_CHECKING(which MPM to use by default)
AC_ARG_WITH(mpm,
APACHE_HELP_STRING(--with-mpm=MPM,Choose the process model for Apache to use by default.
- MPM={event|worker|prefork|winnt}
+ MPM={motorz|event|worker|prefork|winnt}
This will be statically linked as the only available MPM unless
--enable-mpms-shared is also specified.
),[
diff --git a/server/mpm/motorz/MOTORZ.README b/server/mpm/motorz/MOTORZ.README
new file mode 100644
index 00000000000..2d8064a40d9
--- /dev/null
+++ b/server/mpm/motorz/MOTORZ.README
@@ -0,0 +1,213 @@
+The MotorZ MPM aims to create a single MPM, that runs on all modern
+Unix and Win32 platforms, by leveraging APR as much as possible.
+
+The MotorZ MPM uses an APR Poll CB event system, with timers being
+built in. When an event, either an I/O or Timer is ready to run, it
+is pushed to any available thread in the current process. A simple
+APR Thread pool is used.
+
+MotorZ uses Prefork as the framework and Simple for the actual event
+structure.
+
+
+Threading model
+===============
+
+Each child process runs:
+
+ - N poll threads ("pollers", PollersPerChild; default: one per online CPU,
+ capped). Each poller owns its OWN pollset, timer ring (+ guarding mutex)
+ and lock-free transaction-pool recycle list, so pollers never contend with
+ each other. A poller polls, dispatches ready I/O events and expired timers
+ to the worker pool, and (for the listener-owning poller) accepts.
+ - A shared APR thread pool of worker threads (ThreadsPerChild) that run the
+ actual connection/request processing pushed to them; workers never poll.
+ - A supervisor (the child's main thread) that watches MaxRequestsPerChild and
+ the pipe-of-death / generation, signalling the pollers to wind down, then
+ joins them on exit.
+
+A connection is sharded to one poller at accept time (round-robin) and bound to
+it for its whole lifetime: it re-arms in and times out on that poller's
+pollset/ring. (Its transaction pool is recycled back to the ACCEPTING poller's
+free-list, which is the single consumer of that list -- recycling is not
+sharded, only I/O is.) Multiple pollers lift the old single-poll-thread
+throughput ceiling: accept + event dispatch + timer expiry now scale with
+PollersPerChild instead of being serialized on one thread.
+
+Graceful stop
+-------------
+
+A child told to stop gracefully (AP_SIG_GRACEFUL, the pipe-of-death, a
+generation change, or MaxConnectionsPerChild) does not exit at once. The
+supervisor calls motorz_start_drain(): the child reports AP_MPMQ_STOPPING and
+runs child_stopping, the listener-owning poller closes the listening sockets,
+idle keep-alive connections are expired immediately, and connections still
+writing or waiting on I/O run to completion. The child exits when conns_open
+(connections accepted and not yet torn down) reaches zero. SIGTERM/SIGHUP
+still exit immediately. The parent counts a draining child (quiescing) as gone
+and starts its replacement in a free slot, so ServerLimit (default the
+larger of 16 and 2 * StartServers) must leave room for several generations.
+With every slot taken nothing can start, and with no child of the current
+generation nothing accepts connections until a draining child exits; the
+parent logs "scoreboard is full" (AH10657) once when that happens.
+
+There is no child-side deadline on a drain: a connection still writing, or
+waiting on I/O for an asynchronous module (CONN_STATE_ASYNC_WAITIO), is given
+until it completes or its Timeout expires, so a graceful restart can take as
+long as the longest such connection. (mpm_event behaves the same way.)
+GracefulShutdownTimeout only bounds a graceful *stop* of the whole server, in
+the parent.
+
+Admission control (listener backpressure) keeps the child safe under overload:
+when the worker pool saturates, the listener-owning poller removes the
+listening sockets from its pollset (motorz_update_listeners /
+motorz_disable_listeners) and re-adds them once the backlog drains, so the work
+queue stays bounded. A child also stops accepting once it holds ThreadsPerChild
++ AsyncRequestWorkerFactor * (idle workers) connections not in lingering close
+(motorz_connections_above_limit), as in mpm_event: connections parked in the
+poller use no worker, so the worker counts alone do not limit them. A task that
+ends, or a connection that closes, wakes that poller when the child could
+accept again (motorz_wake_admission), so accepting resumes at once rather than
+at the poller's next timeout (at most 500ms, which still covers other cases).
+
+Scoreboard
+----------
+
+A connection is not bound to a thread, so the scoreboard's per-thread slots
+stand for the worker-pool threads. Each worker thread takes a slot the first
+time it runs a task, reports the connection it is processing through that slot
+(SERVER_BUSY_READ/WRITE/KEEPALIVE/CLOSING, so mod_status shows busy workers),
+and sets it back to SERVER_READY when the task ends. A connection parked in the
+poller (keep-alive, write completion, lingering close, async wait) therefore
+does not occupy a slot. The poller and supervisor threads have no slot.
+
+Unsupported
+-----------
+
+ThreadStackSize is ignored (a warning is logged when it is set): the worker
+threads are created by an APR thread pool, which offers no stack size control.
+There is no accept mutex either; the listening sockets are non-blocking and
+polled, so every child's listener-owning poller wakes for each new connection.
+
+Relationship to mpm_event
+-------------------------
+
+MotorZ uses Prefork for process management and an APR thread pool for workers,
+with pollers dispatching to that pool -- distinct from mpm_event's
+listener/worker/fdqueue design where workers themselves re-arm a shared
+thread-safe pollset. In practice, whether more pollers help depends on the
+workload: if the worker threads are the CPU bottleneck (typical for real
+request processing), the poll threads are not the limit and PollersPerChild
+beyond 1-2 yields little. The multiple-poller design removes motorz's
+*structural* single-thread ceiling, but per-box throughput is still governed by
+worker CPU. For the broadest, most battle-tested high-concurrency async
+behavior, mpm_event remains the reference; MotorZ stays a lean, self-contained
+alternative.
+
+
+HTTP/2 async handoff (ENABLED)
+==============================
+
+Status: motorz reports AP_MPMQ_IS_ASYNC = 1 and AP_MPMQ_CAN_WAITIO = 1
+(MOTORZ_ENABLE_ASYNC = 1 in motorz.c). With async on, mod_http2 hands the
+master connection (c1) back to the MPM between requests (CONN_STATE_ASYNC_WAITIO
+in motorz_io_process()) instead of pinning a worker thread to it.
+
+History: async used to be disabled because of intermittent dropped responses
+under HTTP/2 connection churn. That was first attributed to a close-ordering
+race in mod_http2 and "fixed" there; the real cause was in motorz and is
+described below. MOTORZ_ENABLE_ASYNC remains a single flip point should a
+regression ever appear.
+
+Symptom
+-------
+Under HTTP/2 with many short-lived connections (the worst case is one request
+per connection at high concurrency, e.g. `h2load -n 10000 -c 50 -m 1`), motorz
+intermittently lost a few requests per run. h2load reports them as "Process
+Request Failure". All h2 error codes are 0 (graceful), there is no TCP RST and
+no 4xx/5xx. It is timing-sensitive: trace8 logging, lldb and Guard Malloc slow
+the hot path enough to hide it; it reproduces at info level. mpm_event does not
+show it.
+
+Root cause: secondary connections shared the master's conn_state_t
+-------------------------------------------------------------------
+mod_http2 runs each stream on a secondary connection (c2) in its own worker
+thread. The core creates a c2 as a copy of c1 (core_create_secondary_conn(),
+h2_c2_create(): a memcpy of the conn_rec), so c2->cs pointed at c1's
+conn_state_t. In motorz that is scon->cs, the very struct motorz_io_process()
+reads to decide what to do next with the connection.
+
+When a request on a c2 ends, the core writes the connection state through
+c->cs (ap_process_request_after_handler(): WRITE_COMPLETION, or LINGER if the
+c2 is marked aborted); h2_c2.c does the same. Because c2->cs was c1's, those
+writes landed in the master's state:
+
+ 1. c1 sends a stream's last frame, the stream goes to CLEANUP, and
+ mod_http2 aborts the c2 that is still "running" (h2_mplx.c, "c2 is
+ running, abort"). That is harmless in itself: the response has been sent.
+ 2. c1 goes IDLE and returns CONN_STATE_ASYNC_WAITIO; motorz arms the socket.
+ 3. The c2 worker, still finishing, runs its end-of-request code. Aborted, it
+ stores CONN_STATE_LINGER in the shared struct, over ASYNC_WAITIO.
+ 4. The client's next request makes the socket readable. motorz_io_process()
+ finds LINGER, never re-enters the process_connection hooks, and
+ lingering-closes the live connection: h2_session_pre_close() sends GOAWAY
+ (reason='timeout', which only means "state was IDLE at close") and the
+ request that was in flight is lost.
+
+mpm_event does not have the problem because event_pre_connection() gives every
+secondary connection its own conn_state_t (setup_slave_conn()). motorz had no
+pre_connection hook.
+
+The fix
+-------
+motorz_pre_connection() (motorz.c), registered APR_HOOK_REALLY_FIRST, gives a
+secondary connection a private conn_state_t when it has none or shares the
+master's, and clears the motorz module config that mod_http2 copies from c1, so
+motorz_pre_read_request() cannot record a c2 request as the master's current
+request (scon->r). The check mirrors event_pre_connection().
+
+Measured with PollersPerChild 1, ThreadsPerChild 128,
+`h2load -n 10000 -c 50 -m 1`, 20 runs each: before, 11 runs lost responses (63
+lost, and only 194414 of 200000 connections started); after, 0 runs lost any
+and all 200000 connections started. The earlier mod_http2 change (a graceful
+client GOAWAY with streams in flight no longer goes straight to DONE, in
+h2_session.c) was made under the close-ordering theory. It is not the cause of
+this loss and was not shown to be needed; it was left alone.
+
+Measuring it correctly (two pitfalls)
+-------------------------------------
+The committed tests learned two lessons the hard way; preserve them if you edit:
+
+ 1. Assert on RESPONSE LOSS, not on h2load's "failed" total. h2load's "failed"
+ counts BOTH connection-establishment errors AND dropped responses:
+ failed = (total - started) + (started - succeeded)
+ \__ connection setup _/ \__ lost responses __/
+ The first term can also be environmental (ephemeral-port exhaustion and
+ accept-queue pressure when hammering loopback at high -c). Only the
+ second term, started - succeeded, is response loss. The tests compute
+ `lost = started - succeeded` and assert that is 0.
+
+ 2. Measure at LogLevel info, NOT trace8. This is a Heisenbug: trace8 slows
+ the hot path enough to hide it, so a churn assertion run under trace8
+ passes even with the fix removed -- i.e. it is vacuous. smoke.sh runs at
+ trace8 for its state-machine traces, so its churn check is only a gross
+ sanity pass; the load-bearing churn regression is the one in
+ run-http2.sh, which runs at info.
+
+How to reproduce it (if it ever comes back)
+-------------------------------------------
+ 1. Remove the motorz_pre_connection() hook registration and rebuild.
+ 2. Config that maximizes the race (TLS vhost, `Protocols h2 http/1.1`):
+ StartServers 1
+ PollersPerChild 1 ; fewer pollers => more serialized, worse
+ ThreadsPerChild 128 ; large, so it is NOT worker starvation
+ ThreadLimit 128
+ LogLevel info
+ 3. Drive maximum connection churn, one stream per connection:
+ h2load -n 10000 -c 50 -m 1 https://localhost:PORT/
+ Run it several times; about half the runs lose a few requests.
+ 4. To see the close path, use LogLevel trace2 (global; a per-module spec does
+ not emit on this build) with small runs (n=2000) until one fails, then look
+ for sessions that go "IDLE -- local goaway --> DONE" with GOAWAY
+ reason='timeout'. On such a connection the closing thread's first action is
+ h2_session_pre_close(), with no process_conn before it.
diff --git a/server/mpm/motorz/Makefile.in b/server/mpm/motorz/Makefile.in
new file mode 100644
index 00000000000..f34af9cbd66
--- /dev/null
+++ b/server/mpm/motorz/Makefile.in
@@ -0,0 +1 @@
+include $(top_srcdir)/build/special.mk
diff --git a/server/mpm/motorz/config.m4 b/server/mpm/motorz/config.m4
new file mode 100644
index 00000000000..0dc54d09a09
--- /dev/null
+++ b/server/mpm/motorz/config.m4
@@ -0,0 +1,15 @@
+AC_MSG_CHECKING(if motorz MPM supports this platform)
+if test $forking_mpms_supported != yes; then
+ AC_MSG_RESULT(no - This is not a forking platform)
+elif test $ac_cv_define_APR_HAS_THREADS != yes; then
+ AC_MSG_RESULT(no - APR does not support threads)
+elif test $have_threaded_sig_graceful != yes; then
+ AC_MSG_RESULT(no - SIG_GRACEFUL cannot be used with a threaded MPM)
+elif test $ac_cv_have_threadsafe_pollset != yes; then
+ AC_MSG_RESULT(no - APR_POLLSET_THREADSAFE is not supported)
+elif test $apr_has_skiplist != yes; then
+ AC_MSG_RESULT(no - APR skiplist is not available, need APR 1.5.x or later)
+else
+ AC_MSG_RESULT(yes)
+ APACHE_MPM_SUPPORTED(motorz, yes, yes)
+fi
diff --git a/server/mpm/motorz/config3.m4 b/server/mpm/motorz/config3.m4
new file mode 100644
index 00000000000..7cf26379bcf
--- /dev/null
+++ b/server/mpm/motorz/config3.m4
@@ -0,0 +1,7 @@
+dnl ## XXX - Need a more thorough check of the proper flags to use
+
+APACHE_SUBST(MOD_MPM_MOTORZ_LDADD)
+
+APACHE_MPM_MODULE(motorz, $enable_mpm_motorz, motorz.lo,[
+ AC_CHECK_FUNCS(pthread_kill)
+], , [\$(MOD_MPM_MOTORZ_LDADD)])
diff --git a/server/mpm/motorz/motorz.c b/server/mpm/motorz/motorz.c
new file mode 100644
index 00000000000..e0edfa276a0
--- /dev/null
+++ b/server/mpm/motorz/motorz.c
@@ -0,0 +1,3447 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "motorz.h"
+#include "mpm_fdqueue.h"
+
+/* Upper bound on the number of transaction pools kept on the recycle
+ * free-list (motorz_ptrans_get/put). Beyond this, freed pools are destroyed
+ * outright so a burst of connections does not pin memory forever.
+ */
+#define MAX_RECYCLED_POOLS 64
+
+/* Lingering close timeouts. Not exported by the core, so mirror the values
+ * connection.c uses (also mirrored this way by mpm_event). MAX_SECS_TO_LINGER
+ * bounds the whole non-blocking drain; SECONDS_TO_LINGER is the shortened
+ * period used when a module requested it (e.g. DoS mitigation).
+ */
+#ifndef MAX_SECS_TO_LINGER
+#define MAX_SECS_TO_LINGER 30
+#endif
+#define SECONDS_TO_LINGER 2
+
+/**
+ * config globals
+ */
+module AP_MODULE_DECLARE_DATA mpm_motorz_module;
+
+static motorz_core_t *g_motorz_core;
+#define DEFAULT_THREADS_PER_CHILD 16
+static int threads_per_child = DEFAULT_THREADS_PER_CHILD;
+static int ap_num_kids = DEFAULT_START_DAEMON;
+/* Number of poll threads per child (#2 / scaling). 0 means "auto": derive from
+ * online CPUs in child_main, capped so a small box doesn't over-thread. Each
+ * poller owns its own pollset/timer-ring/recycle-list and a shard of the
+ * connections, lifting the single-poll-thread throughput ceiling.
+ */
+static int num_pollers = 0;
+#define MOTORZ_MAX_POLLERS 8
+
+/* Async HTTP/2 handoff is ENABLED (MOTORZ_ENABLE_ASYNC 1).
+ *
+ * When motorz advertises AP_MPMQ_IS_ASYNC=1, mod_http2 hands the master (c1)
+ * connection back to the MPM between requests; motorz then re-dispatches it on
+ * a fresh worker thread when its socket is readable.
+ *
+ * This used to drop responses under rapid HTTP/2 connection churn. The cause
+ * was in motorz, not mod_http2: a secondary (c2) connection is created as a
+ * copy of c1, so it shared c1's conn_state_t. A c2 worker that finished after
+ * c1 had parked the connection (state ASYNC_WAITIO) wrote its end-of-request
+ * state into that shared struct -- LINGER if the c2 had been aborted, which is
+ * harmless for a response already sent. The next dispatch then found LINGER,
+ * skipped process_connection and lingering-closed a live connection, so the
+ * client's next request was lost. motorz_pre_connection() gives every
+ * secondary connection a private conn_state_t, as mpm_event does. The
+ * analysis and reproduction recipe are in MOTORZ.README ("HTTP/2 async
+ * handoff").
+ *
+ * This remains a single flip point: set to 0 to fall back to the old workaround
+ * (report IS_ASYNC=0 so mod_http2 keeps c1 on one worker, driving its own
+ * multiplexer pollset until every c2 completes) should a regression ever
+ * reappear. It gates both AP_MPMQ_IS_ASYNC and AP_MPMQ_CAN_WAITIO
+ * (CONN_STATE_ASYNC_WAITIO is only meaningful when async).
+ */
+#define MOTORZ_ENABLE_ASYNC 1
+/* Upper bound for ThreadsPerChild; matches worker/event in using
+ * DEFAULT_THREAD_LIMIT rather than an arbitrary fraction of MAX_THREAD_LIMIT.
+ */
+static int thread_limit = DEFAULT_THREAD_LIMIT;
+/* Hard limit on child process slots; the scoreboard is sized from it. 0 means
+ * "not configured": motorz_check_config() derives 2 * StartServers, leaving
+ * room for a new generation to start while the old one drains.
+ */
+static int server_limit = 0;
+
+/* Connection ID: child_slot * thread_limit + worker slot, as in the worker and
+ * event MPMs. It names the worker running the connection, so it is unique among
+ * connections being processed and bounded by the number of worker slots, which
+ * mod_cgid relies on for its per-id bookkeeping. It is refreshed whenever a
+ * worker picks the connection up (motorz_worker_claim_sbh).
+ */
+#define ID_FROM_CHILD_THREAD(c, t) ((long)(c) * (long)thread_limit + (long)(t))
+
+/* one_process --- debugging mode variable; can be set from the command line
+ * with the -X flag. If set, this gets you the child_main loop running
+ * in the process which originally started up (no detach, no make_child),
+ * which is a pretty nice debugging environment. (You'll get a SIGHUP
+ * early in standalone_main; just continue through. This is the server
+ * trying to kill off any child processes which it might have lying
+ * around --- Apache doesn't keep track of their pids, it just sends
+ * SIGHUP to the process group, ignoring it in the root process.
+ * Continue through and you'll be fine.).
+ */
+static int one_process = 0;
+
+static apr_pool_t *pconf; /* Pool for config stuff */
+static apr_pool_t *pchild; /* Pool for httpd child stuff */
+
+static pid_t ap_my_pid; /* it seems silly to call getpid all the time */
+static pid_t parent_pid;
+static int my_child_num;
+
+/* Scoreboard worker slots. A connection is not tied to a thread: it is
+ * processed by whichever worker-pool thread it is dispatched to. So the
+ * scoreboard slots stand for the pool's threads, not for connections. Each
+ * worker thread takes the next free slot the first time it runs a task (the
+ * pool never replaces a thread, so no two live threads share one; c->id is
+ * derived from the slot), points the
+ * connection it is working on at that slot for the duration of the task, and
+ * returns the slot to SERVER_READY when the task ends. Without this every
+ * connection reported through slot 0, from many threads at once.
+ */
+static apr_threadkey_t *worker_slot_key;
+static apr_uint32_t next_worker_slot;
+static ap_sb_handle_t **worker_sbhs;
+/* What a worker thread's worker_slot_key points to: its scoreboard handle and
+ * thread number, and its slot in worker_sockets (-1 for none).
+ * threads_per_child entries for the pool's threads, then as many for any
+ * thread past those.
+ */
+typedef struct motorz_worker_slot_t {
+ ap_sb_handle_t *sbh;
+ int thread;
+ int sock_slot;
+} motorz_worker_slot_t;
+static motorz_worker_slot_t *worker_slots;
+/* The sockets the workers are blocked on, per worker slot, for an ungraceful
+ * stop to shut them down (ap_worker_sockets_*() in mpm_fdqueue.h).
+ */
+static /*atomic*/ apr_uint32_t workers_may_exit = AP_WORKERS_RUNNING;
+static ap_worker_sockets_t *worker_sockets;
+/* Set by child_main() when a graceful stop ran to completion. */
+static int drain_completed = 0;
+/* Number of connections accepted by this child so far; compared against
+ * ap_max_requests_per_child. Written by the accepting poller thread
+ * (motorz_io_accept) and read by the supervisor on the main thread
+ * (motorz_supervise). volatile ensures neither side caches a stale value;
+ * a torn read is harmless for a monotone counter used only for a soft cap.
+ */
+static volatile int requests_this_child;
+/* Set to stop the child's main loop. volatile because it's updated from a
+ * signal handler (stop_listening), from poller threads, and from the
+ * supervisor. On ARM (Apple Silicon) the poller->mtx lock/unlock performed
+ * on every poll-loop iteration provides acquire/release barriers, so the
+ * practical visibility lag is bounded by the 500ms poll timeout at worst.
+ */
+static int volatile die_now = 0;
+/* Graceful stop. stop_listening() (a signal handler) only sets
+ * graceful_requested; the supervisor turns that, the pipe-of-death, a
+ * generation change or MaxConnectionsPerChild into draining via
+ * motorz_start_drain(). While draining the child accepts nothing new, closes
+ * idle keep-alive connections, and exits once conns_open reaches zero.
+ * listeners_closed is set by the listener-owning poller once its sockets are
+ * closed, after which every accepted connection is already counted.
+ */
+static int volatile graceful_requested = 0;
+static int volatile draining = 0;
+static int volatile listeners_closed = 0;
+/* Connections accepted by this child and not yet torn down. */
+static apr_uint32_t conns_open = 0;
+/* Those of them in lingering close; they are not counted against the
+ * connection limit (see motorz_connections_above_limit). */
+static apr_uint32_t lingering_count = 0;
+/* Worker-pool tasks running now. Admission counts these itself: the pool counts
+ * a worker idle only after its task has returned, after motorz_task_end(). */
+static apr_uint32_t tasks_running = 0;
+/* AsyncRequestWorkerFactor, scaled so that it can be fractional. */
+#ifndef DEFAULT_WORKER_FACTOR
+#define DEFAULT_WORKER_FACTOR 2
+#endif
+#define WORKER_FACTOR_SCALE 16
+static unsigned int worker_factor = DEFAULT_WORKER_FACTOR * WORKER_FACTOR_SCALE;
+static motorz_child_bucket *all_buckets, /* All listeners buckets */
+ *my_bucket; /* Current child bucket */
+
+static void clean_child_exit(int code) __attribute__ ((noreturn));
+
+/* Join every poller thread, clearing each poller->thread as it is joined so a
+ * second join is a no-op (apr_thread_join -> pthread_join on an already-joined
+ * handle is undefined behavior). clean_child_exit() and child_main() both call
+ * this; on the normal path child_main joins the pollers first and this becomes
+ * a pass over NULL handles.
+ */
+static void motorz_join_pollers(motorz_core_t *mz)
+{
+ apr_os_thread_t self = apr_os_thread_current();
+ apr_os_thread_t *pos;
+ int i;
+
+ if (mz->pollers) {
+ for (i = 0; i < mz->num_pollers; i++) {
+ motorz_poller_t *poller = mz->pollers[i];
+ if (poller && poller->thread
+ && (apr_os_thread_get(&pos, poller->thread) != APR_SUCCESS
+ || pos == NULL
+ || !apr_os_thread_equal(*pos, self))) {
+ apr_status_t pstatus;
+ apr_thread_join(&pstatus, poller->thread);
+ poller->thread = NULL;
+ }
+ }
+ }
+}
+
+static apr_status_t motorz_io_process(motorz_conn_t *scon);
+static void motorz_pollset_del(motorz_poller_t *poller, motorz_conn_t *scon);
+static void motorz_conn_claim(motorz_poller_t *poller, motorz_conn_t *scon);
+static void motorz_conn_done(motorz_conn_t *scon);
+static void motorz_start_lingering_close(motorz_conn_t *scon);
+static apr_status_t motorz_lingering_close(motorz_conn_t *scon);
+static void motorz_update_listeners(motorz_poller_t *poller);
+static int motorz_admission_would_resume(motorz_poller_t *poller);
+
+static motorz_core_t *motorz_core_get(void)
+{
+ return g_motorz_core;
+}
+
+/* A worker or a connection slot is free: if the child stopped accepting and
+ * could start again, have the listener poller do it now instead of at its next
+ * timeout. Waking it for anything less costs throughput when saturated. */
+static void motorz_wake_admission(void)
+{
+ motorz_core_t *mz = motorz_core_get();
+ motorz_poller_t *poller;
+
+ /* No workers: clean_child_exit() destroyed them. */
+ if (!mz || !mz->workers || !mz->pollers || !(poller = mz->pollers[0])) {
+ return;
+ }
+ if (apr_atomic_read32(&poller->admission_paused)
+ && motorz_admission_would_resume(poller)
+ && apr_atomic_cas32(&poller->wake_pending, 1, 0) == 0) {
+ apr_pollset_wakeup(poller->pollset);
+ }
+}
+
+static void motorz_task_begin(void)
+{
+ apr_atomic_inc32(&tasks_running);
+}
+
+static void motorz_task_end(void)
+{
+ apr_atomic_dec32(&tasks_running);
+ motorz_wake_admission();
+}
+
+/* The calling worker thread's slot (see worker_sbhs). */
+static motorz_worker_slot_t *motorz_worker_slot(void)
+{
+ void *ws = NULL;
+
+ apr_threadkey_private_get(&ws, worker_slot_key);
+ if (!ws) {
+ apr_uint32_t n = apr_atomic_inc32(&next_worker_slot);
+
+ /* Should the pool ever replace a thread, the newcomer shares a
+ * scoreboard slot and must not share a socket slot: it gets none.
+ */
+ if (n < (apr_uint32_t)threads_per_child) {
+ ws = &worker_slots[n];
+ }
+ else {
+ ws = &worker_slots[threads_per_child
+ + n % (apr_uint32_t)threads_per_child];
+ }
+ apr_threadkey_private_set(ws, worker_slot_key);
+ }
+ return ws;
+}
+
+/* The calling worker thread's scoreboard handle and, in *thread, its number. */
+static ap_sb_handle_t *motorz_worker_sbh(int *thread)
+{
+ motorz_worker_slot_t *ws = motorz_worker_slot();
+
+ *thread = ws->thread;
+ return ws->sbh;
+}
+
+/* Publish the connection's socket while the calling worker may block on it, so
+ * that an ungraceful stop can shut it down. Returns the slot to pass to
+ * motorz_unpublish_socket(), -1 if not published.
+ */
+static int motorz_publish_socket(motorz_conn_t *scon)
+{
+ int slot = motorz_worker_slot()->sock_slot;
+
+ if (slot < 0 || !worker_sockets || scon->c->master || !scon->sock) {
+ return -1;
+ }
+ ap_worker_sockets_publish(worker_sockets, slot, scon->sock);
+ return slot;
+}
+
+/* Returns 0 if an ungraceful stop took the socket: the child is exiting, close
+ * the connection rather than hand it over.
+ */
+static int motorz_unpublish_socket(motorz_conn_t *scon, int slot)
+{
+ if (slot < 0) {
+ return 1;
+ }
+ return ap_worker_sockets_unpublish(worker_sockets, slot, scon->sock);
+}
+
+/* Run the process_connection hooks with the socket published. If a stop took
+ * it, the connection is closed rather than handed back to a poller, unless a
+ * module suspended it: that module owns it from now on.
+ */
+static void motorz_run_process_connection(motorz_conn_t *scon)
+{
+ int slot = motorz_publish_socket(scon);
+
+ ap_run_process_connection(scon->c);
+ if (!motorz_unpublish_socket(scon, slot)
+ && scon->cs.state != CONN_STATE_SUSPENDED) {
+ scon->c->aborted = 1;
+ scon->cs.state = CONN_STATE_LINGER;
+ }
+}
+
+/* Point scon (and its conn_rec) at the calling worker's slot. Only valid while
+ * the worker owns scon, i.e. after it was claimed and before it is released.
+ */
+static ap_sb_handle_t *motorz_worker_claim_sbh(motorz_conn_t *scon)
+{
+ int thread;
+ ap_sb_handle_t *sbh = motorz_worker_sbh(&thread);
+
+ scon->sbh = sbh;
+ if (scon->c) {
+ scon->c->sbh = sbh;
+ scon->c->id = ID_FROM_CHILD_THREAD(my_child_num, thread);
+ }
+ return sbh;
+}
+
+/* The suspend/resume_connection hooks (mpm_common.h) tell modules that a
+ * connection is leaving a thread and that the thread which continues it has
+ * picked it up. As in mpm_event, suspend is announced by the worker that is
+ * about to park the connection, before it is published to the poller or handed
+ * to a module (afterwards another worker may already be running it), and resume
+ * by the worker that continues it, once that worker is associated with it.
+ */
+static void motorz_notify_suspend(motorz_conn_t *scon)
+{
+ ap_run_suspend_connection(scon->c, scon->r);
+ scon->c->sbh = NULL;
+ scon->suspend_notified = 1;
+}
+
+static void motorz_notify_resume(motorz_conn_t *scon, int cleanup)
+{
+ if (scon->suspend_notified) {
+ scon->suspend_notified = 0;
+ /* A cleanup resume (the connection ends here) may not be on the
+ * worker whose slot scon->sbh names. */
+ scon->c->sbh = cleanup ? NULL : scon->sbh;
+ ap_run_resume_connection(scon->c, scon->r);
+ }
+}
+
+/* Obtain a transaction pool for a new connection, reusing one from the
+ * recycle free-list if available, otherwise creating a fresh one with its
+ * own allocator (so per-connection memory is released as a unit and the
+ * allocator's free blocks can be reused).
+ *
+ * SINGLE-CONSUMER: the lock-free CAS pop below is only safe with one popper,
+ * because it dereferences first->next without atomicity (see mpm_fdqueue.c's
+ * ap_queue_info_pop_pool and its PR caveat). This MUST be called only from the
+ * owning poller's thread (its sole caller is motorz_io_accept, which runs on
+ * that poller). Each poller has its own free-list, so "one popper" holds.
+ * Concurrent lock-free pushes (motorz_ptrans_put, from any worker) are fine.
+ */
+static apr_pool_t *motorz_ptrans_get(motorz_poller_t *poller)
+{
+ apr_pool_t *ptrans;
+
+ for (;;) {
+ motorz_recycled_pool *first = poller->recycled_pools;
+ if (first == NULL) {
+ break;
+ }
+ if (apr_atomic_casptr((void *)&poller->recycled_pools,
+ first->next, first) == first) {
+ apr_atomic_dec32(&poller->num_recycled);
+ /* The node lived inside the pool it describes; the pool is now
+ * ours to hand out (it will be cleared again on next reuse).
+ */
+ return first->pool;
+ }
+ /* CAS lost a race with another pop... but there is only one popper, so
+ * this only happens transiently vs. a push changing the head; retry.
+ */
+ }
+
+ {
+ apr_allocator_t *allocator;
+ apr_allocator_create(&allocator);
+ apr_allocator_max_free_set(allocator, ap_max_mem_free);
+ apr_pool_create_ex(&ptrans, pconf, NULL, allocator);
+ apr_allocator_owner_set(allocator, ptrans);
+ apr_pool_tag(ptrans, "transaction");
+ }
+ return ptrans;
+}
+
+/* Return a finished connection's transaction pool to the recycle free-list,
+ * or destroy it if the list is already at MAX_RECYCLED_POOLS. Clearing the
+ * pool runs all its cleanups (closing the socket, de-registering timers) and
+ * resets it for reuse.
+ *
+ * MULTI-PRODUCER: the lock-free CAS push is safe from any thread (workers and
+ * the poll thread), concurrently with each other and with a single popper.
+ */
+static void motorz_ptrans_put(motorz_poller_t *poller, apr_pool_t *ptrans)
+{
+ motorz_recycled_pool *node;
+
+ /* Bound the free-list. apr_atomic_read32 + inc is not a strict CAS, so the
+ * count may momentarily overshoot MAX_RECYCLED_POOLS under concurrency;
+ * that is harmless (it just caps roughly).
+ */
+ if (apr_atomic_read32(&poller->num_recycled) >= MAX_RECYCLED_POOLS) {
+ apr_pool_destroy(ptrans);
+ return;
+ }
+ apr_atomic_inc32(&poller->num_recycled);
+
+ /* Clear (don't destroy) to keep the allocator and its free blocks; this
+ * also runs the pool's cleanups (closing the socket, de-registering any
+ * timer). Then carve the list node out of the now-empty pool.
+ */
+ apr_pool_clear(ptrans);
+ apr_pool_tag(ptrans, "transaction");
+ node = apr_palloc(ptrans, sizeof(*node));
+ node->pool = ptrans;
+
+ for (;;) {
+ /* Save the current head in a local before the CAS: node->next must not
+ * be re-read after a successful CAS, as a concurrent pusher may have
+ * already changed it (see mpm_fdqueue.c push_pool, PR 44402).
+ */
+ motorz_recycled_pool *next = poller->recycled_pools;
+ node->next = next;
+ if (apr_atomic_casptr((void *)&poller->recycled_pools, node, next) == next) {
+ break;
+ }
+ }
+}
+
+static int timer_comp(void *a, void *b)
+{
+ motorz_timer_t *ta = (motorz_timer_t *) a;
+ motorz_timer_t *tb = (motorz_timer_t *) b;
+ apr_time_t t1 = ta->expires;
+ apr_time_t t2 = tb->expires;
+ AP_DEBUG_ASSERT(t1);
+ AP_DEBUG_ASSERT(t2);
+ /* Identity match: required so that apr_skiplist_remove() (which relies on
+ * the compare function returning 0) can locate the exact timer node. We
+ * must never return 0 for two *distinct* timers, otherwise
+ * apr_skiplist_insert() would drop duplicates (timers created within the
+ * same microsecond) and remove() could delete the wrong connection's
+ * timer. Equal expiry on distinct timers therefore falls back to a stable
+ * total order on the timer address.
+ */
+ if (ta == tb) {
+ return 0;
+ }
+ if (t1 < t2) {
+ return -1;
+ }
+ if (t1 > t2) {
+ return 1;
+ }
+ return (ta < tb) ? -1 : 1;
+}
+
+static apr_status_t motorz_conn_pool_cleanup(void *baton)
+{
+ motorz_conn_t *scon = (motorz_conn_t *)baton;
+
+ if (scon->timer.expires) {
+ motorz_poller_t *poller = scon->poller;
+
+ apr_thread_mutex_lock(poller->mtx);
+ apr_skiplist_remove(poller->timeout_ring, &scon->timer, NULL);
+ apr_thread_mutex_unlock(poller->mtx);
+ }
+
+ return APR_SUCCESS;
+}
+
+/* c->pool's: a module can end a suspended connection by destroying that pool
+ * instead of handing it back, and then it never reaches motorz_conn_done().
+ * Pre-cleanup, so that the resume hooks still see the request. */
+static apr_status_t motorz_conn_pool_pre_cleanup(void *baton)
+{
+ motorz_conn_t *scon = (motorz_conn_t *)baton;
+
+ if (apr_atomic_cas32(&scon->suspended, 0, 1) == 1) {
+ motorz_notify_resume(scon, 1);
+ apr_atomic_dec32(&conns_open);
+ motorz_wake_admission();
+ }
+
+ return APR_SUCCESS;
+}
+
+static APR_INLINE apr_interval_time_t
+motorz_get_timeout(motorz_conn_t *scon)
+{
+ if (scon->c->base_server) {
+ return scon->c->base_server->timeout;
+ }
+ else {
+ return ap_server_conf->timeout;
+ }
+}
+
+static APR_INLINE apr_interval_time_t
+motorz_get_keep_alive_timeout(motorz_conn_t *scon)
+{
+ if (scon->c->base_server) {
+ return scon->c->base_server->keep_alive_timeout;
+ }
+ else {
+ return ap_server_conf->keep_alive_timeout;
+ }
+}
+
+static void motorz_io_timeout_cb(motorz_core_t *mz, void *baton)
+{
+
+ motorz_conn_t *scon = (motorz_conn_t *) baton;
+ conn_rec *c = scon->c;
+
+ ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, APLOGNO(02842)
+ "io timeout hit scon: %pp, c: %pp", scon, c);
+
+ /* The keep-alive/write timeout expired. Begin a non-blocking lingering
+ * close rather than blocking this worker; scon is handed to the poll loop
+ * or torn down inside, and is invalid afterwards. The timer has already
+ * been popped from the ring by the caller.
+ */
+ motorz_start_lingering_close(scon);
+}
+
+static void *motorz_io_setup_conn(apr_thread_t *thread, void *baton)
+{
+ apr_status_t status;
+ ap_sb_handle_t *sbh;
+ long conn_id;
+ int slot;
+ motorz_sb_t *sb;
+ motorz_conn_t *scon = (motorz_conn_t *) baton;
+
+ motorz_task_begin();
+ ap_log_error(APLOG_MARK, APLOG_TRACE8, 0, ap_server_conf, APLOGNO(03316)
+ "motorz_io_setup_conn(): entered");
+
+ sbh = motorz_worker_sbh(&slot);
+ conn_id = ID_FROM_CHILD_THREAD(my_child_num, slot);
+ scon->sbh = sbh;
+ scon->ba = apr_bucket_alloc_create(scon->pool);
+
+ scon->c = ap_run_create_connection(scon->pool, ap_server_conf, scon->sock,
+ conn_id, sbh, scon->ba);
+ if (scon->c == NULL) {
+ /* create_connection failed (e.g. a module declined or hit a resource
+ * limit). There is no conn_rec to process or linger-close; just
+ * release the transaction pool, which closes the accepted socket via
+ * its pool cleanup.
+ */
+ ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf, APLOGNO(10547)
+ "motorz_io_setup_conn: ap_run_create_connection failed");
+ motorz_conn_done(scon);
+ motorz_task_end();
+ return NULL;
+ }
+
+ scon->c->cs = &scon->cs;
+ apr_pool_pre_cleanup_register(scon->c->pool, scon,
+ motorz_conn_pool_pre_cleanup);
+ sb = apr_pcalloc(scon->pool, sizeof(motorz_sb_t));
+
+ /* Publish this scon in the connection's module config so the
+ * pre_read_request hook (and any code needing the current scon from a
+ * conn_rec, e.g. tracking c->r for suspend/resume) can recover it.
+ */
+ ap_set_module_config(scon->c->conn_config, &mpm_motorz_module, scon);
+
+ scon->c->current_thread = thread;
+
+ scon->pfd.p = scon->pool;
+ scon->pfd.desc_type = APR_POLL_SOCKET;
+ scon->pfd.desc.s = scon->sock;
+ scon->pfd.reqevents = APR_POLLIN;
+
+ sb->type = PT_CSD;
+ sb->baton = scon;
+ scon->pfd.client_data = sb;
+
+ ap_update_vhost_given_ip(scon->c);
+
+ status = ap_pre_connection(scon->c, scon->sock);
+ ap_log_error(APLOG_MARK, APLOG_TRACE8, 0, ap_server_conf, APLOGNO(03317)
+ "motorz_io_setup_conn(): did pre-conn");
+ if (status != OK && status != DONE) {
+ ap_log_error(APLOG_MARK, APLOG_TRACE8, 0, ap_server_conf, APLOGNO(02843)
+ "motorz_io_setup_conn: connection aborted");
+ }
+
+ /* pfd is initialized here to ensure reqevents == 0, so the defensive
+ * pollset_remove guard in motorz_io_process is a no-op on this first call.
+ */
+ scon->pfd.reqevents = 0;
+ scon->cs.state = CONN_STATE_PROCESSING;
+ scon->cs.sense = CONN_SENSE_DEFAULT;
+
+ status = motorz_io_process(scon);
+
+ ap_log_error(APLOG_MARK, APLOG_TRACE8, status, ap_server_conf, APLOGNO(02844)
+ "motorz_io_setup_conn: motorz_io_process status: %d", (int)status);
+
+ /* scon may be gone; this worker's own slot is not. */
+ ap_update_child_status(sbh, SERVER_READY, NULL);
+ motorz_task_end();
+ return NULL;
+}
+
+static apr_status_t motorz_io_user(motorz_poller_t *poller, motorz_sb_t *sb)
+{
+ /* PT_USER poll events are not implemented yet. Nothing currently
+ * registers a PT_USER descriptor in the pollset, so reaching here means
+ * an unexpected event; log it rather than silently dropping it.
+ */
+ ap_log_error(APLOG_MARK, APLOG_WARNING, 0, ap_server_conf, APLOGNO(10548)
+ "motorz_io_user: PT_USER poll events are not implemented");
+ return APR_SUCCESS;
+}
+
+static apr_status_t motorz_io_accept(motorz_poller_t *poller, motorz_sb_t *sb)
+{
+ motorz_core_t *mz = poller->mz;
+ apr_status_t rv;
+ apr_pool_t *ptrans;
+ apr_socket_t *socket = NULL;
+ ap_listen_rec *lr = (ap_listen_rec *) sb->baton;
+ motorz_conn_t *scon;
+
+ ap_log_error(APLOG_MARK, APLOG_TRACE8, 0, ap_server_conf, APLOGNO(03318)
+ "motorz_io_accept(): entered");
+
+ if (draining) {
+ /* The listeners are about to be closed by motorz_poller_main(). */
+ return APR_SUCCESS;
+ }
+
+ /* Drain the kernel accept queue in one poll wakeup instead of returning
+ * to apr_pollset_poll() for each connection. Without this, N queued
+ * connections require N round-trips through the poll loop, costing O(N)
+ * wakeups under burst. The loop stops when accept() returns EAGAIN (queue
+ * empty), on a fatal error, when admission control disables the listener,
+ * or when the child is shutting down.
+ *
+ * ap_unixd_accept() outcome buckets:
+ * - APR_SUCCESS + socket set: a connection was accepted;
+ * - APR_EGENERAL: fatal/resource condition (E[MN]FILE, ENETDOWN, etc.) --
+ * stop gracefully rather than spin;
+ * - any other non-success (EAGAIN, EINTR, ECONNABORTED, ...): transient,
+ * log and stop draining.
+ * socket == NULL on every non-SUCCESS path.
+ */
+ do {
+ ptrans = motorz_ptrans_get(poller);
+ socket = NULL;
+ rv = lr->accept_func((void *)&socket, lr, ptrans);
+
+ if (rv == APR_SUCCESS && socket != NULL) {
+ static apr_uint32_t rr;
+ motorz_poller_t *target;
+
+ scon = apr_pcalloc(ptrans, sizeof(motorz_conn_t));
+ scon->pool = ptrans;
+ scon->sock = socket;
+ scon->mz = mz;
+
+ /* Shard I/O across pollers round-robin. The accepting poller is
+ * always poller 0, so this counter needs no atomics.
+ */
+ target = mz->pollers[rr % (apr_uint32_t)mz->num_pollers];
+ rr++;
+ scon->poller = target;
+
+ /* Recycling is NOT sharded: the ptrans came from THIS poller's
+ * free-list (its single-consumer pop home). Return it here.
+ */
+ scon->pool_poller = poller;
+
+ requests_this_child++;
+ apr_atomic_inc32(&conns_open);
+
+ apr_pool_cleanup_register(scon->pool, scon, motorz_conn_pool_cleanup,
+ apr_pool_cleanup_null);
+
+ rv = apr_thread_pool_push(mz->workers,
+ motorz_io_setup_conn,
+ scon,
+ APR_THREAD_TASK_PRIORITY_HIGHEST, NULL);
+ if (rv != APR_SUCCESS) {
+ ap_log_error(APLOG_MARK, APLOG_ERR, rv, ap_server_conf,
+ APLOGNO(03319)
+ "motorz_io_accept: could not queue connection to "
+ "worker pool");
+ apr_atomic_dec32(&conns_open);
+ motorz_ptrans_put(poller, ptrans);
+ }
+
+ /* Re-check admission after each accept: if the worker pool has
+ * become saturated, motorz_update_listeners() will remove the
+ * listener from the pollset and set listeners_disabled, which
+ * terminates the drain loop below.
+ */
+ motorz_update_listeners(poller);
+ }
+ else {
+ /* Nothing accepted (EAGAIN/EINTR/error): recycle the pool. */
+ motorz_ptrans_put(poller, ptrans);
+
+ if (rv == APR_EGENERAL) {
+ /* Let the supervisor drain: connections already accepted are
+ * finished, as for any other graceful stop of the child.
+ */
+ ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf,
+ APLOGNO(02845)
+ "motorz_io_accept: accept failed, shutting down "
+ "child gracefully");
+ graceful_requested = 1;
+ }
+ else if (APR_STATUS_IS_ECONNREFUSED(rv)
+ || APR_STATUS_IS_ECONNABORTED(rv)
+ || APR_STATUS_IS_ECONNRESET(rv)) {
+ /* 2.4.x has no ap_accept_error_is_nonfatal(); inline the same
+ * set of non-fatal accept errors it checks for. */
+ ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, ap_server_conf,
+ APLOGNO(10549)
+ "accept() on client socket failed");
+ }
+
+ break;
+ }
+ } while (!poller->listeners_disabled && !die_now && !draining);
+
+ return APR_SUCCESS;
+}
+
+static void *motorz_timer_invoke(apr_thread_t *thread, void *baton)
+{
+ motorz_timer_t *ep = (motorz_timer_t *)baton;
+ motorz_conn_t *scon = (motorz_conn_t *)ep->baton;
+ ap_sb_handle_t *sbh;
+
+ motorz_task_begin();
+ sbh = motorz_worker_claim_sbh(scon);
+ scon->c->current_thread = thread;
+ motorz_notify_resume(scon, 0);
+
+ ap_log_error(APLOG_MARK, APLOG_TRACE8, 0, ap_server_conf, APLOGNO(03320)
+ "motorz_timer_invoke(): entered");
+
+ ep->cb(ep->mz, ep->baton);
+
+ ap_log_error(APLOG_MARK, APLOG_TRACE8, 0, ap_server_conf, APLOGNO(03321)
+ "motorz_timer_invoke(): exited");
+
+ /* scon may be gone; this worker's own slot is not. */
+ ap_update_child_status(sbh, SERVER_READY, NULL);
+ motorz_task_end();
+
+ return NULL;
+}
+
+static apr_status_t motorz_timer_event_process(motorz_poller_t *poller, motorz_timer_t *te)
+{
+ motorz_conn_t *scon = (motorz_conn_t *)te->baton;
+ apr_status_t rv;
+ scon->timer.expires = 0;
+
+ ap_log_error(APLOG_MARK, APLOG_TRACE8, 0, ap_server_conf, APLOGNO(03322)
+ "motorz_timer_event_process(): entered");
+
+ /* Claim the connection on the poll thread before dispatching the timeout
+ * (fix #5). The timer has already been popped from the ring by the caller
+ * (so there is nothing to remove there -- and we must not take poller->mtx
+ * here as the caller holds it), but the connection's descriptor may still
+ * be armed in the pollset; disarm it so a concurrent/subsequent poll
+ * cannot dispatch the same scon while the timeout worker is closing it.
+ * apr_pollset_remove() takes only the (leaf) pollset lock, so calling it
+ * under poller->mtx introduces no lock-ordering inversion.
+ */
+ motorz_pollset_del(poller, scon);
+
+ rv = apr_thread_pool_push(poller->mz->workers,
+ motorz_timer_invoke,
+ te, APR_THREAD_TASK_PRIORITY_NORMAL, NULL);
+ if (rv != APR_SUCCESS) {
+ /* Nothing will run the timeout, and the connection is no longer
+ * reachable from the poller: close it here. (The pool is created with
+ * all its threads, so a failed push means it is stopping or out of
+ * memory; the task was not queued.) */
+ ap_log_error(APLOG_MARK, APLOG_ERR, rv, ap_server_conf, APLOGNO(10668)
+ "motorz_timer_event_process: could not queue the timeout; "
+ "closing the connection");
+ motorz_conn_done(scon);
+ }
+ return rv;
+}
+
+static void *motorz_io_invoke(apr_thread_t *thread, void *baton)
+{
+ motorz_sb_t *sb = (motorz_sb_t *) baton;
+ motorz_conn_t *scon = (motorz_conn_t *) sb->baton;
+ ap_sb_handle_t *sbh;
+ apr_status_t rv;
+
+ motorz_task_begin();
+ sbh = motorz_worker_claim_sbh(scon);
+ ap_log_error(APLOG_MARK, APLOG_TRACE8, 0, ap_server_conf, APLOGNO(03323)
+ "motorz_io_invoke(): entered");
+ scon->c->current_thread = thread;
+ motorz_notify_resume(scon, 0);
+
+ rv = motorz_io_process(scon);
+
+ if (rv != APR_SUCCESS) {
+ ap_log_error(APLOG_MARK, APLOG_TRACE8, rv, ap_server_conf, APLOGNO(02846)
+ "motorz_io_invoke: motorz_io_process failed (?)");
+ }
+
+ /* scon may be gone; this worker's own slot is not. */
+ ap_update_child_status(sbh, SERVER_READY, NULL);
+ motorz_task_end();
+ return NULL;
+}
+
+static apr_status_t motorz_io_event_process(motorz_poller_t *poller, motorz_sb_t *sb)
+{
+ motorz_conn_t *scon = (motorz_conn_t *) sb->baton;
+ apr_status_t rv;
+
+ /* Take ownership of this connection on the poll thread before handing it
+ * to a worker: disarm its pollset entry and cancel any pending timeout
+ * (fix #5). This guarantees the poll thread cannot dispatch the same scon
+ * again -- neither re-reported by the pollset nor via timer expiry --
+ * until the worker re-arms it at the end of motorz_io_process(). Without
+ * this, two workers could race on one scon and, now that the transaction
+ * pool is freed on teardown, that race is a use-after-free.
+ *
+ * The identity-correct timer_comp (fix #3) is what makes the targeted
+ * skiplist removal reliable.
+ */
+ motorz_conn_claim(poller, scon);
+
+ rv = apr_thread_pool_push(poller->mz->workers,
+ motorz_io_invoke,
+ sb, APR_THREAD_TASK_PRIORITY_NORMAL, NULL);
+ if (rv != APR_SUCCESS) {
+ /* The connection has been claimed, so nothing else would ever reach
+ * it again: close it here. (See motorz_timer_event_process.) */
+ ap_log_error(APLOG_MARK, APLOG_ERR, rv, ap_server_conf, APLOGNO(10669)
+ "motorz_io_event_process: could not queue the connection; "
+ "closing it");
+ motorz_conn_done(scon);
+ }
+ return rv;
+}
+
+static apr_status_t motorz_io_callback(void *baton, const apr_pollfd_t *pfd)
+{
+ apr_status_t status = APR_SUCCESS;
+ motorz_poller_t *poller = (motorz_poller_t *) baton;
+ motorz_sb_t *sb = pfd->client_data;
+
+
+ if (sb->type == PT_ACCEPT) {
+ status = motorz_io_accept(poller, sb);
+ }
+ else if (sb->type == PT_CSD) {
+ status = motorz_io_event_process(poller, sb);
+ }
+ else if (sb->type == PT_USER) {
+ status = motorz_io_user(poller, sb);
+ }
+ return status;
+}
+
+/* Insert/refresh scon's timer in the ring. CALLER MUST HOLD mz->mtx.
+ *
+ * Everything that touches the sort key (expires) and the ring must happen
+ * under mz->mtx. In particular:
+ *
+ * - If this connection's timer is still linked in the ring from an earlier
+ * registration (expires != 0 is, under the lock, exactly the "in ring"
+ * predicate), remove it first -- using its *current* expiry as the key,
+ * before we overwrite it.
+ * - Only then mutate expires and re-insert.
+ *
+ * Re-inserting the same node, or mutating a linked node's sort key in place,
+ * corrupts the skiplist and sends apr_skiplist_insert()'s insert_compare()
+ * into an infinite loop *while holding mz->mtx*, which deadlocks the entire
+ * child. (Found by a load test with StartServers 1 and MaxRequestsPerChild
+ * churn.)
+ */
+static void motorz_register_timeout_locked(motorz_conn_t *scon,
+ motorz_timer_cb cb,
+ apr_interval_time_t relative_time)
+{
+ apr_time_t t = apr_time_now() + relative_time;
+ motorz_timer_t *elem = &scon->timer;
+ motorz_poller_t *poller = scon->poller;
+
+ if (elem->expires) {
+ apr_skiplist_remove(poller->timeout_ring, elem, NULL);
+ }
+
+ elem->expires = t;
+ elem->cb = cb;
+ elem->baton = scon;
+ elem->pool = scon->pool;
+ elem->mz = poller->mz;
+ elem->poller = poller;
+
+#ifdef AP_DEBUG
+ ap_assert(apr_skiplist_insert(poller->timeout_ring, elem));
+#else
+ apr_skiplist_insert(poller->timeout_ring, elem);
+#endif
+}
+
+/* Hand a connection back to the poll thread: arm its pollset entry for
+ * 'reqevents' AND register its timeout, atomically under mz->mtx. This is the
+ * ONLY safe way for a worker to release a connection it still holds a pointer
+ * to: once either the timer or the pollset entry is armed, the poll thread may
+ * fire the timeout (or a readable event) and tear the connection down --
+ * freeing scon. Doing both under one lock, and touching scon nowhere after
+ * this returns, closes the use-after-free window. MUST be the worker's last
+ * action on scon; returns the pollset_add status (scon may already be freed
+ * on a concurrent timeout by the time we look at the return, so the caller
+ * must not deref scon regardless of it).
+ */
+static apr_status_t motorz_conn_register(motorz_conn_t *scon,
+ apr_int16_t reqevents,
+ motorz_timer_cb cb,
+ apr_interval_time_t timeout)
+{
+ motorz_poller_t *poller = scon->poller;
+ apr_status_t rv;
+
+ apr_thread_mutex_lock(poller->mtx);
+ scon->pfd.reqevents = reqevents;
+ scon->cs.sense = CONN_SENSE_DEFAULT;
+ motorz_register_timeout_locked(scon, cb, timeout);
+ rv = apr_pollset_add(poller->pollset, &scon->pfd);
+ if (rv != APR_SUCCESS) {
+ /* Roll back the timer so the half-armed connection isn't left
+ * reachable via the ring with no pollset entry; the caller will tear
+ * it down.
+ */
+ if (scon->pfd.reqevents != 0) {
+ scon->pfd.reqevents = 0;
+ }
+ apr_skiplist_remove(poller->timeout_ring, &scon->timer, NULL);
+ scon->timer.expires = 0;
+ }
+ apr_thread_mutex_unlock(poller->mtx);
+ return rv;
+}
+
+/* Remove scon's descriptor from the pollset if it is currently armed, and
+ * mark it disarmed. Does NOT touch the timer ring. Safe to call without
+ * holding mz->mtx: the pollset is created APR_POLLSET_THREADSAFE, and APR's
+ * pollset lock is never held while acquiring mz->mtx (or vice versa), so no
+ * lock-ordering inversion is possible.
+ *
+ * Some pollset backends (kqueue, epoll) automatically drop a descriptor when
+ * its socket is closed, so APR_NOTFOUND is an acceptable, non-error result.
+ */
+static void motorz_pollset_del(motorz_poller_t *poller, motorz_conn_t *scon)
+{
+ if (scon->pfd.reqevents != 0) {
+ apr_status_t rv = apr_pollset_remove(poller->pollset, &scon->pfd);
+ if (rv != APR_SUCCESS && !APR_STATUS_IS_NOTFOUND(rv)) {
+ ap_log_error(APLOG_MARK, APLOG_TRACE1, rv, ap_server_conf,
+ "motorz_pollset_del: apr_pollset_remove failure");
+ }
+ scon->pfd.reqevents = 0;
+ }
+}
+
+/* Claim a connection on behalf of a worker, on the poll/main thread, before
+ * dispatching it. This is the heart of the per-connection ownership model
+ * (fix #5): it makes the connection invisible to the poll thread for as long
+ * as a worker owns it, so the same scon can never be dispatched twice (once
+ * for an I/O event and again for a timeout, or re-reported by a level-
+ * triggered pollset before the worker has run).
+ *
+ * It removes scon's descriptor from the pollset and cancels any pending
+ * timeout. The worker re-arms the connection (pollset_add + register_timeout)
+ * only at the very end of motorz_io_process(), at which point ownership
+ * returns to the poll thread. MUST be called on the poll thread only.
+ */
+static void motorz_conn_claim(motorz_poller_t *poller, motorz_conn_t *scon)
+{
+ motorz_pollset_del(poller, scon);
+
+ if (scon->timer.expires) {
+ apr_thread_mutex_lock(poller->mtx);
+ apr_skiplist_remove(poller->timeout_ring, &scon->timer, NULL);
+ scon->timer.expires = 0;
+ apr_thread_mutex_unlock(poller->mtx);
+ }
+}
+
+/* Terminal teardown for a connection: remove it from the pollset (if still
+ * registered) and recycle its transaction pool. Clearing the pool (inside
+ * motorz_ptrans_put) releases the conn_rec, bucket allocator and scoreboard
+ * handle allocated within it, and fires motorz_conn_pool_cleanup(), which
+ * de-registers any pending timer from the ring under mz->mtx.
+ *
+ * This MUST be called exactly once per connection, on every path that ends
+ * it (lingering close, abort, or fired timeout). It runs on a worker-pool
+ * thread; removing from the pollset concurrently with the polling thread is
+ * safe because the pollset is created APR_POLLSET_THREADSAFE. By the time a
+ * worker reaches a terminal state the connection has already been claimed
+ * (disarmed) by the poll thread, so motorz_pollset_del() is normally a no-op
+ * here -- it remains as a defensive backstop.
+ */
+static void motorz_conn_done(motorz_conn_t *scon)
+{
+ motorz_poller_t *poller = scon->poller;
+ motorz_poller_t *pool_poller = scon->pool_poller;
+ apr_pool_t *ptrans = scon->pool;
+
+ ap_log_error(APLOG_MARK, APLOG_TRACE6, 0, ap_server_conf,
+ "motorz_conn_done(): scon: %pp", scon);
+
+ if (scon->linger_started) {
+ apr_atomic_dec32(&lingering_count);
+ }
+ if (scon->suspend_notified) {
+ /* Parked, and ended without a worker picking it up again. */
+ motorz_notify_resume(scon, 1);
+ }
+
+ /* Disarm on the I/O poller (its pollset), then recycle to the accepting
+ * poller's free-list (its single-consumer pop home -- not the I/O poller).
+ */
+ motorz_pollset_del(poller, scon);
+
+ /* scon lives in ptrans, so it (and scon->pool) are invalid afterwards. */
+ motorz_ptrans_put(pool_poller, ptrans);
+ apr_atomic_dec32(&conns_open);
+}
+
+/* Timer callback for a lingering close that ran out of time: force the
+ * connection closed. Mirrors motorz_io_timeout_cb but for the linger phase.
+ */
+static void motorz_linger_timeout_cb(motorz_core_t *mz, void *baton)
+{
+ motorz_conn_t *scon = (motorz_conn_t *) baton;
+
+ ap_log_error(APLOG_MARK, APLOG_TRACE6, 0, ap_server_conf,
+ "motorz_linger_timeout_cb(): scon: %pp", scon);
+
+ /* The timer has already been popped from the ring; tear down. */
+ motorz_conn_done(scon);
+}
+
+/* Drain and discard any data the peer is still sending, without blocking.
+ * Called (on a worker thread) when a lingering socket is readable or its
+ * linger timer fires. Returns when the peer has closed/erred (-> teardown)
+ * or there is nothing more to read right now (-> re-arm in the pollset).
+ */
+static apr_status_t motorz_lingering_close(motorz_conn_t *scon)
+{
+ apr_socket_t *csd = scon->sock;
+ char dummybuf[512];
+ apr_size_t nbytes;
+ apr_status_t rv;
+ apr_time_t now;
+ apr_interval_time_t remaining;
+
+ /* A draining child cuts every linger short, but never extends one. */
+ if (draining) {
+ apr_time_t short_end = apr_time_now() + apr_time_from_sec(SECONDS_TO_LINGER);
+
+ if (short_end < scon->linger_deadline) {
+ scon->linger_deadline = short_end;
+ }
+ }
+
+ do {
+ nbytes = sizeof(dummybuf);
+ rv = apr_socket_recv(csd, dummybuf, &nbytes);
+ } while (rv == APR_SUCCESS && apr_time_now() < scon->linger_deadline);
+
+ now = apr_time_now();
+ if (rv == APR_SUCCESS || (!APR_STATUS_IS_EAGAIN(rv))
+ || now >= scon->linger_deadline) {
+ /* Peer closed, reset, hard error, or out of time: we are done. */
+ motorz_conn_done(scon);
+ return APR_SUCCESS;
+ }
+ remaining = scon->linger_deadline - now;
+
+ /* Nothing left to read for now; wait for more readability until the
+ * deadline. A readable PT_CSD dispatch goes through motorz_conn_claim(),
+ * which cancels this connection's timer, so the timeout is re-registered
+ * here alongside (re)arming the pollset -- for the time that is left, so a
+ * peer that keeps dribbling data cannot extend it.
+ *
+ * Arm pollset + timer atomically (motorz_conn_register); after it returns
+ * scon may already have been freed by a concurrent timeout, so we must not
+ * touch it again -- including on the error path, where the rollback inside
+ * motorz_conn_register has disarmed it and we just close.
+ */
+ rv = motorz_conn_register(scon,
+ APR_POLLIN | APR_POLLHUP | APR_POLLERR,
+ motorz_linger_timeout_cb, remaining);
+ if (rv != APR_SUCCESS) {
+ ap_log_error(APLOG_MARK, APLOG_TRACE1, rv, ap_server_conf,
+ "motorz_lingering_close: apr_pollset_add failed; closing");
+ motorz_conn_done(scon);
+ }
+ return APR_SUCCESS;
+}
+
+/* Begin a non-blocking lingering close (fix #3/A3). Runs on a worker thread,
+ * but unlike the old inline ap_lingering_close() it never blocks the worker
+ * for up to MAX_SECS_TO_LINGER: it shuts the write side down, then arms a
+ * linger timeout and hands the socket back to the poll loop, which drives the
+ * drain via motorz_lingering_close() as data arrives.
+ *
+ * Pre-condition: scon has already been claimed (not in the pollset, no timer).
+ */
+static void motorz_start_lingering_close(motorz_conn_t *scon)
+{
+ conn_rec *c = scon->c;
+ apr_socket_t *csd = scon->sock;
+ int slot, closing;
+
+ scon->cs.state = CONN_STATE_LINGER;
+
+ /* ap_start_lingering_close() flushes and shuts down the write side; bound
+ * the flush as mpm_event does. A true return means there is nothing to
+ * linger over (aborted or no half-close needed), so close immediately.
+ * The flush may block, so the socket is published meanwhile.
+ */
+ apr_socket_timeout_set(csd, apr_time_from_sec(SECONDS_TO_LINGER));
+ slot = motorz_publish_socket(scon);
+ closing = ap_start_lingering_close(c);
+ if (!motorz_unpublish_socket(scon, slot)) {
+ closing = 1;
+ }
+ if (closing) {
+ motorz_conn_done(scon);
+ return;
+ }
+
+ scon->linger_started = 1;
+ apr_atomic_inc32(&lingering_count);
+ scon->linger_deadline = apr_time_now() + apr_time_from_sec(
+ (draining || apr_table_get(c->notes, "short-lingering-close"))
+ ? SECONDS_TO_LINGER : MAX_SECS_TO_LINGER);
+
+ /* All draining from here is non-blocking. */
+ apr_socket_timeout_set(csd, 0);
+ apr_socket_opt_set(csd, APR_INCOMPLETE_READ, 0);
+
+ /* First drain attempt. If the peer still has data to send,
+ * motorz_lingering_close() arms both the pollset and the linger timeout;
+ * otherwise it tears the connection down here. We deliberately do not
+ * pre-register a timer (the drain owns that), so scon->timer is inserted
+ * into the ring at most once at a time.
+ */
+ motorz_lingering_close(scon);
+}
+
+/* Track the current request on a suspension-capable connection (fix #2).
+ * motorz_suspend_connection()/motorz_resume_suspended() pass the request_rec
+ * to the suspend/resume_connection hooks; leave it NULL when no request is
+ * active (mpm_common.h documents NULL in that case). Mirror mpm_event's
+ * event_pre_read_request()/event_request_cleanup(): recover scon from the
+ * connection's module config (published in motorz_io_setup_conn) and zero r
+ * when the request pool is torn down.
+ */
+static apr_status_t motorz_request_cleanup(void *dummy)
+{
+ conn_rec *c = dummy;
+ motorz_conn_t *scon = ap_get_module_config(c->conn_config,
+ &mpm_motorz_module);
+ if (scon) {
+ scon->r = NULL;
+ }
+ return APR_SUCCESS;
+}
+
+static void motorz_pre_read_request(request_rec *r, conn_rec *c)
+{
+ motorz_conn_t *scon = ap_get_module_config(c->conn_config,
+ &mpm_motorz_module);
+ if (scon) {
+ scon->r = r;
+ apr_pool_cleanup_register(r->pool, c, motorz_request_cleanup,
+ apr_pool_cleanup_null);
+ }
+}
+
+/* Park a connection that a process_connection hook left in
+ * CONN_STATE_SUSPENDED (A4). Ownership passes to the module, which now drives
+ * the connection itself (via its own threads, registered poll/timed callbacks,
+ * etc.) and interacts with the MPM only through the suspend/resume_connection
+ * hooks. The connection is intentionally left out of the pollset and timer ring
+ * (it has been claimed), and its transaction pool is NOT recycled, so nothing
+ * here tears it down -- which is what previously leaked. Runs on a worker
+ * thread. This mirrors mpm_event's notify_suspend() on 2.4.x: there is no
+ * MPM-level resume-suspended re-injection API in 2.4.x, so a resumed connection
+ * is handled entirely by the owning module.
+ */
+static void motorz_suspend_connection(motorz_conn_t *scon)
+{
+ ap_log_error(APLOG_MARK, APLOG_TRACE6, 0, ap_server_conf,
+ "motorz_suspend_connection(): scon: %pp", scon);
+
+ motorz_notify_suspend(scon);
+ /* Last: from here on the module may end the connection. */
+ apr_atomic_set32(&scon->suspended, 1);
+}
+
+static apr_status_t motorz_io_process(motorz_conn_t *scon)
+{
+ apr_status_t rv;
+ conn_rec *c;
+
+ ap_log_error(APLOG_MARK, APLOG_TRACE8, 0, ap_server_conf, APLOGNO(03325)
+ "motorz_io_process(): entered");
+
+ /* A connection already in non-blocking lingering close (its socket became
+ * readable again, or it was re-dispatched) just continues draining. It
+ * has been claimed, so its pollset entry/timer were cleared; the drain
+ * re-arms them or tears down.
+ */
+ if (scon->linger_started) {
+ return motorz_lingering_close(scon);
+ }
+
+ if (scon->c->clogging_input_filters && !scon->c->aborted) {
+ /* Since we have an input filter which 'clogs' the input stream,
+ * like mod_ssl used to, lets just do the normal read from input
+ * filters, like the Worker MPM does. Filters that need to write
+ * where they would otherwise read, or read where they would
+ * otherwise write, should set the sense appropriately.
+ *
+ * This path bypasses the normal motorz_conn_claim() that precedes
+ * every other call to motorz_io_process(). Do a full claim now:
+ * disarm the pollset entry AND cancel any pending timer under the
+ * poller mutex. Without the timer cancel, a concurrent timer expiry
+ * can dispatch a timeout worker on the same scon while this worker
+ * is inside ap_run_process_connection() -- a use-after-free race.
+ */
+ motorz_conn_claim(scon->poller, scon);
+ motorz_run_process_connection(scon);
+ /* The process_connection hooks set the next connection state on
+ * return; honor it and let the dispatch below act on it, mirroring
+ * the event MPM (see event.c:process_socket()). Async modules reach
+ * this clogging path too: mod_http2's secondary (c2) connections set
+ * clogging_input_filters unconditionally, and come back wanting either
+ * to wait for I/O (CONN_STATE_ASYNC_WAITIO), flush
+ * (CONN_STATE_WRITE_COMPLETION), or suspend -- all of which must be
+ * preserved rather than force-closed.
+ *
+ * A hook-returned CONN_STATE_KEEPALIVE is mapped to
+ * CONN_STATE_WRITE_COMPLETION (as event does) so it flushes any
+ * pending output and then waits for the next request: passing bare
+ * KEEPALIVE through to the dispatch below would hit the
+ * KEEPALIVE -> PROCESSING entry transition and synchronously re-run
+ * ap_run_process_connection() instead of returning to the poller.
+ *
+ * Anything left unfinished -- still CONN_STATE_PROCESSING because a
+ * hook returned DECLINED or OK without setting a state, as a non-async
+ * module would -- gets a lingering close, like the worker MPM. That
+ * also keeps us out of the CONN_STATE_PROCESSING branch below.
+ */
+ if (scon->cs.state == CONN_STATE_KEEPALIVE) {
+ scon->cs.state = CONN_STATE_WRITE_COMPLETION;
+ }
+ else if (scon->cs.state != CONN_STATE_ASYNC_WAITIO
+ && scon->cs.state != CONN_STATE_WRITE_COMPLETION
+ && scon->cs.state != CONN_STATE_SUSPENDED) {
+ scon->cs.state = CONN_STATE_LINGER;
+ }
+ }
+
+ c = scon->c;
+
+ if (!c->aborted) {
+
+ /* On the normal dispatch path (from motorz_io_event_process or
+ * motorz_io_setup_conn), the connection has already been claimed --
+ * pollset entry removed and reqevents cleared -- before reaching here.
+ * No redundant apr_pollset_remove() is needed or performed.
+ */
+
+ if (scon->cs.state == CONN_STATE_KEEPALIVE) {
+ ap_log_error(APLOG_MARK, APLOG_TRACE7, 0, ap_server_conf,
+ APLOGNO(03327)
+ "motorz_io_process(): keepalive -> processing");
+ scon->cs.state = CONN_STATE_PROCESSING;
+ }
+ else if (scon->cs.state == CONN_STATE_ASYNC_WAITIO) {
+ /* The socket this connection was waiting on (CONN_STATE_ASYNC_WAITIO,
+ * armed below) became readable/writable, so we were re-dispatched:
+ * re-enter the process_connection hooks, mirroring how event's loop
+ * maps ASYNC_WAITIO back to PROCESSING. (A Timeout expiry does not
+ * arrive here -- motorz_io_timeout_cb lingers/closes directly.)
+ */
+ ap_log_error(APLOG_MARK, APLOG_TRACE7, 0, ap_server_conf,
+ APLOGNO(10559)
+ "motorz_io_process(): async waitio -> processing");
+ scon->cs.state = CONN_STATE_PROCESSING;
+ }
+
+read_request:
+ if (scon->cs.state == CONN_STATE_PROCESSING) {
+ ap_log_error(APLOG_MARK, APLOG_TRACE7, 0, ap_server_conf,
+ APLOGNO(03328) "motorz_io_process(): processing");
+ if (!c->aborted) {
+ ap_update_child_status(scon->sbh, SERVER_BUSY_READ, NULL);
+ motorz_run_process_connection(scon);
+ /* state will be updated upon return
+ * fall thru to either wait for readability/timeout or
+ * do lingering close
+ */
+ if (scon->cs.state == CONN_STATE_PROCESSING) {
+ /* No hook took the connection on (DECLINED), or one
+ * returned OK without setting a state, as a protocol
+ * module written for worker or prefork does (mod_echo):
+ * nothing below would end it. Close it, as event does.
+ */
+ scon->cs.state = CONN_STATE_LINGER;
+ }
+ }
+ else {
+ ap_log_error(APLOG_MARK, APLOG_TRACE7, 0, ap_server_conf,
+ APLOGNO(03330)
+ "motorz_io_process(): aborted -> linger");
+ scon->cs.state = CONN_STATE_LINGER;
+ }
+ }
+
+ if (scon->cs.state == CONN_STATE_SUSPENDED) {
+ /* A module has taken the connection asynchronous (A4). Park it;
+ * ownership stays with the module (2.4.x has no resume API). Do not
+ * re-arm the pollset/timer or tear it down.
+ */
+ ap_log_error(APLOG_MARK, APLOG_TRACE6, 0, ap_server_conf,
+ APLOGNO(10550)
+ "motorz_io_process(): suspended");
+ motorz_suspend_connection(scon);
+ return APR_SUCCESS;
+ }
+
+ if (scon->cs.state == CONN_STATE_ASYNC_WAITIO) {
+ /* A process_connection hook wants the MPM to wait for the
+ * connection to become readable or writable (per c->cs->sense,
+ * defaulting to read) within the configured Timeout, and then
+ * re-enter the hooks. This is the same wait the WANT_READ
+ * workaround does through WRITE_COMPLETION, but explicit and
+ * without first checking ap_run_output_pending() -- the hook has
+ * told us it is done writing and is now waiting on I/O. Arm the
+ * pollset + timer atomically and do not touch scon afterwards (a
+ * concurrent timeout may free it). On failure scon is already
+ * disarmed by the rollback; close it.
+ */
+ apr_int16_t reqevents;
+
+ ap_log_error(APLOG_MARK, APLOG_TRACE7, 0, ap_server_conf,
+ APLOGNO(10557)
+ "motorz_io_process(): async waitio");
+
+ ap_update_child_status(scon->sbh, SERVER_BUSY_READ, NULL);
+
+ reqevents =
+ (scon->cs.sense == CONN_SENSE_WANT_WRITE ? APR_POLLOUT
+ : APR_POLLIN)
+ | APR_POLLHUP | APR_POLLERR;
+ motorz_notify_suspend(scon);
+ rv = motorz_conn_register(scon, reqevents,
+ motorz_io_timeout_cb,
+ motorz_get_timeout(scon));
+ if (rv != APR_SUCCESS) {
+ ap_log_error(APLOG_MARK, APLOG_WARNING, rv,
+ ap_server_conf, APLOGNO(10558)
+ "apr_pollset_add: failed in async waitio");
+ motorz_conn_done(scon);
+ }
+ return APR_SUCCESS;
+ }
+
+ if (scon->cs.state == CONN_STATE_WRITE_COMPLETION) {
+ ap_filter_t *output_filter;
+ apr_status_t flush_rv;
+
+ ap_log_error(APLOG_MARK, APLOG_TRACE7, 0, ap_server_conf,
+ APLOGNO(03331)
+ "motorz_io_process(): write completion");
+
+ ap_update_child_status(scon->sbh, SERVER_BUSY_WRITE, NULL);
+
+ /* 2.4.x has no ap_run_output_pending()/ap_run_input_pending();
+ * follow mpm_event's WRITE_COMPLETION handling instead. Flush all
+ * pending output by passing a NULL brigade down the last output
+ * filter, then decide based on the conn_rec data_in_*_filters flags
+ * (and CONN_SENSE_WANT_READ) whether output is still pending.
+ */
+ output_filter = c->output_filters;
+ while (output_filter->next != NULL) {
+ output_filter = output_filter->next;
+ }
+ flush_rv = output_filter->frec->filter_func.out_func(output_filter,
+ NULL);
+ if (flush_rv != APR_SUCCESS) {
+ ap_log_cerror(APLOG_MARK, APLOG_DEBUG, flush_rv, c,
+ APLOGNO(10681)
+ "network write failure in core output filter");
+ scon->cs.state = CONN_STATE_LINGER;
+ }
+ else if (c->data_in_output_filters
+ || scon->cs.sense == CONN_SENSE_WANT_READ) {
+ /* Still in WRITE_COMPLETION_STATE: set a read/write timeout and
+ * let the poll thread wait for read/writeability. Arm pollset +
+ * timer atomically and do not touch scon afterwards (it may be
+ * freed by a concurrent timeout). On failure scon is already
+ * disarmed by the rollback; close it.
+ */
+ apr_int16_t reqevents =
+ (scon->cs.sense == CONN_SENSE_WANT_READ ? APR_POLLIN
+ : APR_POLLOUT)
+ | APR_POLLHUP | APR_POLLERR;
+ motorz_notify_suspend(scon);
+ rv = motorz_conn_register(scon, reqevents,
+ motorz_io_timeout_cb,
+ motorz_get_timeout(scon));
+ if (rv != APR_SUCCESS) {
+ ap_log_error(APLOG_MARK, APLOG_WARNING, rv,
+ ap_server_conf, APLOGNO(02849)
+ "apr_pollset_add: failed in write completion");
+ motorz_conn_done(scon);
+ }
+ return APR_SUCCESS;
+ }
+ else if (c->keepalive != AP_CONN_KEEPALIVE || c->aborted) {
+ scon->cs.state = CONN_STATE_LINGER;
+ }
+ else if (c->data_in_input_filters) {
+ scon->cs.state = CONN_STATE_PROCESSING;
+ goto read_request;
+ }
+ else {
+ scon->cs.state = CONN_STATE_KEEPALIVE;
+ }
+ }
+
+ if (scon->cs.state == CONN_STATE_LINGER) {
+ ap_log_error(APLOG_MARK, APLOG_TRACE7, 0, ap_server_conf,
+ APLOGNO(03332) "motorz_io_process(): linger");
+ /* Begin a non-blocking lingering close instead of blocking this
+ * worker for up to MAX_SECS_TO_LINGER (A3). scon may be torn down
+ * or handed back to the poll loop inside; invalid afterwards.
+ */
+ motorz_start_lingering_close(scon);
+ return APR_SUCCESS;
+ }
+
+ if (scon->cs.state == CONN_STATE_KEEPALIVE) {
+ ap_log_error(APLOG_MARK, APLOG_TRACE7, 0, ap_server_conf,
+ APLOGNO(03333) "motorz_io_process(): keepalive");
+ if (draining) {
+ /* Don't park an idle connection in a child that is stopping;
+ * motorz_drain_keepalives() handles ones already parked.
+ */
+ motorz_start_lingering_close(scon);
+ return APR_SUCCESS;
+ }
+ /* Arm pollset + keep-alive timer atomically; do not touch scon
+ * afterwards (a concurrent timeout may free it). On failure scon
+ * is already disarmed by the rollback; close it.
+ */
+ motorz_notify_suspend(scon);
+ rv = motorz_conn_register(scon,
+ APR_POLLIN | APR_POLLHUP | APR_POLLERR,
+ motorz_io_timeout_cb,
+ motorz_get_keep_alive_timeout(scon));
+ if (rv != APR_SUCCESS) {
+ ap_log_error(APLOG_MARK, APLOG_ERR, rv, ap_server_conf,
+ APLOGNO(02850)
+ "process_socket: apr_pollset_add failure in "
+ "read request line");
+ motorz_conn_done(scon);
+ return APR_SUCCESS;
+ }
+ }
+ } else {
+ /* Aborted: begin (non-blocking) lingering close. */
+ motorz_start_lingering_close(scon);
+ return APR_SUCCESS;
+ }
+ return APR_SUCCESS;
+}
+
+/* NOTE: 2.4.x has no MPM-level resume-suspended hook (ap_hook_mpm_resume_suspended
+ * / ap_mpm_resume_suspended() and conn_rec.suspended_baton are trunk-only). A
+ * module that suspends a connection on 2.4.x owns it for the rest of its life
+ * and drives it via its own threads and the suspend/resume_connection hooks; it
+ * does not hand the connection back to the MPM. motorz therefore does not
+ * advertise AP_MPMQ_CAN_SUSPEND and provides no resume-suspended hook, matching
+ * mpm_event on 2.4.x.
+ */
+
+/* One poll thread per poller drives accept/dispatch/timer work for the
+ * connections bound to it; workers only process. Each child runs num_pollers
+ * of these in parallel. See "Scaling / architecture limits" in MOTORZ.README.
+ */
+static apr_status_t motorz_pollset_cb(motorz_poller_t *poller, apr_interval_time_t timeout)
+{
+ apr_status_t rc;
+ const apr_pollfd_t *out_pfd = NULL;
+ apr_int32_t num = 0;
+
+ rc = apr_pollset_poll(poller->pollset, timeout, &num, &out_pfd);
+ if (rc != APR_SUCCESS) {
+ if (APR_STATUS_IS_EINTR(rc) || APR_STATUS_IS_TIMEUP(rc)) {
+ return APR_SUCCESS;
+ } else {
+ return rc;
+ }
+ }
+ while (num > 0) {
+ rc = motorz_io_callback(poller, out_pfd);
+ if (rc != APR_SUCCESS) {
+ ap_log_error(APLOG_MARK, APLOG_CRIT, rc, NULL, APLOGNO(03334)
+ "Call to motorz_io_callback() failed");
+ }
+ out_pfd++;
+ num--;
+ }
+ return APR_SUCCESS;
+}
+
+/**
+ * Create worker thread pool.
+ */
+static apr_status_t motorz_setup_workers(motorz_core_t *mz)
+{
+ apr_status_t rv;
+
+ rv = apr_thread_pool_create(&mz->workers,
+ threads_per_child,
+ threads_per_child, mz->pool);
+
+ if (rv != APR_SUCCESS) {
+ ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL, APLOGNO(02851)
+ "motorz_setup_workers: apr_thread_pool_create with %d threads failed",
+ threads_per_child);
+ return rv;
+ }
+
+ return APR_SUCCESS;
+}
+
+static int motorz_setup_pollset(motorz_poller_t *poller)
+{
+ int i;
+ apr_status_t rv;
+ int good_methods[] = {APR_POLLSET_KQUEUE, APR_POLLSET_PORT, APR_POLLSET_EPOLL};
+ /* Poller 0 owns the listeners; motorz_wake_admission() wakes it. */
+ apr_uint32_t flags = APR_POLLSET_THREADSAFE
+ | (poller->index == 0 ? APR_POLLSET_WAKEABLE : 0);
+
+ /* The pollset is mutated (apr_pollset_{add,remove}) from worker-pool
+ * threads while this poller's thread is blocked in apr_pollset_poll(), so
+ * it MUST be thread-safe. All the preferred backends below
+ * (kqueue/port/epoll) support APR_POLLSET_THREADSAFE.
+ */
+ for (i = 0; i < sizeof(good_methods) / sizeof(good_methods[0]); i++) {
+ rv = apr_pollset_create_ex(&poller->pollset,
+ 512,
+ poller->pollset_pool,
+ APR_POLLSET_NODEFAULT | flags,
+ good_methods[i]);
+ if (rv == APR_SUCCESS) {
+ ap_log_error(APLOG_MARK, APLOG_DEBUG, rv, ap_server_conf, APLOGNO(02852)
+ "motorz_setup_pollset: apr_pollset_create_ex using %s", apr_pollset_method_name(poller->pollset));
+
+ break;
+ }
+ }
+ if (rv != APR_SUCCESS) {
+ ap_log_error(APLOG_MARK, APLOG_INFO, rv, ap_server_conf, APLOGNO(02853)
+ "motorz_setup_pollset: apr_pollset_create_ex failed for all possible backends!");
+ rv = apr_pollset_create(&poller->pollset,
+ 512,
+ poller->pollset_pool,
+ flags);
+ }
+ if (rv != APR_SUCCESS) {
+ ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, APLOGNO(02854)
+ "motorz_setup_pollset: apr_pollset_create failed for all possible backends!");
+ return rv;
+ }
+ ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, APLOGNO(03335)
+ "motorz_setup_pollset: Using %s", apr_pollset_method_name(poller->pollset));
+ return rv;
+}
+
+static void motorz_note_child_killed(int childnum, pid_t pid,
+ ap_generation_t gen)
+{
+ int i;
+
+ AP_DEBUG_ASSERT(childnum != -1); /* no scoreboard squatting with this MPM */
+ ap_run_child_status(ap_server_conf,
+ ap_scoreboard_image->parent[childnum].pid,
+ ap_scoreboard_image->parent[childnum].generation,
+ childnum, MPM_CHILD_EXITED);
+ ap_scoreboard_image->parent[childnum].pid = 0;
+ ap_scoreboard_image->parent[childnum].quiescing = 0;
+ /* Whatever the child's worker slots last said is stale now. */
+ for (i = 0; i < thread_limit; i++) {
+ ap_update_child_status_from_indexes(childnum, i, SERVER_DEAD, NULL);
+ }
+}
+
+static void motorz_note_child_started(motorz_core_t *mz, int slot, pid_t pid)
+{
+ ap_generation_t gen = mz->mpm->my_generation;
+ ap_scoreboard_image->parent[slot].pid = pid;
+ ap_scoreboard_image->parent[slot].generation = gen;
+ ap_scoreboard_image->parent[slot].quiescing = 0;
+ ap_run_child_status(ap_server_conf, pid, gen, slot, MPM_CHILD_STARTED);
+}
+
+/* a clean exit from a child with proper cleanup */
+static void clean_child_exit(int code)
+{
+ motorz_core_t *mz = motorz_core_get();
+
+ mz->mpm->mpm_state = AP_MPMQ_STOPPING;
+
+ apr_signal(SIGHUP, SIG_IGN);
+ apr_signal(SIGTERM, SIG_IGN);
+
+ /* A graceful stop already ran child_stopping in motorz_start_drain(). */
+ if (pchild && !draining) {
+ ap_run_child_stopping(pchild, 0);
+ }
+
+ /* Join the poller threads before tearing down the worker pool. A poller
+ * thread, mid motorz_pollset_cb, may be about to hand a ready connection
+ * to the worker pool via apr_thread_pool_push(mz->workers, ...); if we
+ * destroy mz->workers (or pchild, on which the poller threads were
+ * created) out from under it, that push dereferences freed memory and
+ * crashes in APR's add_task. child_main's normal exit already joins the
+ * pollers before getting here, but the abrupt paths (just_die, and the
+ * mid-startup error exits below where some pollers may already be
+ * running) do not -- so quiesce and join them here too. die_now stops the
+ * poll loops; the join is skipped for any poller running on the *current*
+ * thread (defensive: clean_child_exit is normally reached on the main
+ * thread, never a poller thread).
+ */
+ die_now = 1;
+ motorz_join_pollers(mz);
+
+ /* Drain the worker thread pool before tearing down pools. Without this,
+ * worker threads executing motorz_io_process or motorz_conn_done (which
+ * call ap_log_error and apr_pool_clear) may still be running when pchild
+ * and its log state are destroyed, causing use-after-free crashes.
+ * apr_thread_pool_destroy() joins all worker threads before returning.
+ * mz->workers is NULL only if motorz_setup_workers() was never called
+ * (i.e. we're exiting very early, before child_main set up workers).
+ * Unless a graceful stop completed, shut down the sockets the workers
+ * are blocked on first, or the join waits for their clients.
+ */
+ if (mz->workers) {
+ if (worker_sockets && !drain_completed) {
+ apr_atomic_set32(&workers_may_exit, AP_WORKERS_STOPPING);
+ ap_worker_sockets_shutdown(worker_sockets);
+ }
+ apr_thread_pool_destroy(mz->workers);
+ mz->workers = NULL;
+ }
+
+ if (pchild) {
+ apr_pool_destroy(pchild);
+ }
+
+ if (one_process) {
+ motorz_note_child_killed(/* slot */ 0, 0, 0);
+ }
+
+ ap_mpm_pod_close(my_bucket->pod);
+ if (one_process) {
+ exit(code);
+ }
+ /* Not the parent's atexit() handlers (e.g. OpenSSL's), maybe while
+ * threads we could not join still use what they clean up.
+ */
+ _exit(code);
+}
+
+static int motorz_query(int query_code, int *result, apr_status_t *rv)
+{
+ motorz_core_t *mz = motorz_core_get();
+ *rv = APR_SUCCESS;
+ switch(query_code){
+ case AP_MPMQ_IS_ASYNC:
+ /* See MOTORZ_ENABLE_ASYNC at the top of this file: async HTTP/2 handoff
+ * is enabled. */
+ *result = MOTORZ_ENABLE_ASYNC;
+ break;
+ case AP_MPMQ_CAN_WAITIO:
+ /* CONN_STATE_ASYNC_WAITIO is only requested by modules when the MPM is
+ * async; motorz honors it (polls per c->cs->sense under Timeout and
+ * re-enters the process_connection hooks -- see motorz_io_process()),
+ * but gate it on MOTORZ_ENABLE_ASYNC so it tracks IS_ASYNC. */
+ *result = MOTORZ_ENABLE_ASYNC;
+ break;
+ case AP_MPMQ_MAX_DAEMON_USED:
+ /* Highest child slot ever used, which can exceed StartServers while
+ * a previous generation drains. Children are reaped up to here. */
+ *result = mz->max_daemons_limit > 0 ? mz->max_daemons_limit : 0;
+ break;
+ case AP_MPMQ_IS_THREADED:
+ *result = AP_MPMQ_STATIC;
+ break;
+ case AP_MPMQ_IS_FORKED:
+ *result = AP_MPMQ_STATIC;
+ break;
+ case AP_MPMQ_HARD_LIMIT_DAEMONS:
+ *result = server_limit;
+ break;
+ case AP_MPMQ_HARD_LIMIT_THREADS:
+ *result = thread_limit;
+ break;
+ case AP_MPMQ_MAX_THREADS:
+ *result = threads_per_child;
+ break;
+ case AP_MPMQ_MIN_SPARE_DAEMONS:
+ *result = 0;
+ break;
+ case AP_MPMQ_MIN_SPARE_THREADS:
+ *result = 0;
+ break;
+ case AP_MPMQ_MAX_SPARE_DAEMONS:
+ *result = ap_num_kids;
+ break;
+ case AP_MPMQ_MAX_SPARE_THREADS:
+ *result = 0;
+ break;
+ case AP_MPMQ_MAX_REQUESTS_DAEMON:
+ *result = ap_max_requests_per_child;
+ break;
+ case AP_MPMQ_MAX_DAEMONS:
+ *result = ap_num_kids;
+ break;
+ case AP_MPMQ_MPM_STATE:
+ *result = mz->mpm->mpm_state;
+ break;
+ case AP_MPMQ_GENERATION:
+ *result = mz->mpm->my_generation;
+ break;
+ default:
+ *rv = APR_ENOTIMPL;
+ break;
+ }
+ return OK;
+}
+
+static const char *motorz_get_name(void)
+{
+ return "motorz";
+}
+
+/*****************************************************************
+ * Connection structures and accounting...
+ */
+
+static void just_die(int sig)
+{
+ /* Async-signal context: do the minimum. Setting die_now stops the poller
+ * loops and breaks motorz_supervise on the main thread, which then joins
+ * the pollers and calls clean_child_exit -- the one teardown path that
+ * quiesces the poller threads before destroying mz->workers and pchild.
+ * Calling clean_child_exit() directly from here (the old behaviour) tore
+ * those down while a poller could still be pushing work to the pool, a
+ * use-after-free that crashed in APR's add_task.
+ */
+ die_now = 1;
+}
+
+static void stop_listening(int sig)
+{
+ /* Signal context: only note the request. The supervisor starts draining
+ * (motorz_start_drain()), and the listener-owning poller closes the
+ * listening sockets from its own thread.
+ */
+ graceful_requested = 1;
+}
+
+/*****************************************************************
+ * Child process main loop.
+ * The following vars are static to avoid getting clobbered by longjmp();
+ * they are really private to child_main.
+ */
+
+static int num_listensocks = 0;
+
+/* Listener admission control (#1). The listener pollfds live in the poller
+ * that owns the listeners (poller 0); only that poller toggles them, on its
+ * own thread, so no locking is needed. The hysteresis band is derived from
+ * threads_per_child in child_main.
+ */
+static apr_size_t motorz_throttle_hi;
+static apr_size_t motorz_throttle_lo;
+
+/* Stop accepting: remove the listener sockets from the poller's pollset so it
+ * stops dispatching new connections while workers are saturated. Runs on the
+ * owning poller's thread only; idempotent.
+ */
+static void motorz_disable_listeners(motorz_poller_t *poller)
+{
+ int i;
+
+ if (poller->listeners_disabled) {
+ return;
+ }
+ for (i = 0; i < poller->num_listener_pfds; i++) {
+ apr_status_t rv = apr_pollset_remove(poller->pollset,
+ poller->listener_pfds[i]);
+ if (rv != APR_SUCCESS && !APR_STATUS_IS_NOTFOUND(rv)) {
+ ap_log_error(APLOG_MARK, APLOG_TRACE1, rv, ap_server_conf,
+ "motorz_disable_listeners: apr_pollset_remove failed");
+ }
+ }
+ poller->listeners_disabled = 1;
+ /* cas, a full barrier with APR's builtins: read the task count after */
+ apr_atomic_cas32(&poller->admission_paused, 1, 0);
+ if (my_child_num >= 0) {
+ ap_scoreboard_image->parent[my_child_num].not_accepting = 1;
+ }
+ ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, APLOGNO(10552)
+ "Workers busy, not accepting new connections in this child");
+}
+
+/* Resume accepting: re-add the listener sockets to the poller's pollset. Runs
+ * on the owning poller's thread only; idempotent; a no-op while shutting down.
+ */
+static void motorz_enable_listeners(motorz_poller_t *poller)
+{
+ int i;
+
+ if (!poller->listeners_disabled || die_now || draining) {
+ return;
+ }
+ for (i = 0; i < poller->num_listener_pfds; i++) {
+ apr_status_t rv = apr_pollset_add(poller->pollset,
+ poller->listener_pfds[i]);
+ if (rv != APR_SUCCESS && !APR_STATUS_IS_EEXIST(rv)) {
+ /* Stay disabled and try again on the next pass; say so, but not on
+ * every pass. Take back the ones added so far: a pollset need not
+ * tell that a descriptor is there already. */
+ apr_time_t now = apr_time_now();
+ int j;
+
+ for (j = 0; j < i; j++) {
+ apr_pollset_remove(poller->pollset, poller->listener_pfds[j]);
+ }
+
+ if (now - poller->last_enable_failure > apr_time_from_sec(10)) {
+ poller->last_enable_failure = now;
+ ap_log_error(APLOG_MARK, APLOG_ERR, rv, ap_server_conf,
+ APLOGNO(10671) "motorz_enable_listeners: could not "
+ "accept connections again; retrying");
+ }
+ return;
+ }
+ }
+ poller->listeners_disabled = 0;
+ apr_atomic_set32(&poller->admission_paused, 0);
+ if (my_child_num >= 0) {
+ ap_scoreboard_image->parent[my_child_num].not_accepting = 0;
+ }
+ ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, APLOGNO(10553)
+ "Accepting new connections again in this child");
+}
+
+/* The connection limit, as in mpm_event: a child accepts while the connections
+ * it has, not counting those in lingering close, number fewer than
+ * ThreadsPerChild + AsyncRequestWorkerFactor * idle workers. Parked connections
+ * (keep-alive, waiting for I/O, writing) use no worker, so without this limit
+ * idle clients could pile up without bound. 'idle' is the number of idle
+ * workers, which must be above zero.
+ */
+static int motorz_connections_above_limit(motorz_poller_t *poller,
+ apr_size_t idle)
+{
+ apr_uint32_t open = apr_atomic_read32(&conns_open);
+ apr_uint32_t lingering = apr_atomic_read32(&lingering_count);
+
+ /* While the listeners are off count one idle worker less, so that the
+ * limit does not flip with every connection that closes. */
+ if (apr_atomic_read32(&poller->admission_paused)) {
+ idle--;
+ }
+ return open > lingering
+ && (apr_uint64_t)(open - lingering)
+ >= (apr_uint64_t)threads_per_child
+ + (apr_uint64_t)idle * worker_factor / WORKER_FACTOR_SCALE;
+}
+
+/* Reconsider admission once per poll-loop iteration (owning poller's thread).
+ * Disable listeners when the worker pool is saturated and re-enable once it has
+ * drained. Four complementary saturation signals:
+ *
+ * 1. idle == 0: no thread is free to pick up a new connection right now.
+ * 2. pending >= throttle_hi: the push queue has a full wave of unstarted tasks
+ * (each accepted connection becomes one task), so we are ahead of the workers.
+ * 3. active >= threads_per_child: all threads are occupied, including those
+ * blocked in I/O waits -- catches the slow-client / keep-alive-heavy case
+ * where the task queue looks empty but workers are fully tied up.
+ * 4. the child holds as many connections as the limit allows, whether or not
+ * they use a worker (motorz_connections_above_limit).
+ *
+ * The hysteresis band (hi/lo) on the pending count avoids enable/disable
+ * flapping. A poller that does not own listeners (num_listener_pfds == 0) no-ops.
+ */
+static void motorz_admission_counts(motorz_poller_t *poller, apr_size_t *idle,
+ apr_size_t *pending, apr_size_t *active)
+{
+ apr_size_t total = apr_thread_pool_threads_count(poller->mz->workers);
+ apr_size_t running = apr_atomic_read32(&tasks_running);
+
+ *idle = (total > running) ? (total - running) : 0;
+ *active = running;
+ *pending = apr_thread_pool_tasks_count(poller->mz->workers);
+}
+
+/* Whether a child that stopped accepting would start again now. Also called
+ * from workers, by motorz_wake_admission(). */
+static int motorz_admission_would_resume(motorz_poller_t *poller)
+{
+ apr_size_t idle, pending, active;
+
+ motorz_admission_counts(poller, &idle, &pending, &active);
+ return idle > 0
+ && pending <= motorz_throttle_lo
+ && active < (apr_size_t)threads_per_child
+ && !motorz_connections_above_limit(poller, idle);
+}
+
+static void motorz_update_listeners(motorz_poller_t *poller)
+{
+ apr_size_t idle, pending, active;
+
+ if (poller->num_listener_pfds == 0) {
+ return;
+ }
+ motorz_admission_counts(poller, &idle, &pending, &active);
+
+ if (!poller->listeners_disabled) {
+ if (idle == 0
+ || pending >= motorz_throttle_hi
+ || active >= (apr_size_t)threads_per_child
+ || motorz_connections_above_limit(poller, idle)) {
+ motorz_disable_listeners(poller);
+ }
+ if (!poller->listeners_disabled) {
+ return;
+ }
+ /* A task that ended before admission_paused was set sent no wakeup:
+ * look again. */
+ }
+ if (motorz_admission_would_resume(poller)) {
+ motorz_enable_listeners(poller);
+ }
+}
+
+/* Create and initialize one poller context (its own pool, pollset, timer ring
+ * and ring mutex). The recycle free-list and listener state start zeroed.
+ * 'owns_listeners' marks the poller that holds the accept sockets.
+ */
+static motorz_poller_t *motorz_poller_create(motorz_core_t *mz, int index)
+{
+ apr_status_t rv;
+ motorz_poller_t *poller = apr_pcalloc(mz->pool, sizeof(*poller));
+
+ poller->mz = mz;
+ poller->index = index;
+ apr_pool_create(&poller->pool, mz->pool);
+ apr_pool_tag(poller->pool, "motorz-poller");
+
+ rv = apr_thread_mutex_create(&poller->mtx, APR_THREAD_MUTEX_DEFAULT,
+ poller->pool);
+ if (rv != APR_SUCCESS) {
+ ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, APLOGNO(02966)
+ "motorz_poller_create: apr_thread_mutex_create failed");
+ clean_child_exit(APEXIT_CHILDSICK);
+ }
+
+ apr_skiplist_init(&poller->timeout_ring, poller->pool);
+ apr_skiplist_set_compare(poller->timeout_ring, timer_comp, timer_comp);
+
+ /* Not poller->pool: the pollset allocates under its own lock, the timer
+ * ring under poller->mtx, and listener re-enable adds without that. */
+ apr_pool_create(&poller->pollset_pool, poller->pool);
+ apr_pool_tag(poller->pollset_pool, "motorz-pollset");
+
+ rv = motorz_setup_pollset(poller);
+ if (rv != APR_SUCCESS) {
+ ap_log_error(APLOG_MARK, APLOG_EMERG, rv, ap_server_conf, APLOGNO(02869)
+ "Couldn't setup pollset in child; check system or user limits");
+ clean_child_exit(APEXIT_CHILDSICK); /* assume temporary resource issue */
+ }
+
+ return poller;
+}
+
+/* Add this child's listening sockets to 'poller' and capture them so admission
+ * control can pause/resume accepting (#1). Only the listener-owning poller
+ * calls this.
+ */
+static void motorz_poller_add_listeners(motorz_poller_t *poller)
+{
+ apr_status_t status;
+ ap_listen_rec *lr;
+ int i;
+
+ poller->listener_pfds = apr_pcalloc(poller->pool,
+ num_listensocks * sizeof(apr_pollfd_t *));
+ poller->num_listener_pfds = 0;
+ poller->listeners_disabled = 0;
+
+ for (lr = my_bucket->listeners, i = num_listensocks; i--; lr = lr->next) {
+ apr_pollfd_t *pfd = apr_pcalloc(poller->pool, sizeof *pfd);
+ motorz_sb_t *sb = apr_pcalloc(poller->pool, sizeof(motorz_sb_t));
+
+ pfd->desc_type = APR_POLL_SOCKET;
+ pfd->desc.s = lr->sd;
+ pfd->reqevents = APR_POLLIN;
+ pfd->p = poller->pool;
+ pfd->client_data = sb;
+
+ sb->type = PT_ACCEPT;
+ sb->baton = lr;
+
+ poller->listener_pfds[poller->num_listener_pfds++] = pfd;
+
+ status = apr_socket_opt_set(pfd->desc.s, APR_SO_NONBLOCK, 1);
+ if (status != APR_SUCCESS) {
+ ap_log_error(APLOG_MARK, APLOG_CRIT, status, NULL, APLOGNO(02870)
+ "apr_socket_opt_set(APR_SO_NONBLOCK = 1) failed on %pI",
+ lr->bind_addr);
+ clean_child_exit(0);
+ }
+
+ status = apr_pollset_add(poller->pollset, pfd);
+ if (status != APR_SUCCESS) {
+ /* If the child processed a SIGWINCH before setting up the
+ * pollset, this error path is expected and harmless,
+ * since the listener fd was already closed; so don't
+ * pollute the logs in that case.
+ */
+ if (!die_now) {
+ ap_log_error(APLOG_MARK, APLOG_EMERG, status, ap_server_conf, APLOGNO(02871)
+ "Couldn't add listener to pollset; check system or user limits");
+ clean_child_exit(APEXIT_CHILDSICK);
+ }
+ clean_child_exit(0);
+ }
+
+ lr->accept_func = ap_unixd_accept;
+ }
+}
+
+/* Draining: stop accepting for good. Runs on the listener-owning poller's own
+ * thread, the only one that touches its listener pollfds, so the sockets are
+ * removed from the pollset before they are closed.
+ */
+static void motorz_close_listeners(motorz_poller_t *poller)
+{
+ if (poller->num_listener_pfds == 0 || listeners_closed) {
+ return;
+ }
+ motorz_disable_listeners(poller);
+ ap_close_listeners_ex(my_bucket->listeners);
+ listeners_closed = 1;
+}
+
+#define MOTORZ_DRAIN_BATCH 64
+
+/* Draining: close the idle keep-alive connections parked on this poller by
+ * expiring their timers now. Connections waiting on write completion or on
+ * ASYNC_WAITIO are left alone to finish, as mpm_event does. Returns the number
+ * expired; a full batch means there may be more.
+ */
+static int motorz_drain_keepalives(motorz_poller_t *poller)
+{
+ motorz_timer_t *batch[MOTORZ_DRAIN_BATCH];
+ apr_skiplistnode *node;
+ int n = 0, i;
+
+ apr_thread_mutex_lock(poller->mtx);
+ for (node = apr_skiplist_getlist(poller->timeout_ring);
+ node && n < MOTORZ_DRAIN_BATCH;
+ apr_skiplist_next(poller->timeout_ring, &node)) {
+ motorz_timer_t *te = apr_skiplist_element(node);
+ motorz_conn_t *scon = te->baton;
+
+ if (te->cb == motorz_io_timeout_cb
+ && scon->cs.state == CONN_STATE_KEEPALIVE) {
+ batch[n++] = te;
+ }
+ }
+ for (i = 0; i < n; i++) {
+ apr_skiplist_remove(poller->timeout_ring, batch[i], NULL);
+ motorz_timer_event_process(poller, batch[i]);
+ }
+ apr_thread_mutex_unlock(poller->mtx);
+
+ return n;
+}
+
+/* One poller's poll loop: poll, dispatch ready events to workers, expire
+ * timers, reconsider admission. Runs until die_now / shutdown / restart. Each
+ * poller runs this on its own thread; the child's main thread is the
+ * supervisor (motorz_supervise) that owns the MaxRequestsPerChild / pod /
+ * generation checks and sets die_now. A fatal poll error sets die_now and
+ * returns rather than exiting the process, so the other pollers can wind down
+ * and the supervisor can clean up.
+ */
+static void *APR_THREAD_FUNC motorz_poller_main(apr_thread_t *thread, void *baton)
+{
+ motorz_poller_t *poller = (motorz_poller_t *) baton;
+ motorz_core_t *mz = poller->mz;
+ apr_status_t status;
+
+ while (!die_now
+ && !mz->mpm->shutdown_pending
+ && !mz->mpm->restart_pending) {
+ apr_time_t tnow = apr_time_now();
+ motorz_timer_t *te;
+ apr_interval_time_t maxwait = apr_time_from_msec(draining ? 100 : 500);
+ apr_interval_time_t timeout = maxwait;
+
+ apr_thread_mutex_lock(poller->mtx);
+ te = apr_skiplist_peek(poller->timeout_ring);
+
+ if (te) {
+ if (tnow < te->expires) {
+ timeout = (te->expires - tnow);
+ if (timeout > maxwait) {
+ timeout = maxwait;
+ }
+ }
+ else {
+ timeout = 0;
+ }
+ }
+ apr_thread_mutex_unlock(poller->mtx);
+
+ status = motorz_pollset_cb(poller, timeout);
+ /* A full barrier (cas, with APR's atomic builtins): wakeups from here
+ * on are not coalesced away. */
+ apr_atomic_cas32(&poller->wake_pending, 0, 1);
+
+ tnow = apr_time_now();
+
+ if (status != APR_SUCCESS) {
+ if (!APR_STATUS_IS_EINTR(status) && !APR_STATUS_IS_TIMEUP(status)) {
+ ap_log_error(APLOG_MARK, APLOG_CRIT, status, NULL, APLOGNO(03117)
+ "motorz_main_loop: apr_pollcb_poll failed");
+ die_now = 1;
+ break;
+ }
+ }
+
+ apr_thread_mutex_lock(poller->mtx);
+
+ /* Now iterate any expired timers and push them to the worker
+ * pool. The loop is driven entirely off a fresh peek taken under
+ * the lock rather than the 'te' cached before the poll: while the
+ * lock was dropped for polling, a worker thread may have inserted
+ * a timer that is now the earliest in the ring. Peeking and
+ * popping the minimum in lock-step keeps the popped node and the
+ * processed node consistent.
+ */
+ while ((te = apr_skiplist_peek(poller->timeout_ring))
+ && te->expires < tnow) {
+ apr_skiplist_pop(poller->timeout_ring, NULL);
+ motorz_timer_event_process(poller, te);
+ }
+
+ apr_thread_mutex_unlock(poller->mtx);
+
+ /* Admission control (#1): pause/resume accepting based on worker-pool
+ * saturation. Done here, on the poll thread and outside poller->mtx,
+ * once per iteration. While listeners are disabled, a task ending or a
+ * connection closing wakes the loop (motorz_wake_admission()); the
+ * 500ms timeout floor covers anything else. No-op on pollers that do
+ * not own the listeners.
+ */
+ motorz_update_listeners(poller);
+
+ if (draining) {
+ motorz_close_listeners(poller);
+ while (motorz_drain_keepalives(poller) == MOTORZ_DRAIN_BATCH) {
+ /* more idle connections to close */
+ }
+ }
+ }
+
+ return NULL;
+}
+
+/* Begin a graceful stop: from here the child accepts nothing new, closes idle
+ * keep-alive connections, lets everything else finish, and exits when the last
+ * connection is gone (see motorz_supervise()). Runs on the supervisor thread.
+ * The core's keep-alive logic and mod_http2 see AP_MPMQ_STOPPING and wind
+ * their connections down.
+ */
+static void motorz_start_drain(motorz_core_t *mz)
+{
+ if (draining) {
+ return;
+ }
+ mz->mpm->mpm_state = AP_MPMQ_STOPPING;
+ draining = 1;
+ ap_scoreboard_image->parent[my_child_num].quiescing = 1;
+ ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, ap_server_conf, APLOGNO(10653)
+ "child draining: %u connection(s) open",
+ (unsigned)apr_atomic_read32(&conns_open));
+ ap_run_child_stopping(pchild, 1);
+}
+
+/* Child supervisor loop, run on the child's main thread while the poller
+ * threads do the I/O. Watches MaxConnectionsPerChild, the pipe-of-death,
+ * AP_SIG_GRACEFUL and the generation, and starts draining when any asks the
+ * child to stop. While draining it returns 1 once the listeners are closed and
+ * every connection is gone; die_now (SIGTERM) or the single-process
+ * shutdown/restart flags end it early, with 0, even mid-drain.
+ */
+static int motorz_supervise(motorz_core_t *mz)
+{
+ while (!die_now
+ && !mz->mpm->shutdown_pending
+ && !mz->mpm->restart_pending) {
+
+ if (draining) {
+ if (listeners_closed && apr_atomic_read32(&conns_open) == 0) {
+ return 1;
+ }
+ }
+ else {
+ /* requests_this_child is bumped per accepted connection by the
+ * listener-owning poller. The pod and generation checks are for
+ * a graceful restart or stop and an idle kill; a hard restart
+ * arrives as SIGHUP/SIGTERM and sets die_now directly.
+ */
+ if (graceful_requested
+ || (ap_max_requests_per_child > 0
+ && requests_this_child >= ap_max_requests_per_child)
+ || ap_mpm_pod_check(my_bucket->pod) == APR_SUCCESS
+ || mz->mpm->my_generation !=
+ ap_scoreboard_image->global->running_generation) {
+ motorz_start_drain(mz);
+ continue;
+ }
+ }
+
+ /* Nothing to do; sleep briefly so we don't spin. The pollers run
+ * independently, so the supervisor only needs coarse latency.
+ */
+ apr_sleep(apr_time_from_msec(100));
+ }
+ return 0;
+}
+
+static void child_main(motorz_core_t *mz, int child_num_arg, int child_bucket)
+{
+#if APR_HAS_THREADS
+ apr_thread_t *thd = NULL;
+ apr_os_thread_t osthd;
+#endif
+ apr_status_t status;
+ int i;
+ motorz_poller_t *poller;
+
+ /* for benefit of any hooks that run as this child initializes */
+ mz->mpm->mpm_state = AP_MPMQ_STARTING;
+
+ my_child_num = child_num_arg;
+ ap_my_pid = getpid();
+ requests_this_child = 0;
+
+ ap_fatal_signal_child_setup(ap_server_conf);
+
+ /* Get a sub context for global allocations in this child, so that
+ * we can have cleanups occur when the child exits.
+ */
+ apr_pool_create(&pchild, pconf);
+ apr_pool_tag(pchild, "pchild");
+
+#if APR_HAS_THREADS
+ osthd = apr_os_thread_current();
+ apr_os_thread_put(&thd, &osthd, pconf);
+#endif
+
+ /* close unused listeners and pods */
+ for (i = 0; i < mz->mpm->num_buckets; i++) {
+ if (i != child_bucket) {
+ ap_close_listeners_ex(all_buckets[i].listeners);
+ ap_mpm_pod_close(all_buckets[i].pod);
+ }
+ }
+
+ /* needs to be done before we switch UIDs so we have permissions; on
+ * pconf, as what the child keeps until it exits (pchild goes first)
+ */
+ ap_reopen_scoreboard(pconf, NULL, 0);
+
+ if (ap_run_drop_privileges(pconf, ap_server_conf)) {
+ clean_child_exit(APEXIT_CHILDFATAL);
+ }
+
+ ap_run_child_init(pchild, ap_server_conf);
+
+ /* One scoreboard slot per worker thread, all idle until used. */
+ status = apr_threadkey_private_create(&worker_slot_key, NULL, pchild);
+ if (status != APR_SUCCESS) {
+ ap_log_error(APLOG_MARK, APLOG_CRIT, status, ap_server_conf, APLOGNO(10654)
+ "child_main: apr_threadkey_private_create failed");
+ clean_child_exit(APEXIT_CHILDSICK);
+ }
+ next_worker_slot = 0;
+ worker_sbhs = apr_pcalloc(pchild, threads_per_child * sizeof(*worker_sbhs));
+ worker_slots = apr_pcalloc(pchild,
+ 2 * threads_per_child * sizeof(*worker_slots));
+ for (i = 0; i < threads_per_child; i++) {
+ ap_create_sb_handle(&worker_sbhs[i], pchild, my_child_num, i);
+ ap_update_child_status(worker_sbhs[i], SERVER_READY, NULL);
+ worker_slots[i].sbh = worker_sbhs[i];
+ worker_slots[i].thread = i;
+ worker_slots[i].sock_slot = i;
+ worker_slots[threads_per_child + i].sbh = worker_sbhs[i];
+ worker_slots[threads_per_child + i].thread = i;
+ worker_slots[threads_per_child + i].sock_slot = -1;
+ }
+ ap_worker_sockets_create(&worker_sockets, threads_per_child,
+ &workers_may_exit, pchild);
+
+ status = motorz_setup_workers(mz);
+ if (status != APR_SUCCESS) {
+ ap_log_error(APLOG_MARK, APLOG_CRIT, status, ap_server_conf, APLOGNO(02868)
+ "child_main: motorz_setup_workers failed");
+ clean_child_exit(APEXIT_CHILDSICK);
+ }
+
+ /* Admission-control hysteresis band: pause accepting once the pending
+ * backlog reaches a full wave (threads_per_child) and resume once it
+ * drains to 75%. The 75% low-water mark (vs. the old 50%) re-enables the
+ * listener sooner, reducing latency spikes at the cost of slightly more
+ * frequent enable/disable transitions -- a good trade under variable load.
+ */
+ motorz_throttle_hi = threads_per_child;
+ motorz_throttle_lo = (threads_per_child * 3) / 4;
+
+ /* Resolve the poller count: explicit PollersPerChild, else auto from online
+ * CPUs (capped). Never more pollers than worker threads, and at least 1.
+ */
+ mz->num_pollers = num_pollers;
+ if (mz->num_pollers <= 0) {
+#ifdef _SC_NPROCESSORS_ONLN
+ long ncpu = sysconf(_SC_NPROCESSORS_ONLN);
+ mz->num_pollers = (ncpu > 0) ? (int)ncpu : 1;
+#else
+ mz->num_pollers = 1;
+#endif
+ if (mz->num_pollers > MOTORZ_MAX_POLLERS) {
+ mz->num_pollers = MOTORZ_MAX_POLLERS;
+ }
+ }
+ if (mz->num_pollers > threads_per_child) {
+ mz->num_pollers = threads_per_child;
+ }
+ if (mz->num_pollers < 1) {
+ mz->num_pollers = 1;
+ }
+
+ /* Create N pollers, each on its own thread, supervised by this thread.
+ * Poller 0 owns the listening sockets (and thus does the accepting) and
+ * shards the accepted connections across all pollers.
+ */
+ mz->pollers = apr_pcalloc(mz->pool,
+ mz->num_pollers * sizeof(motorz_poller_t *));
+ for (i = 0; i < mz->num_pollers; i++) {
+ mz->pollers[i] = motorz_poller_create(mz, i);
+ }
+ /* Listeners live in poller 0. */
+ motorz_poller_add_listeners(mz->pollers[0]);
+
+ mz->mpm->mpm_state = AP_MPMQ_RUNNING;
+
+ /* die_now is set by SIGTERM/SIGHUP or a fatal error;
+ * {shutdown,restart}_pending are set when a signal is received while
+ * running in single process mode. A graceful stop sets draining instead.
+ */
+ for (i = 0; i < mz->num_pollers; i++) {
+ poller = mz->pollers[i];
+ status = apr_thread_create(&poller->thread, NULL,
+ motorz_poller_main, poller, pchild);
+ if (status != APR_SUCCESS) {
+ ap_log_error(APLOG_MARK, APLOG_EMERG, status, ap_server_conf, APLOGNO(10554)
+ "child_main: apr_thread_create failed for poller %d", i);
+ die_now = 1;
+ clean_child_exit(APEXIT_CHILDSICK);
+ }
+ }
+
+ /* Supervise on this thread; returns when the child should wind down. */
+ drain_completed = motorz_supervise(mz);
+
+ /* Set die_now so the pollers wind down, then join them so their
+ * pollsets/rings are quiescent before we tear the child down. This clears
+ * poller->thread so clean_child_exit()'s join is a no-op (no double
+ * pthread_join).
+ */
+ die_now = 1;
+ motorz_join_pollers(mz);
+
+ clean_child_exit(0);
+}
+
+static int make_child(motorz_core_t *mz, server_rec *s, int slot)
+{
+ int bucket = slot % mz->mpm->num_buckets;
+ int pid;
+
+ if (slot + 1 > mz->max_daemons_limit) {
+ mz->max_daemons_limit = slot + 1;
+ }
+
+ if (one_process) {
+ my_bucket = &all_buckets[0];
+
+ motorz_note_child_started(mz, slot, getpid());
+ child_main(mz, slot, 0);
+ /* NOTREACHED */
+ ap_assert(0);
+ return -1;
+ }
+
+ ap_update_child_status_from_indexes(slot, 0, SERVER_STARTING, NULL);
+
+ if ((pid = fork()) == -1) {
+ ap_log_error(APLOG_MARK, APLOG_ERR, errno, s, APLOGNO(02872) "fork: Unable to fork new process");
+
+ /* fork didn't succeed. Fix the scoreboard or else
+ * it will say SERVER_STARTING forever and ever
+ */
+ ap_update_child_status_from_indexes(slot, 0, SERVER_DEAD, NULL);
+
+ /* In case system resources are maxxed out, we don't want
+ * Apache running away with the CPU trying to fork over and
+ * over and over again.
+ */
+ sleep(10);
+
+ return -1;
+ }
+
+ if (!pid) {
+ my_bucket = &all_buckets[bucket];
+
+#ifdef HAVE_BINDPROCESSOR
+ /* by default AIX binds to a single processor
+ * this bit unbinds children which will then bind to another cpu
+ */
+ int status = bindprocessor(BINDPROCESS, (int)getpid(),
+ PROCESSOR_CLASS_ANY);
+ if (status != OK) {
+ ap_log_error(APLOG_MARK, APLOG_DEBUG, errno,
+ ap_server_conf, APLOGNO(02873) "processor unbind failed");
+ }
+#endif
+ RAISE_SIGSTOP(MAKE_CHILD);
+ AP_MONCONTROL(1);
+ /* Disable the parent's signal handlers and set up proper handling in
+ * the child.
+ */
+ apr_signal(SIGHUP, just_die);
+ apr_signal(SIGTERM, just_die);
+ /* Ignore SIGINT in child. This fixes race-condition in signals
+ * handling when httpd is running on foreground and user hits ctrl+c.
+ * In this case, SIGINT is sent to all children followed by SIGTERM
+ * from the main process, which interrupts the SIGINT handler and
+ * leads to inconsistency.
+ */
+ apr_signal(SIGINT, SIG_IGN);
+ /* The child process just closes listeners on AP_SIG_GRACEFUL.
+ * The pod is used for signalling the graceful restart.
+ */
+ apr_signal(AP_SIG_GRACEFUL, stop_listening);
+ child_main(mz, slot, bucket);
+ }
+
+ motorz_note_child_started(mz, slot, pid);
+
+ return 0;
+}
+
+
+/* Start up to number_to_start children in free scoreboard slots; returns how
+ * many were started. A slot is free when no child is recorded in it, so a
+ * previous generation that is still draining keeps its slot.
+ */
+static int startup_children(motorz_core_t *mz, int number_to_start)
+{
+ int i;
+ int started = 0;
+
+ for (i = 0; started < number_to_start && i < server_limit; ++i) {
+ if (ap_scoreboard_image->parent[i].pid != 0) {
+ continue;
+ }
+ if (make_child(mz, ap_server_conf, i) < 0) {
+ break;
+ }
+ ++started;
+ }
+ return started;
+}
+
+/* Keep StartServers children of the current generation running. A child
+ * counts from the moment it is forked (its pid is recorded then, well before
+ * it reports SERVER_READY), unless it has begun draining. At most one child is
+ * started per call; with no free slot nothing is started.
+ */
+static void perform_idle_server_maintenance(motorz_core_t *mz, apr_pool_t *p)
+{
+ static int no_slot_reported = 0; /* log once per episode */
+ int free_slot = -1;
+ int active = 0;
+ int draining_kids = 0;
+ int i;
+
+ for (i = 0; i < server_limit; ++i) {
+ process_score *ps = &ap_scoreboard_image->parent[i];
+
+ if (ps->pid == 0) {
+ if (free_slot < 0) {
+ free_slot = i;
+ }
+ }
+ else if (ps->generation == mz->mpm->my_generation && !ps->quiescing) {
+ active++;
+ }
+ else {
+ draining_kids++;
+ }
+ }
+
+ if (active > ap_num_kids) {
+ static int bucket_kill_child_record = -1;
+ /* kill off one child... we use the pod because that'll cause it to
+ * drain gracefully, in case it happened to pick up a request
+ * while we were counting
+ */
+ bucket_kill_child_record = (bucket_kill_child_record + 1) % mz->mpm->num_buckets;
+ ap_mpm_pod_signal(all_buckets[bucket_kill_child_record].pod);
+ }
+ else if (active < ap_num_kids && free_slot >= 0) {
+ make_child(mz, ap_server_conf, free_slot);
+ }
+
+ /* Draining children keep their slots, so with every slot taken nothing can
+ * start, and if no current child is left nothing accepts connections until
+ * an old one exits. Say so once, as mpm_event does.
+ */
+ if (active < ap_num_kids && free_slot < 0) {
+ if (!no_slot_reported) {
+ ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf, APLOGNO(10657)
+ "scoreboard is full, cannot start %d of %d child "
+ "process(es): %d of the %d slots are held by children "
+ "still draining connections after a restart. "
+ "Increase ServerLimit.",
+ ap_num_kids - active, ap_num_kids, draining_kids,
+ server_limit);
+ no_slot_reported = 1;
+ }
+ }
+ else {
+ no_slot_reported = 0;
+ }
+}
+
+/*****************************************************************
+ * Executive routines.
+ */
+
+static int motorz_run(apr_pool_t *_pconf, apr_pool_t *plog, server_rec *s)
+{
+ int index;
+ int remaining_children_to_start;
+ int i;
+ motorz_core_t *mz = motorz_core_get();
+
+ ap_log_pid(pconf, ap_pid_fname);
+
+ if (!mz->mpm->was_graceful) {
+ if (ap_run_pre_mpm(s->process->pool, SB_SHARED) != OK) {
+ mz->mpm->mpm_state = AP_MPMQ_STOPPING;
+ return !OK;
+ }
+ /* fix the generation number in the global score; we just got a new,
+ * cleared scoreboard
+ */
+ ap_scoreboard_image->global->running_generation = mz->mpm->my_generation;
+ }
+
+ ap_unixd_mpm_set_signals(pconf, one_process);
+
+ if (one_process) {
+ AP_MONCONTROL(1);
+ make_child(mz, ap_server_conf, 0);
+ /* NOTREACHED */
+ ap_assert(0);
+ return !OK;
+ }
+
+ /* Don't thrash since num_buckets depends on the
+ * system and the number of online CPU cores...
+ */
+ if (ap_num_kids < mz->mpm->num_buckets) {
+ ap_num_kids = mz->mpm->num_buckets;
+ if (ap_num_kids > server_limit) {
+ ap_num_kids = server_limit;
+ }
+ }
+
+ /* The new generation starts in the slots the previous one does not hold;
+ * ServerLimit leaves room for that while the old children drain. Any
+ * children that did not fit are started 1-for-1 as old ones exit (or after
+ * a quiet second), without the 1 second penalty between each fork.
+ */
+ remaining_children_to_start = ap_num_kids
+ - startup_children(mz, ap_num_kids);
+
+ ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, APLOGNO(02874)
+ "%s configured -- resuming normal operations",
+ ap_get_server_description());
+ ap_log_error(APLOG_MARK, APLOG_INFO, 0, ap_server_conf, APLOGNO(02875)
+ "Server built: %s", ap_get_server_built());
+ ap_log_command_line(plog, s);
+ ap_log_mpm_common(s);
+
+ mz->mpm->mpm_state = AP_MPMQ_RUNNING;
+
+ while (!mz->mpm->restart_pending && !mz->mpm->shutdown_pending) {
+ int child_slot;
+ apr_exit_why_e exitwhy;
+ int status, processed_status;
+ /* this is a memory leak, but I'll fix it later. */
+ apr_proc_t pid;
+
+ ap_wait_or_timeout(&exitwhy, &status, &pid, pconf, ap_server_conf);
+
+ /* XXX: if it takes longer than 1 second for all our children
+ * to start up and get into IDLE state then we may spawn an
+ * extra child
+ */
+ if (pid.pid != -1) {
+ processed_status = ap_process_child_status(&pid, exitwhy, status);
+ child_slot = ap_find_child_by_pid(&pid);
+ if (processed_status == APEXIT_CHILDFATAL) {
+ /* fix race condition found in PR 39311
+ * A child created at the same time as a graceful happens
+ * can find the lock missing and create a fatal error.
+ * It is not fatal for the last generation to be in this state.
+ */
+ if (child_slot < 0
+ || ap_get_scoreboard_process(child_slot)->generation
+ == mz->mpm->my_generation) {
+ mz->mpm->mpm_state = AP_MPMQ_STOPPING;
+ return !OK;
+ }
+ else {
+ ap_log_error(APLOG_MARK, APLOG_WARNING, 0, ap_server_conf, APLOGNO(02877)
+ "Ignoring fatal error in child of previous "
+ "generation (pid %ld).",
+ (long)pid.pid);
+ }
+ }
+
+ /* non-fatal death... note that it's gone in the scoreboard. */
+ if (child_slot >= 0) {
+ ap_update_child_status_from_indexes(child_slot, 0,
+ SERVER_DEAD, NULL);
+ motorz_note_child_killed(child_slot, 0, 0);
+ if (remaining_children_to_start
+ && child_slot < server_limit) {
+ /* we're still doing a 1-for-1 replacement of dead
+ * children with new children
+ */
+ make_child(mz, ap_server_conf, child_slot);
+ --remaining_children_to_start;
+ }
+#if APR_HAS_OTHER_CHILD
+ }
+ else if (apr_proc_other_child_alert(&pid, APR_OC_REASON_DEATH, status) == APR_SUCCESS) {
+ /* handled */
+#endif
+ }
+ else if (mz->mpm->was_graceful) {
+ /* Great, we've probably just lost a slot in the
+ * scoreboard. Somehow we don't know about this
+ * child.
+ */
+ ap_log_error(APLOG_MARK, APLOG_WARNING,
+ 0, ap_server_conf, APLOGNO(02878)
+ "long lost child came home! (pid %ld)", (long)pid.pid);
+ }
+ /* Don't perform idle maintenance when a child dies,
+ * only do it when there's a timeout. Remember only a
+ * finite number of children can die, and it's pretty
+ * pathological for a lot to die suddenly.
+ */
+ continue;
+ }
+ else if (remaining_children_to_start) {
+ /* we hit a 1 second timeout in which none of the previous
+ * generation of children needed to be reaped... so assume
+ * they're all done, and pick up the slack if any is left.
+ */
+ startup_children(mz, remaining_children_to_start);
+ remaining_children_to_start = 0;
+ /* In any event we really shouldn't do the code below because
+ * few of the servers we just started are in the IDLE state
+ * yet, so we'd mistakenly create an extra server.
+ */
+ continue;
+ }
+
+ perform_idle_server_maintenance(mz, pconf);
+ }
+
+ mz->mpm->mpm_state = AP_MPMQ_STOPPING;
+
+ if (mz->mpm->shutdown_pending && mz->mpm->is_ungraceful) {
+ /* Time to shut down:
+ * Kill child processes, tell them to call child_exit, etc...
+ */
+ if (ap_unixd_killpg(getpgrp(), SIGTERM) < 0) {
+ ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, APLOGNO(02879) "killpg SIGTERM");
+ }
+ ap_reclaim_child_processes(1, /* Start with SIGTERM */
+ motorz_note_child_killed);
+
+ /* cleanup pid file on normal shutdown */
+ ap_remove_pid(pconf, ap_pid_fname);
+ ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, APLOGNO(02880)
+ "caught SIGTERM, shutting down");
+
+ return DONE;
+ }
+
+ if (mz->mpm->shutdown_pending) {
+ /* Time to perform a graceful shut down:
+ * Reap the inactive children, and ask the active ones
+ * to close their listeners, then wait until they are
+ * all done to exit.
+ */
+ int active_children;
+ apr_time_t cutoff = 0;
+
+ /* Stop listening */
+ ap_close_listeners();
+
+ /* kill off the idle ones */
+ for (i = 0; i < mz->mpm->num_buckets; i++) {
+ ap_mpm_pod_killpg(all_buckets[i].pod, mz->max_daemons_limit);
+ }
+
+ /* Send SIGUSR1 to the active children */
+ active_children = 0;
+ for (index = 0; index < mz->max_daemons_limit; ++index) {
+ if (MPM_CHILD_PID(index) != 0) {
+ /* Ask each child to start draining. */
+ ap_mpm_safe_kill(MPM_CHILD_PID(index), AP_SIG_GRACEFUL);
+ active_children++;
+ }
+ }
+
+ /* Allow each child which actually finished to exit */
+ ap_relieve_child_processes(motorz_note_child_killed);
+
+ /* cleanup pid file */
+ ap_remove_pid(pconf, ap_pid_fname);
+ ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, APLOGNO(02881)
+ "caught " AP_SIG_GRACEFUL_STOP_STRING ", shutting down gracefully");
+
+ if (ap_graceful_shutdown_timeout) {
+ cutoff = apr_time_now() +
+ apr_time_from_sec(ap_graceful_shutdown_timeout);
+ }
+
+ /* Don't really exit until each child has finished */
+ mz->mpm->shutdown_pending = 0;
+ do {
+ /* Pause for a second */
+ sleep(1);
+
+ /* Relieve any children which have now exited */
+ ap_relieve_child_processes(motorz_note_child_killed);
+
+ active_children = 0;
+ for (index = 0; index < mz->max_daemons_limit; ++index) {
+ if (MPM_CHILD_PID(index) != 0
+ && ap_mpm_safe_kill(MPM_CHILD_PID(index), 0) == APR_SUCCESS) {
+ active_children = 1;
+ /* Having just one child is enough to stay around */
+ break;
+ }
+ }
+ } while (!mz->mpm->shutdown_pending && active_children &&
+ (!ap_graceful_shutdown_timeout || apr_time_now() < cutoff));
+
+ /* We might be here because we received SIGTERM, either
+ * way, try and make sure that all of our processes are
+ * really dead.
+ */
+ ap_unixd_killpg(getpgrp(), SIGTERM);
+
+ return DONE;
+ }
+
+ /* we've been told to restart */
+ if (one_process) {
+ /* not worth thinking about */
+ return DONE;
+ }
+
+ /* advance to the next generation */
+ /* XXX: we really need to make sure this new generation number isn't in
+ * use by any of the children.
+ */
+ ++mz->mpm->my_generation;
+ ap_scoreboard_image->global->running_generation = mz->mpm->my_generation;
+
+ if (!mz->mpm->is_ungraceful) {
+ ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, APLOGNO(02882)
+ "Graceful restart requested, doing restart");
+
+ /* kill off the idle ones */
+ for (i = 0; i < mz->mpm->num_buckets; i++) {
+ ap_mpm_pod_killpg(all_buckets[i].pod, mz->max_daemons_limit);
+ }
+
+ /* This is mostly for debugging... so that we know what is still
+ * gracefully dealing with existing request. This will break
+ * in a very nasty way if we ever have the scoreboard totally
+ * file-based (no shared memory)
+ */
+ for (index = 0; index < mz->max_daemons_limit; ++index) {
+ if (MPM_CHILD_PID(index) != 0) {
+ ap_scoreboard_image->servers[index][0].status = SERVER_GRACEFUL;
+ /* Ask each child to start draining.
+ *
+ * NOTE: we use the scoreboard, because if we send SIGUSR1
+ * to every process in the group, this may include CGI's,
+ * piped loggers, etc. They almost certainly won't handle
+ * it gracefully.
+ */
+ ap_mpm_safe_kill(ap_scoreboard_image->parent[index].pid, AP_SIG_GRACEFUL);
+ }
+ }
+ }
+ else {
+ /* Kill 'em off */
+ if (ap_unixd_killpg(getpgrp(), SIGHUP) < 0) {
+ ap_log_error(APLOG_MARK, APLOG_WARNING, errno, ap_server_conf, APLOGNO(02883) "killpg SIGHUP");
+ }
+ ap_reclaim_child_processes(0, /* Not when just starting up */
+ motorz_note_child_killed);
+ ap_log_error(APLOG_MARK, APLOG_NOTICE, 0, ap_server_conf, APLOGNO(02884)
+ "SIGHUP received. Attempting to restart");
+ }
+
+ return OK;
+}
+
+/* This really should be a post_config hook, but the error log is already
+ * redirected by that point, so we need to do this in the open_logs phase.
+ */
+static int motorz_open_logs(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s)
+{
+ int startup = 0;
+ int level_flags = 0;
+ ap_listen_rec **listen_buckets;
+ apr_status_t rv;
+ int i;
+
+ motorz_core_t *mz = motorz_core_get();
+ pconf = p;
+
+ /* the reverse of pre_config, we want this only the first time around */
+ if (mz->mpm->module_loads == 1) {
+ startup = 1;
+ level_flags |= APLOG_STARTUP;
+ }
+
+ if ((num_listensocks = ap_setup_listeners(ap_server_conf)) < 1) {
+ ap_log_error(APLOG_MARK, APLOG_ALERT | level_flags, 0,
+ (startup ? NULL : s), APLOGNO(03275)
+ "no listening sockets available, shutting down");
+ return !OK;
+ }
+
+ if (one_process) {
+ mz->mpm->num_buckets = 1;
+ }
+ else if (!mz->mpm->was_graceful) {
+ /* Preserve the number of buckets on graceful restarts. */
+ mz->mpm->num_buckets = 0;
+ }
+ if ((rv = ap_duplicate_listeners(pconf, ap_server_conf,
+ &listen_buckets, &mz->mpm->num_buckets))) {
+ ap_log_error(APLOG_MARK, APLOG_CRIT | level_flags, rv,
+ (startup ? NULL : s), APLOGNO(03276)
+ "could not duplicate listeners");
+ return !OK;
+ }
+ /* Every bucket needs a child. The scoreboard is sized from server_limit
+ * when it is created, on the first start only: after that a hard restart
+ * reuses it, so the buckets have to fit in it.
+ */
+ if (server_limit < mz->mpm->num_buckets) {
+ if (!ap_scoreboard_image) {
+ server_limit = mz->first_server_limit = mz->mpm->num_buckets;
+ }
+ else {
+ ap_listen_rec *lr;
+
+ ap_log_error(APLOG_MARK, APLOG_WARNING | level_flags, 0,
+ (startup ? NULL : s), APLOGNO(10680)
+ "ServerLimit of %d cannot be raised on a restart: "
+ "using %d listener buckets instead of %d",
+ server_limit, server_limit, mz->mpm->num_buckets);
+ /* Close the surplus duplicates, or the kernel keeps handing them
+ * connections that nobody accepts. */
+ for (i = server_limit; i < mz->mpm->num_buckets; i++) {
+ for (lr = listen_buckets[i]; lr; lr = lr->next) {
+ apr_socket_close(lr->sd);
+ }
+ }
+ mz->mpm->num_buckets = ap_num_listen_buckets = server_limit;
+ }
+ }
+ all_buckets = apr_pcalloc(pconf, mz->mpm->num_buckets *
+ sizeof(motorz_child_bucket));
+ for (i = 0; i < mz->mpm->num_buckets; i++) {
+ if ((rv = ap_mpm_pod_open(pconf, &all_buckets[i].pod))) {
+ ap_log_error(APLOG_MARK, APLOG_CRIT | level_flags, rv,
+ (startup ? NULL : s), APLOGNO(03277)
+ "could not open pipe-of-death");
+ return !OK;
+ }
+ all_buckets[i].listeners = listen_buckets[i];
+ }
+
+ return OK;
+}
+
+static int motorz_pre_config(apr_pool_t *p, apr_pool_t *plog, apr_pool_t *ptemp)
+{
+ int no_detach, debug, foreground;
+ apr_status_t rv;
+ const char *userdata_key = "mpm_motorz_module";
+ motorz_core_t *mz;
+
+ debug = ap_exists_config_define("DEBUG");
+
+ if (debug) {
+ foreground = one_process = 1;
+ no_detach = 0;
+ }
+ else
+ {
+ no_detach = ap_exists_config_define("NO_DETACH");
+ one_process = ap_exists_config_define("ONE_PROCESS");
+ foreground = ap_exists_config_define("FOREGROUND");
+ }
+
+ /* motorz never serializes accept() (the listening sockets are non-blocking
+ * and polled), so there is no accept mutex to create. The type is still
+ * registered so that an existing "Mutex accept ..." line keeps parsing.
+ */
+ ap_mutex_register(p, AP_ACCEPT_MUTEX_TYPE, NULL, APR_LOCK_DEFAULT, 0);
+
+ mz = g_motorz_core = ap_retained_data_get(userdata_key);
+ if (!g_motorz_core) {
+ mz = g_motorz_core = ap_retained_data_create(userdata_key, sizeof(*g_motorz_core));
+ mz->mpm = ap_unixd_mpm_get_retained_data();
+ mz->mpm->baton = mz;
+ mz->max_daemons_limit = -1;
+ /* Pollsets, timer rings and their mutexes are now per-poller and are
+ * created per child in motorz_poller_create(); nothing to seed here.
+ */
+ }
+ else if (mz->mpm->baton != mz) {
+ /* If the MPM changes on restart, be ungraceful */
+ mz->mpm->baton = mz;
+ mz->mpm->was_graceful = 0;
+ }
+ mz->mpm->mpm_state = AP_MPMQ_STARTING;
+ ++mz->mpm->module_loads;
+
+ /* sigh, want this only the second time around */
+ if (mz->mpm->module_loads == 2) {
+ if (!one_process && !foreground) {
+ /* before we detach, setup crash handlers to log to errorlog */
+ ap_fatal_signal_setup(ap_server_conf, p /* pconf */);
+ rv = apr_proc_detach(no_detach ? APR_PROC_DETACH_FOREGROUND
+ : APR_PROC_DETACH_DAEMONIZE);
+ if (rv != APR_SUCCESS) {
+ ap_log_error(APLOG_MARK, APLOG_CRIT, rv, NULL, APLOGNO(02885)
+ "apr_proc_detach failed");
+ return HTTP_INTERNAL_SERVER_ERROR;
+ }
+ }
+ apr_pool_create(&mz->pool, ap_pglobal);
+ apr_pool_tag(mz->pool, "motorz-mpm-core");
+ /* Per-poller ring mutexes are created in motorz_poller_create(). */
+ }
+
+ parent_pid = ap_my_pid = getpid();
+
+ ap_listen_pre_config();
+ /* Back to the defaults for every directive, so that one removed before a
+ * restart does not keep its old value (a static MPM is not reloaded). */
+ ap_num_kids = DEFAULT_START_DAEMON;
+ threads_per_child = DEFAULT_THREADS_PER_CHILD;
+ thread_limit = DEFAULT_THREAD_LIMIT;
+ server_limit = 0;
+ num_pollers = 0;
+ worker_factor = DEFAULT_WORKER_FACTOR * WORKER_FACTOR_SCALE;
+ ap_extended_status = 0;
+
+ return OK;
+}
+
+static int motorz_check_config(apr_pool_t *p, apr_pool_t *plog,
+ apr_pool_t *ptemp, server_rec *s)
+{
+ int startup = 0;
+ motorz_core_t *mz = motorz_core_get();
+
+ /* the reverse of pre_config, we want this only the first time around */
+ if (mz->mpm->module_loads == 1) {
+ startup = 1;
+ }
+
+ if (ap_num_kids < 1) {
+ if (startup) {
+ ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(02888)
+ "WARNING: StartServers of %d not allowed, "
+ "increasing to 1.", ap_num_kids);
+ } else {
+ ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(02889)
+ "StartServers of %d not allowed, increasing to 1",
+ ap_num_kids);
+ }
+ ap_num_kids = 1;
+ }
+
+ if (thread_limit > MAX_THREAD_LIMIT) {
+ if (startup) {
+ ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(10015)
+ "WARNING: ThreadLimit of %d exceeds compile-time "
+ "limit of %d threads, decreasing to %d.",
+ thread_limit, MAX_THREAD_LIMIT, MAX_THREAD_LIMIT);
+ } else {
+ ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(10016)
+ "ThreadLimit of %d exceeds compile-time limit "
+ "of %d, decreasing to match",
+ thread_limit, MAX_THREAD_LIMIT);
+ }
+ thread_limit = MAX_THREAD_LIMIT;
+ }
+ else if (thread_limit < 1) {
+ if (startup) {
+ ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(10017)
+ "WARNING: ThreadLimit of %d not allowed, "
+ "increasing to 1.", thread_limit);
+ } else {
+ ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(10018)
+ "ThreadLimit of %d not allowed, increasing to 1",
+ thread_limit);
+ }
+ thread_limit = 1;
+ }
+
+ /* The scoreboard is sized from ServerLimit and ThreadLimit once, when it
+ * is first created, and survives graceful restarts, so neither can change
+ * afterwards.
+ */
+ if (!mz->first_thread_limit) {
+ mz->first_thread_limit = thread_limit;
+ }
+ else if (thread_limit != mz->first_thread_limit) {
+ ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(10645)
+ "changing ThreadLimit to %d from original value of %d "
+ "not allowed during restart",
+ thread_limit, mz->first_thread_limit);
+ thread_limit = mz->first_thread_limit;
+ }
+
+ if (server_limit == 0) {
+ /* Not configured: twice StartServers, but at least
+ * DEFAULT_SERVER_LIMIT, so that new generations can start while
+ * several earlier ones still drain, and then whatever the first
+ * startup chose.
+ */
+ if (mz->first_server_limit) {
+ server_limit = mz->first_server_limit;
+ }
+ else if (ap_num_kids > MAX_SERVER_LIMIT / 2) {
+ server_limit = MAX_SERVER_LIMIT;
+ }
+ else {
+ server_limit = 2 * ap_num_kids;
+ if (server_limit < DEFAULT_SERVER_LIMIT) {
+ server_limit = DEFAULT_SERVER_LIMIT;
+ }
+ }
+ }
+ else {
+ if (server_limit > MAX_SERVER_LIMIT) {
+ if (startup) {
+ ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(10647)
+ "WARNING: ServerLimit of %d exceeds compile-time "
+ "limit of %d servers, decreasing to %d.",
+ server_limit, MAX_SERVER_LIMIT, MAX_SERVER_LIMIT);
+ } else {
+ ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(10648)
+ "ServerLimit of %d exceeds compile-time limit "
+ "of %d, decreasing to match",
+ server_limit, MAX_SERVER_LIMIT);
+ }
+ server_limit = MAX_SERVER_LIMIT;
+ }
+ else if (server_limit < 1) {
+ if (startup) {
+ ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(10649)
+ "WARNING: ServerLimit of %d not allowed, "
+ "increasing to 1.", server_limit);
+ } else {
+ ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(10650)
+ "ServerLimit of %d not allowed, increasing to 1",
+ server_limit);
+ }
+ server_limit = 1;
+ }
+
+ if (mz->first_server_limit && server_limit != mz->first_server_limit) {
+ ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(10646)
+ "changing ServerLimit to %d from original value of "
+ "%d not allowed during restart",
+ server_limit, mz->first_server_limit);
+ server_limit = mz->first_server_limit;
+ }
+ }
+ if (!mz->first_server_limit) {
+ mz->first_server_limit = server_limit;
+ }
+
+ if (ap_num_kids > server_limit) {
+ if (startup) {
+ ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(10651)
+ "WARNING: StartServers of %d exceeds ServerLimit "
+ "of %d, decreasing to %d.",
+ ap_num_kids, server_limit, server_limit);
+ } else {
+ ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(10652)
+ "StartServers of %d exceeds ServerLimit of %d, "
+ "decreasing to match",
+ ap_num_kids, server_limit);
+ }
+ ap_num_kids = server_limit;
+ }
+
+ if (threads_per_child > thread_limit) {
+ if (startup) {
+ ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(03336)
+ "WARNING: ThreadsPerChild of %d exceeds run-time "
+ "limit of", threads_per_child);
+ ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(03337)
+ " %d servers, decreasing to %d.",
+ thread_limit, thread_limit);
+ } else {
+ ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(03338)
+ "ThreadsPerChild of %d exceeds run-time limit "
+ "of %d, decreasing to match",
+ threads_per_child, thread_limit);
+ }
+ threads_per_child = thread_limit;
+ }
+ else if (threads_per_child < 1) {
+ if (startup) {
+ ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL, APLOGNO(03339)
+ "WARNING: ThreadsPerChild of %d not allowed, "
+ "increasing to 1.", threads_per_child);
+ } else {
+ ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(03340)
+ "ThreadsPerChild of %d not allowed, increasing to 1",
+ threads_per_child);
+ }
+ threads_per_child = 1;
+ }
+
+ /* Warn about ThreadsPerChild 1: the admission-control low-water mark
+ * becomes (1*3)/4 = 0, so listeners only re-enable when the task queue
+ * is completely empty, causing severe throughput degradation under any
+ * sustained load. ThreadsPerChild >= 4 is strongly recommended.
+ */
+ if (threads_per_child == 1) {
+ if (startup) {
+ ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
+ APLOGNO(10555)
+ "WARNING: ThreadsPerChild 1 causes severe throughput "
+ "degradation in motorz due to admission-control "
+ "hysteresis. Use ThreadsPerChild >= 4.");
+ }
+ else {
+ ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(10556)
+ "ThreadsPerChild 1 causes severe throughput "
+ "degradation in motorz. Use ThreadsPerChild >= 4.");
+ }
+ }
+
+ /* The request-processing threads belong to an APR thread pool, which has no
+ * way to give them a stack size, so ThreadStackSize cannot be honoured.
+ */
+ if (ap_thread_stacksize != 0) {
+ if (startup) {
+ ap_log_error(APLOG_MARK, APLOG_WARNING | APLOG_STARTUP, 0, NULL,
+ APLOGNO(10655)
+ "WARNING: ThreadStackSize is not supported by "
+ "mpm_motorz and is ignored.");
+ }
+ else {
+ ap_log_error(APLOG_MARK, APLOG_WARNING, 0, s, APLOGNO(10656)
+ "ThreadStackSize is not supported by mpm_motorz and "
+ "is ignored");
+ }
+ }
+
+ return OK;
+}
+
+/* A secondary (e.g. mod_http2 c2) connection is created as a copy of its
+ * master, so it points at the master's conn_state_t. It is processed on its
+ * own thread and writes its state when a request ends (c->cs->state =
+ * WRITE_COMPLETION, or LINGER if it was aborted), which would clobber the
+ * state the master parked in the MPM (e.g. ASYNC_WAITIO) and make the next
+ * dispatch lingering-close a live connection. Give it a private state, and
+ * keep it from inheriting the master's motorz_conn_t, as mpm_event does.
+ */
+static int motorz_pre_connection(conn_rec *c, void *csd)
+{
+ if (c->master && (!c->cs || c->cs == c->master->cs)) {
+ conn_state_t *cs = apr_pcalloc(c->pool, sizeof(*cs));
+
+ cs->state = CONN_STATE_PROCESSING;
+ cs->sense = CONN_SENSE_DEFAULT;
+ c->cs = cs;
+ ap_set_module_config(c->conn_config, &mpm_motorz_module, NULL);
+ }
+ return OK;
+}
+
+static void motorz_hooks(apr_pool_t *p)
+{
+ /* Our open_logs hook function must run before the core's, or stderr
+ * will be redirected to a file, and the messages won't print to the
+ * console.
+ */
+ static const char *const aszSucc[] = {"core.c", NULL};
+
+ ap_hook_open_logs(motorz_open_logs, NULL, aszSucc, APR_HOOK_REALLY_FIRST);
+ /* we need to set the MPM state before other pre-config hooks use MPM query
+ * to retrieve it, so register as REALLY_FIRST
+ */
+ ap_hook_pre_config(motorz_pre_config, NULL, NULL, APR_HOOK_REALLY_FIRST);
+ ap_hook_check_config(motorz_check_config, NULL, NULL, APR_HOOK_MIDDLE);
+ ap_hook_mpm(motorz_run, NULL, NULL, APR_HOOK_MIDDLE);
+ ap_hook_mpm_query(motorz_query, NULL, NULL, APR_HOOK_MIDDLE);
+ ap_hook_mpm_get_name(motorz_get_name, NULL, NULL, APR_HOOK_MIDDLE);
+ ap_hook_pre_read_request(motorz_pre_read_request, NULL, NULL,
+ APR_HOOK_MIDDLE);
+ ap_hook_pre_connection(motorz_pre_connection, NULL, NULL,
+ APR_HOOK_REALLY_FIRST);
+}
+
+static const char *set_daemons_to_start(cmd_parms *cmd, void *dummy, const char *arg)
+{
+ const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
+ if (err != NULL) {
+ return err;
+ }
+ ap_num_kids = atoi(arg);
+ return NULL;
+}
+
+static const char *set_threads_per_child(cmd_parms * cmd, void *dummy,
+ const char *arg)
+{
+ const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
+ if (err != NULL) {
+ return err;
+ }
+ threads_per_child = atoi(arg);
+ return NULL;
+}
+
+static const char *set_thread_limit (cmd_parms *cmd, void *dummy, const char *arg)
+{
+ const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
+ if (err != NULL) {
+ return err;
+ }
+
+ thread_limit = atoi(arg);
+ return NULL;
+}
+
+static const char *set_server_limit(cmd_parms *cmd, void *dummy, const char *arg)
+{
+ const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
+ if (err != NULL) {
+ return err;
+ }
+
+ server_limit = atoi(arg);
+ return NULL;
+}
+
+static const char *set_pollers_per_child(cmd_parms *cmd, void *dummy,
+ const char *arg)
+{
+ const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
+ if (err != NULL) {
+ return err;
+ }
+ num_pollers = atoi(arg);
+ return NULL;
+}
+
+static const char *set_worker_factor(cmd_parms *cmd, void *dummy,
+ const char *arg)
+{
+ double val;
+ char *endptr;
+ const char *err = ap_check_cmd_context(cmd, GLOBAL_ONLY);
+
+ if (err != NULL) {
+ return err;
+ }
+
+ val = strtod(arg, &endptr);
+ if (*endptr) {
+ return "error parsing value";
+ }
+ if (val <= 0) {
+ return "AsyncRequestWorkerFactor argument must be a positive number";
+ }
+
+ worker_factor = val * WORKER_FACTOR_SCALE;
+ if (worker_factor < WORKER_FACTOR_SCALE) {
+ worker_factor = WORKER_FACTOR_SCALE;
+ }
+ return NULL;
+}
+
+static const command_rec motorz_cmds[] = {
+LISTEN_COMMANDS,
+AP_INIT_TAKE1("StartServers", set_daemons_to_start, NULL, RSRC_CONF,
+ "Number of child processes launched at server startup"),
+AP_INIT_TAKE1("ThreadsPerChild", set_threads_per_child, NULL, RSRC_CONF,
+ "Number of threads each child creates"),
+AP_INIT_TAKE1("ServerLimit", set_server_limit, NULL, RSRC_CONF,
+ "Maximum number of child processes for this run of Apache - Upper limit for StartServers (default: the larger of 16 and twice StartServers)"),
+AP_INIT_TAKE1("ThreadLimit", set_thread_limit, NULL, RSRC_CONF,
+ "Maximum number of worker threads per child process for this run of Apache - Upper limit for ThreadsPerChild"),
+AP_INIT_TAKE1("PollersPerChild", set_pollers_per_child, NULL, RSRC_CONF,
+ "Number of poll threads per child process (0 = auto from online CPUs)"),
+AP_INIT_TAKE1("AsyncRequestWorkerFactor", set_worker_factor, NULL, RSRC_CONF,
+ "Limit concurrent connections per process: ThreadsPerChild plus this factor times the number of idle workers"),
+AP_GRACEFUL_SHUTDOWN_TIMEOUT_COMMAND,
+{ NULL }
+};
+
+AP_DECLARE_MODULE(mpm_motorz) = {
+ MPM20_MODULE_STUFF,
+ NULL, /* hook to run before apache parses args */
+ NULL, /* create per-directory config structure */
+ NULL, /* merge per-directory config structures */
+ NULL, /* create per-server config structure */
+ NULL, /* merge per-server config structures */
+ motorz_cmds, /* command apr_table_t */
+ motorz_hooks, /* register hooks */
+};
diff --git a/server/mpm/motorz/motorz.h b/server/mpm/motorz/motorz.h
new file mode 100644
index 00000000000..b3fbe292142
--- /dev/null
+++ b/server/mpm/motorz/motorz.h
@@ -0,0 +1,256 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "apr.h"
+#include "apr_atomic.h"
+#include "apr_portable.h"
+#include "apr_strings.h"
+#include "apr_thread_proc.h"
+#include "apr_signal.h"
+
+#define APR_WANT_STDIO
+#define APR_WANT_STRFUNC
+#include "apr_want.h"
+
+#if APR_HAVE_UNISTD_H
+#include
+#endif
+#if APR_HAVE_SYS_TYPES_H
+#include
+#endif
+
+#include "ap_config.h"
+#include "httpd.h"
+#include "mpm_default.h"
+#include "http_main.h"
+#include "http_log.h"
+#include "http_config.h"
+#include "http_core.h" /* for get_remote_host */
+#include "http_protocol.h" /* for pre_read_request hook */
+#include "http_connection.h"
+#include "scoreboard.h"
+#include "ap_mpm.h"
+#include "util_mutex.h"
+#include "unixd.h"
+#include "http_vhost.h"
+#include "mpm_common.h"
+#include "ap_listen.h"
+#include "ap_mmn.h"
+#include "apr_poll.h"
+#include "apr_skiplist.h"
+#include "apr_thread_pool.h"
+#include "util_time.h"
+
+#include
+
+#ifdef HAVE_TIME_H
+#include
+#endif
+#ifdef HAVE_SYS_PROCESSOR_H
+#include /* for bindprocessor() */
+#endif
+
+#include
+#include
+
+/* Admin can't tune ServerLimit beyond MAX_SERVER_LIMIT. We want
+ * some sort of compile-time limit to help catch typos, and to keep the
+ * scoreboard small enough that we can read the whole thing without worrying
+ * too much about the overhead.
+ */
+#ifndef MAX_SERVER_LIMIT
+#define MAX_SERVER_LIMIT 200000
+#endif
+
+/* ServerLimit defaults to the larger of this and twice StartServers. A graceful
+ * restart leaves the old children in their slots until their connections are
+ * done, and no replacement can start while every slot is taken, so the default
+ * must leave room for several restarts in a row.
+ */
+#ifndef DEFAULT_SERVER_LIMIT
+#define DEFAULT_SERVER_LIMIT 16
+#endif
+
+/* Limit on the threads per process. Clients will be locked out if more than
+ * this are needed.
+ *
+ * We keep this for one reason it keeps the size of the scoreboard file small
+ * enough that we can read the whole thing without worrying too much about
+ * the overhead.
+ */
+#ifndef DEFAULT_THREAD_LIMIT
+#define DEFAULT_THREAD_LIMIT 64
+#endif
+
+/* Admin can't tune ThreadLimit beyond MAX_THREAD_LIMIT. We want
+ * some sort of compile-time limit to help catch typos.
+ */
+#ifndef MAX_THREAD_LIMIT
+#define MAX_THREAD_LIMIT 100000
+#endif
+
+#define MPM_CHILD_PID(i) (ap_scoreboard_image->parent[i].pid)
+
+/**
+ * typedefs
+ */
+/* data retained by prefork across load/unload of the module
+ * allocated on first call to pre-config hook; located on
+ * subsequent calls to pre-config hook
+ */
+typedef struct motorz_poller_t motorz_poller_t;
+
+typedef struct motorz_core_t motorz_core_t;
+struct motorz_core_t {
+ ap_unixd_mpm_retained_data *mpm;
+
+ /* ServerLimit/ThreadLimit as first configured: the scoreboard is sized
+ * from them once and survives graceful restarts, so they cannot change.
+ */
+ int first_server_limit;
+ int first_thread_limit;
+ int maxclients_reported;
+ /*
+ * The max child slot ever assigned, preserved across restarts. Necessary
+ * to deal with MaxRequestWorkers changes across AP_SIG_GRACEFUL restarts. We
+ * use this value to optimize routines that have to scan the entire scoreboard.
+ */
+ int max_daemons_limit;
+ apr_pool_t *pool;
+ /* Worker thread pool, shared by all pollers in this child. */
+ apr_thread_pool_t *workers;
+ /* Per-child array of pollers. Each owns its own pollset + timer ring +
+ * recycle list, so the single-poll-thread throughput ceiling scales with
+ * num_pollers. A connection is bound to one poller for its lifetime
+ * (scon->poller) and always re-arms there. See MOTORZ.README.
+ */
+ motorz_poller_t **pollers;
+ int num_pollers;
+};
+
+typedef struct motorz_recycled_pool motorz_recycled_pool;
+struct motorz_recycled_pool {
+ apr_pool_t *pool;
+ motorz_recycled_pool *next;
+};
+
+/* One poll thread's context. Each poller owns its pollset, timer ring and the
+ * mutex guarding that ring, plus its own lock-free transaction-pool recycle
+ * list and listener-admission state -- so pollers do not contend with each
+ * other. A connection is permanently bound to the poller that accepted it
+ * (scon->poller), which is what makes connection sharding across pollers
+ * correct: it always re-arms in, and recycles to, its own poller.
+ */
+struct motorz_poller_t {
+ motorz_core_t *mz; /* back-pointer to the shared child core */
+ int index; /* 0 .. num_pollers-1 */
+ apr_pool_t *pool; /* subpool of mz->pool for this poller */
+ apr_thread_t *thread; /* the poll thread running motorz_poller_main */
+ apr_pool_t *pollset_pool; /* see motorz_poller_create */
+ apr_pollset_t *pollset;
+ apr_skiplist *timeout_ring;
+ apr_thread_mutex_t *mtx; /* guards this poller's timeout_ring */
+ /* Lock-free (CAS) recycle free-list: multi-producer push (any worker), but
+ * single-consumer pop (THIS poller's thread only) -- the same MPSC
+ * contract as mpm_fdqueue.c's ap_queue_info_{push,pop}_pool.
+ */
+ struct motorz_recycled_pool *volatile recycled_pools;
+ apr_uint32_t num_recycled;
+ /* Listener admission control (poller that owns the listeners only). */
+ apr_pollfd_t **listener_pfds;
+ int num_listener_pfds;
+ int listeners_disabled;
+ apr_uint32_t admission_paused; /* listeners_disabled, for the workers */
+ apr_uint32_t wake_pending; /* a wakeup is sent and not yet seen */
+ apr_time_t last_enable_failure; /* rate limits the error for it */
+};
+
+typedef struct motorz_child_bucket motorz_child_bucket;
+struct motorz_child_bucket {
+ ap_pod_t *pod;
+ ap_listen_rec *listeners;
+};
+
+typedef enum
+{
+ PT_CSD,
+ PT_ACCEPT,
+ PT_USER
+} motorz_poll_type_e;
+
+typedef struct motorz_sb_t motorz_sb_t;
+struct motorz_sb_t
+{
+ motorz_poll_type_e type;
+ void *baton;
+};
+
+typedef void (*motorz_timer_cb) (motorz_core_t *mz, void *baton);
+typedef void (*motorz_io_sock_cb) (motorz_core_t *mz, apr_socket_t *sock,
+ int flags, void *baton);
+typedef void (*motorz_io_file_cb) (motorz_core_t *mz, apr_socket_t *sock,
+ int flags, void *baton);
+
+
+typedef struct motorz_timer_t motorz_timer_t;
+struct motorz_timer_t
+{
+ apr_time_t expires;
+ motorz_timer_cb cb;
+ void *baton;
+ apr_pool_t *pool;
+ motorz_core_t *mz;
+ motorz_poller_t *poller; /* the poller whose ring this timer is in */
+};
+
+typedef struct motorz_conn_t motorz_conn_t;
+struct motorz_conn_t
+{
+ apr_pool_t *pool;
+ motorz_core_t *mz;
+ /* The poller this connection does its I/O on for its whole lifetime: it
+ * re-arms in, and times out on, this poller's pollset/ring. Sharded across
+ * pollers at accept time to spread load. */
+ motorz_poller_t *poller;
+ /* The poller that owns this connection's transaction-pool recycling -- the
+ * poller that accepted it (and popped its ptrans). Recycling must return to
+ * the same single-consumer free-list it came from, which (unlike I/O) is
+ * NOT sharded: only the accepting poller pops, so only it may be the home.
+ */
+ motorz_poller_t *pool_poller;
+ apr_socket_t *sock;
+ apr_bucket_alloc_t *ba;
+ ap_sb_handle_t *sbh;
+ /** connection record this struct refers to */
+ conn_rec *c;
+ /** request record (if any) this struct refers to */
+ request_rec *r;
+ /** is the current conn_rec suspended by a module? (atomic: set by the
+ * worker that parks it, cleared by whoever hands it back) */
+ apr_uint32_t suspended;
+ /** suspend_connection hooks ran and the resume_connection ones have not */
+ int suspend_notified;
+ /** has ap_start_lingering_close() been called for this conn? */
+ int linger_started;
+ /** absolute end of the lingering close; set once, only ever shortened */
+ apr_time_t linger_deadline;
+ /** poll file descriptor information */
+ apr_pollfd_t pfd;
+ /** public parts of the connection state */
+ conn_state_t cs;
+ /** timer associated with the connection */
+ motorz_timer_t timer;
+};
diff --git a/server/mpm/motorz/mpm_default.h b/server/mpm/motorz/mpm_default.h
new file mode 100644
index 00000000000..9bc59f0ae66
--- /dev/null
+++ b/server/mpm/motorz/mpm_default.h
@@ -0,0 +1,36 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @file motorz/mpm_default.h
+ * @brief MotorZ MPM defaults
+ *
+ * @defgroup APACHE_MPM_MOTORZ MotorZ MPM
+ * @ingroup APACHE_INTERNAL
+ * @{
+ */
+
+#ifndef APACHE_MPM_DEFAULT_H
+#define APACHE_MPM_DEFAULT_H
+
+/* Number of servers to spawn off by default ---
+ */
+#ifndef DEFAULT_START_DAEMON
+#define DEFAULT_START_DAEMON 2
+#endif
+
+#endif /* AP_MPM_DEFAULT_H */
+/** @} */
diff --git a/server/mpm/motorz/test/README.md b/server/mpm/motorz/test/README.md
new file mode 100644
index 00000000000..0e405fe7b99
--- /dev/null
+++ b/server/mpm/motorz/test/README.md
@@ -0,0 +1,186 @@
+# motorz MPM test harness
+
+Self-contained smoke / regression tests for the **motorz** MPM
+(`server/mpm/motorz/motorz.c`). These drive a real `httpd` built from this tree
+against a throwaway `ServerRoot` in a temp dir; nothing is installed and no
+existing config is touched.
+
+## Build & configure (do this first)
+
+The tests run a real `httpd` built from this tree. The easiest way to get a
+correctly-configured build is the bootstrap script — it runs `buildconf` (only
+if `./configure` is missing), `./configure` with the right flags, `make`, and
+then verifies every module the tests need is present:
+
+```sh
+server/mpm/motorz/test/setup.sh # configure (if needed) + build + verify
+server/mpm/motorz/test/setup.sh --reconfigure # force a fresh ./configure
+server/mpm/motorz/test/setup.sh --jobs 8 # control make parallelism
+```
+
+It does **not** install httpd; the tests use the freshly built `./httpd` in
+place. On success it prints `setup OK` and the run-all command.
+
+### Doing it by hand instead
+
+```sh
+# from the build top. (Run ./buildconf first only on a fresh git checkout that
+# has no ./configure; needs autoconf + libtool + python3.)
+./configure --with-included-apr \
+ --enable-mpms-shared='event motorz' \
+ --enable-so --enable-unixd \
+ --enable-authz_core --enable-authz_host --enable-log_config \
+ --enable-mime --enable-dir \
+ --enable-socache_shmcb --enable-ssl --enable-http2
+make
+```
+
+`--with-included-apr` uses the bundled APR/APR-Util (no system APR needed).
+`event` is built alongside `motorz` because `bench.sh` compares against it.
+(`mod_ssl`/`mod_http2` are also part of the default `most` module set, so a
+plain `./configure --enable-mpms-shared='event motorz' --with-included-apr`
+usually yields them too; the explicit flags above just make it deterministic.)
+
+### What the tests need
+
+The harness finds the `httpd` binary at the top of the build tree and locates
+the shared module `.so` files under `modules/` and `server/mpm/`. Required for
+the HTTP/1.1 suite + smoke: `mod_mpm_motorz`, `mod_unixd`, `mod_authz_core`,
+`mod_authz_host`, `mod_log_config`, `mod_mime`, `mod_dir`. The HTTP/2 suite
+additionally needs `mod_ssl`, `mod_http2`, `mod_socache_shmcb` (building these
+requires OpenSSL headers and `libnghttp2`), plus an `openssl` CLI and a `curl`
+built with HTTP/2 — it **self-skips** (exit 0) with a clear message if any are
+missing. If [`h2load`](https://nghttp2.org/) (from nghttp2) is on `PATH`, the
+HTTP/2 suite adds real multiplexed load tests; otherwise those are skipped (not
+failed). `bench.sh` needs `mod_mpm_event` and `ab`/`h2load`.
+
+## Running
+
+```sh
+server/mpm/motorz/test/run-all.sh # smoke + both suites
+server/mpm/motorz/test/smoke.sh # fast change-mapped smoke test only
+server/mpm/motorz/test/run-http1.sh # HTTP/1.1 only
+server/mpm/motorz/test/run-http2.sh # HTTP/2-over-TLS only
+server/mpm/motorz/test/bench.sh # motorz vs event throughput comparison
+```
+
+### bench.sh — motorz vs event
+
+Runs identical `ab` (HTTP/1.1) and `h2load` (HTTP/2) workloads against the same
+build configured first with the event MPM, then motorz, with matched tunables,
+and prints a req/s comparison table.
+
+**Note:** keep the worker count above the peak connection concurrency of the
+benchmark, so that it compares the MPMs and not worker starvation. `bench.sh`
+defaults `THREADS=128` (≥ the c=50 default) and **flags any run with
+failed/errored requests** (its req/s is then not a valid figure). Env knobs:
+`REQS CONC H2_REQS H2_CONC H2_STREAMS H2_BIG_REQS THREADS PORT`.
+
+Observed (12-core arm64, 1 child, adequate workers): motorz tracks event within
+~1–2% on all four workloads. (An intermittent loss of h2 responses under rapid
+connection churn that was seen once is fixed: `run-http2.sh` checks that 30000
+started requests lose none.)
+
+Environment knobs:
+
+- `PORT` / `TLS_PORT` — listen ports (default 8099 / 8443).
+- `KEEP=1` — keep the temp `ServerRoot` after the run for inspection
+ (path is printed); otherwise it is removed on exit.
+
+Exit status is non-zero if any assertion fails.
+
+## What is covered
+
+**`smoke.sh`** — fast (~10 s) robust smoke test whose checks map one-to-one to
+the changes made on this branch, so a failure points straight at what broke:
+
+1. **forward-decl of `motorz_update_listeners()`** — motorz loads, parses
+ config, and serves (the bug was a C89 implicit-declaration / link error);
+2. **clogging-input-filters branch honors hook state** — h2 keep-alive reuses
+ one connection instead of collapsing to one-shot (h2 c2 connections set
+ `clogging_input_filters` unconditionally);
+3. **async HTTP/2 handoff is enabled** (`MOTORZ_ENABLE_ASYNC 1`) — asserts
+ motorz *does* return the c1 connection to MPM monitoring (async hand-back)
+ and that HTTP/2 connection churn (`h2load -n 10000 -c 50 -m 1`) still drops
+ **0** requests. This is the regression test for the dropped-request bug,
+ which was fixed in motorz (secondary connections now get their own
+ `conn_state_t`, see `motorz_pre_connection()`); see MOTORZ.README "HTTP/2
+ async handoff" for the root cause.
+
+Runs h2-over-TLS when ssl/http2/openssl/h2-curl are present, else an
+HTTP/1.1-only subset.
+
+**`run-http1.sh`** — exercises the connection state machine in
+`motorz_io_process()`:
+
+- basic GET / 404 / body correctness
+- **keep-alive reuse** (5 requests, asserts a single TCP connection) — the
+ KEEPALIVE → WRITE_COMPLETION path
+- 200KB body (write-completion cycling)
+- concurrency / load: keep-alive correctness is checked with **curl** (3000
+ reused requests, all 200) because `ab` miscounts a server-closed keep-alive
+ connection's final read as a non-2xx failure — a known `ab` artifact, more
+ frequent with `MOTORZ_ENABLE_ASYNC=0` since idle keep-alive closes via the
+ blocking path; `ab` is still used for the completion count and the
+ non-keep-alive lingering-close path (no `-k`, so no artifact)
+- slow client: a partial request line completed after a pause (read-wait path)
+- **lifecycle**: graceful restart under load, and 5× restart churn under
+ continuous load — the skiplist/worker-drain scenario this branch hardened
+- error-log scan for crash/crit/emerg/assert/deadlock
+
+**`run-http2.sh`** — mod_http2 + mod_ssl on motorz:
+
+- h2 ALPN negotiation (`http_version == 2`)
+- request multiplexing over a single connection (10 streams, 1 connect)
+- large multi-frame body
+- **`h2load` load tests** (when available): 5000 req / 20 clients / 25 streams,
+ 1000 req of the 200KB body / 50 streams (flow control), and a rate-limited
+ run with idle gaps — each asserting **zero** failed/errored and all-2xx
+- inspects the `motorz_io_process()` state traces, asserting PROCESSING is
+ driven (with async on, an idle c1 is handed back as `CONN_STATE_ASYNC_WAITIO`
+ rather than via WRITE_COMPLETION; HTTP/1.1 still covers WRITE_COMPLETION)
+- **asserts async is enabled**: the `CONN_STATE_ASYNC_WAITIO` arm (`AH10557`)
+ appears and h2 logs "returning to mpm c1 monitoring" (see below)
+- h2 still negotiated after a graceful restart
+- error-log scan
+
+### Two-phase logging (why)
+
+The state traces require global `LogLevel trace8`, but the `h2load` phase
+pushes thousands of requests — at trace8 the error_log would balloon to
+**gigabytes** and make the log greps crawl. So the suite runs the load phase at
+`LogLevel info` (quiet) and only switches to `trace8` (via `set_loglevel()`,
+which rewrites the marked LogLevel line and gracefully restarts) for the light
+trace phase. Trace scans read only past a marker line written at the switch,
+keeping them fast.
+
+### Async is enabled; the suite asserts it is on
+
+motorz reports `AP_MPMQ_IS_ASYNC = 1` (`MOTORZ_ENABLE_ASYNC 1` in `motorz.c`).
+The HTTP/2 churn bug it used to expose is fixed in motorz (a secondary
+connection no longer shares its master's `conn_state_t`; see MOTORZ.README
+"HTTP/2 async handoff"). Consequences the suite asserts:
+mod_http2 requests `CONN_STATE_ASYNC_WAITIO` of an async MPM, so the WAITIO arm
+trace `AH10557` **does** appear, and h2 **does** log "returning to mpm c1
+monitoring" — while the churn run stays at 0 dropped requests. The suite drives
+the WAITIO path (an idle raw-h2 `openssl s_client` connection — preface + empty
+`SETTINGS`, no request) via `trigger_async_waitio()` in `lib.sh` and confirms it
+arms ≥ 1 time.
+
+This positively exercises the branch added in this work. The suite also
+confirms (via the `info`-level log) that motorz's `AP_MPMQ_IS_ASYNC = 1` drives
+mod_http2's async idle-return ("returning to mpm c1 monitoring"), rather than
+the prefork-style blocking poll.
+
+## Layout
+
+```
+setup.sh configure + build httpd with the modules the tests need
+lib.sh shared helpers (build-tree discovery, config gen, assert API,
+ set_loglevel, trigger_async_waitio, h2load_stat)
+smoke.sh fast change-mapped smoke test
+run-http1.sh HTTP/1.1 functional + lifecycle suite
+run-http2.sh HTTP/2-over-TLS suite (+ h2load load tests)
+run-all.sh runs smoke + both suites, aggregates pass/fail
+bench.sh motorz vs event throughput comparison (not in run-all)
+```
diff --git a/server/mpm/motorz/test/bench.sh b/server/mpm/motorz/test/bench.sh
new file mode 100755
index 00000000000..7a4bf8d37cc
--- /dev/null
+++ b/server/mpm/motorz/test/bench.sh
@@ -0,0 +1,214 @@
+#!/bin/bash
+#
+# motorz vs event -- head-to-head MPM performance comparison.
+#
+# Runs identical workloads against the SAME httpd build configured first with
+# the event MPM, then the motorz MPM, with matched tunables (one child,
+# ThreadsPerChild 16, quiet logging) so the only variable is the MPM.
+#
+# Workloads:
+# - HTTP/1.1 keep-alive (ab -k) small body
+# - HTTP/1.1 no keep-alive (ab) small body (accept/linger cost)
+# - HTTP/2 multiplexed (h2load) small body
+# - HTTP/2 large body (h2load) 200 KB (write/flow control)
+#
+# Reports req/s and mean latency for each, side by side. NOT a rigorous
+# microbenchmark -- it's a practical apples-to-apples smoke of relative
+# throughput on this machine. Run it a couple of times; numbers vary.
+#
+# Usage: server/mpm/motorz/test/bench.sh [REQS=50000 CONC=50 DUR=...]
+# Env: PORT (TLS+plain reuse one port per run), KEEP=1
+
+. "$(dirname "$0")/lib.sh"
+
+require_httpd
+
+REQS="${REQS:-50000}" # ab request count (keep-alive run)
+REQS_NOKA="${REQS_NOKA:-20000}"
+CONC="${CONC:-50}"
+H2_REQS="${H2_REQS:-50000}"
+H2_CONC="${H2_CONC:-50}"
+H2_STREAMS="${H2_STREAMS:-25}"
+H2_BIG_REQS="${H2_BIG_REQS:-5000}"
+# Worker threads MUST exceed the peak concurrent CONNECTION count: under HTTP/2
+# each connection holds a worker for its lifetime (the h2 c1 connection is
+# dispatched to a worker), so fewer workers than connections starves the pool
+# and h2load reports spurious failures/resets on BOTH MPMs -- making any req/s
+# number meaningless. Size generously above max(CONC, H2_CONC).
+THREADS="${THREADS:-128}"
+PORT="${PORT:-8551}"
+
+have_ab=0; command -v ab >/dev/null 2>&1 && have_ab=1
+have_h2load=0; command -v h2load >/dev/null 2>&1 && have_h2load=1
+have_ssl=1
+for n in mod_ssl.so mod_http2.so mod_socache_shmcb.so; do
+ find "$TOP/modules" -name "$n" -path '*/.libs/*' 2>/dev/null | grep -q . || have_ssl=0
+done
+[ "$have_h2load" -eq 1 ] && [ "$have_ssl" -eq 1 ] && do_h2=1 || do_h2=0
+
+make_rundir
+trap cleanup EXIT INT TERM
+openssl req -x509 -newkey rsa:2048 -nodes -keyout "$RUNDIR/key.pem" \
+ -out "$RUNDIR/cert.pem" -days 2 -subj "/CN=localhost" >/dev/null 2>&1
+
+# Result accumulators (one column per MPM), kept as text rows we print at the end.
+RESULTS_FILE="$RUNDIR/results.txt"
+: > "$RESULTS_FILE"
+record() { printf '%s\t%s\t%s\n' "$1" "$2" "$3" >> "$RESULTS_FILE"; } # workload, mpm, "val"
+
+# --- write a config for the given MPM ($1 = event|motorz) -------------------
+write_conf() {
+ local mpm="$1" mpm_line tune
+ if [ "$mpm" = event ]; then
+ mpm_line="$(load mpm_event_module mod_mpm_event.so)"
+ tune="StartServers 1
+ServerLimit 1
+ThreadLimit $THREADS
+ThreadsPerChild $THREADS
+MinSpareThreads $THREADS
+MaxSpareThreads $THREADS
+MaxRequestWorkers $THREADS"
+ else
+ mpm_line="$(load mpm_motorz_module mod_mpm_motorz.so)"
+ tune="StartServers 1
+ThreadLimit $THREADS
+ThreadsPerChild $THREADS
+PollersPerChild 2"
+ fi
+ # Both MPMs run ONE child with $THREADS worker threads, sized above the peak
+ # connection concurrency so neither starves under h2 (see THREADS note).
+ {
+ echo "ServerRoot \"$RUNDIR\""
+ echo "ServerName localhost"
+ echo "PidFile \"$RUNDIR/httpd.pid\""
+ echo "Listen $PORT"
+ echo "$mpm_line"
+ load unixd_module mod_unixd.so
+ load authz_core_module mod_authz_core.so
+ load authz_host_module mod_authz_host.so
+ load log_config_module mod_log_config.so
+ load mime_module mod_mime.so
+ load dir_module mod_dir.so
+ if [ "$do_h2" -eq 1 ]; then
+ load socache_shmcb_module mod_socache_shmcb.so
+ load ssl_module mod_ssl.so
+ load http2_module mod_http2.so
+ fi
+ echo "$tune"
+ echo "ErrorLog \"$RUNDIR/logs/error_log\""
+ echo "LogLevel error" # quiet: logging must not skew the numbers
+ echo "TypesConfig /dev/null"
+ echo "AddType text/html .html"
+ echo "AddType text/plain .txt"
+ echo "EnableSendfile On"
+ echo "DocumentRoot \"$RUNDIR/htdocs\""
+ echo "DirectoryIndex index.html"
+ echo ""
+ echo " Require all granted"
+ echo ""
+ if [ "$do_h2" -eq 1 ]; then
+ echo "Protocols h2 http/1.1"
+ echo "SSLSessionCache \"shmcb:$RUNDIR/logs/sc(512000)\""
+ echo ""
+ echo " ServerName localhost"
+ echo " SSLEngine on"
+ echo " SSLCertificateFile \"$RUNDIR/cert.pem\""
+ echo " SSLCertificateKeyFile \"$RUNDIR/key.pem\""
+ echo " Protocols h2 http/1.1"
+ echo ""
+ fi
+ } > "$RUNDIR/httpd.conf"
+}
+
+# extract "Requests per second" and "Time per request (mean)" from ab output
+ab_rps() { printf '%s\n' "$1" | awk '/Requests per second/{print $4; exit}'; }
+ab_mean() { printf '%s\n' "$1" | awk '/Time per request/ && /\(mean\)/{print $4; exit}'; }
+# h2load: "finished in Xs, NNN.NN req/s, ..." and the req mean from the table
+h2_rps() { printf '%s\n' "$1" | awk -F',' '/req\/s/{for(i=1;i<=NF;i++) if($i ~ /req\/s/){gsub(/[^0-9.]/,"",$i); print $i; exit}}'; }
+# Warn loudly if an h2load run had ANY failed/errored requests -- the req/s of
+# such a run is not a valid throughput figure (it raced a starved pool or a
+# crash). $1=output $2=workload $3=mpm.
+h2_check_clean() {
+ local f e
+ f=$(printf '%s\n' "$1" | sed -nE 's/.* ([0-9]+) failed.*/\1/p')
+ e=$(printf '%s\n' "$1" | sed -nE 's/.* ([0-9]+) errored.*/\1/p')
+ if [ "${f:-0}" -ne 0 ] || [ "${e:-0}" -ne 0 ]; then
+ echo " !! WARNING: $2/$3 had $f failed / $e errored -- req/s is NOT valid"
+ record "${2}-FAILED" "$mpm" "$f/$e"
+ fi
+}
+
+run_mpm() {
+ local mpm="$1" base out rps mean
+ echo
+ echo "######## $mpm ########"
+ write_conf "$mpm"
+ "$HTTPD" -f "$RUNDIR/httpd.conf" -t >/dev/null 2>&1 \
+ || { echo " config invalid for $mpm; skipping"; return; }
+ start_httpd
+ # confirm which MPM is actually serving
+ sleep 0.5
+
+ if [ "$have_ab" -eq 1 ]; then
+ base="http://127.0.0.1:$PORT"
+ echo "-- HTTP/1.1 keep-alive ($REQS req, c=$CONC)"
+ out=$(ab -n "$REQS" -c "$CONC" -k -q "$base/" 2>&1)
+ rps=$(ab_rps "$out"); mean=$(ab_mean "$out")
+ echo " req/s=$rps mean(ms/req-across-conc)=$mean"
+ record "h1-keepalive" "$mpm" "$rps"
+
+ echo "-- HTTP/1.1 no keep-alive ($REQS_NOKA req, c=$CONC)"
+ out=$(ab -n "$REQS_NOKA" -c "$CONC" -q "$base/" 2>&1)
+ rps=$(ab_rps "$out")
+ echo " req/s=$rps"
+ record "h1-no-keepalive" "$mpm" "$rps"
+ else
+ echo "-- ab not found; skipping HTTP/1.1 throughput"
+ fi
+
+ if [ "$do_h2" -eq 1 ]; then
+ base="https://localhost:$PORT"
+ echo "-- HTTP/2 ($H2_REQS req, c=$H2_CONC, m=$H2_STREAMS, small body)"
+ out=$(h2load -n "$H2_REQS" -c "$H2_CONC" -m "$H2_STREAMS" "$base/" 2>&1)
+ rps=$(h2_rps "$out"); h2_check_clean "$out" "h2-small" "$mpm"
+ echo " req/s=$rps ($(h2load_stat "$out" '^requests:'))"
+ record "h2-small" "$mpm" "$rps"
+
+ echo "-- HTTP/2 large body ($H2_BIG_REQS req, c=$H2_CONC, m=$H2_STREAMS, 200KB)"
+ out=$(h2load -n "$H2_BIG_REQS" -c "$H2_CONC" -m "$H2_STREAMS" "$base/big.txt" 2>&1)
+ rps=$(h2_rps "$out"); h2_check_clean "$out" "h2-large" "$mpm"
+ echo " req/s=$rps"
+ record "h2-large" "$mpm" "$rps"
+ else
+ echo "-- h2load/ssl unavailable; skipping HTTP/2 throughput"
+ fi
+
+ stop_httpd
+}
+
+echo "==== motorz vs event MPM benchmark ===="
+echo "host: $(uname -sm), cpus: $(sysctl -n hw.ncpu 2>/dev/null || nproc 2>/dev/null)"
+echo "settings: 1 child, ThreadsPerChild=$THREADS, LogLevel error"
+echo "tools: ab=$have_ab h2load=$have_h2load ssl=$have_ssl"
+
+run_mpm event
+run_mpm motorz
+
+# ---- comparison table ------------------------------------------------------
+echo
+echo "==== req/s comparison (higher is better) ===="
+awk -F'\t' '
+ { v[$1"|"$2]=$3; if(!seen[$1]++) order[++n]=$1 }
+ END {
+ printf "%-18s %12s %12s %10s\n", "workload", "event", "motorz", "motorz/event"
+ printf "%-18s %12s %12s %10s\n", "--------", "-----", "------", "-----------"
+ for(i=1;i<=n;i++){
+ w=order[i]; e=v[w"|event"]; m=v[w"|motorz"]
+ ratio = (e+0>0 && m+0>0) ? sprintf("%.2fx", m/e) : "n/a"
+ printf "%-18s %12s %12s %10s\n", w, (e==""?"-":e), (m==""?"-":m), ratio
+ }
+ }
+' "$RESULTS_FILE"
+echo
+echo "(req/s; ratio = motorz relative to event. Re-run a few times -- single"
+echo " runs are noisy. LogLevel was 'error' so logging did not skew results.)"
diff --git a/server/mpm/motorz/test/lib.sh b/server/mpm/motorz/test/lib.sh
new file mode 100644
index 00000000000..3fd4e542156
--- /dev/null
+++ b/server/mpm/motorz/test/lib.sh
@@ -0,0 +1,177 @@
+# Shared helpers for the motorz MPM test harness.
+#
+# Sourced by run-http1.sh and run-http2.sh. Not executable on its own.
+#
+# Resolves the httpd build tree, locates the shared MPM/module .so files,
+# generates a throwaway ServerRoot under a temp dir, and provides start/stop
+# plus a tiny assertion API. Everything lives under a per-run temp dir that is
+# removed on exit unless KEEP=1 is set in the environment.
+
+set -u
+
+# --- locate the build tree -------------------------------------------------
+# This script lives in /server/mpm/motorz/test/. The top of the
+# build tree is four levels up.
+TEST_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+TOP="$(cd "$TEST_DIR/../../../.." && pwd)"
+
+HTTPD="$TOP/httpd"
+PORT="${PORT:-8099}" # http1 default; http2 suite overrides to 8443
+TLS_PORT="${TLS_PORT:-8443}"
+
+PASS=0
+FAIL=0
+RUNDIR=""
+
+fail() { echo " FAIL: $*"; FAIL=$((FAIL + 1)); }
+pass() { echo " ok: $*"; PASS=$((PASS + 1)); }
+
+# assert_eq