Skip to contentSkip to conversation

Jobserver support

PATCH Superseded Martin Hundebøll 5 participants 13 messages Apr 3, 2024 – May 18, 2024

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore
#0 lore raw

cover Jobserver support

The parallelism of bitbake easily uses every available core on the build host. But since every task is run with the same number of parallel threads/processes, multiple tasks might load the CPU excessively, which in turn slows down the build due to scheduling overhead.

This patch series adds a class that creates a fifo filled with PARALLEL_MAKE tokens. The path to the created fifo is then configured in the MAKEFLAGS environment variable, which is read by make and a patched ninja (and gcc if doing lto).

The benefits from using the jobserver depends on the set of executed
tasks: running multiple large do_compile tasks simultaneously benefits more than multiple do_fetch tasks. A simple test building the following tasks (and all their dependencies) yields a ~5% improvement in build time (20:20 -> 19:20):

nodejs-native
rust-llvm-native
rust-native
linux-yocto
qemu-native

On build machines shared by multiple users, a single jobserver can be shared between multiple builds (using the JOBSERVER_FIFO variable). Running the above build in two different build directories at the same time gives a ~12% improvement (43:17 -> 37:55).

Finally, the memory pressure from e.g. compiling multiple c++ based projects is also reduced. In our case, a cloud based build machine (with 32 cores and 32GB RAM) fails to compile llvm-rust-native (in parallel to nodejs) without the jobserver due to a lack of memory.

This patch set is roughly based on previous work by Richard[1]. That patch lists three TODO items, which are all addressed by these patches:
* The fifo path defaults to TMPDIR/jobserver_fifo, but can be configured using JOBSERVER_FIFO.
* The number of make threads defaults to the value from PARALLEL_MAKE (which is then redundant).
* If PARALLEL_MAKE is unset, the jobserver functionality is skipped.

Further work in addition to this patch set could be to make bitbake tasks jobserver aware.

Changes since the RFC[2]:
* The ninja src uri change in patch 3 is converted to a set of patches
* The qemu fix in patch 4 is converted to a submitted patch

[1] https://lore.kernel.org/openembedded-core/[email protected]/
[2] https://lore.kernel.org/openembedded-core/[email protected]/

Martin Hundebøll (5):
classes: jobserver: support gnu make fifo jobserver
scripts: build-env: allow passing JOBSERVER_FIFO from environment
ninja: build modified version with GNU Make jobserver support
qemu: enable parallel builds when using the jobserver class
contrib: add python service and systemd unit to run shared jobserver

 contrib/jobserver/jobserver.py                |   78 +
 contrib/jobserver/jobserver.service           |   10 +
 meta/classes-global/jobserver.bbclass         |   80 +
 meta/conf/bitbake.conf                        |    2 +-
 ...dd-GNU-make-jobserver-client-support.patch |  494 +++++++
 ...l-monitoring-to-SubprocessSet-DoWork.patch |  560 +++++++
 ...er-when-jN-is-forced-on-command-line.patch |  198 +++
 .../files/0004-Honor-lN-from-MAKEFLAGS.patch  |  134 ++
 ...e-LinePrinter-for-TokenPool-messages.patch |  128 ++
 .../files/0006-Prepare-PR-for-merging.patch   |  156 ++
 .../files/0007-Add-tests-for-TokenPool.patch  |  237 +++
 ...0008-Add-tests-for-subprocess-module.patch |  121 ++
 .../0009-Add-tests-for-build-module.patch     |  397 +++++
 ...-implementation-for-GNUmakeTokenPool.patch | 1283 +++++++++++++++++
 .../0011-Prepare-PR-for-merging-part-II.patch |  744 ++++++++++
 ...ename-TokenPool-Setup-to-SetupClient.patch |  109 ++
 ...013-Add-TokenPool-SetupMaster-method.patch |   78 +
 ...mmand-line-option-m-tokenpool-master.patch |  101 ++
 ...plement-GNUmakeTokenPool-SetupMaster.patch |  152 ++
 ...mplement-GNUmakeTokenPool-CreatePool.patch |   87 ++
 ...-Add-tests-for-TokenPool-SetupMaster.patch |  145 ++
 ...-jobserver-fifo-style-client-support.patch |  265 ++++
 ...ional-argument-to-m-tokenpool-master.patch |  368 +++++
 ...-jobserver-fifo-style-master-support.patch |  287 ++++
 meta/recipes-devtools/ninja/ninja_1.11.1.bb   |   33 -
 meta/recipes-devtools/ninja/ninja_1.12.0.bb   |   55 +
 meta/recipes-devtools/qemu/qemu.inc           |    1 +
 ...e-jobserver-auth-argument-when-calli.patch |   37 +
 scripts/oe-buildenv-internal                  |    2 +-
 29 files changed, 6307 insertions(+), 35 deletions(-)
 create mode 100644 contrib/jobserver/jobserver.py
 create mode 100644 contrib/jobserver/jobserver.service
 create mode 100644 meta/classes-global/jobserver.bbclass
 create mode 100644 meta/recipes-devtools/ninja/files/0001-Add-GNU-make-jobserver-client-support.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0002-Add-TokenPool-monitoring-to-SubprocessSet-DoWork.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0003-Ignore-jobserver-when-jN-is-forced-on-command-line.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0004-Honor-lN-from-MAKEFLAGS.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0005-Use-LinePrinter-for-TokenPool-messages.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0006-Prepare-PR-for-merging.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0007-Add-tests-for-TokenPool.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0008-Add-tests-for-subprocess-module.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0009-Add-tests-for-build-module.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0010-Add-Win32-implementation-for-GNUmakeTokenPool.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0011-Prepare-PR-for-merging-part-II.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0012-Rename-TokenPool-Setup-to-SetupClient.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0013-Add-TokenPool-SetupMaster-method.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0014-Add-command-line-option-m-tokenpool-master.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0015-Implement-GNUmakeTokenPool-SetupMaster.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0016-Implement-GNUmakeTokenPool-CreatePool.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0017-Add-tests-for-TokenPool-SetupMaster.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0018-Add-GNU-make-jobserver-fifo-style-client-support.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0019-Add-optional-argument-to-m-tokenpool-master.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0020-Add-GNU-make-jobserver-fifo-style-master-support.patch
 delete mode 100644 meta/recipes-devtools/ninja/ninja_1.11.1.bb
 create mode 100644 meta/recipes-devtools/ninja/ninja_1.12.0.bb
 create mode 100644 meta/recipes-devtools/qemu/qemu/0013-Makefile-preserve-jobserver-auth-argument-when-calli.patch
Signature · 1 line
2.44.0
#1 lore raw

PATCH 1/5 classes: jobserver: support gnu make fifo jobserver

Add a class to implement the gnu make fifo style jobserver. The class can be activated by symply adding an INHERIT += "jobserver" to the local configuration.

Furthermore, one can configure an external jobserver (i.e. a server shared between multiple builds), by configured the JOBSERVER_FIFO variable to point at an existing jobserver fifo.

The jobserver class uses the fifo style jobserver, which doesn't require passing open file descriptors around. It does, however, require make-4.4, which isn't available in common distro yet. To work around this, the class make all recipes (except make and its dependencies itself) depend on virtual/make-native.

---
 meta/classes-global/jobserver.bbclass | 80 +++++++++++++++++++++++++++
 meta/conf/bitbake.conf                |  2 +-
 2 files changed, 81 insertions(+), 1 deletion(-)
 create mode 100644 meta/classes-global/jobserver.bbclass
meta/classes-global/jobserver.bbclass new file +80 -0
new file mode 100644
index 0000000000..c76909fe50
@@ -0,0 +1,80 @@
+JOBSERVER_FIFO ?= ""
+JOBSERVER_FIFO[doc] = "Path to external jobserver fifo to use instead of creating a per-build server."
+
+addhandler jobserver_setup_fifo
+jobserver_setup_fifo[eventmask] = "bb.event.ConfigParsed"
+
+python jobserver_setup_fifo() {
+    # don't setup a per-build fifo, if an external one is configured
+    if d.getVar("JOBSERVER_FIFO"):
+        return
+
+    # don't use a job-server if no parallelism is configured
+    jobs = oe.utils.parallel_make(d)
+    if jobs in (None, 1):
+        return
+
+    # reduce jobs by one as a token has implicitly been handed to the
+    # process requesting tokens
+    jobs -= 1
+
+    fifo = d.getVar("TMPDIR") + "/jobserver_fifo"
+
+    # and old fifo might be lingering; remove it
+    if os.path.exists(fifo):
+        os.remove(fifo)
+
+    # create a new fifo to use for communicating tokens
+    os.mkfifo(fifo)
+
+    # fill the fifo with the number of tokens to hand out
+    wfd = os.open(fifo, os.O_RDWR)
+    written = os.write(wfd, b"+" * jobs)
+    if written != (jobs):
+        bb.error("Failed to fil make fifo: {} != {}".format(written, jobs))
+
+    # configure the per-build fifo path to use
+    d.setVar("JOBSERVER_FIFO", fifo)
+}
+
+python () {
+    # don't configure the fifo if none is defined
+    fifo = d.getVar("JOBSERVER_FIFO")
+    if not fifo:
+        return
+
+    # avoid making make-native or its dependencies depend on make-native itself
+    if d.getVar("PN") in (
+                "make-native",
+                "libtool-native",
+                "pkgconfig-native",
+                "automake-native",
+                "autoconf-native",
+                "m4-native",
+                "texinfo-dummy-native",
+                "gettext-minimal-native",
+                "quilt-native",
+                "gnu-config-native",
+            ):
+        return
+
+    # don't make unwilling recipes depend on make-native
+    if d.getVar('INHIBIT_DEFAULT_DEPS', False):
+        return
+
+    # make other recipes depend on make-native to make sure it is new enough to
+    # support the --jobserver-auth=fifo:<path> syntax (from make-4.4 and onwards)
+    d.appendVar("DEPENDS", " virtual/make-native")
+
+    # disable the "-j <jobs>" flag, as that overrides the jobserver fifo tokens
+    d.setVar("PARALLEL_MAKE", "")
+    d.setVar("PARALLEL_MAKEINST", "")
+
+    # set and export the jobserver in the environment
+    d.appendVar("MAKEFLAGS", " --jobserver-auth=fifo:" + fifo)
+    d.setVarFlag("MAKEFLAGS", "export", "1")
+
+    # ignore the joberserver argument part of MAKEFLAGS in the hash, as that
+    # shouldn't change the build output
+    d.appendVarFlag("MAKEFLAGS", "vardepvalueexclude", "| --jobserver-auth=fifo:" + fifo)
+}
meta/conf/bitbake.conf +1 -1
index 6f180d18b0..23a016b31e 100644
@@ -960,7 +960,7 @@ BB_HASHEXCLUDE_COMMON ?= "TMPDIR FILE PATH PWD BB_TASKHASH BBPATH BBSERVER DL_DI
     BB_WORKERCONTEXT BB_LIMITEDDEPS BB_UNIHASH extend_recipe_sysroot DEPLOY_DIR \
     SSTATE_HASHEQUIV_METHOD SSTATE_HASHEQUIV_REPORT_TASKDATA \
     SSTATE_HASHEQUIV_OWNER CCACHE_TOP_DIR BB_HASHSERVE GIT_CEILING_DIRECTORIES \
-    OMP_NUM_THREADS BB_CURRENTTASK"
+    OMP_NUM_THREADS BB_CURRENTTASK JOBSERVER_FIFO"
 BB_BASEHASH_IGNORE_VARS ?= "${BB_HASHEXCLUDE_COMMON} PSEUDO_IGNORE_PATHS BUILDHISTORY_DIR \
     SSTATE_DIR SOURCE_DATE_EPOCH RUST_BUILD_SYS RUST_HOST_SYS RUST_TARGET_SYS"
 BB_HASHCONFIG_IGNORE_VARS ?= "${BB_HASHEXCLUDE_COMMON} DATE TIME SSH_AGENT_PID \
Signature · 1 line
2.44.0
#2 lore raw

Re: [OE-core] [PATCH 1/5] classes: jobserver: support gnu make fifo jobserver

Hi

Very interesting patch series. I stumbled upon a couple of spelling errors while looking through it, and have a question about the hardcoded dependency list.

Quoted 2 lines · Martin Hundeb?ll

Add a class to implement the gnu make fifo style jobserver. The class can be activated by symply adding an INHERIT += "jobserver" to the

s/symply/simply/

Quoted 72 lines

local configuration.

Furthermore, one can configure an external jobserver (i.e. a server shared between multiple builds), by configured the JOBSERVER_FIFO variable to point at an existing jobserver fifo.

The jobserver class uses the fifo style jobserver, which doesn't require passing open file descriptors around. It does, however, require make-4.4, which isn't available in common distro yet. To work around this, the class make all recipes (except make and its dependencies itself) depend on virtual/make-native.

---
 meta/classes-global/jobserver.bbclass | 80 +++++++++++++++++++++++++++
 meta/conf/bitbake.conf                |  2 +-
 2 files changed, 81 insertions(+), 1 deletion(-)
 create mode 100644 meta/classes-global/jobserver.bbclass
meta/classes-global/jobserver.bbclass new file +47 -0
new file mode 100644
index 0000000000..c76909fe50
@@ -0,0 +1,80 @@
+JOBSERVER_FIFO ?= ""
+JOBSERVER_FIFO[doc] = "Path to external jobserver fifo to use instead of creating a per-build server."
+
+addhandler jobserver_setup_fifo
+jobserver_setup_fifo[eventmask] = "bb.event.ConfigParsed"
+
+python jobserver_setup_fifo() {
+    # don't setup a per-build fifo, if an external one is configured
+    if d.getVar("JOBSERVER_FIFO"):
+        return
+
+    # don't use a job-server if no parallelism is configured
+    jobs = oe.utils.parallel_make(d)
+    if jobs in (None, 1):
+        return
+
+    # reduce jobs by one as a token has implicitly been handed to the
+    # process requesting tokens
+    jobs -= 1
+
+    fifo = d.getVar("TMPDIR") + "/jobserver_fifo"
+
+    # and old fifo might be lingering; remove it
+    if os.path.exists(fifo):
+        os.remove(fifo)
+
+    # create a new fifo to use for communicating tokens
+    os.mkfifo(fifo)
+
+    # fill the fifo with the number of tokens to hand out
+    wfd = os.open(fifo, os.O_RDWR)
+    written = os.write(wfd, b"+" * jobs)
+    if written != (jobs):
+        bb.error("Failed to fil make fifo: {} != {}".format(written, jobs))
+
+    # configure the per-build fifo path to use
+    d.setVar("JOBSERVER_FIFO", fifo)
+}
+
+python () {
+    # don't configure the fifo if none is defined
+    fifo = d.getVar("JOBSERVER_FIFO")
+    if not fifo:
+        return
+
+    # avoid making make-native or its dependencies depend on make-native itself
+    if d.getVar("PN") in (

meta/classes-global/jobserver.bbclass line 57

Quoted 10 lines
meta/classes-global/jobserver.bbclass new file +10 -0
+                "make-native",
+                "libtool-native",
+                "pkgconfig-native",
+                "automake-native",
+                "autoconf-native",
+                "m4-native",
+                "texinfo-dummy-native",
+                "gettext-minimal-native",
+                "quilt-native",
+                "gnu-config-native",

This seems a bit brittle, but I guess make's dependencies doesn't change often. So it is probably not a big issue.

How does it break if a dependency is missing?

Quoted 10 lines
meta/classes-global/jobserver.bbclass new file +10 -0
+            ):
+        return
+
+    # don't make unwilling recipes depend on make-native
+    if d.getVar('INHIBIT_DEFAULT_DEPS', False):
+        return
+
+    # make other recipes depend on make-native to make sure it is new enough to
+    # support the --jobserver-auth=fifo:<path> syntax (from make-4.4 and onwards)
+    d.appendVar("DEPENDS", " virtual/make-native")

meta/classes-global/jobserver.bbclass line 77

Quoted 10 lines
meta/classes-global/jobserver.bbclass new file +10 -0
+
+    # disable the "-j <jobs>" flag, as that overrides the jobserver fifo tokens
+    d.setVar("PARALLEL_MAKE", "")
+    d.setVar("PARALLEL_MAKEINST", "")
+
+    # set and export the jobserver in the environment
+    d.appendVar("MAKEFLAGS", " --jobserver-auth=fifo:" + fifo)
+    d.setVarFlag("MAKEFLAGS", "export", "1")
+
+    # ignore the joberserver argument part of MAKEFLAGS in the hash, as that

s/joberserver/jobserver/

Quoted 17 lines
meta/classes-global/jobserver.bbclass new file +3 -0
+    # shouldn't change the build output
+    d.appendVarFlag("MAKEFLAGS", "vardepvalueexclude", "| --jobserver-auth=fifo:" + fifo)
+}
meta/conf/bitbake.conf +1 -2
index 6f180d18b0..23a016b31e 100644
@@ -960,7 +960,7 @@ BB_HASHEXCLUDE_COMMON ?= "TMPDIR FILE PATH PWD BB_TASKHASH BBPATH BBSERVER DL_DI
     BB_WORKERCONTEXT BB_LIMITEDDEPS BB_UNIHASH extend_recipe_sysroot DEPLOY_DIR \
     SSTATE_HASHEQUIV_METHOD SSTATE_HASHEQUIV_REPORT_TASKDATA \
     SSTATE_HASHEQUIV_OWNER CCACHE_TOP_DIR BB_HASHSERVE GIT_CEILING_DIRECTORIES \
-    OMP_NUM_THREADS BB_CURRENTTASK"
+    OMP_NUM_THREADS BB_CURRENTTASK JOBSERVER_FIFO"
 BB_BASEHASH_IGNORE_VARS ?= "${BB_HASHEXCLUDE_COMMON} PSEUDO_IGNORE_PATHS BUILDHISTORY_DIR \
     SSTATE_DIR SOURCE_DATE_EPOCH RUST_BUILD_SYS RUST_HOST_SYS RUST_TARGET_SYS"
 BB_HASHCONFIG_IGNORE_VARS ?= "${BB_HASHEXCLUDE_COMMON} DATE TIME SSH_AGENT_PID \
-=-=-=-=-=-=-=-=-=-=-=-
Quoted 7 lines

Links: You receive all messages sent to this group.
View/Reply Online (#197910): https://lists.openembedded.org/g/openembedded-core/message/197910
Mute This Topic: https://lists.openembedded.org/mt/105304233/7501392
Group Owner: [email protected]
Unsubscribe: https://lists.openembedded.org/g/openembedded-core/unsub [[email protected]]
-=-=-=-=-=-=-=-=-=-=-=-

/Andreas

#3 lore raw

Re: [OE-core] [PATCH 1/5] classes: jobserver: support gnu make fifo jobserver

Hi Andreas,

Quoted 14 lines · Andreas Helbech Kleist
Quoted 5 lines

+    # avoid making make-native or its dependencies depend on make- native itself
+    if d.getVar("PN") in (
+                "make-native",
+                "libtool-native",

Quoted 8 lines

+                "pkgconfig-native",
+                "automake-native",
+                "autoconf-native",
+                "m4-native",
+                "texinfo-dummy-native",
+                "gettext-minimal-native",
+                "quilt-native",
+                "gnu-config-native",

Quoted 4 lines

This seems a bit brittle, but I guess make's dependencies doesn't change often. So it is probably not a big issue.

How does it break if a dependency is missing?

Bitbake errors out with a dependency loop.

// Martin

#4 lore raw

PATCH 2/5 scripts: build-env: allow passing JOBSERVER_FIFO from environment

In reply to Martin Hundebøll

Sharing a common jobserver fifo between multiple (containerized) builds is much easier, if an administrator can configure said jobserver fifo path in the environment. Append the JOBSERVER_FIFO variable name to the list of variables configurable through the environment.

---
 scripts/oe-buildenv-internal | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
scripts/oe-buildenv-internal +1 -1
index 2fdb19565a..c8e67ffb8f 100755
@@ -112,7 +112,7 @@ HTTPS_PROXY https_proxy FTP_PROXY ftp_proxy FTPS_PROXY ftps_proxy ALL_PROXY \
 all_proxy NO_PROXY no_proxy SSH_AGENT_PID SSH_AUTH_SOCK BB_SRCREV_POLICY \
 SDKMACHINE BB_NUMBER_THREADS BB_NO_NETWORK PARALLEL_MAKE GIT_PROXY_COMMAND \
 SOCKS5_PASSWD SOCKS5_USER SCREENDIR STAMPS_DIR BBPATH_EXTRA BB_SETSCENE_ENFORCE \
-BB_LOGCONFIG"
+BB_LOGCONFIG JOBSERVER_FIFO"
 
 BB_ENV_PASSTHROUGH_ADDITIONS="$(echo $BB_ENV_PASSTHROUGH_ADDITIONS $BB_ENV_PASSTHROUGH_ADDITIONS_OE | tr ' ' '\n' | LC_ALL=C sort --unique | tr '\n' ' ')"
 
Signature · 1 line
2.44.0
#5 lore raw

PATCH 3/5 ninja: build modified version with GNU Make jobserver support

In reply to Martin Hundebøll

Ninja doesn't (yet) support the GNU Make jobserver out of the box, but there is a pull request adding that support[1]. Add the pull request commits as patches to ninja to make it cooperate with the make jobserver feature.

In order to make the patces apply, the ninja version is bumped to the unreleased 1.12.0.

[1] https://github.com/ninja-build/ninja/pull/2263

---
 ...dd-GNU-make-jobserver-client-support.patch |  494 +++++++
 ...l-monitoring-to-SubprocessSet-DoWork.patch |  560 +++++++
 ...er-when-jN-is-forced-on-command-line.patch |  198 +++
 .../files/0004-Honor-lN-from-MAKEFLAGS.patch  |  134 ++
 ...e-LinePrinter-for-TokenPool-messages.patch |  128 ++
 .../files/0006-Prepare-PR-for-merging.patch   |  156 ++
 .../files/0007-Add-tests-for-TokenPool.patch  |  237 +++
 ...0008-Add-tests-for-subprocess-module.patch |  121 ++
 .../0009-Add-tests-for-build-module.patch     |  397 +++++
 ...-implementation-for-GNUmakeTokenPool.patch | 1283 +++++++++++++++++
 .../0011-Prepare-PR-for-merging-part-II.patch |  744 ++++++++++
 ...ename-TokenPool-Setup-to-SetupClient.patch |  109 ++
 ...013-Add-TokenPool-SetupMaster-method.patch |   78 +
 ...mmand-line-option-m-tokenpool-master.patch |  101 ++
 ...plement-GNUmakeTokenPool-SetupMaster.patch |  152 ++
 ...mplement-GNUmakeTokenPool-CreatePool.patch |   87 ++
 ...-Add-tests-for-TokenPool-SetupMaster.patch |  145 ++
 ...-jobserver-fifo-style-client-support.patch |  265 ++++
 ...ional-argument-to-m-tokenpool-master.patch |  368 +++++
 ...-jobserver-fifo-style-master-support.patch |  287 ++++
 meta/recipes-devtools/ninja/ninja_1.11.1.bb   |   33 -
 meta/recipes-devtools/ninja/ninja_1.12.0.bb   |   55 +
 22 files changed, 6099 insertions(+), 33 deletions(-)
 create mode 100644 meta/recipes-devtools/ninja/files/0001-Add-GNU-make-jobserver-client-support.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0002-Add-TokenPool-monitoring-to-SubprocessSet-DoWork.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0003-Ignore-jobserver-when-jN-is-forced-on-command-line.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0004-Honor-lN-from-MAKEFLAGS.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0005-Use-LinePrinter-for-TokenPool-messages.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0006-Prepare-PR-for-merging.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0007-Add-tests-for-TokenPool.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0008-Add-tests-for-subprocess-module.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0009-Add-tests-for-build-module.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0010-Add-Win32-implementation-for-GNUmakeTokenPool.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0011-Prepare-PR-for-merging-part-II.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0012-Rename-TokenPool-Setup-to-SetupClient.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0013-Add-TokenPool-SetupMaster-method.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0014-Add-command-line-option-m-tokenpool-master.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0015-Implement-GNUmakeTokenPool-SetupMaster.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0016-Implement-GNUmakeTokenPool-CreatePool.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0017-Add-tests-for-TokenPool-SetupMaster.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0018-Add-GNU-make-jobserver-fifo-style-client-support.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0019-Add-optional-argument-to-m-tokenpool-master.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0020-Add-GNU-make-jobserver-fifo-style-master-support.patch
 delete mode 100644 meta/recipes-devtools/ninja/ninja_1.11.1.bb
 create mode 100644 meta/recipes-devtools/ninja/ninja_1.12.0.bb
meta/recipes-devtools/ninja/files/0001-Add-GNU-make-jobserver-client-support.patch new file +494 -0
new file mode 100644
index 0000000000..c882a57a90
@@ -0,0 +1,494 @@
+From 3e04d21231e64129f6fffba7fd37d94b185dae45 Mon Sep 17 00:00:00 2001
+From: Stefan Becker <[email protected]>
+Date: Tue, 22 Mar 2016 13:48:07 +0200
+Subject: [PATCH 01/20] Add GNU make jobserver client support
+
+- add new TokenPool interface
+- GNU make implementation for TokenPool parses and verifies the magic
+  information from the MAKEFLAGS environment variable
+- RealCommandRunner tries to acquire TokenPool
+  * if no token pool is available then there is no change in behaviour
+- When a token pool is available then RealCommandRunner behaviour
+  changes as follows
+  * CanRunMore() only returns true if TokenPool::Acquire() returns true
+  * StartCommand() calls TokenPool::Reserve()
+  * WaitForCommand() calls TokenPool::Release()
+
+Documentation for GNU make jobserver
+
+  http://make.mad-scientist.net/papers/jobserver-implementation/
+
+Fixes https://github.com/ninja-build/ninja/issues/1139
+
+Upstream-Status: Submitted [https://github.com/ninja-build/ninja/pull/1140]
+---
+ configure.py              |   2 +
+ src/build.cc              |  63 ++++++++----
+ src/build.h               |   3 +
+ src/tokenpool-gnu-make.cc | 211 ++++++++++++++++++++++++++++++++++++++
+ src/tokenpool-none.cc     |  27 +++++
+ src/tokenpool.h           |  26 +++++
+ 6 files changed, 310 insertions(+), 22 deletions(-)
+ create mode 100644 src/tokenpool-gnu-make.cc
+ create mode 100644 src/tokenpool-none.cc
+ create mode 100644 src/tokenpool.h
+
+diff --git a/configure.py b/configure.py
+index 588250a..d95fad8 100755
+--- a/configure.py
++++ b/configure.py
+@@ -543,6 +543,7 @@ for name in ['build',
+     objs += cxx(name, variables=cxxvariables)
+ if platform.is_windows():
+     for name in ['subprocess-win32',
++                 'tokenpool-none',
+                  'includes_normalize-win32',
+                  'msvc_helper-win32',
+                  'msvc_helper_main-win32']:
+@@ -552,6 +553,7 @@ if platform.is_windows():
+     objs += cc('getopt')
+ else:
+     objs += cxx('subprocess-posix')
++    objs += cxx('tokenpool-gnu-make')
+ if platform.is_aix():
+     objs += cc('getopt')
+ if platform.is_msvc():
+diff --git a/src/build.cc b/src/build.cc
+index 76ff93a..02ea93b 100644
+--- a/src/build.cc
++++ b/src/build.cc
+@@ -35,6 +35,7 @@
+ #include "state.h"
+ #include "status.h"
+ #include "subprocess.h"
++#include "tokenpool.h"
+ #include "util.h"
+ 
+ using namespace std;
+@@ -149,7 +150,7 @@ void Plan::EdgeWanted(const Edge* edge) {
+ }
+ 
+ Edge* Plan::FindWork() {
+-  if (ready_.empty())
++  if (!more_ready())
+     return NULL;
+   EdgeSet::iterator e = ready_.begin();
+   Edge* edge = *e;
+@@ -448,8 +449,8 @@ void Plan::Dump() const {
+ }
+ 
+ struct RealCommandRunner : public CommandRunner {
+-  explicit RealCommandRunner(const BuildConfig& config) : config_(config) {}
+-  virtual ~RealCommandRunner() {}
++  explicit RealCommandRunner(const BuildConfig& config);
++  virtual ~RealCommandRunner();
+   virtual bool CanRunMore() const;
+   virtual bool StartCommand(Edge* edge);
+   virtual bool WaitForCommand(Result* result);
+@@ -458,9 +459,18 @@ struct RealCommandRunner : public CommandRunner {
+ 
+   const BuildConfig& config_;
+   SubprocessSet subprocs_;
++  TokenPool *tokens_;
+   map<const Subprocess*, Edge*> subproc_to_edge_;
+ };
+ 
++RealCommandRunner::RealCommandRunner(const BuildConfig& config) : config_(config) {
++  tokens_ = TokenPool::Get();
++}
++
++RealCommandRunner::~RealCommandRunner() {
++  delete tokens_;
++}
++
+ vector<Edge*> RealCommandRunner::GetActiveEdges() {
+   vector<Edge*> edges;
+   for (map<const Subprocess*, Edge*>::iterator e = subproc_to_edge_.begin();
+@@ -471,14 +481,18 @@ vector<Edge*> RealCommandRunner::GetActiveEdges() {
+ 
+ void RealCommandRunner::Abort() {
+   subprocs_.Clear();
++  if (tokens_)
++    tokens_->Clear();
+ }
+ 
+ bool RealCommandRunner::CanRunMore() const {
+   size_t subproc_number =
+       subprocs_.running_.size() + subprocs_.finished_.size();
+   return (int)subproc_number < config_.parallelism
+-    && ((subprocs_.running_.empty() || config_.max_load_average <= 0.0f)
+-        || GetLoadAverage() < config_.max_load_average);
++    && (subprocs_.running_.empty() ||
++        ((config_.max_load_average <= 0.0f ||
++          GetLoadAverage() < config_.max_load_average)
++      && (!tokens_ || tokens_->Acquire())));
+ }
+ 
+ bool RealCommandRunner::StartCommand(Edge* edge) {
+@@ -486,6 +500,8 @@ bool RealCommandRunner::StartCommand(Edge* edge) {
+   Subprocess* subproc = subprocs_.Add(command, edge->use_console());
+   if (!subproc)
+     return false;
++  if (tokens_)
++    tokens_->Reserve();
+   subproc_to_edge_.insert(make_pair(subproc, edge));
+ 
+   return true;
+@@ -499,6 +515,9 @@ bool RealCommandRunner::WaitForCommand(Result* result) {
+       return false;
+   }
+ 
++  if (tokens_)
++    tokens_->Release();
++
+   result->status = subproc->Finish();
+   result->output = subproc->GetOutput();
+ 
+@@ -629,31 +648,31 @@ bool Builder::Build(string* err) {
+   // Second, we attempt to wait for / reap the next finished command.
+   while (plan_.more_to_do()) {
+     // See if we can start any more commands.
+-    if (failures_allowed && command_runner_->CanRunMore()) {
+-      if (Edge* edge = plan_.FindWork()) {
+-        if (edge->GetBindingBool("generator")) {
++    if (failures_allowed && plan_.more_ready() &&
++        command_runner_->CanRunMore()) {
++      Edge* edge = plan_.FindWork();
++      if (edge->GetBindingBool("generator")) {
+           scan_.build_log()->Close();
+         }
+ 
+-        if (!StartEdge(edge, err)) {
++      if (!StartEdge(edge, err)) {
++        Cleanup();
++        status_->BuildFinished();
++        return false;
++      }
++
++      if (edge->is_phony()) {
++        if (!plan_.EdgeFinished(edge, Plan::kEdgeSucceeded, err)) {
+           Cleanup();
+           status_->BuildFinished();
+           return false;
+         }
+-
+-        if (edge->is_phony()) {
+-          if (!plan_.EdgeFinished(edge, Plan::kEdgeSucceeded, err)) {
+-            Cleanup();
+-            status_->BuildFinished();
+-            return false;
+-          }
+-        } else {
+-          ++pending_commands;
+-        }
+-
+-        // We made some progress; go back to the main loop.
+-        continue;
++      } else {
++        ++pending_commands;
+       }
++
++      // We made some progress; go back to the main loop.
++      continue;
+     }
+ 
+     // See if we can reap any finished commands.
+diff --git a/src/build.h b/src/build.h
+index 8ec2355..09667aa 100644
+--- a/src/build.h
++++ b/src/build.h
+@@ -52,6 +52,9 @@ struct Plan {
+   /// Returns true if there's more work to be done.
+   bool more_to_do() const { return wanted_edges_ > 0 && command_edges_ > 0; }
+ 
++  /// Returns true if there's more edges ready to start
++  bool more_ready() const { return !ready_.empty(); }
++
+   /// Dumps the current state of the plan.
+   void Dump() const;
+ 
+diff --git a/src/tokenpool-gnu-make.cc b/src/tokenpool-gnu-make.cc
+new file mode 100644
+index 0000000..a8f9b71
+--- /dev/null
++++ b/src/tokenpool-gnu-make.cc
+@@ -0,0 +1,211 @@
++// Copyright 2016 Google Inc. All Rights Reserved.
++//
++// Licensed 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 "tokenpool.h"
++
++#include <errno.h>
++#include <fcntl.h>
++#include <poll.h>
++#include <unistd.h>
++#include <signal.h>
++#include <stdio.h>
++#include <string.h>
++#include <stdlib.h>
++
++// TokenPool implementation for GNU make jobserver
++// (http://make.mad-scientist.net/papers/jobserver-implementation/)
++struct GNUmakeTokenPool : public TokenPool {
++  GNUmakeTokenPool();
++  virtual ~GNUmakeTokenPool();
++
++  virtual bool Acquire();
++  virtual void Reserve();
++  virtual void Release();
++  virtual void Clear();
++
++  bool Setup();
++
++ private:
++  int available_;
++  int used_;
++
++#ifdef _WIN32
++  // @TODO
++#else
++  int rfd_;
++  int wfd_;
++
++  struct sigaction old_act_;
++  bool restore_;
++
++  static int dup_rfd_;
++  static void CloseDupRfd(int signum);
++
++  bool CheckFd(int fd);
++  bool SetAlarmHandler();
++#endif
++
++  void Return();
++};
++
++// every instance owns an implicit token -> available_ == 1
++GNUmakeTokenPool::GNUmakeTokenPool() : available_(1), used_(0),
++                                       rfd_(-1), wfd_(-1), restore_(false) {
++}
++
++GNUmakeTokenPool::~GNUmakeTokenPool() {
++  Clear();
++  if (restore_)
++    sigaction(SIGALRM, &old_act_, NULL);
++}
++
++bool GNUmakeTokenPool::CheckFd(int fd) {
++  if (fd < 0)
++    return false;
++  int ret = fcntl(fd, F_GETFD);
++  if (ret < 0)
++    return false;
++  return true;
++}
++
++int GNUmakeTokenPool::dup_rfd_ = -1;
++
++void GNUmakeTokenPool::CloseDupRfd(int signum) {
++  close(dup_rfd_);
++  dup_rfd_ = -1;
++}
++
++bool GNUmakeTokenPool::SetAlarmHandler() {
++  struct sigaction act;
++  memset(&act, 0, sizeof(act));
++  act.sa_handler = CloseDupRfd;
++  if (sigaction(SIGALRM, &act, &old_act_) < 0) {
++    perror("sigaction:");
++    return(false);
++  } else {
++    restore_ = true;
++    return(true);
++  }
++}
++
++bool GNUmakeTokenPool::Setup() {
++  const char *value = getenv("MAKEFLAGS");
++  if (value) {
++    // GNU make <= 4.1
++    const char *jobserver = strstr(value, "--jobserver-fds=");
++    // GNU make => 4.2
++    if (!jobserver)
++      jobserver = strstr(value, "--jobserver-auth=");
++    if (jobserver) {
++      int rfd = -1;
++      int wfd = -1;
++      if ((sscanf(jobserver, "%*[^=]=%d,%d", &rfd, &wfd) == 2) &&
++          CheckFd(rfd) &&
++          CheckFd(wfd) &&
++          SetAlarmHandler()) {
++        printf("ninja: using GNU make jobserver.\n");
++        rfd_ = rfd;
++        wfd_ = wfd;
++        return true;
++      }
++    }
++  }
++
++  return false;
++}
++
++bool GNUmakeTokenPool::Acquire() {
++  if (available_ > 0)
++    return true;
++
++#ifdef USE_PPOLL
++  pollfd pollfds[] = {{rfd_, POLLIN, 0}};
++  int ret = poll(pollfds, 1, 0);
++#else
++  fd_set set;
++  struct timeval timeout = { 0, 0 };
++  FD_ZERO(&set);
++  FD_SET(rfd_, &set);
++  int ret = select(rfd_ + 1, &set, NULL, NULL, &timeout);
++#endif
++  if (ret > 0) {
++    dup_rfd_ = dup(rfd_);
++
++    if (dup_rfd_ != -1) {
++      struct sigaction act, old_act;
++      int ret = 0;
++
++      memset(&act, 0, sizeof(act));
++      act.sa_handler = CloseDupRfd;
++      if (sigaction(SIGCHLD, &act, &old_act) == 0) {
++        char buf;
++
++        // block until token read, child exits or timeout
++        alarm(1);
++        ret = read(dup_rfd_, &buf, 1);
++        alarm(0);
++
++        sigaction(SIGCHLD, &old_act, NULL);
++      }
++
++      CloseDupRfd(0);
++
++      if (ret > 0) {
++        available_++;
++        return true;
++      }
++    }
++  }
++  return false;
++}
++
++void GNUmakeTokenPool::Reserve() {
++  available_--;
++  used_++;
++}
++
++void GNUmakeTokenPool::Return() {
++  const char buf = '+';
++  while (1) {
++    int ret = write(wfd_, &buf, 1);
++    if (ret > 0)
++      available_--;
++    if ((ret != -1) || (errno != EINTR))
++      return;
++    // write got interrupted - retry
++  }
++}
++
++void GNUmakeTokenPool::Release() {
++  available_++;
++  used_--;
++  if (available_ > 1)
++    Return();
++}
++
++void GNUmakeTokenPool::Clear() {
++  while (used_ > 0)
++    Release();
++  while (available_ > 1)
++    Return();
++}
++
++struct TokenPool *TokenPool::Get(void) {
++  GNUmakeTokenPool *tokenpool = new GNUmakeTokenPool;
++  if (tokenpool->Setup())
++    return tokenpool;
++  else
++    delete tokenpool;
++  return NULL;
++}
+diff --git a/src/tokenpool-none.cc b/src/tokenpool-none.cc
+new file mode 100644
+index 0000000..602b331
+--- /dev/null
++++ b/src/tokenpool-none.cc
+@@ -0,0 +1,27 @@
++// Copyright 2016 Google Inc. All Rights Reserved.
++//
++// Licensed 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 "tokenpool.h"
++
++#include <fcntl.h>
++#include <poll.h>
++#include <unistd.h>
++#include <stdio.h>
++#include <string.h>
++#include <stdlib.h>
++
++// No-op TokenPool implementation
++struct TokenPool *TokenPool::Get(void) {
++  return NULL;
++}
+diff --git a/src/tokenpool.h b/src/tokenpool.h
+new file mode 100644
+index 0000000..f560b10
+--- /dev/null
++++ b/src/tokenpool.h
+@@ -0,0 +1,26 @@
++// Copyright 2016 Google Inc. All Rights Reserved.
++//
++// Licensed 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.
++
++// interface to token pool
++struct TokenPool {
++  virtual ~TokenPool() {}
++
++  virtual bool Acquire() = 0;
++  virtual void Reserve() = 0;
++  virtual void Release() = 0;
++  virtual void Clear() = 0;
++
++  // returns NULL if token pool is not available
++  static struct TokenPool *Get(void);
++};
+-- 
+2.44.0
+
meta/recipes-devtools/ninja/files/0002-Add-TokenPool-monitoring-to-SubprocessSet-DoWork.patch new file +560 -0

560 lines not on this page · raw message

meta/recipes-devtools/ninja/files/0003-Ignore-jobserver-when-jN-is-forced-on-command-line.patch new file +198 -0

198 lines not on this page · raw message

meta/recipes-devtools/ninja/files/0004-Honor-lN-from-MAKEFLAGS.patch new file +134 -0

134 lines not on this page · raw message

meta/recipes-devtools/ninja/files/0005-Use-LinePrinter-for-TokenPool-messages.patch new file +128 -0

128 lines not on this page · raw message

meta/recipes-devtools/ninja/files/0006-Prepare-PR-for-merging.patch new file +156 -0

156 lines not on this page · raw message

meta/recipes-devtools/ninja/files/0007-Add-tests-for-TokenPool.patch new file +237 -0

237 lines not on this page · raw message

meta/recipes-devtools/ninja/files/0008-Add-tests-for-subprocess-module.patch new file +121 -0

121 lines not on this page · raw message

meta/recipes-devtools/ninja/files/0009-Add-tests-for-build-module.patch new file +397 -0

397 lines not on this page · raw message

meta/recipes-devtools/ninja/files/0010-Add-Win32-implementation-for-GNUmakeTokenPool.patch new file +1283 -0

575 lines not on this page · raw message

meta/recipes-devtools/ninja/files/0011-Prepare-PR-for-merging-part-II.patch new file +744 -0

744 lines not on this page · raw message

meta/recipes-devtools/ninja/files/0012-Rename-TokenPool-Setup-to-SetupClient.patch new file +109 -0

109 lines not on this page · raw message

meta/recipes-devtools/ninja/files/0013-Add-TokenPool-SetupMaster-method.patch new file +78 -0

78 lines not on this page · raw message

meta/recipes-devtools/ninja/files/0014-Add-command-line-option-m-tokenpool-master.patch new file +101 -0

101 lines not on this page · raw message

meta/recipes-devtools/ninja/files/0015-Implement-GNUmakeTokenPool-SetupMaster.patch new file +152 -0

152 lines not on this page · raw message

meta/recipes-devtools/ninja/files/0016-Implement-GNUmakeTokenPool-CreatePool.patch new file +87 -0

87 lines not on this page · raw message

meta/recipes-devtools/ninja/files/0017-Add-tests-for-TokenPool-SetupMaster.patch new file +145 -0

145 lines not on this page · raw message

meta/recipes-devtools/ninja/files/0018-Add-GNU-make-jobserver-fifo-style-client-support.patch new file +265 -0

265 lines not on this page · raw message

meta/recipes-devtools/ninja/files/0019-Add-optional-argument-to-m-tokenpool-master.patch new file +368 -0

368 lines not on this page · raw message

meta/recipes-devtools/ninja/files/0020-Add-GNU-make-jobserver-fifo-style-master-support.patch new file +287 -0

287 lines not on this page · raw message

meta/recipes-devtools/ninja/ninja_1.11.1.bb deleted +0 -33
deleted file mode 100644
index 8e297ec4d4..0000000000

Lines of this file are not shown. View the raw message.

meta/recipes-devtools/ninja/ninja_1.12.0.bb new file +55 -0

55 lines not on this page · raw message

The rest of this diff is not shown. View the raw message.

Signature · 1 line
2.44.0

Part of the diff is not shown here. View the raw message.

#6 lore raw

Patchtest results for [PATCH 3/5] ninja: build modified version with GNU Make jobserver support

Thank you for your submission. Patchtest identified one or more issues with the patch. Please see the log below for more information:

---
Testing patch /home/patchtest/share/mboxes/3-5-ninja-build-modified-version-with-GNU-Make-jobserver-support.patch

FAIL: test Signed-off-by presence: A patch file has been added without a Signed-off-by tag: '0001-Add-GNU-make-jobserver-client-support.patch' (test_patch.TestPatch.test_signed_off_by_presence)

PASS: test CVE tag format (test_patch.TestPatch.test_cve_tag_format)
PASS: test Signed-off-by presence (test_mbox.TestMbox.test_signed_off_by_presence)
PASS: test Upstream-Status presence (test_patch.TestPatch.test_upstream_status_presence_format)
PASS: test author valid (test_mbox.TestMbox.test_author_valid)
PASS: test commit message presence (test_mbox.TestMbox.test_commit_message_presence)
PASS: test lic files chksum presence (test_metadata.TestMetadata.test_lic_files_chksum_presence)
PASS: test license presence (test_metadata.TestMetadata.test_license_presence)
PASS: test max line length (test_metadata.TestMetadata.test_max_line_length)
PASS: test mbox format (test_mbox.TestMbox.test_mbox_format)
PASS: test non-AUH upgrade (test_mbox.TestMbox.test_non_auh_upgrade)
PASS: test shortlog format (test_mbox.TestMbox.test_shortlog_format)
PASS: test shortlog length (test_mbox.TestMbox.test_shortlog_length)
PASS: test summary presence (test_metadata.TestMetadata.test_summary_presence)

SKIP: pretest pylint: No python related patches, skipping test (test_python_pylint.PyLint.pretest_pylint)
SKIP: pretest src uri left files: No modified recipes, skipping pretest (test_metadata.TestMetadata.pretest_src_uri_left_files)
SKIP: test CVE check ignore: No modified recipes or older target branch, skipping test (test_metadata.TestMetadata.test_cve_check_ignore)
SKIP: test bugzilla entry format: No bug ID found (test_mbox.TestMbox.test_bugzilla_entry_format)
SKIP: test lic files chksum modified not mentioned: No modified recipes, skipping test (test_metadata.TestMetadata.test_lic_files_chksum_modified_not_mentioned)
SKIP: test pylint: No python related patches, skipping test (test_python_pylint.PyLint.test_pylint)
SKIP: test series merge on head: Merge test is disabled for now (test_mbox.TestMbox.test_series_merge_on_head)
SKIP: test src uri left files: No modified recipes, skipping pretest (test_metadata.TestMetadata.test_src_uri_left_files)
SKIP: test target mailing list: Series merged, no reason to check other mailing lists (test_mbox.TestMbox.test_target_mailing_list)

---

Please address the issues identified and
submit a new revision of the patch, or alternatively, reply to this email with an explanation of why the patch should be accepted. If you believe these results are due to an error in patchtest, please submit a bug at https://bugzilla.yoctoproject.org/ (use the 'Patchtest' category under 'Yocto Project Subprojects'). For more information on specific failures, see: https://wiki.yoctoproject.org/wiki/Patchtest. Thank you!

#7 lore raw

Re: [PATCH 3/5] ninja: build modified version with GNU Make jobserver support

In reply to Martin Hundebøll

We can't carry this mass of patches. It has to land upstream first.

Are you able/willing to drive the upstream pull request to completion?

Alex

Quoted 6,326 lines · Martin Hundebøll

Ninja doesn't (yet) support the GNU Make jobserver out of the box, but there is a pull request adding that support[1]. Add the pull request commits as patches to ninja to make it cooperate with the make jobserver feature.

In order to make the patces apply, the ninja version is bumped to the unreleased 1.12.0.

[1] https://github.com/ninja-build/ninja/pull/2263

---
 ...dd-GNU-make-jobserver-client-support.patch |  494 +++++++
 ...l-monitoring-to-SubprocessSet-DoWork.patch |  560 +++++++
 ...er-when-jN-is-forced-on-command-line.patch |  198 +++
 .../files/0004-Honor-lN-from-MAKEFLAGS.patch  |  134 ++
 ...e-LinePrinter-for-TokenPool-messages.patch |  128 ++
 .../files/0006-Prepare-PR-for-merging.patch   |  156 ++
 .../files/0007-Add-tests-for-TokenPool.patch  |  237 +++
 ...0008-Add-tests-for-subprocess-module.patch |  121 ++
 .../0009-Add-tests-for-build-module.patch     |  397 +++++
 ...-implementation-for-GNUmakeTokenPool.patch | 1283 +++++++++++++++++
 .../0011-Prepare-PR-for-merging-part-II.patch |  744 ++++++++++
 ...ename-TokenPool-Setup-to-SetupClient.patch |  109 ++
 ...013-Add-TokenPool-SetupMaster-method.patch |   78 +
 ...mmand-line-option-m-tokenpool-master.patch |  101 ++
 ...plement-GNUmakeTokenPool-SetupMaster.patch |  152 ++
 ...mplement-GNUmakeTokenPool-CreatePool.patch |   87 ++
 ...-Add-tests-for-TokenPool-SetupMaster.patch |  145 ++
 ...-jobserver-fifo-style-client-support.patch |  265 ++++
 ...ional-argument-to-m-tokenpool-master.patch |  368 +++++
 ...-jobserver-fifo-style-master-support.patch |  287 ++++
 meta/recipes-devtools/ninja/ninja_1.11.1.bb   |   33 -
 meta/recipes-devtools/ninja/ninja_1.12.0.bb   |   55 +
 22 files changed, 6099 insertions(+), 33 deletions(-)
 create mode 100644 meta/recipes-devtools/ninja/files/0001-Add-GNU-make-jobserver-client-support.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0002-Add-TokenPool-monitoring-to-SubprocessSet-DoWork.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0003-Ignore-jobserver-when-jN-is-forced-on-command-line.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0004-Honor-lN-from-MAKEFLAGS.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0005-Use-LinePrinter-for-TokenPool-messages.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0006-Prepare-PR-for-merging.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0007-Add-tests-for-TokenPool.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0008-Add-tests-for-subprocess-module.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0009-Add-tests-for-build-module.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0010-Add-Win32-implementation-for-GNUmakeTokenPool.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0011-Prepare-PR-for-merging-part-II.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0012-Rename-TokenPool-Setup-to-SetupClient.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0013-Add-TokenPool-SetupMaster-method.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0014-Add-command-line-option-m-tokenpool-master.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0015-Implement-GNUmakeTokenPool-SetupMaster.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0016-Implement-GNUmakeTokenPool-CreatePool.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0017-Add-tests-for-TokenPool-SetupMaster.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0018-Add-GNU-make-jobserver-fifo-style-client-support.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0019-Add-optional-argument-to-m-tokenpool-master.patch
 create mode 100644 meta/recipes-devtools/ninja/files/0020-Add-GNU-make-jobserver-fifo-style-master-support.patch
 delete mode 100644 meta/recipes-devtools/ninja/ninja_1.11.1.bb
 create mode 100644 meta/recipes-devtools/ninja/ninja_1.12.0.bb
meta/recipes-devtools/ninja/files/0001-Add-GNU-make-jobserver-client-support.patch new file +494 -0
new file mode 100644
index 0000000000..c882a57a90
@@ -0,0 +1,494 @@
+From 3e04d21231e64129f6fffba7fd37d94b185dae45 Mon Sep 17 00:00:00 2001
+From: Stefan Becker <[email protected]>
+Date: Tue, 22 Mar 2016 13:48:07 +0200
+Subject: [PATCH 01/20] Add GNU make jobserver client support
+
+- add new TokenPool interface
+- GNU make implementation for TokenPool parses and verifies the magic
+  information from the MAKEFLAGS environment variable
+- RealCommandRunner tries to acquire TokenPool
+  * if no token pool is available then there is no change in behaviour
+- When a token pool is available then RealCommandRunner behaviour
+  changes as follows
+  * CanRunMore() only returns true if TokenPool::Acquire() returns true
+  * StartCommand() calls TokenPool::Reserve()
+  * WaitForCommand() calls TokenPool::Release()
+
+Documentation for GNU make jobserver
+
+  http://make.mad-scientist.net/papers/jobserver-implementation/
+
+Fixes https://github.com/ninja-build/ninja/issues/1139
+
+Upstream-Status: Submitted [https://github.com/ninja-build/ninja/pull/1140]
+---
+ configure.py              |   2 +
+ src/build.cc              |  63 ++++++++----
+ src/build.h               |   3 +
+ src/tokenpool-gnu-make.cc | 211 ++++++++++++++++++++++++++++++++++++++
+ src/tokenpool-none.cc     |  27 +++++
+ src/tokenpool.h           |  26 +++++
+ 6 files changed, 310 insertions(+), 22 deletions(-)
+ create mode 100644 src/tokenpool-gnu-make.cc
+ create mode 100644 src/tokenpool-none.cc
+ create mode 100644 src/tokenpool.h
+
+diff --git a/configure.py b/configure.py
+index 588250a..d95fad8 100755
+--- a/configure.py
++++ b/configure.py
+@@ -543,6 +543,7 @@ for name in ['build',
+     objs += cxx(name, variables=cxxvariables)
+ if platform.is_windows():
+     for name in ['subprocess-win32',
++                 'tokenpool-none',
+                  'includes_normalize-win32',
+                  'msvc_helper-win32',
+                  'msvc_helper_main-win32']:
+@@ -552,6 +553,7 @@ if platform.is_windows():
+     objs += cc('getopt')
+ else:
+     objs += cxx('subprocess-posix')
++    objs += cxx('tokenpool-gnu-make')
+ if platform.is_aix():
+     objs += cc('getopt')
+ if platform.is_msvc():
+diff --git a/src/build.cc b/src/build.cc
+index 76ff93a..02ea93b 100644
+--- a/src/build.cc
++++ b/src/build.cc
+@@ -35,6 +35,7 @@
+ #include "state.h"
+ #include "status.h"
+ #include "subprocess.h"
++#include "tokenpool.h"
+ #include "util.h"
+
+ using namespace std;
+@@ -149,7 +150,7 @@ void Plan::EdgeWanted(const Edge* edge) {
+ }
+
+ Edge* Plan::FindWork() {
+-  if (ready_.empty())
++  if (!more_ready())
+     return NULL;
+   EdgeSet::iterator e = ready_.begin();
+   Edge* edge = *e;
+@@ -448,8 +449,8 @@ void Plan::Dump() const {
+ }
+
+ struct RealCommandRunner : public CommandRunner {
+-  explicit RealCommandRunner(const BuildConfig& config) : config_(config) {}
+-  virtual ~RealCommandRunner() {}
++  explicit RealCommandRunner(const BuildConfig& config);
++  virtual ~RealCommandRunner();
+   virtual bool CanRunMore() const;
+   virtual bool StartCommand(Edge* edge);
+   virtual bool WaitForCommand(Result* result);
+@@ -458,9 +459,18 @@ struct RealCommandRunner : public CommandRunner {
+
+   const BuildConfig& config_;
+   SubprocessSet subprocs_;
++  TokenPool *tokens_;
+   map<const Subprocess*, Edge*> subproc_to_edge_;
+ };
+
++RealCommandRunner::RealCommandRunner(const BuildConfig& config) : config_(config) {
++  tokens_ = TokenPool::Get();
++}
++
++RealCommandRunner::~RealCommandRunner() {
++  delete tokens_;
++}
++
+ vector<Edge*> RealCommandRunner::GetActiveEdges() {
+   vector<Edge*> edges;
+   for (map<const Subprocess*, Edge*>::iterator e = subproc_to_edge_.begin();
+@@ -471,14 +481,18 @@ vector<Edge*> RealCommandRunner::GetActiveEdges() {
+
+ void RealCommandRunner::Abort() {
+   subprocs_.Clear();
++  if (tokens_)
++    tokens_->Clear();
+ }
+
+ bool RealCommandRunner::CanRunMore() const {
+   size_t subproc_number =
+       subprocs_.running_.size() + subprocs_.finished_.size();
+   return (int)subproc_number < config_.parallelism
+-    && ((subprocs_.running_.empty() || config_.max_load_average <= 0.0f)
+-        || GetLoadAverage() < config_.max_load_average);
++    && (subprocs_.running_.empty() ||
++        ((config_.max_load_average <= 0.0f ||
++          GetLoadAverage() < config_.max_load_average)
++      && (!tokens_ || tokens_->Acquire())));
+ }
+
+ bool RealCommandRunner::StartCommand(Edge* edge) {
+@@ -486,6 +500,8 @@ bool RealCommandRunner::StartCommand(Edge* edge) {
+   Subprocess* subproc = subprocs_.Add(command, edge->use_console());
+   if (!subproc)
+     return false;
++  if (tokens_)
++    tokens_->Reserve();
+   subproc_to_edge_.insert(make_pair(subproc, edge));
+
+   return true;
+@@ -499,6 +515,9 @@ bool RealCommandRunner::WaitForCommand(Result* result) {
+       return false;
+   }
+
++  if (tokens_)
++    tokens_->Release();
++
+   result->status = subproc->Finish();
+   result->output = subproc->GetOutput();
+
+@@ -629,31 +648,31 @@ bool Builder::Build(string* err) {
+   // Second, we attempt to wait for / reap the next finished command.
+   while (plan_.more_to_do()) {
+     // See if we can start any more commands.
+-    if (failures_allowed && command_runner_->CanRunMore()) {
+-      if (Edge* edge = plan_.FindWork()) {
+-        if (edge->GetBindingBool("generator")) {
++    if (failures_allowed && plan_.more_ready() &&
++        command_runner_->CanRunMore()) {
++      Edge* edge = plan_.FindWork();
++      if (edge->GetBindingBool("generator")) {
+           scan_.build_log()->Close();
+         }
+
+-        if (!StartEdge(edge, err)) {
++      if (!StartEdge(edge, err)) {
++        Cleanup();
++        status_->BuildFinished();
++        return false;
++      }
++
++      if (edge->is_phony()) {
++        if (!plan_.EdgeFinished(edge, Plan::kEdgeSucceeded, err)) {
+           Cleanup();
+           status_->BuildFinished();
+           return false;
+         }
+-
+-        if (edge->is_phony()) {
+-          if (!plan_.EdgeFinished(edge, Plan::kEdgeSucceeded, err)) {
+-            Cleanup();
+-            status_->BuildFinished();
+-            return false;
+-          }
+-        } else {
+-          ++pending_commands;
+-        }
+-
+-        // We made some progress; go back to the main loop.
+-        continue;
++      } else {
++        ++pending_commands;
+       }
++
++      // We made some progress; go back to the main loop.
++      continue;
+     }
+
+     // See if we can reap any finished commands.
+diff --git a/src/build.h b/src/build.h
+index 8ec2355..09667aa 100644
+--- a/src/build.h
++++ b/src/build.h
+@@ -52,6 +52,9 @@ struct Plan {
+   /// Returns true if there's more work to be done.
+   bool more_to_do() const { return wanted_edges_ > 0 && command_edges_ > 0; }
+
++  /// Returns true if there's more edges ready to start
++  bool more_ready() const { return !ready_.empty(); }
++
+   /// Dumps the current state of the plan.
+   void Dump() const;
+
+diff --git a/src/tokenpool-gnu-make.cc b/src/tokenpool-gnu-make.cc
+new file mode 100644
+index 0000000..a8f9b71
+--- /dev/null
++++ b/src/tokenpool-gnu-make.cc
+@@ -0,0 +1,211 @@
++// Copyright 2016 Google Inc. All Rights Reserved.
++//
++// Licensed 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 "tokenpool.h"
++
++#include <errno.h>
++#include <fcntl.h>
++#include <poll.h>
++#include <unistd.h>
++#include <signal.h>
++#include <stdio.h>
++#include <string.h>
++#include <stdlib.h>
++
++// TokenPool implementation for GNU make jobserver
++// (http://make.mad-scientist.net/papers/jobserver-implementation/)
++struct GNUmakeTokenPool : public TokenPool {
++  GNUmakeTokenPool();
++  virtual ~GNUmakeTokenPool();
++
++  virtual bool Acquire();
++  virtual void Reserve();
++  virtual void Release();
++  virtual void Clear();
++
++  bool Setup();
++
++ private:
++  int available_;
++  int used_;
++
++#ifdef _WIN32
++  // @TODO
++#else
++  int rfd_;
++  int wfd_;
++
++  struct sigaction old_act_;
++  bool restore_;
++
++  static int dup_rfd_;
++  static void CloseDupRfd(int signum);
++
++  bool CheckFd(int fd);
++  bool SetAlarmHandler();
++#endif
++
++  void Return();
++};
++
++// every instance owns an implicit token -> available_ == 1
++GNUmakeTokenPool::GNUmakeTokenPool() : available_(1), used_(0),
++                                       rfd_(-1), wfd_(-1), restore_(false) {
++}
++
++GNUmakeTokenPool::~GNUmakeTokenPool() {
++  Clear();
++  if (restore_)
++    sigaction(SIGALRM, &old_act_, NULL);
++}
++
++bool GNUmakeTokenPool::CheckFd(int fd) {
++  if (fd < 0)
++    return false;
++  int ret = fcntl(fd, F_GETFD);
++  if (ret < 0)
++    return false;
++  return true;
++}
++
++int GNUmakeTokenPool::dup_rfd_ = -1;
++
++void GNUmakeTokenPool::CloseDupRfd(int signum) {
++  close(dup_rfd_);
++  dup_rfd_ = -1;
++}
++
++bool GNUmakeTokenPool::SetAlarmHandler() {
++  struct sigaction act;
++  memset(&act, 0, sizeof(act));
++  act.sa_handler = CloseDupRfd;
++  if (sigaction(SIGALRM, &act, &old_act_) < 0) {
++    perror("sigaction:");
++    return(false);
++  } else {
++    restore_ = true;
++    return(true);
++  }
++}
++
++bool GNUmakeTokenPool::Setup() {
++  const char *value = getenv("MAKEFLAGS");
++  if (value) {
++    // GNU make <= 4.1
++    const char *jobserver = strstr(value, "--jobserver-fds=");
++    // GNU make => 4.2
++    if (!jobserver)
++      jobserver = strstr(value, "--jobserver-auth=");
++    if (jobserver) {
++      int rfd = -1;
++      int wfd = -1;
++      if ((sscanf(jobserver, "%*[^=]=%d,%d", &rfd, &wfd) == 2) &&
++          CheckFd(rfd) &&
++          CheckFd(wfd) &&
++          SetAlarmHandler()) {
++        printf("ninja: using GNU make jobserver.\n");
++        rfd_ = rfd;
++        wfd_ = wfd;
++        return true;
++      }
++    }
++  }
++
++  return false;
++}
++
++bool GNUmakeTokenPool::Acquire() {
++  if (available_ > 0)
++    return true;
++
++#ifdef USE_PPOLL
++  pollfd pollfds[] = {{rfd_, POLLIN, 0}};
++  int ret = poll(pollfds, 1, 0);
++#else
++  fd_set set;
++  struct timeval timeout = { 0, 0 };
++  FD_ZERO(&set);
++  FD_SET(rfd_, &set);
++  int ret = select(rfd_ + 1, &set, NULL, NULL, &timeout);
++#endif
++  if (ret > 0) {
++    dup_rfd_ = dup(rfd_);
++
++    if (dup_rfd_ != -1) {
++      struct sigaction act, old_act;
++      int ret = 0;
++
++      memset(&act, 0, sizeof(act));
++      act.sa_handler = CloseDupRfd;
++      if (sigaction(SIGCHLD, &act, &old_act) == 0) {
++        char buf;
++
++        // block until token read, child exits or timeout
++        alarm(1);
++        ret = read(dup_rfd_, &buf, 1);
++        alarm(0);
++
++        sigaction(SIGCHLD, &old_act, NULL);
++      }
++
++      CloseDupRfd(0);
++
++      if (ret > 0) {
++        available_++;
++        return true;
++      }
++    }
++  }
++  return false;
++}
++
++void GNUmakeTokenPool::Reserve() {
++  available_--;
++  used_++;
++}
++
++void GNUmakeTokenPool::Return() {
++  const char buf = '+';
++  while (1) {
++    int ret = write(wfd_, &buf, 1);
++    if (ret > 0)
++      available_--;
++    if ((ret != -1) || (errno != EINTR))
++      return;
++    // write got interrupted - retry
++  }
++}
++
++void GNUmakeTokenPool::Release() {
++  available_++;
++  used_--;
++  if (available_ > 1)
++    Return();
++}
++
++void GNUmakeTokenPool::Clear() {
++  while (used_ > 0)
++    Release();
++  while (available_ > 1)
++    Return();
++}
++
++struct TokenPool *TokenPool::Get(void) {
++  GNUmakeTokenPool *tokenpool = new GNUmakeTokenPool;
++  if (tokenpool->Setup())
++    return tokenpool;
++  else
++    delete tokenpool;
++  return NULL;
++}
+diff --git a/src/tokenpool-none.cc b/src/tokenpool-none.cc
+new file mode 100644
+index 0000000..602b331
+--- /dev/null
++++ b/src/tokenpool-none.cc
+@@ -0,0 +1,27 @@
++// Copyright 2016 Google Inc. All Rights Reserved.
++//
++// Licensed 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 "tokenpool.h"
++
++#include <fcntl.h>
++#include <poll.h>
++#include <unistd.h>
++#include <stdio.h>
++#include <string.h>
++#include <stdlib.h>
++
++// No-op TokenPool implementation
++struct TokenPool *TokenPool::Get(void) {
++  return NULL;
++}
+diff --git a/src/tokenpool.h b/src/tokenpool.h
+new file mode 100644
+index 0000000..f560b10
+--- /dev/null
++++ b/src/tokenpool.h
+@@ -0,0 +1,26 @@
++// Copyright 2016 Google Inc. All Rights Reserved.
++//
++// Licensed 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.
++
++// interface to token pool
++struct TokenPool {
++  virtual ~TokenPool() {}
++
++  virtual bool Acquire() = 0;
++  virtual void Reserve() = 0;
++  virtual void Release() = 0;
++  virtual void Clear() = 0;
++
++  // returns NULL if token pool is not available
++  static struct TokenPool *Get(void);
++};
+--
+2.44.0
+
meta/recipes-devtools/ninja/files/0002-Add-TokenPool-monitoring-to-SubprocessSet-DoWork.patch new file +560 -0
new file mode 100644
index 0000000000..73c361211d
@@ -0,0 +1,560 @@
+From 5c8dc535c2bfdfb1d8e1bc62fa34afe536e9533e Mon Sep 17 00:00:00 2001
+From: Stefan Becker <[email protected]>
+Date: Fri, 27 May 2016 16:47:10 +0300
+Subject: [PATCH 02/20] Add TokenPool monitoring to SubprocessSet::DoWork()
+
+Improve on the original jobserver client implementation. This makes
+ninja a more aggressive GNU make jobserver client.
+
+- add monitor interface to TokenPool
+- TokenPool is passed down when main loop indicates that more work is
+  ready and would be allowed to start if a token becomes available
+- posix: update DoWork() to monitor TokenPool read file descriptor
+- WaitForCommand() exits when DoWork() sets token flag
+- Main loop starts over when WaitForCommand() sets token exit status
+
+Upstream-Status: Submitted [https://github.com/ninja-build/ninja/pull/1140]
+---
+ src/build.cc              | 53 +++++++++++++++++++++++++++++----------
+ src/build.h               |  3 ++-
+ src/build_test.cc         |  9 +++++--
+ src/exit_status.h         |  3 ++-
+ src/subprocess-posix.cc   | 33 ++++++++++++++++++++++--
+ src/subprocess-win32.cc   |  2 +-
+ src/subprocess.h          |  8 +++++-
+ src/subprocess_test.cc    | 47 +++++++++++++++++++++++-----------
+ src/tokenpool-gnu-make.cc |  5 ++++
+ src/tokenpool.h           |  6 +++++
+ 10 files changed, 134 insertions(+), 35 deletions(-)
+
+diff --git a/src/build.cc b/src/build.cc
+index 02ea93b..01a4b6b 100644
+--- a/src/build.cc
++++ b/src/build.cc
+@@ -48,8 +48,9 @@ struct DryRunCommandRunner : public CommandRunner {
+
+   // Overridden from CommandRunner:
+   virtual bool CanRunMore() const;
++  virtual bool AcquireToken();
+   virtual bool StartCommand(Edge* edge);
+-  virtual bool WaitForCommand(Result* result);
++  virtual bool WaitForCommand(Result* result, bool more_ready);
+
+  private:
+   queue<Edge*> finished_;
+@@ -59,12 +60,16 @@ bool DryRunCommandRunner::CanRunMore() const {
+   return true;
+ }
+
++bool DryRunCommandRunner::AcquireToken() {
++  return true;
++}
++
+ bool DryRunCommandRunner::StartCommand(Edge* edge) {
+   finished_.push(edge);
+   return true;
+ }
+
+-bool DryRunCommandRunner::WaitForCommand(Result* result) {
++bool DryRunCommandRunner::WaitForCommand(Result* result, bool more_ready) {
+    if (finished_.empty())
+      return false;
+
+@@ -452,8 +457,9 @@ struct RealCommandRunner : public CommandRunner {
+   explicit RealCommandRunner(const BuildConfig& config);
+   virtual ~RealCommandRunner();
+   virtual bool CanRunMore() const;
++  virtual bool AcquireToken();
+   virtual bool StartCommand(Edge* edge);
+-  virtual bool WaitForCommand(Result* result);
++  virtual bool WaitForCommand(Result* result, bool more_ready);
+   virtual vector<Edge*> GetActiveEdges();
+   virtual void Abort();
+
+@@ -490,9 +496,12 @@ bool RealCommandRunner::CanRunMore() const {
+       subprocs_.running_.size() + subprocs_.finished_.size();
+   return (int)subproc_number < config_.parallelism
+     && (subprocs_.running_.empty() ||
+-        ((config_.max_load_average <= 0.0f ||
+-          GetLoadAverage() < config_.max_load_average)
+-      && (!tokens_ || tokens_->Acquire())));
++        (config_.max_load_average <= 0.0f ||
++         GetLoadAverage() < config_.max_load_average));
++}
++
++bool RealCommandRunner::AcquireToken() {
++  return (!tokens_ || tokens_->Acquire());
+ }
+
+ bool RealCommandRunner::StartCommand(Edge* edge) {
+@@ -507,14 +516,23 @@ bool RealCommandRunner::StartCommand(Edge* edge) {
+   return true;
+ }
+
+-bool RealCommandRunner::WaitForCommand(Result* result) {
++bool RealCommandRunner::WaitForCommand(Result* result, bool more_ready) {
+   Subprocess* subproc;
+-  while ((subproc = subprocs_.NextFinished()) == NULL) {
+-    bool interrupted = subprocs_.DoWork();
++  subprocs_.ResetTokenAvailable();
++  while (((subproc = subprocs_.NextFinished()) == NULL) &&
++         !subprocs_.IsTokenAvailable()) {
++    bool interrupted = subprocs_.DoWork(more_ready ? tokens_ : NULL);
+     if (interrupted)
+       return false;
+   }
+
++  // token became available
++  if (subproc == NULL) {
++    result->status = ExitTokenAvailable;
++    return true;
++  }
++
++  // command completed
+   if (tokens_)
+     tokens_->Release();
+
+@@ -647,9 +665,14 @@ bool Builder::Build(string* err) {
+   // command runner.
+   // Second, we attempt to wait for / reap the next finished command.
+   while (plan_.more_to_do()) {
+-    // See if we can start any more commands.
+-    if (failures_allowed && plan_.more_ready() &&
+-        command_runner_->CanRunMore()) {
++    // See if we can start any more commands...
++    bool can_run_more =
++        failures_allowed   &&
++        plan_.more_ready() &&
++        command_runner_->CanRunMore();
++
++    // ... but we also need a token to do that.
++    if (can_run_more && command_runner_->AcquireToken()) {
+       Edge* edge = plan_.FindWork();
+       if (edge->GetBindingBool("generator")) {
+           scan_.build_log()->Close();
+@@ -678,7 +701,7 @@ bool Builder::Build(string* err) {
+     // See if we can reap any finished commands.
+     if (pending_commands) {
+       CommandRunner::Result result;
+-      if (!command_runner_->WaitForCommand(&result) ||
++      if (!command_runner_->WaitForCommand(&result, can_run_more) ||
+           result.status == ExitInterrupted) {
+         Cleanup();
+         status_->BuildFinished();
+@@ -686,6 +709,10 @@ bool Builder::Build(string* err) {
+         return false;
+       }
+
++      // We might be able to start another command; start the main loop over.
++      if (result.status == ExitTokenAvailable)
++        continue;
++
+       --pending_commands;
+       if (!FinishCommand(&result, err)) {
+         Cleanup();
+diff --git a/src/build.h b/src/build.h
+index 09667aa..50b4be3 100644
+--- a/src/build.h
++++ b/src/build.h
+@@ -139,6 +139,7 @@ private:
+ struct CommandRunner {
+   virtual ~CommandRunner() {}
+   virtual bool CanRunMore() const = 0;
++  virtual bool AcquireToken() = 0;
+   virtual bool StartCommand(Edge* edge) = 0;
+
+   /// The result of waiting for a command.
+@@ -150,7 +151,7 @@ struct CommandRunner {
+     bool success() const { return status == ExitSuccess; }
+   };
+   /// Wait for a command to complete, or return false if interrupted.
+-  virtual bool WaitForCommand(Result* result) = 0;
++  virtual bool WaitForCommand(Result* result, bool more_ready) = 0;
+
+   virtual std::vector<Edge*> GetActiveEdges() { return std::vector<Edge*>(); }
+   virtual void Abort() {}
+diff --git a/src/build_test.cc b/src/build_test.cc
+index 3908761..efa5662 100644
+--- a/src/build_test.cc
++++ b/src/build_test.cc
+@@ -474,8 +474,9 @@ struct FakeCommandRunner : public CommandRunner {
+
+   // CommandRunner impl
+   virtual bool CanRunMore() const;
++  virtual bool AcquireToken();
+   virtual bool StartCommand(Edge* edge);
+-  virtual bool WaitForCommand(Result* result);
++  virtual bool WaitForCommand(Result* result, bool more_ready);
+   virtual vector<Edge*> GetActiveEdges();
+   virtual void Abort();
+
+@@ -578,6 +579,10 @@ bool FakeCommandRunner::CanRunMore() const {
+   return active_edges_.size() < max_active_edges_;
+ }
+
++bool FakeCommandRunner::AcquireToken() {
++  return true;
++}
++
+ bool FakeCommandRunner::StartCommand(Edge* edge) {
+   assert(active_edges_.size() < max_active_edges_);
+   assert(find(active_edges_.begin(), active_edges_.end(), edge)
+@@ -669,7 +674,7 @@ bool FakeCommandRunner::StartCommand(Edge* edge) {
+   return true;
+ }
+
+-bool FakeCommandRunner::WaitForCommand(Result* result) {
++bool FakeCommandRunner::WaitForCommand(Result* result, bool more_ready) {
+   if (active_edges_.empty())
+     return false;
+
+diff --git a/src/exit_status.h b/src/exit_status.h
+index a714ece..75ebf6a 100644
+--- a/src/exit_status.h
++++ b/src/exit_status.h
+@@ -18,7 +18,8 @@
+ enum ExitStatus {
+   ExitSuccess,
+   ExitFailure,
+-  ExitInterrupted
++  ExitTokenAvailable,
++  ExitInterrupted,
+ };
+
+ #endif  // NINJA_EXIT_STATUS_H_
+diff --git a/src/subprocess-posix.cc b/src/subprocess-posix.cc
+index 8e78540..74451b0 100644
+--- a/src/subprocess-posix.cc
++++ b/src/subprocess-posix.cc
+@@ -13,6 +13,7 @@
+ // limitations under the License.
+
+ #include "subprocess.h"
++#include "tokenpool.h"
+
+ #include <sys/select.h>
+ #include <assert.h>
+@@ -249,7 +250,7 @@ Subprocess *SubprocessSet::Add(const string& command, bool use_console) {
+ }
+
+ #ifdef USE_PPOLL
+-bool SubprocessSet::DoWork() {
++bool SubprocessSet::DoWork(struct TokenPool* tokens) {
+   vector<pollfd> fds;
+   nfds_t nfds = 0;
+
+@@ -263,6 +264,12 @@ bool SubprocessSet::DoWork() {
+     ++nfds;
+   }
+
++  if (tokens) {
++    pollfd pfd = { tokens->GetMonitorFd(), POLLIN | POLLPRI, 0 };
++    fds.push_back(pfd);
++    ++nfds;
++  }
++
+   interrupted_ = 0;
+   int ret = ppoll(&fds.front(), nfds, NULL, &old_mask_);
+   if (ret == -1) {
+@@ -295,11 +302,20 @@ bool SubprocessSet::DoWork() {
+     ++i;
+   }
+
++  if (tokens) {
++    pollfd *pfd = &fds[nfds - 1];
++    if (pfd->fd >= 0) {
++      assert(pfd->fd == tokens->GetMonitorFd());
++      if (pfd->revents != 0)
++        token_available_ = true;
++    }
++  }
++
+   return IsInterrupted();
+ }
+
+ #else  // !defined(USE_PPOLL)
+-bool SubprocessSet::DoWork() {
++bool SubprocessSet::DoWork(struct TokenPool* tokens) {
+   fd_set set;
+   int nfds = 0;
+   FD_ZERO(&set);
+@@ -314,6 +330,13 @@ bool SubprocessSet::DoWork() {
+     }
+   }
+
++  if (tokens) {
++    int fd = tokens->GetMonitorFd();
++    FD_SET(fd, &set);
++    if (nfds < fd+1)
++      nfds = fd+1;
++  }
++
+   interrupted_ = 0;
+   int ret = pselect(nfds, &set, 0, 0, 0, &old_mask_);
+   if (ret == -1) {
+@@ -342,6 +365,12 @@ bool SubprocessSet::DoWork() {
+     ++i;
+   }
+
++  if (tokens) {
++    int fd = tokens->GetMonitorFd();
++    if ((fd >= 0) && FD_ISSET(fd, &set))
++    token_available_ = true;
++  }
++
+   return IsInterrupted();
+ }
+ #endif  // !defined(USE_PPOLL)
+diff --git a/src/subprocess-win32.cc b/src/subprocess-win32.cc
+index ff3baac..66d2c2c 100644
+--- a/src/subprocess-win32.cc
++++ b/src/subprocess-win32.cc
+@@ -251,7 +251,7 @@ Subprocess *SubprocessSet::Add(const string& command, bool use_console) {
+   return subprocess;
+ }
+
+-bool SubprocessSet::DoWork() {
++bool SubprocessSet::DoWork(struct TokenPool* tokens) {
+   DWORD bytes_read;
+   Subprocess* subproc;
+   OVERLAPPED* overlapped;
+diff --git a/src/subprocess.h b/src/subprocess.h
+index 9e3d2ee..9ea67ea 100644
+--- a/src/subprocess.h
++++ b/src/subprocess.h
+@@ -76,6 +76,8 @@ struct Subprocess {
+   friend struct SubprocessSet;
+ };
+
++struct TokenPool;
++
+ /// SubprocessSet runs a ppoll/pselect() loop around a set of Subprocesses.
+ /// DoWork() waits for any state change in subprocesses; finished_
+ /// is a queue of subprocesses as they finish.
+@@ -84,13 +86,17 @@ struct SubprocessSet {
+   ~SubprocessSet();
+
+   Subprocess* Add(const std::string& command, bool use_console = false);
+-  bool DoWork();
++  bool DoWork(struct TokenPool* tokens);
+   Subprocess* NextFinished();
+   void Clear();
+
+   std::vector<Subprocess*> running_;
+   std::queue<Subprocess*> finished_;
+
++  bool token_available_;
++  bool IsTokenAvailable() { return token_available_; }
++  void ResetTokenAvailable() { token_available_ = false; }
++
+ #ifdef _WIN32
+   static BOOL WINAPI NotifyInterrupted(DWORD dwCtrlType);
+   static HANDLE ioport_;
+diff --git a/src/subprocess_test.cc b/src/subprocess_test.cc
+index 073fe86..4bc8083 100644
+--- a/src/subprocess_test.cc
++++ b/src/subprocess_test.cc
+@@ -45,10 +45,12 @@ TEST_F(SubprocessTest, BadCommandStderr) {
+   Subprocess* subproc = subprocs_.Add("cmd /c ninja_no_such_command");
+   ASSERT_NE((Subprocess *) 0, subproc);
+
++  subprocs_.ResetTokenAvailable();
+   while (!subproc->Done()) {
+     // Pretend we discovered that stderr was ready for writing.
+-    subprocs_.DoWork();
++    subprocs_.DoWork(NULL);
+   }
++  ASSERT_EQ(false, subprocs_.IsTokenAvailable());
+
+   EXPECT_EQ(ExitFailure, subproc->Finish());
+   EXPECT_NE("", subproc->GetOutput());
+@@ -59,10 +61,12 @@ TEST_F(SubprocessTest, NoSuchCommand) {
+   Subprocess* subproc = subprocs_.Add("ninja_no_such_command");
+   ASSERT_NE((Subprocess *) 0, subproc);
+
++  subprocs_.ResetTokenAvailable();
+   while (!subproc->Done()) {
+     // Pretend we discovered that stderr was ready for writing.
+-    subprocs_.DoWork();
++    subprocs_.DoWork(NULL);
+   }
++  ASSERT_EQ(false, subprocs_.IsTokenAvailable());
+
+   EXPECT_EQ(ExitFailure, subproc->Finish());
+   EXPECT_NE("", subproc->GetOutput());
+@@ -78,9 +82,11 @@ TEST_F(SubprocessTest, InterruptChild) {
+   Subprocess* subproc = subprocs_.Add("kill -INT $$");
+   ASSERT_NE((Subprocess *) 0, subproc);
+
++  subprocs_.ResetTokenAvailable();
+   while (!subproc->Done()) {
+-    subprocs_.DoWork();
++    subprocs_.DoWork(NULL);
+   }
++  ASSERT_EQ(false, subprocs_.IsTokenAvailable());
+
+   EXPECT_EQ(ExitInterrupted, subproc->Finish());
+ }
+@@ -90,7 +96,7 @@ TEST_F(SubprocessTest, InterruptParent) {
+   ASSERT_NE((Subprocess *) 0, subproc);
+
+   while (!subproc->Done()) {
+-    bool interrupted = subprocs_.DoWork();
++    bool interrupted = subprocs_.DoWork(NULL);
+     if (interrupted)
+       return;
+   }
+@@ -102,9 +108,11 @@ TEST_F(SubprocessTest, InterruptChildWithSigTerm) {
+   Subprocess* subproc = subprocs_.Add("kill -TERM $$");
+   ASSERT_NE((Subprocess *) 0, subproc);
+
++  subprocs_.ResetTokenAvailable();
+   while (!subproc->Done()) {
+-    subprocs_.DoWork();
++    subprocs_.DoWork(NULL);
+   }
++  ASSERT_EQ(false, subprocs_.IsTokenAvailable());
+
+   EXPECT_EQ(ExitInterrupted, subproc->Finish());
+ }
+@@ -114,7 +122,7 @@ TEST_F(SubprocessTest, InterruptParentWithSigTerm) {
+   ASSERT_NE((Subprocess *) 0, subproc);
+
+   while (!subproc->Done()) {
+-    bool interrupted = subprocs_.DoWork();
++    bool interrupted = subprocs_.DoWork(NULL);
+     if (interrupted)
+       return;
+   }
+@@ -126,9 +134,11 @@ TEST_F(SubprocessTest, InterruptChildWithSigHup) {
+   Subprocess* subproc = subprocs_.Add("kill -HUP $$");
+   ASSERT_NE((Subprocess *) 0, subproc);
+
++  subprocs_.ResetTokenAvailable();
+   while (!subproc->Done()) {
+-    subprocs_.DoWork();
++    subprocs_.DoWork(NULL);
+   }
++  ASSERT_EQ(false, subprocs_.IsTokenAvailable());
+
+   EXPECT_EQ(ExitInterrupted, subproc->Finish());
+ }
+@@ -138,7 +148,7 @@ TEST_F(SubprocessTest, InterruptParentWithSigHup) {
+   ASSERT_NE((Subprocess *) 0, subproc);
+
+   while (!subproc->Done()) {
+-    bool interrupted = subprocs_.DoWork();
++    bool interrupted = subprocs_.DoWork(NULL);
+     if (interrupted)
+       return;
+   }
+@@ -153,9 +163,11 @@ TEST_F(SubprocessTest, Console) {
+         subprocs_.Add("test -t 0 -a -t 1 -a -t 2", /*use_console=*/true);
+     ASSERT_NE((Subprocess*)0, subproc);
+
++    subprocs_.ResetTokenAvailable();
+     while (!subproc->Done()) {
+-      subprocs_.DoWork();
++      subprocs_.DoWork(NULL);
+     }
++    ASSERT_EQ(false, subprocs_.IsTokenAvailable());
+
+     EXPECT_EQ(ExitSuccess, subproc->Finish());
+   }
+@@ -167,9 +179,11 @@ TEST_F(SubprocessTest, SetWithSingle) {
+   Subprocess* subproc = subprocs_.Add(kSimpleCommand);
+   ASSERT_NE((Subprocess *) 0, subproc);
+
++  subprocs_.ResetTokenAvailable();
+   while (!subproc->Done()) {
+-    subprocs_.DoWork();
++    subprocs_.DoWork(NULL);
+   }
++  ASSERT_EQ(false, subprocs_.IsTokenAvailable());
+   ASSERT_EQ(ExitSuccess, subproc->Finish());
+   ASSERT_NE("", subproc->GetOutput());
+
+@@ -200,12 +214,13 @@ TEST_F(SubprocessTest, SetWithMulti) {
+     ASSERT_EQ("", processes[i]->GetOutput());
+   }
+
++  subprocs_.ResetTokenAvailable();
+   while (!processes[0]->Done() || !processes[1]->Done() ||
+          !processes[2]->Done()) {
+     ASSERT_GT(subprocs_.running_.size(), 0u);
+-    subprocs_.DoWork();
++    subprocs_.DoWork(NULL);
+   }
+-
++  ASSERT_EQ(false, subprocs_.IsTokenAvailable());
+   ASSERT_EQ(0u, subprocs_.running_.size());
+   ASSERT_EQ(3u, subprocs_.finished_.size());
+
+@@ -237,8 +252,10 @@ TEST_F(SubprocessTest, SetWithLots) {
+     ASSERT_NE((Subprocess *) 0, subproc);
+     procs.push_back(subproc);
+   }
++  subprocs_.ResetTokenAvailable();
+   while (!subprocs_.running_.empty())
+-    subprocs_.DoWork();
++    subprocs_.DoWork(NULL);
++  ASSERT_EQ(false, subprocs_.IsTokenAvailable());
+   for (size_t i = 0; i < procs.size(); ++i) {
+     ASSERT_EQ(ExitSuccess, procs[i]->Finish());
+     ASSERT_NE("", procs[i]->GetOutput());
+@@ -254,9 +271,11 @@ TEST_F(SubprocessTest, SetWithLots) {
+ // that stdin is closed.
+ TEST_F(SubprocessTest, ReadStdin) {
+   Subprocess* subproc = subprocs_.Add("cat -");
++  subprocs_.ResetTokenAvailable();
+   while (!subproc->Done()) {
+-    subprocs_.DoWork();
++    subprocs_.DoWork(NULL);
+   }
++  ASSERT_EQ(false, subprocs_.IsTokenAvailable());
+   ASSERT_EQ(ExitSuccess, subproc->Finish());
+   ASSERT_EQ(1u, subprocs_.finished_.size());
+ }
+diff --git a/src/tokenpool-gnu-make.cc b/src/tokenpool-gnu-make.cc
+index a8f9b71..396bb7d 100644
+--- a/src/tokenpool-gnu-make.cc
++++ b/src/tokenpool-gnu-make.cc
+@@ -33,6 +33,7 @@ struct GNUmakeTokenPool : public TokenPool {
+   virtual void Reserve();
+   virtual void Release();
+   virtual void Clear();
++  virtual int GetMonitorFd();
+
+   bool Setup();
+
+@@ -201,6 +202,10 @@ void GNUmakeTokenPool::Clear() {
+     Return();
+ }
+
++int GNUmakeTokenPool::GetMonitorFd() {
++  return(rfd_);
++}
++
+ struct TokenPool *TokenPool::Get(void) {
+   GNUmakeTokenPool *tokenpool = new GNUmakeTokenPool;
+   if (tokenpool->Setup())
+diff --git a/src/tokenpool.h b/src/tokenpool.h
+index f560b10..301e199 100644
+--- a/src/tokenpool.h
++++ b/src/tokenpool.h
+@@ -21,6 +21,12 @@ struct TokenPool {
+   virtual void Release() = 0;
+   virtual void Clear() = 0;
+
++#ifdef _WIN32
++  // @TODO
++#else
++  virtual int GetMonitorFd() = 0;
++#endif
++
+   // returns NULL if token pool is not available
+   static struct TokenPool *Get(void);
+ };
+--
+2.44.0
+
meta/recipes-devtools/ninja/files/0003-Ignore-jobserver-when-jN-is-forced-on-command-line.patch new file +198 -0
new file mode 100644
index 0000000000..d0c96350b4
@@ -0,0 +1,198 @@
+From a6eec5c72869947f27e13b967897e5a59f25badf Mon Sep 17 00:00:00 2001
+From: Stefan Becker <[email protected]>
+Date: Sun, 12 Nov 2017 16:58:55 +0200
+Subject: [PATCH 03/20] Ignore jobserver when -jN is forced on command line
+
+This emulates the behaviour of GNU make.
+
+- add parallelism_from_cmdline flag to build configuration
+- set the flag when -jN is given on command line
+- pass the flag to TokenPool::Get()
+- GNUmakeTokenPool::Setup()
+  * prints a warning when the flag is true and jobserver was detected
+  * returns false, i.e. jobserver will be ignored
+- ignore config.parallelism in CanRunMore() when we have a valid
+  TokenPool, because it gets always initialized to a default when not
+  given on the command line
+
+Upstream-Status: Submitted [https://github.com/ninja-build/ninja/pull/1140]
+---
+ src/build.cc              | 10 ++++++----
+ src/build.h               |  4 +++-
+ src/ninja.cc              |  1 +
+ src/tokenpool-gnu-make.cc | 34 +++++++++++++++++++---------------
+ src/tokenpool-none.cc     |  4 ++--
+ src/tokenpool.h           |  4 ++--
+ 6 files changed, 33 insertions(+), 24 deletions(-)
+
+diff --git a/src/build.cc b/src/build.cc
+index 01a4b6b..e35dafc 100644
+--- a/src/build.cc
++++ b/src/build.cc
+@@ -470,7 +470,7 @@ struct RealCommandRunner : public CommandRunner {
+ };
+
+ RealCommandRunner::RealCommandRunner(const BuildConfig& config) : config_(config) {
+-  tokens_ = TokenPool::Get();
++  tokens_ = TokenPool::Get(config_.parallelism_from_cmdline);
+ }
+
+ RealCommandRunner::~RealCommandRunner() {
+@@ -492,9 +492,11 @@ void RealCommandRunner::Abort() {
+ }
+
+ bool RealCommandRunner::CanRunMore() const {
+-  size_t subproc_number =
+-      subprocs_.running_.size() + subprocs_.finished_.size();
+-  return (int)subproc_number < config_.parallelism
++  bool parallelism_limit_not_reached =
++    tokens_ || // ignore config_.parallelism
++    ((int) (subprocs_.running_.size() +
++            subprocs_.finished_.size()) < config_.parallelism);
++  return parallelism_limit_not_reached
+     && (subprocs_.running_.empty() ||
+         (config_.max_load_average <= 0.0f ||
+          GetLoadAverage() < config_.max_load_average));
+diff --git a/src/build.h b/src/build.h
+index 50b4be3..111ada8 100644
+--- a/src/build.h
++++ b/src/build.h
+@@ -159,7 +159,8 @@ struct CommandRunner {
+
+ /// Options (e.g. verbosity, parallelism) passed to a build.
+ struct BuildConfig {
+-  BuildConfig() : verbosity(NORMAL), dry_run(false), parallelism(1),
++  BuildConfig() : verbosity(NORMAL), dry_run(false),
++                  parallelism(1), parallelism_from_cmdline(false),
+                   failures_allowed(1), max_load_average(-0.0f) {}
+
+   enum Verbosity {
+@@ -171,6 +172,7 @@ struct BuildConfig {
+   Verbosity verbosity;
+   bool dry_run;
+   int parallelism;
++  bool parallelism_from_cmdline;
+   int failures_allowed;
+   /// The maximum load average we must not exceed. A negative value
+   /// means that we do not have any limit.
+diff --git a/src/ninja.cc b/src/ninja.cc
+index 887d89f..74c1194 100644
+--- a/src/ninja.cc
++++ b/src/ninja.cc
+@@ -1448,6 +1448,7 @@ int ReadFlags(int* argc, char*** argv,
+         // We want to run N jobs in parallel. For N = 0, INT_MAX
+         // is close enough to infinite for most sane builds.
+         config->parallelism = value > 0 ? value : INT_MAX;
++        config->parallelism_from_cmdline = true;
+         deferGuessParallelism.needGuess = false;
+         break;
+       }
+diff --git a/src/tokenpool-gnu-make.cc b/src/tokenpool-gnu-make.cc
+index 396bb7d..af4be05 100644
+--- a/src/tokenpool-gnu-make.cc
++++ b/src/tokenpool-gnu-make.cc
+@@ -1,4 +1,4 @@
+-// Copyright 2016 Google Inc. All Rights Reserved.
++// Copyright 2016-2017 Google Inc. All Rights Reserved.
+ //
+ // Licensed under the Apache License, Version 2.0 (the "License");
+ // you may not use this file except in compliance with the License.
+@@ -35,7 +35,7 @@ struct GNUmakeTokenPool : public TokenPool {
+   virtual void Clear();
+   virtual int GetMonitorFd();
+
+-  bool Setup();
++  bool Setup(bool ignore);
+
+  private:
+   int available_;
+@@ -100,7 +100,7 @@ bool GNUmakeTokenPool::SetAlarmHandler() {
+   }
+ }
+
+-bool GNUmakeTokenPool::Setup() {
++bool GNUmakeTokenPool::Setup(bool ignore) {
+   const char *value = getenv("MAKEFLAGS");
+   if (value) {
+     // GNU make <= 4.1
+@@ -109,16 +109,20 @@ bool GNUmakeTokenPool::Setup() {
+     if (!jobserver)
+       jobserver = strstr(value, "--jobserver-auth=");
+     if (jobserver) {
+-      int rfd = -1;
+-      int wfd = -1;
+-      if ((sscanf(jobserver, "%*[^=]=%d,%d", &rfd, &wfd) == 2) &&
+-          CheckFd(rfd) &&
+-          CheckFd(wfd) &&
+-          SetAlarmHandler()) {
+-        printf("ninja: using GNU make jobserver.\n");
+-        rfd_ = rfd;
+-        wfd_ = wfd;
+-        return true;
++      if (ignore) {
++        printf("ninja: warning: -jN forced on command line; ignoring GNU make jobserver.\n");
++      } else {
++        int rfd = -1;
++        int wfd = -1;
++        if ((sscanf(jobserver, "%*[^=]=%d,%d", &rfd, &wfd) == 2) &&
++            CheckFd(rfd) &&
++            CheckFd(wfd) &&
++            SetAlarmHandler()) {
++          printf("ninja: using GNU make jobserver.\n");
++          rfd_ = rfd;
++          wfd_ = wfd;
++          return true;
++        }
+       }
+     }
+   }
+@@ -206,9 +210,9 @@ int GNUmakeTokenPool::GetMonitorFd() {
+   return(rfd_);
+ }
+
+-struct TokenPool *TokenPool::Get(void) {
++struct TokenPool *TokenPool::Get(bool ignore) {
+   GNUmakeTokenPool *tokenpool = new GNUmakeTokenPool;
+-  if (tokenpool->Setup())
++  if (tokenpool->Setup(ignore))
+     return tokenpool;
+   else
+     delete tokenpool;
+diff --git a/src/tokenpool-none.cc b/src/tokenpool-none.cc
+index 602b331..199b222 100644
+--- a/src/tokenpool-none.cc
++++ b/src/tokenpool-none.cc
+@@ -1,4 +1,4 @@
+-// Copyright 2016 Google Inc. All Rights Reserved.
++// Copyright 2016-2017 Google Inc. All Rights Reserved.
+ //
+ // Licensed under the Apache License, Version 2.0 (the "License");
+ // you may not use this file except in compliance with the License.
+@@ -22,6 +22,6 @@
+ #include <stdlib.h>
+
+ // No-op TokenPool implementation
+-struct TokenPool *TokenPool::Get(void) {
++struct TokenPool *TokenPool::Get(bool ignore) {
+   return NULL;
+ }
+diff --git a/src/tokenpool.h b/src/tokenpool.h
+index 301e199..878a093 100644
+--- a/src/tokenpool.h
++++ b/src/tokenpool.h
+@@ -1,4 +1,4 @@
+-// Copyright 2016 Google Inc. All Rights Reserved.
++// Copyright 2016-2017 Google Inc. All Rights Reserved.
+ //
+ // Licensed under the Apache License, Version 2.0 (the "License");
+ // you may not use this file except in compliance with the License.
+@@ -28,5 +28,5 @@ struct TokenPool {
+ #endif
+
+   // returns NULL if token pool is not available
+-  static struct TokenPool *Get(void);
++  static struct TokenPool *Get(bool ignore);
+ };
+--
+2.44.0
+
meta/recipes-devtools/ninja/files/0004-Honor-lN-from-MAKEFLAGS.patch new file +134 -0
new file mode 100644
index 0000000000..5e4328bc6c
@@ -0,0 +1,134 @@
+From 3d15060e6b025c5002b56539d59481dcdde696c3 Mon Sep 17 00:00:00 2001
+From: Stefan Becker <[email protected]>
+Date: Sun, 12 Nov 2017 18:04:12 +0200
+Subject: [PATCH 04/20] Honor -lN from MAKEFLAGS
+
+This emulates the behaviour of GNU make.
+
+- build: make a copy of max_load_average and pass it to TokenPool.
+- GNUmakeTokenPool: if we detect a jobserver and a valid -lN argument in
+  MAKEFLAGS then set max_load_average to N.
+
+Upstream-Status: Submitted [https://github.com/ninja-build/ninja/pull/1140]
+---
+ src/build.cc              | 10 +++++++---
+ src/tokenpool-gnu-make.cc | 19 +++++++++++++++----
+ src/tokenpool-none.cc     |  2 +-
+ src/tokenpool.h           |  2 +-
+ 4 files changed, 24 insertions(+), 9 deletions(-)
+
+diff --git a/src/build.cc b/src/build.cc
+index e35dafc..042971e 100644
+--- a/src/build.cc
++++ b/src/build.cc
+@@ -464,13 +464,17 @@ struct RealCommandRunner : public CommandRunner {
+   virtual void Abort();
+
+   const BuildConfig& config_;
++  // copy of config_.max_load_average; can be modified by TokenPool setup
++  double max_load_average_;
+   SubprocessSet subprocs_;
+   TokenPool *tokens_;
+   map<const Subprocess*, Edge*> subproc_to_edge_;
+ };
+
+ RealCommandRunner::RealCommandRunner(const BuildConfig& config) : config_(config) {
+-  tokens_ = TokenPool::Get(config_.parallelism_from_cmdline);
++  max_load_average_ = config.max_load_average;
++  tokens_ = TokenPool::Get(config_.parallelism_from_cmdline,
++                           max_load_average_);
+ }
+
+ RealCommandRunner::~RealCommandRunner() {
+@@ -498,8 +502,8 @@ bool RealCommandRunner::CanRunMore() const {
+             subprocs_.finished_.size()) < config_.parallelism);
+   return parallelism_limit_not_reached
+     && (subprocs_.running_.empty() ||
+-        (config_.max_load_average <= 0.0f ||
+-         GetLoadAverage() < config_.max_load_average));
++        (max_load_average_ <= 0.0f ||
++         GetLoadAverage() < max_load_average_));
+ }
+
+ bool RealCommandRunner::AcquireToken() {
+diff --git a/src/tokenpool-gnu-make.cc b/src/tokenpool-gnu-make.cc
+index af4be05..fb654c4 100644
+--- a/src/tokenpool-gnu-make.cc
++++ b/src/tokenpool-gnu-make.cc
+@@ -35,7 +35,7 @@ struct GNUmakeTokenPool : public TokenPool {
+   virtual void Clear();
+   virtual int GetMonitorFd();
+
+-  bool Setup(bool ignore);
++  bool Setup(bool ignore, double& max_load_average);
+
+  private:
+   int available_;
+@@ -100,7 +100,7 @@ bool GNUmakeTokenPool::SetAlarmHandler() {
+   }
+ }
+
+-bool GNUmakeTokenPool::Setup(bool ignore) {
++bool GNUmakeTokenPool::Setup(bool ignore, double& max_load_average) {
+   const char *value = getenv("MAKEFLAGS");
+   if (value) {
+     // GNU make <= 4.1
+@@ -118,9 +118,20 @@ bool GNUmakeTokenPool::Setup(bool ignore) {
+             CheckFd(rfd) &&
+             CheckFd(wfd) &&
+             SetAlarmHandler()) {
++          const char *l_arg = strstr(value, " -l");
++          int load_limit = -1;
++
+           printf("ninja: using GNU make jobserver.\n");
+           rfd_ = rfd;
+           wfd_ = wfd;
++
++          // translate GNU make -lN to ninja -lN
++          if (l_arg &&
++              (sscanf(l_arg + 3, "%d ", &load_limit) == 1) &&
++              (load_limit > 0)) {
++            max_load_average = load_limit;
++          }
++
+           return true;
+         }
+       }
+@@ -210,9 +221,9 @@ int GNUmakeTokenPool::GetMonitorFd() {
+   return(rfd_);
+ }
+
+-struct TokenPool *TokenPool::Get(bool ignore) {
++struct TokenPool *TokenPool::Get(bool ignore, double& max_load_average) {
+   GNUmakeTokenPool *tokenpool = new GNUmakeTokenPool;
+-  if (tokenpool->Setup(ignore))
++  if (tokenpool->Setup(ignore, max_load_average))
+     return tokenpool;
+   else
+     delete tokenpool;
+diff --git a/src/tokenpool-none.cc b/src/tokenpool-none.cc
+index 199b222..e8e2542 100644
+--- a/src/tokenpool-none.cc
++++ b/src/tokenpool-none.cc
+@@ -22,6 +22,6 @@
+ #include <stdlib.h>
+
+ // No-op TokenPool implementation
+-struct TokenPool *TokenPool::Get(bool ignore) {
++struct TokenPool *TokenPool::Get(bool ignore, double& max_load_average) {
+   return NULL;
+ }
+diff --git a/src/tokenpool.h b/src/tokenpool.h
+index 878a093..f9e8cc2 100644
+--- a/src/tokenpool.h
++++ b/src/tokenpool.h
+@@ -28,5 +28,5 @@ struct TokenPool {
+ #endif
+
+   // returns NULL if token pool is not available
+-  static struct TokenPool *Get(bool ignore);
++  static struct TokenPool *Get(bool ignore, double& max_load_average);
+ };
+--
+2.44.0
+
meta/recipes-devtools/ninja/files/0005-Use-LinePrinter-for-TokenPool-messages.patch new file +128 -0
new file mode 100644
index 0000000000..190e98a165
@@ -0,0 +1,128 @@
+From 1157e43c5172588792d519fc6a64043358161717 Mon Sep 17 00:00:00 2001
+From: Stefan Becker <[email protected]>
+Date: Wed, 6 Dec 2017 22:14:21 +0200
+Subject: [PATCH 05/20] Use LinePrinter for TokenPool messages
+
+- replace printf() with calls to LinePrinter
+- print GNU make jobserver message only when verbose build is requested
+
+Upstream-Status: Submitted [https://github.com/ninja-build/ninja/pull/1140]
+---
+ src/build.cc              |  1 +
+ src/tokenpool-gnu-make.cc | 22 ++++++++++++++++------
+ src/tokenpool-none.cc     |  4 +++-
+ src/tokenpool.h           |  4 +++-
+ 4 files changed, 23 insertions(+), 8 deletions(-)
+
+diff --git a/src/build.cc b/src/build.cc
+index 042971e..da1faa8 100644
+--- a/src/build.cc
++++ b/src/build.cc
+@@ -474,6 +474,7 @@ struct RealCommandRunner : public CommandRunner {
+ RealCommandRunner::RealCommandRunner(const BuildConfig& config) : config_(config) {
+   max_load_average_ = config.max_load_average;
+   tokens_ = TokenPool::Get(config_.parallelism_from_cmdline,
++                           config_.verbosity == BuildConfig::VERBOSE,
+                            max_load_average_);
+ }
+
+diff --git a/src/tokenpool-gnu-make.cc b/src/tokenpool-gnu-make.cc
+index fb654c4..b0d3e6e 100644
+--- a/src/tokenpool-gnu-make.cc
++++ b/src/tokenpool-gnu-make.cc
+@@ -23,6 +23,8 @@
+ #include <string.h>
+ #include <stdlib.h>
+
++#include "line_printer.h"
++
+ // TokenPool implementation for GNU make jobserver
+ // (http://make.mad-scientist.net/papers/jobserver-implementation/)
+ struct GNUmakeTokenPool : public TokenPool {
+@@ -35,7 +37,7 @@ struct GNUmakeTokenPool : public TokenPool {
+   virtual void Clear();
+   virtual int GetMonitorFd();
+
+-  bool Setup(bool ignore, double& max_load_average);
++  bool Setup(bool ignore, bool verbose, double& max_load_average);
+
+  private:
+   int available_;
+@@ -100,7 +102,9 @@ bool GNUmakeTokenPool::SetAlarmHandler() {
+   }
+ }
+
+-bool GNUmakeTokenPool::Setup(bool ignore, double& max_load_average) {
++bool GNUmakeTokenPool::Setup(bool ignore,
++                             bool verbose,
++                             double& max_load_average) {
+   const char *value = getenv("MAKEFLAGS");
+   if (value) {
+     // GNU make <= 4.1
+@@ -109,8 +113,10 @@ bool GNUmakeTokenPool::Setup(bool ignore, double& max_load_average) {
+     if (!jobserver)
+       jobserver = strstr(value, "--jobserver-auth=");
+     if (jobserver) {
++      LinePrinter printer;
++
+       if (ignore) {
+-        printf("ninja: warning: -jN forced on command line; ignoring GNU make jobserver.\n");
++        printer.PrintOnNewLine("ninja: warning: -jN forced on command line; ignoring GNU make jobserver.\n");
+       } else {
+         int rfd = -1;
+         int wfd = -1;
+@@ -121,7 +127,9 @@ bool GNUmakeTokenPool::Setup(bool ignore, double& max_load_average) {
+           const char *l_arg = strstr(value, " -l");
+           int load_limit = -1;
+
+-          printf("ninja: using GNU make jobserver.\n");
++          if (verbose) {
++            printer.PrintOnNewLine("ninja: using GNU make jobserver.\n");
++          }
+           rfd_ = rfd;
+           wfd_ = wfd;
+
+@@ -221,9 +229,11 @@ int GNUmakeTokenPool::GetMonitorFd() {
+   return(rfd_);
+ }
+
+-struct TokenPool *TokenPool::Get(bool ignore, double& max_load_average) {
++struct TokenPool *TokenPool::Get(bool ignore,
++                                 bool verbose,
++                                 double& max_load_average) {
+   GNUmakeTokenPool *tokenpool = new GNUmakeTokenPool;
+-  if (tokenpool->Setup(ignore, max_load_average))
++  if (tokenpool->Setup(ignore, verbose, max_load_average))
+     return tokenpool;
+   else
+     delete tokenpool;
+diff --git a/src/tokenpool-none.cc b/src/tokenpool-none.cc
+index e8e2542..1c1c499 100644
+--- a/src/tokenpool-none.cc
++++ b/src/tokenpool-none.cc
+@@ -22,6 +22,8 @@
+ #include <stdlib.h>
+
+ // No-op TokenPool implementation
+-struct TokenPool *TokenPool::Get(bool ignore, double& max_load_average) {
++struct TokenPool *TokenPool::Get(bool ignore,
++                                 bool verbose,
++                                 double& max_load_average) {
+   return NULL;
+ }
+diff --git a/src/tokenpool.h b/src/tokenpool.h
+index f9e8cc2..4bf477f 100644
+--- a/src/tokenpool.h
++++ b/src/tokenpool.h
+@@ -28,5 +28,7 @@ struct TokenPool {
+ #endif
+
+   // returns NULL if token pool is not available
+-  static struct TokenPool *Get(bool ignore, double& max_load_average);
++  static struct TokenPool *Get(bool ignore,
++                               bool verbose,
++                               double& max_load_average);
+ };
+--
+2.44.0
+
meta/recipes-devtools/ninja/files/0006-Prepare-PR-for-merging.patch new file +156 -0
new file mode 100644
index 0000000000..60890d29f0
@@ -0,0 +1,156 @@
+From 610086315e8ba8b819a0c38f84412fcc20debc34 Mon Sep 17 00:00:00 2001
+From: Stefan Becker <[email protected]>
+Date: Sat, 7 Apr 2018 17:11:21 +0300
+Subject: [PATCH 06/20] Prepare PR for merging
+
+- fix Windows build error in no-op TokenPool implementation
+- improve Acquire() to block for a maximum of 100ms
+- address review comments
+
+Upstream-Status: Submitted [https://github.com/ninja-build/ninja/pull/1140]
+---
+ src/build.h               |  2 ++
+ src/tokenpool-gnu-make.cc | 51 ++++++++++++++++++++++++++++++++++-----
+ src/tokenpool-none.cc     |  7 +-----
+ 3 files changed, 48 insertions(+), 12 deletions(-)
+
+diff --git a/src/build.h b/src/build.h
+index 111ada8..c12a085 100644
+--- a/src/build.h
++++ b/src/build.h
+@@ -151,6 +151,8 @@ struct CommandRunner {
+     bool success() const { return status == ExitSuccess; }
+   };
+   /// Wait for a command to complete, or return false if interrupted.
++  /// If more_ready is true then the optional TokenPool is monitored too
++  /// and we return when a token becomes available.
+   virtual bool WaitForCommand(Result* result, bool more_ready) = 0;
+
+   virtual std::vector<Edge*> GetActiveEdges() { return std::vector<Edge*>(); }
+diff --git a/src/tokenpool-gnu-make.cc b/src/tokenpool-gnu-make.cc
+index b0d3e6e..4132bb0 100644
+--- a/src/tokenpool-gnu-make.cc
++++ b/src/tokenpool-gnu-make.cc
+@@ -1,4 +1,4 @@
+-// Copyright 2016-2017 Google Inc. All Rights Reserved.
++// Copyright 2016-2018 Google Inc. All Rights Reserved.
+ //
+ // Licensed under the Apache License, Version 2.0 (the "License");
+ // you may not use this file except in compliance with the License.
+@@ -19,6 +19,7 @@
+ #include <poll.h>
+ #include <unistd.h>
+ #include <signal.h>
++#include <sys/time.h>
+ #include <stdio.h>
+ #include <string.h>
+ #include <stdlib.h>
+@@ -153,6 +154,15 @@ bool GNUmakeTokenPool::Acquire() {
+   if (available_ > 0)
+     return true;
+
++  // Please read
++  //
++  //   http://make.mad-scientist.net/papers/jobserver-implementation/
++  //
++  // for the reasoning behind the following code.
++  //
++  // Try to read one character from the pipe. Returns true on success.
++  //
++  // First check if read() would succeed without blocking.
+ #ifdef USE_PPOLL
+   pollfd pollfds[] = {{rfd_, POLLIN, 0}};
+   int ret = poll(pollfds, 1, 0);
+@@ -164,33 +174,62 @@ bool GNUmakeTokenPool::Acquire() {
+   int ret = select(rfd_ + 1, &set, NULL, NULL, &timeout);
+ #endif
+   if (ret > 0) {
++    // Handle potential race condition:
++    //  - the above check succeeded, i.e. read() should not block
++    //  - the character disappears before we call read()
++    //
++    // Create a duplicate of rfd_. The duplicate file descriptor dup_rfd_
++    // can safely be closed by signal handlers without affecting rfd_.
+     dup_rfd_ = dup(rfd_);
+
+     if (dup_rfd_ != -1) {
+       struct sigaction act, old_act;
+       int ret = 0;
+
++      // Temporarily replace SIGCHLD handler with our own
+       memset(&act, 0, sizeof(act));
+       act.sa_handler = CloseDupRfd;
+       if (sigaction(SIGCHLD, &act, &old_act) == 0) {
+-        char buf;
++        struct itimerval timeout;
+
+-        // block until token read, child exits or timeout
+-        alarm(1);
+-        ret = read(dup_rfd_, &buf, 1);
+-        alarm(0);
++        // install a 100ms timeout that generates SIGALARM on expiration
++        memset(&timeout, 0, sizeof(timeout));
++        timeout.it_value.tv_usec = 100 * 1000; // [ms] -> [usec]
++        if (setitimer(ITIMER_REAL, &timeout, NULL) == 0) {
++          char buf;
++
++          // Now try to read() from dup_rfd_. Return values from read():
++          //
++          // 1. token read                               ->  1
++          // 2. pipe closed                              ->  0
++          // 3. alarm expires                            -> -1 (EINTR)
++          // 4. child exits                              -> -1 (EINTR)
++          // 5. alarm expired before entering read()     -> -1 (EBADF)
++          // 6. child exited before entering read()      -> -1 (EBADF)
++          // 7. child exited before handler is installed -> go to 1 - 3
++          ret = read(dup_rfd_, &buf, 1);
++
++          // disarm timer
++          memset(&timeout, 0, sizeof(timeout));
++          setitimer(ITIMER_REAL, &timeout, NULL);
++        }
+
+         sigaction(SIGCHLD, &old_act, NULL);
+       }
+
+       CloseDupRfd(0);
+
++      // Case 1 from above list
+       if (ret > 0) {
+         available_++;
+         return true;
+       }
+     }
+   }
++
++  // read() would block, i.e. no token available,
++  // cases 2-6 from above list or
++  // select() / poll() / dup() / sigaction() / setitimer() failed
+   return false;
+ }
+
+diff --git a/src/tokenpool-none.cc b/src/tokenpool-none.cc
+index 1c1c499..4c59287 100644
+--- a/src/tokenpool-none.cc
++++ b/src/tokenpool-none.cc
+@@ -1,4 +1,4 @@
+-// Copyright 2016-2017 Google Inc. All Rights Reserved.
++// Copyright 2016-2018 Google Inc. All Rights Reserved.
+ //
+ // Licensed under the Apache License, Version 2.0 (the "License");
+ // you may not use this file except in compliance with the License.
+@@ -14,11 +14,6 @@
+
+ #include "tokenpool.h"
+
+-#include <fcntl.h>
+-#include <poll.h>
+-#include <unistd.h>
+-#include <stdio.h>
+-#include <string.h>
+ #include <stdlib.h>
+
+ // No-op TokenPool implementation
+--
+2.44.0
+
meta/recipes-devtools/ninja/files/0007-Add-tests-for-TokenPool.patch new file +237 -0
new file mode 100644
index 0000000000..e716dac9c3
@@ -0,0 +1,237 @@
+From 008bc6ed9213406a24b366d69f560c625369da0f Mon Sep 17 00:00:00 2001
+From: Stefan Becker <[email protected]>
+Date: Fri, 25 May 2018 00:17:07 +0300
+Subject: [PATCH 07/20] Add tests for TokenPool
+
+- TokenPool setup
+- GetMonitorFd() API
+- implicit token and tokens in jobserver pipe
+- Acquire() / Reserve() / Release() protocol
+- Clear() API
+
+Upstream-Status: Submitted [https://github.com/ninja-build/ninja/pull/1140]
+---
+ configure.py          |   1 +
+ src/tokenpool_test.cc | 198 ++++++++++++++++++++++++++++++++++++++++++
+ 2 files changed, 199 insertions(+)
+ create mode 100644 src/tokenpool_test.cc
+
+diff --git a/configure.py b/configure.py
+index d95fad8..41f9428 100755
+--- a/configure.py
++++ b/configure.py
+@@ -611,6 +611,7 @@ for name in ['build_log_test',
+              'string_piece_util_test',
+              'subprocess_test',
+              'test',
++             'tokenpool_test',
+              'util_test']:
+     objs += cxx(name, variables=cxxvariables)
+ if platform.is_windows():
+diff --git a/src/tokenpool_test.cc b/src/tokenpool_test.cc
+new file mode 100644
+index 0000000..6c89064
+--- /dev/null
++++ b/src/tokenpool_test.cc
+@@ -0,0 +1,198 @@
++// Copyright 2018 Google Inc. All Rights Reserved.
++//
++// Licensed 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 "tokenpool.h"
++
++#include "test.h"
++
++#ifndef _WIN32
++#include <stdio.h>
++#include <stdlib.h>
++#include <unistd.h>
++
++#define ENVIRONMENT_CLEAR() unsetenv("MAKEFLAGS")
++#define ENVIRONMENT_INIT(v) setenv("MAKEFLAGS", v, true);
++#endif
++
++namespace {
++
++const double kLoadAverageDefault = -1.23456789;
++
++struct TokenPoolTest : public testing::Test {
++  double load_avg_;
++  TokenPool *tokens_;
++#ifndef _WIN32
++  char buf_[1024];
++  int fds_[2];
++#endif
++
++  virtual void SetUp() {
++    load_avg_ = kLoadAverageDefault;
++    tokens_ = NULL;
++#ifndef _WIN32
++    ENVIRONMENT_CLEAR();
++    if (pipe(fds_) < 0)
++      ASSERT_TRUE(false);
++#endif
++  }
++
++  void CreatePool(const char *format, bool ignore_jobserver) {
++#ifndef _WIN32
++    if (format) {
++      sprintf(buf_, format, fds_[0], fds_[1]);
++      ENVIRONMENT_INIT(buf_);
++    }
++#endif
++    tokens_ = TokenPool::Get(ignore_jobserver, false, load_avg_);
++  }
++
++  void CreateDefaultPool() {
++    CreatePool("foo --jobserver-auth=%d,%d bar", false);
++  }
++
++  virtual void TearDown() {
++    if (tokens_)
++      delete tokens_;
++#ifndef _WIN32
++    close(fds_[0]);
++    close(fds_[1]);
++    ENVIRONMENT_CLEAR();
++#endif
++  }
++};
++
++} // anonymous namespace
++
++// verifies none implementation
++TEST_F(TokenPoolTest, NoTokenPool) {
++  CreatePool(NULL, false);
++
++  EXPECT_EQ(NULL, tokens_);
++  EXPECT_EQ(kLoadAverageDefault, load_avg_);
++}
++
++#ifndef _WIN32
++TEST_F(TokenPoolTest, SuccessfulOldSetup) {
++  // GNUmake <= 4.1
++  CreatePool("foo --jobserver-fds=%d,%d bar", false);
++
++  EXPECT_NE(NULL, tokens_);
++  EXPECT_EQ(kLoadAverageDefault, load_avg_);
++}
++
++TEST_F(TokenPoolTest, SuccessfulNewSetup) {
++  // GNUmake => 4.2
++  CreateDefaultPool();
++
++  EXPECT_NE(NULL, tokens_);
++  EXPECT_EQ(kLoadAverageDefault, load_avg_);
++}
++
++TEST_F(TokenPoolTest, IgnoreWithJN) {
++  CreatePool("foo --jobserver-auth=%d,%d bar", true);
++
++  EXPECT_EQ(NULL, tokens_);
++  EXPECT_EQ(kLoadAverageDefault, load_avg_);
++}
++
++TEST_F(TokenPoolTest, HonorLN) {
++  CreatePool("foo -l9 --jobserver-auth=%d,%d bar", false);
++
++  EXPECT_NE(NULL, tokens_);
++  EXPECT_EQ(9.0, load_avg_);
++}
++
++TEST_F(TokenPoolTest, MonitorFD) {
++  CreateDefaultPool();
++
++  ASSERT_NE(NULL, tokens_);
++  EXPECT_EQ(kLoadAverageDefault, load_avg_);
++
++  EXPECT_EQ(fds_[0], tokens_->GetMonitorFd());
++}
++
++TEST_F(TokenPoolTest, ImplicitToken) {
++  CreateDefaultPool();
++
++  ASSERT_NE(NULL, tokens_);
++  EXPECT_EQ(kLoadAverageDefault, load_avg_);
++
++  EXPECT_TRUE(tokens_->Acquire());
++  tokens_->Reserve();
++  EXPECT_FALSE(tokens_->Acquire());
++  tokens_->Release();
++  EXPECT_TRUE(tokens_->Acquire());
++}
++
++TEST_F(TokenPoolTest, TwoTokens) {
++  CreateDefaultPool();
++
++  ASSERT_NE(NULL, tokens_);
++  EXPECT_EQ(kLoadAverageDefault, load_avg_);
++
++  // implicit token
++  EXPECT_TRUE(tokens_->Acquire());
++  tokens_->Reserve();
++  EXPECT_FALSE(tokens_->Acquire());
++
++  // jobserver offers 2nd token
++  ASSERT_EQ(1u, write(fds_[1], "T", 1));
++  EXPECT_TRUE(tokens_->Acquire());
++  tokens_->Reserve();
++  EXPECT_FALSE(tokens_->Acquire());
++
++  // release 2nd token
++  tokens_->Release();
++  EXPECT_TRUE(tokens_->Acquire());
++
++  // release implict token - must return 2nd token back to jobserver
++  tokens_->Release();
++  EXPECT_TRUE(tokens_->Acquire());
++
++  // there must be one token in the pipe
++  EXPECT_EQ(1u, read(fds_[0], buf_, sizeof(buf_)));
++
++  // implicit token
++  EXPECT_TRUE(tokens_->Acquire());
++}
++
++TEST_F(TokenPoolTest, Clear) {
++  CreateDefaultPool();
++
++  ASSERT_NE(NULL, tokens_);
++  EXPECT_EQ(kLoadAverageDefault, load_avg_);
++
++  // implicit token
++  EXPECT_TRUE(tokens_->Acquire());
++  tokens_->Reserve();
++  EXPECT_FALSE(tokens_->Acquire());
++
++  // jobserver offers 2nd & 3rd token
++  ASSERT_EQ(2u, write(fds_[1], "TT", 2));
++  EXPECT_TRUE(tokens_->Acquire());
++  tokens_->Reserve();
++  EXPECT_TRUE(tokens_->Acquire());
++  tokens_->Reserve();
++  EXPECT_FALSE(tokens_->Acquire());
++
++  tokens_->Clear();
++  EXPECT_TRUE(tokens_->Acquire());
++
++  // there must be two tokens in the pipe
++  EXPECT_EQ(2u, read(fds_[0], buf_, sizeof(buf_)));
++
++  // implicit token
++  EXPECT_TRUE(tokens_->Acquire());
++}
++#endif
+--
+2.44.0
+
meta/recipes-devtools/ninja/files/0008-Add-tests-for-subprocess-module.patch new file +121 -0
new file mode 100644
index 0000000000..df8b030fc9
@@ -0,0 +1,121 @@
+From cf02adcc6cdb56dd728f1f4cc02939352635a9a9 Mon Sep 17 00:00:00 2001
+From: Stefan Becker <[email protected]>
+Date: Thu, 24 May 2018 18:52:45 +0300
+Subject: [PATCH 08/20] Add tests for subprocess module
+
+- add TokenPoolTest stub to provide TokenPool::GetMonitorFd()
+- add two tests
+  * both tests set up a dummy GNUmake jobserver pipe
+  * both tests call DoWork() with TokenPoolTest
+  * test 1: verify that DoWork() detects when a token is available
+  * test 2: verify that DoWork() works as before without a token
+- the tests are not compiled in under Windows
+
+Upstream-Status: Submitted [https://github.com/ninja-build/ninja/pull/1140]
+---
+ src/subprocess_test.cc | 76 ++++++++++++++++++++++++++++++++++++++++++
+ 1 file changed, 76 insertions(+)
+
+diff --git a/src/subprocess_test.cc b/src/subprocess_test.cc
+index 4bc8083..6264c8b 100644
+--- a/src/subprocess_test.cc
++++ b/src/subprocess_test.cc
+@@ -13,6 +13,7 @@
+ // limitations under the License.
+
+ #include "subprocess.h"
++#include "tokenpool.h"
+
+ #include "test.h"
+
+@@ -34,8 +35,23 @@ const char* kSimpleCommand = "cmd /c dir \\";
+ const char* kSimpleCommand = "ls /";
+ #endif
+
++struct TokenPoolTest : public TokenPool {
++  bool Acquire()     { return false; }
++  void Reserve()     {}
++  void Release()     {}
++  void Clear()       {}
++
++#ifdef _WIN32
++  // @TODO
++#else
++  int _fd;
++  int GetMonitorFd() { return _fd; }
++#endif
++};
++
+ struct SubprocessTest : public testing::Test {
+   SubprocessSet subprocs_;
++  TokenPoolTest tokens_;
+ };
+
+ }  // anonymous namespace
+@@ -280,3 +296,63 @@ TEST_F(SubprocessTest, ReadStdin) {
+   ASSERT_EQ(1u, subprocs_.finished_.size());
+ }
+ #endif  // _WIN32
++
++// @TODO: remove once TokenPool implementation for Windows is available
++#ifndef _WIN32
++TEST_F(SubprocessTest, TokenAvailable) {
++  Subprocess* subproc = subprocs_.Add(kSimpleCommand);
++  ASSERT_NE((Subprocess *) 0, subproc);
++
++  // simulate GNUmake jobserver pipe with 1 token
++  int fds[2];
++  ASSERT_EQ(0u, pipe(fds));
++  tokens_._fd = fds[0];
++  ASSERT_EQ(1u, write(fds[1], "T", 1));
++
++  subprocs_.ResetTokenAvailable();
++  subprocs_.DoWork(&tokens_);
++
++  EXPECT_TRUE(subprocs_.IsTokenAvailable());
++  EXPECT_EQ(0u, subprocs_.finished_.size());
++
++  // remove token to let DoWork() wait for command again
++  char token;
++  ASSERT_EQ(1u, read(fds[0], &token, 1));
++
++  while (!subproc->Done()) {
++    subprocs_.DoWork(&tokens_);
++  }
++
++  close(fds[1]);
++  close(fds[0]);
++
++  EXPECT_EQ(ExitSuccess, subproc->Finish());
++  EXPECT_NE("", subproc->GetOutput());
++
++  EXPECT_EQ(1u, subprocs_.finished_.size());
++}
++
++TEST_F(SubprocessTest, TokenNotAvailable) {
++  Subprocess* subproc = subprocs_.Add(kSimpleCommand);
++  ASSERT_NE((Subprocess *) 0, subproc);
++
++  // simulate GNUmake jobserver pipe with 0 tokens
++  int fds[2];
++  ASSERT_EQ(0u, pipe(fds));
++  tokens_._fd = fds[0];
++
++  subprocs_.ResetTokenAvailable();
++  while (!subproc->Done()) {
++    subprocs_.DoWork(&tokens_);
++  }
++
++  close(fds[1]);
++  close(fds[0]);
++
++  EXPECT_FALSE(subprocs_.IsTokenAvailable());
++  EXPECT_EQ(ExitSuccess, subproc->Finish());
++  EXPECT_NE("", subproc->GetOutput());
++
++  EXPECT_EQ(1u, subprocs_.finished_.size());
++}
++#endif  // _WIN32
+--
+2.44.0
+
meta/recipes-devtools/ninja/files/0009-Add-tests-for-build-module.patch new file +397 -0
new file mode 100644
index 0000000000..fae5552e1a
@@ -0,0 +1,397 @@
+From f99d747d859a10421afedc7e9808a4e3defc2465 Mon Sep 17 00:00:00 2001
+From: Stefan Becker <[email protected]>
+Date: Sat, 26 May 2018 23:17:51 +0300
+Subject: [PATCH 09/20] Add tests for build module
+
+Add tests that verify the token functionality of the builder main loop.
+We replace the default fake command runner with a special version where
+the tests can control each call to AcquireToken(), CanRunMore() and
+WaitForCommand().
+
+Upstream-Status: Submitted [https://github.com/ninja-build/ninja/pull/1140]
+---
+ src/build_test.cc | 364 ++++++++++++++++++++++++++++++++++++++++++++++
+ 1 file changed, 364 insertions(+)
+
+diff --git a/src/build_test.cc b/src/build_test.cc
+index efa5662..0ef6ece 100644
+--- a/src/build_test.cc
++++ b/src/build_test.cc
+@@ -15,6 +15,7 @@
+ #include "build.h"
+
+ #include <assert.h>
++#include <stdarg.h>
+
+ #include "build_log.h"
+ #include "deps_log.h"
+@@ -4298,3 +4299,366 @@ TEST_F(BuildTest, ValidationWithCircularDependency) {
+   EXPECT_FALSE(builder_.AddTarget("out", &err));
+   EXPECT_EQ("dependency cycle: validate -> validate_in -> validate", err);
+ }
++
++/// The token tests are concerned with the main loop functionality when
++// the CommandRunner has an active TokenPool. It is therefore intentional
++// that the plan doesn't complete and that builder_.Build() returns false!
++
++/// Fake implementation of CommandRunner that simulates a TokenPool
++struct FakeTokenCommandRunner : public CommandRunner {
++  explicit FakeTokenCommandRunner() {}
++
++  // CommandRunner impl
++  virtual bool CanRunMore() const;
++  virtual bool AcquireToken();
++  virtual bool StartCommand(Edge* edge);
++  virtual bool WaitForCommand(Result* result, bool more_ready);
++  virtual vector<Edge*> GetActiveEdges();
++  virtual void Abort();
++
++  vector<string> commands_ran_;
++  vector<Edge *> edges_;
++
++  vector<bool> acquire_token_;
++  vector<bool> can_run_more_;
++  vector<bool> wait_for_command_;
++};
++
++bool FakeTokenCommandRunner::CanRunMore() const {
++  if (can_run_more_.size() == 0) {
++    EXPECT_FALSE("unexpected call to CommandRunner::CanRunMore()");
++    return false;
++  }
++
++  bool result = can_run_more_[0];
++
++  // Unfortunately CanRunMore() isn't "const" for tests
++  const_cast<FakeTokenCommandRunner*>(this)->can_run_more_.erase(
++    const_cast<FakeTokenCommandRunner*>(this)->can_run_more_.begin()
++  );
++
++  return result;
++}
++
++bool FakeTokenCommandRunner::AcquireToken() {
++  if (acquire_token_.size() == 0) {
++    EXPECT_FALSE("unexpected call to CommandRunner::AcquireToken()");
++    return false;
++  }
++
++  bool result = acquire_token_[0];
++  acquire_token_.erase(acquire_token_.begin());
++  return result;
++}
++
++bool FakeTokenCommandRunner::StartCommand(Edge* edge) {
++  commands_ran_.push_back(edge->EvaluateCommand());
++  edges_.push_back(edge);
++  return true;
++}
++
++bool FakeTokenCommandRunner::WaitForCommand(Result* result, bool more_ready) {
++  if (wait_for_command_.size() == 0) {
++    EXPECT_FALSE("unexpected call to CommandRunner::WaitForCommand()");
++    return false;
++  }
++
++  bool expected = wait_for_command_[0];
++  if (expected != more_ready) {
++    EXPECT_EQ(expected, more_ready);
++    return false;
++  }
++  wait_for_command_.erase(wait_for_command_.begin());
++
++  if (edges_.size() == 0)
++    return false;
++
++  Edge* edge = edges_[0];
++  result->edge = edge;
++
++  if (more_ready &&
++      (edge->rule().name() == "token-available")) {
++    result->status = ExitTokenAvailable;
++  } else {
++    edges_.erase(edges_.begin());
++    result->status = ExitSuccess;
++  }
++
++  return true;
++}
++
++vector<Edge*> FakeTokenCommandRunner::GetActiveEdges() {
++  return edges_;
++}
++
++void FakeTokenCommandRunner::Abort() {
++  edges_.clear();
++}
++
++struct BuildTokenTest : public BuildTest {
++  virtual void SetUp();
++  virtual void TearDown();
++
++  FakeTokenCommandRunner token_command_runner_;
++
++  void ExpectAcquireToken(int count, ...);
++  void ExpectCanRunMore(int count, ...);
++  void ExpectWaitForCommand(int count, ...);
++
++private:
++  void EnqueueBooleans(vector<bool>& booleans, int count, va_list ao);
++};
++
++void BuildTokenTest::SetUp() {
++  BuildTest::SetUp();
++
++  // replace FakeCommandRunner with FakeTokenCommandRunner
++  builder_.command_runner_.release();
++  builder_.command_runner_.reset(&token_command_runner_);
++}
++void BuildTokenTest::TearDown() {
++  EXPECT_EQ(0u, token_command_runner_.acquire_token_.size());
++  EXPECT_EQ(0u, token_command_runner_.can_run_more_.size());
++  EXPECT_EQ(0u, token_command_runner_.wait_for_command_.size());
++
++  BuildTest::TearDown();
++}
++
++void BuildTokenTest::ExpectAcquireToken(int count, ...) {
++  va_list ap;
++  va_start(ap, count);
++  EnqueueBooleans(token_command_runner_.acquire_token_, count, ap);
++  va_end(ap);
++}
++
++void BuildTokenTest::ExpectCanRunMore(int count, ...) {
++  va_list ap;
++  va_start(ap, count);
++  EnqueueBooleans(token_command_runner_.can_run_more_, count, ap);
++  va_end(ap);
++}
++
++void BuildTokenTest::ExpectWaitForCommand(int count, ...) {
++  va_list ap;
++  va_start(ap, count);
++  EnqueueBooleans(token_command_runner_.wait_for_command_, count, ap);
++  va_end(ap);
++}
++
++void BuildTokenTest::EnqueueBooleans(vector<bool>& booleans, int count, va_list ap) {
++  while (count--) {
++    int value = va_arg(ap, int);
++    booleans.push_back(!!value); // force bool
++  }
++}
++
++TEST_F(BuildTokenTest, CompleteNoWork) {
++  // plan should not execute anything
++  string err;
++
++  EXPECT_TRUE(builder_.Build(&err));
++  EXPECT_EQ("", err);
++
++  EXPECT_EQ(0u, token_command_runner_.commands_ran_.size());
++}
++
++TEST_F(BuildTokenTest, DoNotAquireToken) {
++  // plan should execute one command
++  string err;
++  EXPECT_TRUE(builder_.AddTarget("cat1", &err));
++  ASSERT_EQ("", err);
++
++  // pretend we can't run anything
++  ExpectCanRunMore(1, false);
++
++  EXPECT_FALSE(builder_.Build(&err));
++  EXPECT_EQ("stuck [this is a bug]", err);
++
++  EXPECT_EQ(0u, token_command_runner_.commands_ran_.size());
++}
++
++TEST_F(BuildTokenTest, DoNotStartWithoutToken) {
++  // plan should execute one command
++  string err;
++  EXPECT_TRUE(builder_.AddTarget("cat1", &err));
++  ASSERT_EQ("", err);
++
++  // we could run a command but do not have a token for it
++  ExpectCanRunMore(1,   true);
++  ExpectAcquireToken(1, false);
++
++  EXPECT_FALSE(builder_.Build(&err));
++  EXPECT_EQ("stuck [this is a bug]", err);
++
++  EXPECT_EQ(0u, token_command_runner_.commands_ran_.size());
++}
++
++TEST_F(BuildTokenTest, CompleteOneStep) {
++  // plan should execute one command
++  string err;
++  EXPECT_TRUE(builder_.AddTarget("cat1", &err));
++  ASSERT_EQ("", err);
++
++  // allow running of one command
++  ExpectCanRunMore(1,   true);
++  ExpectAcquireToken(1, true);
++  // block and wait for command to finalize
++  ExpectWaitForCommand(1, false);
++
++  EXPECT_TRUE(builder_.Build(&err));
++  EXPECT_EQ("", err);
++
++  EXPECT_EQ(1u, token_command_runner_.commands_ran_.size());
++  EXPECT_TRUE(token_command_runner_.commands_ran_[0] == "cat in1 > cat1");
++}
++
++TEST_F(BuildTokenTest, AcquireOneToken) {
++  // plan should execute more than one command
++  string err;
++  EXPECT_TRUE(builder_.AddTarget("cat12", &err));
++  ASSERT_EQ("", err);
++
++  // allow running of one command
++  ExpectCanRunMore(3,     true, false, false);
++  ExpectAcquireToken(1,   true);
++  // block and wait for command to finalize
++  ExpectWaitForCommand(1, false);
++
++  EXPECT_FALSE(builder_.Build(&err));
++  EXPECT_EQ("stuck [this is a bug]", err);
++
++  EXPECT_EQ(1u, token_command_runner_.commands_ran_.size());
++  // any of the two dependencies could have been executed
++  EXPECT_TRUE(token_command_runner_.commands_ran_[0] == "cat in1 > cat1" ||
++              token_command_runner_.commands_ran_[0] == "cat in1 in2 > cat2");
++}
++
++TEST_F(BuildTokenTest, WantTwoTokens) {
++  // plan should execute more than one command
++  string err;
++  EXPECT_TRUE(builder_.AddTarget("cat12", &err));
++  ASSERT_EQ("", err);
++
++  // allow running of one command
++  ExpectCanRunMore(3,     true, true, false);
++  ExpectAcquireToken(2,   true, false);
++  // wait for command to finalize or token to become available
++  ExpectWaitForCommand(1, true);
++
++  EXPECT_FALSE(builder_.Build(&err));
++  EXPECT_EQ("stuck [this is a bug]", err);
++
++  EXPECT_EQ(1u, token_command_runner_.commands_ran_.size());
++  // any of the two dependencies could have been executed
++  EXPECT_TRUE(token_command_runner_.commands_ran_[0] == "cat in1 > cat1" ||
++              token_command_runner_.commands_ran_[0] == "cat in1 in2 > cat2");
++}
++
++TEST_F(BuildTokenTest, CompleteTwoSteps) {
++  ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
++"build out1: cat in1\n"
++"build out2: cat out1\n"));
++
++  // plan should execute more than one command
++  string err;
++  EXPECT_TRUE(builder_.AddTarget("out2", &err));
++  ASSERT_EQ("", err);
++
++  // allow running of two commands
++  ExpectCanRunMore(2,     true, true);
++  ExpectAcquireToken(2,   true, true);
++  // wait for commands to finalize
++  ExpectWaitForCommand(2, false, false);
++
++  EXPECT_TRUE(builder_.Build(&err));
++  EXPECT_EQ("", err);
++
++  EXPECT_EQ(2u, token_command_runner_.commands_ran_.size());
++  EXPECT_TRUE(token_command_runner_.commands_ran_[0] == "cat in1 > out1");
++  EXPECT_TRUE(token_command_runner_.commands_ran_[1] == "cat out1 > out2");
++}
++
++TEST_F(BuildTokenTest, TwoCommandsInParallel) {
++  ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
++"rule token-available\n"
++"  command = cat $in > $out\n"
++"build out1: token-available in1\n"
++"build out2: token-available in2\n"
++"build out12: cat out1 out2\n"));
++
++  // plan should execute more than one command
++  string err;
++  EXPECT_TRUE(builder_.AddTarget("out12", &err));
++  ASSERT_EQ("", err);
++
++  // 1st command: token available -> allow running
++  // 2nd command: no token available but becomes available later
++  ExpectCanRunMore(4,     true, true,  true,  false);
++  ExpectAcquireToken(3,   true, false, true);
++  // 1st call waits for command to finalize or token to become available
++  // 2nd call waits for command to finalize
++  // 3rd call waits for command to finalize
++  ExpectWaitForCommand(3, true, false, false);
++
++  EXPECT_FALSE(builder_.Build(&err));
++  EXPECT_EQ("stuck [this is a bug]", err);
++
++  EXPECT_EQ(2u, token_command_runner_.commands_ran_.size());
++  EXPECT_TRUE((token_command_runner_.commands_ran_[0] == "cat in1 > out1" &&
++               token_command_runner_.commands_ran_[1] == "cat in2 > out2") ||
++              (token_command_runner_.commands_ran_[0] == "cat in2 > out2" &&
++               token_command_runner_.commands_ran_[1] == "cat in1 > out1"));
++}
++
++TEST_F(BuildTokenTest, CompleteThreeStepsSerial) {
++  // plan should execute more than one command
++  string err;
++  EXPECT_TRUE(builder_.AddTarget("cat12", &err));
++  ASSERT_EQ("", err);
++
++  // allow running of all commands
++  ExpectCanRunMore(4,     true, true,  true,  true);
++  ExpectAcquireToken(4,   true, false, true,  true);
++  // wait for commands to finalize
++  ExpectWaitForCommand(3, true, false, false);
++
++  EXPECT_TRUE(builder_.Build(&err));
++  EXPECT_EQ("", err);
++
++  EXPECT_EQ(3u, token_command_runner_.commands_ran_.size());
++  EXPECT_TRUE((token_command_runner_.commands_ran_[0] == "cat in1 > cat1"     &&
++               token_command_runner_.commands_ran_[1] == "cat in1 in2 > cat2") ||
++              (token_command_runner_.commands_ran_[0] == "cat in1 in2 > cat2" &&
++               token_command_runner_.commands_ran_[1] == "cat in1 > cat1"    ));
++  EXPECT_TRUE(token_command_runner_.commands_ran_[2] == "cat cat1 cat2 > cat12");
++}
++
++TEST_F(BuildTokenTest, CompleteThreeStepsParallel) {
++  ASSERT_NO_FATAL_FAILURE(AssertParse(&state_,
++"rule token-available\n"
++"  command = cat $in > $out\n"
++"build out1: token-available in1\n"
++"build out2: token-available in2\n"
++"build out12: cat out1 out2\n"));
++
++  // plan should execute more than one command
++  string err;
++  EXPECT_TRUE(builder_.AddTarget("out12", &err));
++  ASSERT_EQ("", err);
++
++  // allow running of all commands
++  ExpectCanRunMore(4,     true, true,  true,  true);
++  ExpectAcquireToken(4,   true, false, true,  true);
++  // wait for commands to finalize
++  ExpectWaitForCommand(4, true, false, false, false);
++
++  EXPECT_TRUE(builder_.Build(&err));
++  EXPECT_EQ("", err);
++
++  EXPECT_EQ(3u, token_command_runner_.commands_ran_.size());
++  EXPECT_TRUE((token_command_runner_.commands_ran_[0] == "cat in1 > out1" &&
++               token_command_runner_.commands_ran_[1] == "cat in2 > out2") ||
++              (token_command_runner_.commands_ran_[0] == "cat in2 > out2" &&
++               token_command_runner_.commands_ran_[1] == "cat in1 > out1"));
++  EXPECT_TRUE(token_command_runner_.commands_ran_[2] == "cat out1 out2 > out12");
++}
+--
+2.44.0
+
meta/recipes-devtools/ninja/files/0010-Add-Win32-implementation-for-GNUmakeTokenPool.patch new file +1283 -0
new file mode 100644
index 0000000000..5aa74d97e9
@@ -0,0 +1,1283 @@
+From 71ad7daae069341f1b7827da911288024d208686 Mon Sep 17 00:00:00 2001
+From: Stefan Becker <[email protected]>
+Date: Mon, 8 Oct 2018 17:47:50 +0300
+Subject: [PATCH 10/20] Add Win32 implementation for GNUmakeTokenPool
+
+GNU make uses a semaphore as jobserver protocol on Win32. See also
+
+   https://www.gnu.org/software/make/manual/html_node/Windows-Jobserver.html
+
+Usage is pretty simple and straightforward, i.e. WaitForSingleObject()
+to obtain a token and ReleaseSemaphore() to return it.
+
+Unfortunately subprocess-win32.cc uses an I/O completion port (IOCP).
+IOCPs aren't waitable objects, i.e. we can't use WaitForMultipleObjects()
+to wait on the IOCP and the token semaphore at the same time.
+
+Therefore GNUmakeTokenPoolWin32 creates a child thread that waits on the
+token semaphore and posts a dummy I/O completion status on the IOCP when
+it was able to obtain a token. That unblocks SubprocessSet::DoWork() and
+it can then check if a token became available or not.
+
+- split existing GNUmakeTokenPool into common and platform bits
+- add GNUmakeTokenPool interface
+- move the Posix bits to GNUmakeTokenPoolPosix
+- add the Win32 bits as GNUmakeTokenPoolWin32
+- move Setup() method up to TokenPool interface
+- update Subprocess & TokenPool tests accordingly
+
+Upstream-Status: Submitted [https://github.com/ninja-build/ninja/pull/1140]
+---
+ configure.py                    |   8 +-
+ src/build.cc                    |  11 +-
+ src/subprocess-win32.cc         |   9 ++
+ src/subprocess_test.cc          |  34 ++++-
+ src/tokenpool-gnu-make-posix.cc | 203 +++++++++++++++++++++++++++
+ src/tokenpool-gnu-make-win32.cc | 237 ++++++++++++++++++++++++++++++++
+ src/tokenpool-gnu-make.cc       | 203 ++-------------------------
+ src/tokenpool-gnu-make.h        |  40 ++++++
+ src/tokenpool-none.cc           |   4 +-
+ src/tokenpool.h                 |  18 ++-
+ src/tokenpool_test.cc           | 113 ++++++++++++---
+ 11 files changed, 653 insertions(+), 227 deletions(-)
+ create mode 100644 src/tokenpool-gnu-make-posix.cc
+ create mode 100644 src/tokenpool-gnu-make-win32.cc
+ create mode 100644 src/tokenpool-gnu-make.h
+
+diff --git a/configure.py b/configure.py
+index 41f9428..9bfa02f 100755
+--- a/configure.py
++++ b/configure.py
+@@ -538,12 +538,13 @@ for name in ['build',
+              'state',
+              'status',
+              'string_piece_util',
++             'tokenpool-gnu-make',
+              'util',
+              'version']:
+     objs += cxx(name, variables=cxxvariables)
+ if platform.is_windows():
+     for name in ['subprocess-win32',
+-                 'tokenpool-none',
++                 'tokenpool-gnu-make-win32',
+                  'includes_normalize-win32',
+                  'msvc_helper-win32',
+                  'msvc_helper_main-win32']:
+@@ -552,8 +553,9 @@ if platform.is_windows():
+         objs += cxx('minidump-win32', variables=cxxvariables)
+     objs += cc('getopt')
+ else:
+-    objs += cxx('subprocess-posix')
+-    objs += cxx('tokenpool-gnu-make')
++    for name in ['subprocess-posix',
++                 'tokenpool-gnu-make-posix']:
++        objs += cxx(name)
+ if platform.is_aix():
+     objs += cc('getopt')
+ if platform.is_msvc():
+diff --git a/src/build.cc b/src/build.cc
+index da1faa8..0763dd5 100644
+--- a/src/build.cc
++++ b/src/build.cc
+@@ -473,9 +473,14 @@ struct RealCommandRunner : public CommandRunner {
+
+ RealCommandRunner::RealCommandRunner(const BuildConfig& config) : config_(config) {
+   max_load_average_ = config.max_load_average;
+-  tokens_ = TokenPool::Get(config_.parallelism_from_cmdline,
+-                           config_.verbosity == BuildConfig::VERBOSE,
+-                           max_load_average_);
++  if ((tokens_ = TokenPool::Get()) != NULL) {
++    if (!tokens_->Setup(config_.parallelism_from_cmdline,
++                        config_.verbosity == BuildConfig::VERBOSE,
++                        max_load_average_)) {
++      delete tokens_;
++      tokens_ = NULL;
++    }
++  }
+ }
+
+ RealCommandRunner::~RealCommandRunner() {
+diff --git a/src/subprocess-win32.cc b/src/subprocess-win32.cc
+index 66d2c2c..ce3e2c2 100644
+--- a/src/subprocess-win32.cc
++++ b/src/subprocess-win32.cc
+@@ -13,6 +13,7 @@
+ // limitations under the License.
+
+ #include "subprocess.h"
++#include "tokenpool.h"
+
+ #include <assert.h>
+ #include <stdio.h>
+@@ -256,6 +257,9 @@ bool SubprocessSet::DoWork(struct TokenPool* tokens) {
+   Subprocess* subproc;
+   OVERLAPPED* overlapped;
+
++  if (tokens)
++    tokens->WaitForTokenAvailability(ioport_);
++
+   if (!GetQueuedCompletionStatus(ioport_, &bytes_read, (PULONG_PTR)&subproc,
+                                  &overlapped, INFINITE)) {
+     if (GetLastError() != ERROR_BROKEN_PIPE)
+@@ -266,6 +270,11 @@ bool SubprocessSet::DoWork(struct TokenPool* tokens) {
+                 // delivered by NotifyInterrupted above.
+     return true;
+
++  if (tokens && tokens->TokenIsAvailable((ULONG_PTR)subproc)) {
++    token_available_ = true;
++    return false;
++  }
++
+   subproc->OnPipeReady();
+
+   if (subproc->Done()) {
+diff --git a/src/subprocess_test.cc b/src/subprocess_test.cc
+index 6264c8b..f625963 100644
+--- a/src/subprocess_test.cc
++++ b/src/subprocess_test.cc
+@@ -40,9 +40,16 @@ struct TokenPoolTest : public TokenPool {
+   void Reserve()     {}
+   void Release()     {}
+   void Clear()       {}
++  bool Setup(bool ignore_unused, bool verbose, double& max_load_average) { return false; }
+
+ #ifdef _WIN32
+-  // @TODO
++  bool _token_available;
++  void WaitForTokenAvailability(HANDLE ioport) {
++    if (_token_available)
++      // unblock GetQueuedCompletionStatus()
++      PostQueuedCompletionStatus(ioport, 0, (ULONG_PTR) this, NULL);
++  }
++  bool TokenIsAvailable(ULONG_PTR key) { return key == (ULONG_PTR) this; }
+ #else
+   int _fd;
+   int GetMonitorFd() { return _fd; }
+@@ -297,34 +304,48 @@ TEST_F(SubprocessTest, ReadStdin) {
+ }
+ #endif  // _WIN32
+
+-// @TODO: remove once TokenPool implementation for Windows is available
+-#ifndef _WIN32
+ TEST_F(SubprocessTest, TokenAvailable) {
+   Subprocess* subproc = subprocs_.Add(kSimpleCommand);
+   ASSERT_NE((Subprocess *) 0, subproc);
+
+   // simulate GNUmake jobserver pipe with 1 token
++#ifdef _WIN32
++  tokens_._token_available = true;
++#else
+   int fds[2];
+   ASSERT_EQ(0u, pipe(fds));
+   tokens_._fd = fds[0];
+   ASSERT_EQ(1u, write(fds[1], "T", 1));
++#endif
+
+   subprocs_.ResetTokenAvailable();
+   subprocs_.DoWork(&tokens_);
++#ifdef _WIN32
++  tokens_._token_available = false;
++  // we need to loop here as we have no conrol where the token
++  // I/O completion post ends up in the queue
++  while (!subproc->Done() && !subprocs_.IsTokenAvailable()) {
++    subprocs_.DoWork(&tokens_);
++  }
++#endif
+
+   EXPECT_TRUE(subprocs_.IsTokenAvailable());
+   EXPECT_EQ(0u, subprocs_.finished_.size());
+
+   // remove token to let DoWork() wait for command again
++#ifndef _WIN32
+   char token;
+   ASSERT_EQ(1u, read(fds[0], &token, 1));
++#endif
+
+   while (!subproc->Done()) {
+     subprocs_.DoWork(&tokens_);
+   }
+
++#ifndef _WIN32
+   close(fds[1]);
+   close(fds[0]);
++#endif
+
+   EXPECT_EQ(ExitSuccess, subproc->Finish());
+   EXPECT_NE("", subproc->GetOutput());
+@@ -337,17 +358,23 @@ TEST_F(SubprocessTest, TokenNotAvailable) {
+   ASSERT_NE((Subprocess *) 0, subproc);
+
+   // simulate GNUmake jobserver pipe with 0 tokens
++#ifdef _WIN32
++  tokens_._token_available = false;
++#else
+   int fds[2];
+   ASSERT_EQ(0u, pipe(fds));
+   tokens_._fd = fds[0];
++#endif
+
+   subprocs_.ResetTokenAvailable();
+   while (!subproc->Done()) {
+     subprocs_.DoWork(&tokens_);
+   }
+
++#ifndef _WIN32
+   close(fds[1]);
+   close(fds[0]);
++#endif
+
+   EXPECT_FALSE(subprocs_.IsTokenAvailable());
+   EXPECT_EQ(ExitSuccess, subproc->Finish());
+@@ -355,4 +382,3 @@ TEST_F(SubprocessTest, TokenNotAvailable) {
+
+   EXPECT_EQ(1u, subprocs_.finished_.size());
+ }
+-#endif  // _WIN32
+diff --git a/src/tokenpool-gnu-make-posix.cc b/src/tokenpool-gnu-make-posix.cc
+new file mode 100644
+index 0000000..70d84bf
+--- /dev/null
++++ b/src/tokenpool-gnu-make-posix.cc
+@@ -0,0 +1,203 @@
++// Copyright 2016-2018 Google Inc. All Rights Reserved.
++//
++// Licensed 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 "tokenpool-gnu-make.h"
++
++#include <errno.h>
++#include <fcntl.h>
++#include <poll.h>
++#include <unistd.h>
++#include <signal.h>
++#include <sys/time.h>
++#include <stdio.h>
++#include <string.h>
++#include <stdlib.h>
++
++// TokenPool implementation for GNU make jobserver - POSIX implementation
++// (http://make.mad-scientist.net/papers/jobserver-implementation/)
++struct GNUmakeTokenPoolPosix : public GNUmakeTokenPool {
++  GNUmakeTokenPoolPosix();
++  virtual ~GNUmakeTokenPoolPosix();
++
++  virtual int GetMonitorFd();
++
++  virtual const char *GetEnv(const char *name) { return getenv(name); };
++  virtual bool ParseAuth(const char *jobserver);
++  virtual bool AcquireToken();
++  virtual bool ReturnToken();
++
++ private:
++  int rfd_;
++  int wfd_;
++
++  struct sigaction old_act_;
++  bool restore_;
++
++  static int dup_rfd_;
++  static void CloseDupRfd(int signum);
++
++  bool CheckFd(int fd);
++  bool SetAlarmHandler();
++};
++
++GNUmakeTokenPoolPosix::GNUmakeTokenPoolPosix() : rfd_(-1), wfd_(-1), restore_(false) {
++}
++
++GNUmakeTokenPoolPosix::~GNUmakeTokenPoolPosix() {
++  Clear();
++  if (restore_)
++    sigaction(SIGALRM, &old_act_, NULL);
++}
++
++bool GNUmakeTokenPoolPosix::CheckFd(int fd) {
++  if (fd < 0)
++    return false;
++  int ret = fcntl(fd, F_GETFD);
++  if (ret < 0)
++    return false;
++  return true;
++}
++
++int GNUmakeTokenPoolPosix::dup_rfd_ = -1;
++
++void GNUmakeTokenPoolPosix::CloseDupRfd(int signum) {
++  close(dup_rfd_);
++  dup_rfd_ = -1;
++}
++
++bool GNUmakeTokenPoolPosix::SetAlarmHandler() {
++  struct sigaction act;
++  memset(&act, 0, sizeof(act));
++  act.sa_handler = CloseDupRfd;
++  if (sigaction(SIGALRM, &act, &old_act_) < 0) {
++    perror("sigaction:");
++    return(false);
++  } else {
++    restore_ = true;
++    return(true);
++  }
++}
++
++bool GNUmakeTokenPoolPosix::ParseAuth(const char *jobserver) {
++  int rfd = -1;
++  int wfd = -1;
++  if ((sscanf(jobserver, "%*[^=]=%d,%d", &rfd, &wfd) == 2) &&
++      CheckFd(rfd) &&
++      CheckFd(wfd) &&
++      SetAlarmHandler()) {
++    rfd_ = rfd;
++    wfd_ = wfd;
++    return true;
++  }
++
++  return false;
++}
++
++bool GNUmakeTokenPoolPosix::AcquireToken() {
++  // Please read
++  //
++  //   http://make.mad-scientist.net/papers/jobserver-implementation/
++  //
++  // for the reasoning behind the following code.
++  //
++  // Try to read one character from the pipe. Returns true on success.
++  //
++  // First check if read() would succeed without blocking.
++#ifdef USE_PPOLL
++  pollfd pollfds[] = {{rfd_, POLLIN, 0}};
++  int ret = poll(pollfds, 1, 0);
++#else
++  fd_set set;
++  struct timeval timeout = { 0, 0 };
++  FD_ZERO(&set);
++  FD_SET(rfd_, &set);
++  int ret = select(rfd_ + 1, &set, NULL, NULL, &timeout);
++#endif
++  if (ret > 0) {
++    // Handle potential race condition:
++    //  - the above check succeeded, i.e. read() should not block
++    //  - the character disappears before we call read()
++    //
++    // Create a duplicate of rfd_. The duplicate file descriptor dup_rfd_
++    // can safely be closed by signal handlers without affecting rfd_.
++    dup_rfd_ = dup(rfd_);
++
++    if (dup_rfd_ != -1) {
++      struct sigaction act, old_act;
++      int ret = 0;
++
++      // Temporarily replace SIGCHLD handler with our own
++      memset(&act, 0, sizeof(act));
++      act.sa_handler = CloseDupRfd;
++      if (sigaction(SIGCHLD, &act, &old_act) == 0) {
++        struct itimerval timeout;
++
++        // install a 100ms timeout that generates SIGALARM on expiration
++        memset(&timeout, 0, sizeof(timeout));
++        timeout.it_value.tv_usec = 100 * 1000; // [ms] -> [usec]
++        if (setitimer(ITIMER_REAL, &timeout, NULL) == 0) {
++          char buf;
++
++          // Now try to read() from dup_rfd_. Return values from read():
++          //
++          // 1. token read                               ->  1
++          // 2. pipe closed                              ->  0
++          // 3. alarm expires                            -> -1 (EINTR)
++          // 4. child exits                              -> -1 (EINTR)
++          // 5. alarm expired before entering read()     -> -1 (EBADF)
++          // 6. child exited before entering read()      -> -1 (EBADF)
++          // 7. child exited before handler is installed -> go to 1 - 3
++          ret = read(dup_rfd_, &buf, 1);
++
++          // disarm timer
++          memset(&timeout, 0, sizeof(timeout));
++          setitimer(ITIMER_REAL, &timeout, NULL);
++        }
++
++        sigaction(SIGCHLD, &old_act, NULL);
++      }
++
++      CloseDupRfd(0);
++
++      // Case 1 from above list
++      if (ret > 0)
++        return true;
++    }
++  }
++
++  // read() would block, i.e. no token available,
++  // cases 2-6 from above list or
++  // select() / poll() / dup() / sigaction() / setitimer() failed
++  return false;
++}
++
++bool GNUmakeTokenPoolPosix::ReturnToken() {
++  const char buf = '+';
++  while (1) {
++    int ret = write(wfd_, &buf, 1);
++    if (ret > 0)
++      return true;
++    if ((ret != -1) || (errno != EINTR))
++      return false;
++    // write got interrupted - retry
++  }
++}
++
++int GNUmakeTokenPoolPosix::GetMonitorFd() {
++  return(rfd_);
++}
++
++struct TokenPool *TokenPool::Get() {
++  return new GNUmakeTokenPoolPosix;
++}
+diff --git a/src/tokenpool-gnu-make-win32.cc b/src/tokenpool-gnu-make-win32.cc
+new file mode 100644
+index 0000000..2719f2c
+--- /dev/null
++++ b/src/tokenpool-gnu-make-win32.cc
+@@ -0,0 +1,237 @@
++// Copyright 2018 Google Inc. All Rights Reserved.
++//
++// Licensed 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 "tokenpool-gnu-make.h"
++
++// always include first to make sure other headers do the correct thing...
++#include <windows.h>
++
++#include <ctype.h>
++#include <stdlib.h>
++#include <string.h>
++
++#include "util.h"
++
++// TokenPool implementation for GNU make jobserver - Win32 implementation
++// (https://www.gnu.org/software/make/manual/html_node/Windows-Jobserver.html)
++struct GNUmakeTokenPoolWin32 : public GNUmakeTokenPool {
++  GNUmakeTokenPoolWin32();
++  virtual ~GNUmakeTokenPoolWin32();
++
++  virtual void WaitForTokenAvailability(HANDLE ioport);
++  virtual bool TokenIsAvailable(ULONG_PTR key);
++
++  virtual const char *GetEnv(const char *name);
++  virtual bool ParseAuth(const char *jobserver);
++  virtual bool AcquireToken();
++  virtual bool ReturnToken();
++
++ private:
++  // Semaphore for GNU make jobserver protocol
++  HANDLE semaphore_jobserver_;
++  // Semaphore Child -> Parent
++  // - child releases it before entering wait on jobserver semaphore
++  // - parent blocks on it to know when child enters wait
++  HANDLE semaphore_enter_wait_;
++  // Semaphore Parent -> Child
++  // - parent releases it to allow child to restart loop
++  // - child blocks on it to know when to restart loop
++  HANDLE semaphore_restart_;
++  // set to false if child should exit loop and terminate thread
++  bool running_;
++  // child thread
++  HANDLE child_;
++  // I/O completion port from SubprocessSet
++  HANDLE ioport_;
++
++
++  DWORD SemaphoreThread();
++  void ReleaseSemaphore(HANDLE semaphore);
++  void WaitForObject(HANDLE object);
++  static DWORD WINAPI SemaphoreThreadWrapper(LPVOID param);
++  static void NoopAPCFunc(ULONG_PTR param);
++};
++
++GNUmakeTokenPoolWin32::GNUmakeTokenPoolWin32() : semaphore_jobserver_(NULL),
++                                                 semaphore_enter_wait_(NULL),
++                                                 semaphore_restart_(NULL),
++                                                 running_(false),
++                                                 child_(NULL),
++                                                 ioport_(NULL) {
++}
++
++GNUmakeTokenPoolWin32::~GNUmakeTokenPoolWin32() {
++  Clear();
++  CloseHandle(semaphore_jobserver_);
++  semaphore_jobserver_ = NULL;
++
++  if (child_) {
++    // tell child thread to exit
++    running_ = false;
++    ReleaseSemaphore(semaphore_restart_);
++
++    // wait for child thread to exit
++    WaitForObject(child_);
++    CloseHandle(child_);
++    child_ = NULL;
++  }
++
++  if (semaphore_restart_) {
++    CloseHandle(semaphore_restart_);
++    semaphore_restart_ = NULL;
++  }
++
++  if (semaphore_enter_wait_) {
++    CloseHandle(semaphore_enter_wait_);
++    semaphore_enter_wait_ = NULL;
++  }
++}
++
++const char *GNUmakeTokenPoolWin32::GetEnv(const char *name) {
++  // getenv() does not work correctly together with tokenpool_tests.cc
++  static char buffer[MAX_PATH + 1];
++  if (GetEnvironmentVariable("MAKEFLAGS", buffer, sizeof(buffer)) == 0)
++    return NULL;
++  return(buffer);
++}
++
++bool GNUmakeTokenPoolWin32::ParseAuth(const char *jobserver) {
++  // match "--jobserver-auth=gmake_semaphore_<INTEGER>..."
++  const char *start = strchr(jobserver, '=');
++  if (start) {
++    const char *end = start;
++    unsigned int len;
++    char c, *auth;
++
++    while ((c = *++end) != '\0')
++      if (!(isalnum(c) || (c == '_')))
++        break;
++    len = end - start; // includes string terminator in count
++
++    if ((len > 1) && ((auth = (char *)malloc(len)) != NULL)) {
++      strncpy(auth, start + 1, len - 1);
++      auth[len - 1] = '\0';
++
[… more lines in the raw message]

Lines of this file are not shown. View the raw message.

meta/recipes-devtools/ninja/files/0011-Prepare-PR-for-merging-part-II.patch new file +744 -0
new file mode 100644
index 0000000000..62c5be39e1

Lines of this file are not shown. View the raw message.

meta/recipes-devtools/ninja/files/0012-Rename-TokenPool-Setup-to-SetupClient.patch new file +109 -0
new file mode 100644
index 0000000000..dc2feb3005

Lines of this file are not shown. View the raw message.

meta/recipes-devtools/ninja/files/0013-Add-TokenPool-SetupMaster-method.patch new file +78 -0
new file mode 100644
index 0000000000..673e0d911f

Lines of this file are not shown. View the raw message.

meta/recipes-devtools/ninja/files/0014-Add-command-line-option-m-tokenpool-master.patch new file +101 -0
new file mode 100644
index 0000000000..a99e4a5cb8

Lines of this file are not shown. View the raw message.

meta/recipes-devtools/ninja/files/0015-Implement-GNUmakeTokenPool-SetupMaster.patch new file +152 -0
new file mode 100644
index 0000000000..fed6340a6a

Lines of this file are not shown. View the raw message.

meta/recipes-devtools/ninja/files/0016-Implement-GNUmakeTokenPool-CreatePool.patch new file +87 -0
new file mode 100644
index 0000000000..5ee38061df

Lines of this file are not shown. View the raw message.

meta/recipes-devtools/ninja/files/0017-Add-tests-for-TokenPool-SetupMaster.patch new file +145 -0
new file mode 100644
index 0000000000..aafb82b282

Lines of this file are not shown. View the raw message.

meta/recipes-devtools/ninja/files/0018-Add-GNU-make-jobserver-fifo-style-client-support.patch new file +265 -0
new file mode 100644
index 0000000000..8b57932689

Lines of this file are not shown. View the raw message.

meta/recipes-devtools/ninja/files/0019-Add-optional-argument-to-m-tokenpool-master.patch new file +368 -0
new file mode 100644
index 0000000000..5a874ca50e

Lines of this file are not shown. View the raw message.

meta/recipes-devtools/ninja/files/0020-Add-GNU-make-jobserver-fifo-style-master-support.patch new file +287 -0
new file mode 100644
index 0000000000..cb3c5d372a

Lines of this file are not shown. View the raw message.

meta/recipes-devtools/ninja/ninja_1.11.1.bb deleted +0 -33
deleted file mode 100644
index 8e297ec4d4..0000000000

Lines of this file are not shown. View the raw message.

meta/recipes-devtools/ninja/ninja_1.12.0.bb new file +55 -1
new file mode 100644
index 0000000000..a7dcdc0d1f

Lines of this file are not shown. View the raw message.

The rest of this diff is not shown. View the raw message.

2.44.0

Part of the diff is not shown here. View the raw message.

#8 lore raw

Re: [PATCH 3/5] ninja: build modified version with GNU Make jobserver support

Quoted 1 line · Alexander Kanavin

We can't carry this mass of patches. It has to land upstream first.

Understandable.

Quoted 2 lines

Are you able/willing to drive the upstream pull request to completion?

No, I don't think so. I'm not familiar with the ninja codebase, and the pull requests has been lingering for too long.

Another option might be to propose adding the fifo feature to the kitware fork of ninja:
https://github.com/Kitware/ninja

They have forked ninja to get the jobserver feature in, but haven't taken the fifo part so far.

The kitware fork is also used by buildroot:
https://gitlab.com/buildroot.org/buildroot/-/blob/master/package/ninja/ninja.mk

// Martin

#9 lore raw

Re: [PATCH 3/5] ninja: build modified version with GNU Make jobserver support

Quoted 13 lines · Martin Hundebøll
Quoted 1 line · Alexander Kanavin

We can't carry this mass of patches. It has to land upstream first.

Understandable.

Quoted 2 lines

Are you able/willing to drive the upstream pull request to completion?

No, I don't think so. I'm not familiar with the ninja codebase, and the pull requests has been lingering for too long.

Another option might be to propose adding the fifo feature to the kitware fork of ninja:
https://github.com/Kitware/ninja

Quoted 7 lines

They have forked ninja to get the jobserver feature in, but haven't taken the fifo part so far.

The kitware fork is also used by buildroot:
https://gitlab.com/buildroot.org/buildroot/-/blob/master/package/ninja/ninja.mk

// Martin

I see that v2 has switched to kitware, which is fine in the short run.

I'm just back from vacation. I plan to test this patchset out.

I can spend some time convincing upstream ninja that a solution is needed for our use-case and that perhaps the jobsever approach and the kitware fork is a good starting point.

Of course, I can't promise to "drive it to completion" but I'll hound the upstream devs for months or even years!

Thanks for re-submitting the patchset Martin!

Signature · 2 lines
# Randy MacLeod
# Wind River Linux
#10 lore raw

Re: [PATCH 3/5] ninja: build modified version with GNU Make jobserver support

Hi Randy,

Quoted 34 lines · Randy MacLeod
Quoted 17 lines · Martin Hundebøll
Quoted 3 lines · Alexander Kanavin

We can't carry this mass of patches. It has to land upstream first.

Understandable.

Quoted 4 lines

Are you able/willing to drive the upstream pull request to completion?

No, I don't think so. I'm not familiar with the ninja codebase, and the
pull requests has been lingering for too long.

Another option might be to propose adding the fifo feature to the kitware fork of ninja:
https://github.com/Kitware/ninja

Quoted 6 lines

They have forked ninja to get the jobserver feature in, but haven't taken the fifo part so far.

The kitware fork is also used by buildroot:
https://gitlab.com/buildroot.org/buildroot/-/blob/master/package/ninja/ninja.mk

I see that v2 has switched to kitware, which is fine in the short run.

 I'm just back from vacation. I plan to test this patchset out.

 I can spend some time convincing upstream ninja that a solution is needed for our use-case and
 that perhaps the jobsever approach and the kitware fork is a good starting point.

Quoted 5 lines

 Of course, I can't promise to "drive it to completion" but I'll hound the upstream devs for months or even years!

Thanks for re-submitting the patchset Martin!

I got hit by a strike of motivation and submitted a new attempt on jobserver support to ninja:
https://github.com/ninja-build/ninja/pull/2450

First review from the ninja maintainer seems positive. I'll resubmit the my patchset to OE once the ninja PR is (hopefully) merged.

// Martin

#11 lore raw

PATCH 4/5 qemu: enable parallel builds when using the jobserver class

In reply to Martin Hundebøll

If the jobserver class is enabled, the PARALLEL_MAKE variable is unset in favor of configuring a shared jobserver in the MAKEFLAGS variable. However, the qemu makefile translates the missing -j<N> argument to -j1 when calling into meson / ninja. Add a patch to make the qemu makefile consider the --jobserver-auth option too.

---
 meta/recipes-devtools/qemu/qemu.inc           |  1 +
 ...e-jobserver-auth-argument-when-calli.patch | 37 +++++++++++++++++++
 2 files changed, 38 insertions(+)
 create mode 100644 meta/recipes-devtools/qemu/qemu/0013-Makefile-preserve-jobserver-auth-argument-when-calli.patch
meta/recipes-devtools/qemu/qemu.inc +1 -0
index 4501f84c2b..1f86bf5a44 100644
@@ -39,6 +39,7 @@ SRC_URI = "https://download.qemu.org/${BPN}-${PV}.tar.xz \
            file://0003-linux-user-Add-strace-for-shmat.patch \
            file://0004-linux-user-Rewrite-target_shmat.patch \
            file://0005-tests-tcg-Check-that-shmat-does-not-break-proc-self-.patch \
+           file://0013-Makefile-preserve-jobserver-auth-argument-when-calli.patch \
            file://CVE-2023-6683.patch \
            file://qemu-guest-agent.init \
            file://qemu-guest-agent.udev \
meta/recipes-devtools/qemu/qemu/0013-Makefile-preserve-jobserver-auth-argument-when-calli.patch new file +37 -0
new file mode 100644
index 0000000000..33db8b7ddc
@@ -0,0 +1,37 @@
+From 730530c5f01e00cdc3754ebb8f3d7ff995f3376e Mon Sep 17 00:00:00 2001
+From: =?UTF-8?q?Martin=20Hundeb=C3=B8ll?= <[email protected]>
+Date: Thu, 21 Sep 2023 10:57:45 +0200
+Subject: [PATCH] Makefile: preserve --jobserver-auth argument when calling
+ ninja
+MIME-Version: 1.0
+Content-Type: text/plain; charset=UTF-8
+Content-Transfer-Encoding: 8bit
+
+Qemu wraps its call to ninja in a Makefile. Since ninja, as opposed to
+make, utilizes all CPU cores by default, the qemu Makefile translates
+the absense of a `-jN` argument into `-j1`. This breaks jobserver
+functionality, so update the -jN mangling to take the --jobserver-auth
+argument into considerationa too.
+
+Signed-off-by: Martin Hundebøll <[email protected]>
+Upstream-Status: Submitted [https://gitlab.com/qemu-project/qemu/-/issues/1898]
+---
+ Makefile | 2 +-
+ 1 file changed, 1 insertion(+), 1 deletion(-)
+
+diff --git a/Makefile b/Makefile
+index 8f36990335..183756018f 100644
+--- a/Makefile
++++ b/Makefile
+@@ -142,7 +142,7 @@ MAKE.k = $(findstring k,$(firstword $(filter-out --%,$(MAKEFLAGS))))
+ MAKE.q = $(findstring q,$(firstword $(filter-out --%,$(MAKEFLAGS))))
+ MAKE.nq = $(if $(word 2, $(MAKE.n) $(MAKE.q)),nq)
+ NINJAFLAGS = $(if $V,-v) $(if $(MAKE.n), -n) $(if $(MAKE.k), -k0) \
+-        $(filter-out -j, $(lastword -j1 $(filter -l% -j%, $(MAKEFLAGS)))) \
++        $(or $(filter -l% -j%, $(MAKEFLAGS)), $(if $(filter --jobserver-auth=%, $(MAKEFLAGS)),, -j1)) \
+         -d keepdepfile
+ ninja-cmd-goals = $(or $(MAKECMDGOALS), all)
+ ninja-cmd-goals += $(foreach g, $(MAKECMDGOALS), $(.ninja-goals.$g))
+-- 
+2.44.0
+
Signature · 1 line
2.44.0
#12 lore raw

PATCH 5/5 contrib: add python service and systemd unit to run shared jobserver

In reply to Martin Hundebøll

For CI setups that might end up building multiple yocto builds in parallel, a shared jobserver can reduce the total load of the system. Setting up such a jobserver is simple, but it does require a process hanging around to keep the jobserver fifo open (to avoid blocking token requests).

Add a simple python script that creates such a jobserver fifo and waits forever. Also add a systemd unit file to start the python service at boot.

The systemd unit can be installed in $HOME/.config/systemd/user/, but one might need to add a droplet config (i.e. systemctl --user edit jobserver.service) to setup the PYTHONPATH variable to make the python script loadable.

---
 contrib/jobserver/jobserver.py      | 78 +++++++++++++++++++++++++++++
 contrib/jobserver/jobserver.service | 10 ++++
 2 files changed, 88 insertions(+)
 create mode 100644 contrib/jobserver/jobserver.py
 create mode 100644 contrib/jobserver/jobserver.service
contrib/jobserver/jobserver.py new file +78 -0
new file mode 100644
index 0000000000..41b085f47f
@@ -0,0 +1,78 @@
+#!/usr/bin/env python3
+
+from pathlib import Path
+from threading import Event
+import argparse
+import os
+import shutil
+import signal
+
+resumed = Event()
+runtime_dir = os.environ.get("XDG_RUNTIME_DIR", "/run")
+
+def signal_handler(signum, _frame):
+    """Wait for an external signal exit the process gracefully."""
+    resumed.set()
+
+
+def main(path, user, group, mode, jobs):
+    """Setup a fifo to used as jobserver shared between builds."""
+    try:
+        path.unlink(missing_ok=True)
+        os.mkfifo(path)
+        shutil.chown(path, user, group)
+        os.chmod(path, mode)
+    except (FileNotFoundError, PermissionError) as exc:
+        raise SystemExit(f"failed to create fifo: {path}: {exc.strerror}")
+
+    print(f"jobserver: {path}: {jobs} jobs")
+    fifo = os.open(path, os.O_RDWR)
+    os.write(fifo, b"+" * jobs)
+
+    print("jobserver: ready; waiting indefinitely")
+    signal.signal(signal.SIGTERM, signal_handler)
+    signal.signal(signal.SIGINT, signal_handler)
+    resumed.wait()
+
+    print("jobserver: exiting")
+    path.unlink()
+    os.close(fifo)
+
+
+if __name__ == "__main__":
+    parser = argparse.ArgumentParser(
+        prog='Make jobserver',
+        description='Simple application to instantiate a jobserver fifo and hang around',
+    )
+    parser.add_argument(
+        "--mode",
+        help="Permission to apply to jobserver fifo",
+        type=lambda v: int(v, 8),
+        default=0o0666,
+    )
+    parser.add_argument(
+        "--user",
+        help="Username or id to assign ownership of fifo to",
+        default=os.getuid(),
+    )
+    parser.add_argument(
+        "--group",
+        help="Groupname of id to assign ownership of fifo to",
+        default=os.getgid(),
+    )
+    parser.add_argument(
+        "path",
+        help="Path to jobserver fifo path",
+        type=Path,
+        nargs='?',
+        default=f"{runtime_dir}/jobserver",
+    )
+    parser.add_argument(
+        "jobs",
+        help="Number of tokens to load jobserver with",
+        type=int,
+        nargs='?',
+        default=os.cpu_count(),
+    )
+    args = parser.parse_args()
+    main(args.path, args.user, args.group, args.mode, args.jobs)
contrib/jobserver/jobserver.service new file +10 -0
new file mode 100644
index 0000000000..bbc7167ac0
@@ -0,0 +1,10 @@
+[Unit]
+Description=Shared jobserver fifo
+
+[Service]
+Type=simple
+Environment=PYTHONUNBUFFERED=1
+ExecStart=python jobserver.py
+
+[Install]
+WantedBy=multi-user.target
Signature · 1 line
2.44.0