diff --git a/doc/bitbake-user-manual/bitbake-user-manual-metadata.rst b/doc/bitbake-user-manual/bitbake-user-manual-metadata.rst
index 27711b2c849..3fe4489aebb 100644
--- a/doc/bitbake-user-manual/bitbake-user-manual-metadata.rst
+++ b/doc/bitbake-user-manual/bitbake-user-manual-metadata.rst
@@ -1021,7 +1021,7 @@ variable like this::
    OE_FRAGMENTS = "core/domain/somefragment core/someotherfragment anotherlayer/anotherdomain/anotherfragment"
 
 Fragment names listed in this variable must be prefixed by the layer name
-where a fragment file is located, defined by :term:`BBFILE_COLLECTIONS` in ``layer.conf``.
+where a fragment file is located, defined by :term:`LAYERNAME` in ``layer.conf``.
 
 The implementation then expands this list into
 :ref:`require <bitbake-user-manual/bitbake-user-manual-metadata:\`\`require\`\` directive>`
diff --git a/doc/bitbake-user-manual/bitbake-user-manual-ref-variables.rst b/doc/bitbake-user-manual/bitbake-user-manual-ref-variables.rst
index e258e7afd64..7d3b97bc6ba 100644
--- a/doc/bitbake-user-manual/bitbake-user-manual-ref-variables.rst
+++ b/doc/bitbake-user-manual/bitbake-user-manual-ref-variables.rst
@@ -922,48 +922,6 @@ overview of their function and contents.
          You must set this variable in the external environment in order
          for it to work.
 
-   :term:`BBFILE_COLLECTIONS`
-      Lists the names of configured layers. These names are used to find
-      the other ``BBFILE_*`` variables. Typically, each layer appends its
-      name to this variable in its ``conf/layer.conf`` file.
-
-   :term:`BBFILE_PATTERN`
-      Variable that expands to match files from
-      :term:`BBFILES` in a particular layer. This
-      variable is used in the ``conf/layer.conf`` file and must be suffixed
-      with the name of the specific layer (e.g.
-      ``BBFILE_PATTERN_emenlow``).
-
-   :term:`BBFILE_PRIORITY`
-      Assigns the priority for recipe files in each layer.
-
-      This variable is used in the ``conf/layer.conf`` file and must be
-      suffixed with a `_` followed by the name of the specific layer (e.g.
-      ``BBFILE_PRIORITY_emenlow``). Colon as separator is not supported.
-
-      This variable is useful in situations where the same recipe appears
-      in more than one layer. Setting this variable allows you to
-      prioritize a layer against other layers that contain the same recipe
-      --- effectively letting you control the precedence for the multiple
-      layers. The precedence established through this variable stands
-      regardless of a recipe's version (:term:`PV` variable).
-      For example, a layer that has a recipe with a higher :term:`PV` value but
-      for which the :term:`BBFILE_PRIORITY` is set to have a lower precedence
-      still has a lower precedence.
-
-      A larger value for the :term:`BBFILE_PRIORITY` variable results in a
-      higher precedence. For example, the value 6 has a higher precedence
-      than the value 5. If not specified, the :term:`BBFILE_PRIORITY` variable
-      is set based on layer dependencies (see the :term:`LAYERDEPENDS` variable
-      for more information). The default priority, if unspecified for a
-      layer with no dependencies, is the lowest defined priority + 1 (or 1
-      if no priorities are defined).
-
-      .. tip::
-
-         You can use the command bitbake-layers show-layers to list all
-         configured layers along with their priorities.
-
    :term:`BBFILES`
       A space-separated list of recipe files BitBake uses to build
       software.
@@ -1198,6 +1156,9 @@ overview of their function and contents.
       Allows you to use a configuration file to add to the list of
       command-line target recipes you want to build.
 
+   :term:`BITBAKEDIR`
+      BitBake sets this to location where bitbake is being run from.
+
    :term:`BITBAKE_UI`
       Used to specify the UI module to use when running BitBake. Using this
       variable is equivalent to using the ``-u`` command-line option.
@@ -1375,12 +1336,13 @@ overview of their function and contents.
       available outside of ``layer.conf`` and references are expanded
       immediately when parsing of the file completes.
 
-   :term:`LAYERDIR_RE`
+   :term:`LAYERDIR_<layername>`
+
+      LAYERDIR_<layername> is defined as the path each named layer is located.
+
+   :term:`LAYERNAME`
       When used inside the ``layer.conf`` configuration file, this variable
-      provides the path of the current layer, escaped for use in a regular
-      expression (:term:`BBFILE_PATTERN`). This
-      variable is not available outside of ``layer.conf`` and references
-      are expanded immediately when parsing of the file completes.
+      provides the name assigned to the current layer.
 
    :term:`LAYERSERIES_COMPAT`
       Lists the versions of the OpenEmbedded-Core (OE-Core) for which
diff --git a/lib/bb/command.py b/lib/bb/command.py
index 9848b7a6732..b33e81d3e9a 100644
--- a/lib/bb/command.py
+++ b/lib/bb/command.py
@@ -300,15 +300,6 @@ class CommandsSync:
         command.cooker.parseConfiguration()
     parseConfiguration.needconfig = False
 
-    def getLayerPriorities(self, command, params):
-        command.cooker.parseConfiguration()
-        ret = []
-        # regex objects cannot be marshalled by xmlrpc
-        for collection, pattern, regex, pri in command.cooker.bbfile_config_priorities:
-            ret.append((collection, pattern, regex.pattern, pri))
-        return ret
-    getLayerPriorities.readonly = True
-
     def revalidateCaches(self, command, params):
         """Called by UI clients when metadata may have changed"""
         command.cooker.revalidateCaches()
diff --git a/lib/bb/cooker.py b/lib/bb/cooker.py
index 7fca4ac2f74..31a78743406 100644
--- a/lib/bb/cooker.py
+++ b/lib/bb/cooker.py
@@ -454,10 +454,9 @@ You can also remove the BB_HASHSERVE_UPSTREAM setting, but this may result in si
         for mc in self.multiconfigs:
             self.recipecaches[mc] = bb.cache.CacheData(self.caches_array)
 
-        self.handleCollections(self.data.getVar("BBFILE_COLLECTIONS"))
         self.collections = {}
         for mc in self.multiconfigs:
-            self.collections[mc] = CookerCollectFiles(self.bbfile_config_priorities, mc)
+            self.collections[mc] = CookerCollectFiles(self.databuilder.layerdata, mc)
             self.collections[mc].collect_bbfiles(self.databuilder.mcdata[mc], self.databuilder.mcdata[mc])
 
         self._parsecache_set(False)
@@ -791,7 +790,7 @@ You can also remove the BB_HASHSERVE_UPSTREAM setting, but this may result in si
         depend_tree["rdepends-pkg"] = {}
         depend_tree["rrecs-pkg"] = {}
         depend_tree['providermap'] = {}
-        depend_tree["layer-priorities"] = self.bbfile_config_priorities
+        depend_tree["layer-priorities"] = None
 
         for mc in taskdata:
             for name, fn in list(taskdata[mc].get_providermap().items()):
@@ -1181,129 +1180,6 @@ You can also remove the BB_HASHSERVE_UPSTREAM setting, but this may result in si
         else:
             shell.start( self )
 
-
-    def handleCollections(self, collections):
-        """Handle collections"""
-        errors = False
-        self.bbfile_config_priorities = []
-        if collections:
-            collection_priorities = {}
-            collection_depends = {}
-            collection_list = collections.split()
-            min_prio = 0
-            for c in collection_list:
-                bb.debug(1,'Processing %s in collection list' % (c))
-
-                # Get collection priority if defined explicitly
-                priority = self.data.getVar("BBFILE_PRIORITY_%s" % c)
-                if priority:
-                    try:
-                        prio = int(priority)
-                    except ValueError:
-                        parselog.error("invalid value for BBFILE_PRIORITY_%s: \"%s\"", c, priority)
-                        errors = True
-                    if min_prio == 0 or prio < min_prio:
-                        min_prio = prio
-                    collection_priorities[c] = prio
-                else:
-                    collection_priorities[c] = None
-
-                # Check dependencies and store information for priority calculation
-                deps = self.data.getVar("LAYERDEPENDS_%s" % c)
-                if deps:
-                    try:
-                        depDict = bb.utils.explode_dep_versions2(deps)
-                    except bb.utils.VersionStringException as vse:
-                        bb.fatal('Error parsing LAYERDEPENDS_%s: %s' % (c, str(vse)))
-                    for dep, oplist in list(depDict.items()):
-                        if dep in collection_list:
-                            for opstr in oplist:
-                                layerver = self.data.getVar("LAYERVERSION_%s" % dep)
-                                (op, depver) = opstr.split()
-                                if layerver:
-                                    try:
-                                        res = bb.utils.vercmp_string_op(layerver, depver, op)
-                                    except bb.utils.VersionStringException as vse:
-                                        bb.fatal('Error parsing LAYERDEPENDS_%s: %s' % (c, str(vse)))
-                                    if not res:
-                                        parselog.error("Layer '%s' depends on version %s of layer '%s', but version %s is currently enabled in your configuration. Check that you are using the correct matching versions/branches of these two layers.", c, opstr, dep, layerver)
-                                        errors = True
-                                else:
-                                    parselog.error("Layer '%s' depends on version %s of layer '%s', which exists in your configuration but does not specify a version. Check that you are using the correct matching versions/branches of these two layers.", c, opstr, dep)
-                                    errors = True
-                        else:
-                            parselog.error("Layer '%s' depends on layer '%s', but this layer is not enabled in your configuration", c, dep)
-                            errors = True
-                    collection_depends[c] = list(depDict.keys())
-                else:
-                    collection_depends[c] = []
-
-                # Check recommends and store information for priority calculation
-                recs = self.data.getVar("LAYERRECOMMENDS_%s" % c)
-                if recs:
-                    try:
-                        recDict = bb.utils.explode_dep_versions2(recs)
-                    except bb.utils.VersionStringException as vse:
-                        bb.fatal('Error parsing LAYERRECOMMENDS_%s: %s' % (c, str(vse)))
-                    for rec, oplist in list(recDict.items()):
-                        if rec in collection_list:
-                            if oplist:
-                                opstr = oplist[0]
-                                layerver = self.data.getVar("LAYERVERSION_%s" % rec)
-                                if layerver:
-                                    (op, recver) = opstr.split()
-                                    try:
-                                        res = bb.utils.vercmp_string_op(layerver, recver, op)
-                                    except bb.utils.VersionStringException as vse:
-                                        bb.fatal('Error parsing LAYERRECOMMENDS_%s: %s' % (c, str(vse)))
-                                    if not res:
-                                        parselog.debug3("Layer '%s' recommends version %s of layer '%s', but version %s is currently enabled in your configuration. Check that you are using the correct matching versions/branches of these two layers.", c, opstr, rec, layerver)
-                                        continue
-                                else:
-                                    parselog.debug3("Layer '%s' recommends version %s of layer '%s', which exists in your configuration but does not specify a version. Check that you are using the correct matching versions/branches of these two layers.", c, opstr, rec)
-                                    continue
-                            parselog.debug3("Layer '%s' recommends layer '%s', so we are adding it", c, rec)
-                            collection_depends[c].append(rec)
-                        else:
-                            parselog.debug3("Layer '%s' recommends layer '%s', but this layer is not enabled in your configuration", c, rec)
-
-            # Recursively work out collection priorities based on dependencies
-            def calc_layer_priority(collection):
-                if not collection_priorities[collection]:
-                    max_depprio = min_prio
-                    for dep in collection_depends[collection]:
-                        calc_layer_priority(dep)
-                        depprio = collection_priorities[dep]
-                        if depprio > max_depprio:
-                            max_depprio = depprio
-                    max_depprio += 1
-                    parselog.debug("Calculated priority of layer %s as %d", collection, max_depprio)
-                    collection_priorities[collection] = max_depprio
-
-            # Calculate all layer priorities using calc_layer_priority and store in bbfile_config_priorities
-            for c in collection_list:
-                calc_layer_priority(c)
-                regex = self.data.getVar("BBFILE_PATTERN_%s" % c)
-                if regex is None:
-                    parselog.error("BBFILE_PATTERN_%s not defined" % c)
-                    errors = True
-                    continue
-                elif regex == "":
-                    parselog.debug("BBFILE_PATTERN_%s is empty" % c)
-                    cre = re.compile('^NULL$')
-                    errors = False
-                else:
-                    try:
-                        cre = re.compile(regex)
-                    except re.error:
-                        parselog.error("BBFILE_PATTERN_%s \"%s\" is not a valid regular expression", c, regex)
-                        errors = True
-                        continue
-                self.bbfile_config_priorities.append((c, regex, cre, collection_priorities[c]))
-        if errors:
-            # We've already printed the actual error(s)
-            raise CollectionError("Errors during parsing layer configuration")
-
     def buildSetVars(self):
         """
         Setup any variables needed before starting a build
@@ -1621,7 +1497,7 @@ You can also remove the BB_HASHSERVE_UPSTREAM setting, but this may result in si
                 if flags and "func" in flags and "python" in flags:
                     expand = False
                 v = self.data.getVar(k, expand)
-                if not k.startswith("__") and not isinstance(v, bb.data_smart.DataSmart):
+                if not k.startswith("__") and not isinstance(v, bb.data_smart.DataSmart) and not isinstance(v, dict):
                     dump[k] = {
     'v' : str(v) ,
     'history' : self.data.varhistory.variable(k),
@@ -1819,25 +1695,16 @@ class CookerExit(bb.event.Event):
 
 
 class CookerCollectFiles(object):
-    def __init__(self, priorities, mc=''):
+    def __init__(self, layerdata, mc=''):
         self.mc = mc
         self.bbappends = []
         self.overlayed = None
-        # Priorities is a list of tuples, with the second element as the pattern.
-        # We need to sort the list with the longest pattern first, and so on to
-        # the shortest.  This allows nested layers to be properly evaluated.
-        self.bbfile_config_priorities = sorted(priorities, key=lambda tup: tup[1], reverse=True)
-
-    def calc_bbfile_priority(self, filename):
-        for layername, _, regex, pri in self.bbfile_config_priorities:
-            if regex.match(filename):
-                return pri, regex, layername
-        return 0, None, None
+        self.layerdata = layerdata
 
     def get_layername(self, filename):
-        for layername, _, regex, _ in self.bbfile_config_priorities:
-            if regex.match(filename):
-                return layername
+        for layer in self.layerdata:
+            if filename.startswith(self.layerdata[layer].path + "/"):
+                return layer
         return None
 
     def get_bbfiles(self):
@@ -1857,7 +1724,8 @@ class CookerCollectFiles(object):
             for ignored in ('SCCS', 'CVS', '.svn'):
                 if ignored in dirs:
                     dirs.remove(ignored)
-            found += [os.path.join(dir, f) for f in files if (f.endswith(('.bb', '.bbappend')))]
+            dirs.sort()
+            found += [os.path.join(dir, f) for f in sorted(files) if (f.endswith(('.bb', '.bbappend')))]
 
         return found
 
@@ -1992,68 +1860,6 @@ class CookerCollectFiles(object):
                 filelist.append(filename)
         return tuple(filelist)
 
-    def collection_priorities(self, pkgfns, fns, d):
-        # Return the priorities of the entries in pkgfns
-        # Also check that all the regexes in self.bbfile_config_priorities are used
-        # (but to do that we need to ensure skipped recipes aren't counted, nor
-        # collections in BBFILE_PATTERN_IGNORE_EMPTY)
-
-        priorities = {}
-        seen = set()
-        matched = set()
-
-        matched_regex = set()
-        unmatched_regex = set()
-        for _, _, regex, _ in self.bbfile_config_priorities:
-            unmatched_regex.add(regex)
-
-        # Calculate priorities for each file
-        for p in pkgfns:
-            realfn, cls, mc = bb.cache.virtualfn2realfn(p)
-            priorities[p], regex, _ = self.calc_bbfile_priority(realfn)
-            if regex in unmatched_regex:
-                matched_regex.add(regex)
-                unmatched_regex.remove(regex)
-            seen.add(realfn)
-            if regex:
-                matched.add(realfn)
-
-        if unmatched_regex:
-            # Account for bbappend files
-            for b in self.bbappends:
-                (bbfile, append) = b
-                seen.add(append)
-
-            # Account for skipped recipes
-            seen.update(fns)
-
-            seen.difference_update(matched)
-
-            def already_matched(fn):
-                for regex in matched_regex:
-                    if regex.match(fn):
-                        return True
-                return False
-
-            for unmatch in unmatched_regex.copy():
-                for fn in seen:
-                    if unmatch.match(fn):
-                        # If the bbappend or file was already matched by another regex, skip it
-                        # e.g. for a layer within a layer, the outer regex could match, the inner
-                        # regex may match nothing and we should warn about that
-                        if already_matched(fn):
-                            continue
-                        unmatched_regex.remove(unmatch)
-                        break
-
-        for collection, pattern, regex, _ in self.bbfile_config_priorities:
-            if regex in unmatched_regex:
-                if d.getVar('BBFILE_PATTERN_IGNORE_EMPTY_%s' % collection) != '1':
-                    collectlog.warning("No bb files in %s matched BBFILE_PATTERN_%s '%s'" % (self.mc if self.mc else 'default',
-                                                                                             collection, pattern))
-
-        return priorities
-
 class ParsingFailure(Exception):
     def __init__(self, realexception, recipe):
         self.realexception = realexception
diff --git a/lib/bb/cookerdata.py b/lib/bb/cookerdata.py
index 87310af7ce6..3bea91e2387 100644
--- a/lib/bb/cookerdata.py
+++ b/lib/bb/cookerdata.py
@@ -10,11 +10,13 @@
 # SPDX-License-Identifier: GPL-2.0-only
 #
 
+import dataclasses
 import logging
 import os
 import re
 import sys
 import hashlib
+import graphlib
 from functools import wraps
 
 import bb.cache
@@ -226,6 +228,22 @@ def findTopdir():
 
     return os.path.abspath(os.getcwd())
 
+@dataclasses.dataclass(repr=False)
+class Layer:
+    path: str
+    version: str
+    compat: set[str] = dataclasses.field(default_factory=set)
+    depends: dict[dict] = dataclasses.field(default_factory=dict)
+    recommends: dict[dict] = dataclasses.field(default_factory=dict)
+    fragment_recommends_any: set[str] = dataclasses.field(default_factory=set)
+
+    # We need the cache to have a consistent value which sets won't allow so we need
+    # a custom sortable repr.
+    def __repr__(self):
+        return "Layer(path=%r, version=%r, compat=%r, depends=%r, recommends=%r, fragment_recommends_any=%r)" % (
+            self.path, self.version, sorted(self.compat), self.depends,
+            self.recommends, sorted(self.fragment_recommends_any))
+
 class CookerDataBuilder(object):
 
     def __init__(self, cookercfg, worker = False):
@@ -280,7 +298,7 @@ class CookerDataBuilder(object):
     def parseBaseConfiguration(self, worker=False):
         mcdata = {}
         try:
-            self.data = self.parseConfigurationFiles(self.prefiles, self.postfiles)
+            self.data, self.layerdata = self.parseConfigurationFiles(self.prefiles, self.postfiles)
 
             servercontext = self.data.getVar("BB_WORKERCONTEXT", False) is None and not worker
             bb.fetch.fetcher_init(self.data, servercontext)
@@ -296,7 +314,7 @@ class CookerDataBuilder(object):
                     raise Exception("Too deep config re-parse loop. Check locations where "
                                     "BB_INVALIDCONF is being set (ConfigParsed event handlers)")
                 self.data.setVar("BB_INVALIDCONF", False)
-                self.data = self.parseConfigurationFiles(self.prefiles, self.postfiles)
+                self.data, self.layerdata = self.parseConfigurationFiles(self.prefiles, self.postfiles)
                 reparse_cnt += 1
                 bb.event.fire(bb.event.ConfigParsed(), self.data)
 
@@ -307,7 +325,7 @@ class CookerDataBuilder(object):
             for config in multiconfig:
                 if config[0].isdigit():
                     bb.fatal("Multiconfig name '%s' is invalid as multiconfigs cannot start with a digit" % config)
-                parsed_mcdata = self.parseConfigurationFiles(self.prefiles, self.postfiles, config)
+                parsed_mcdata, _ = self.parseConfigurationFiles(self.prefiles, self.postfiles, config)
                 bb.event.fire(bb.event.ConfigParsed(), parsed_mcdata)
                 mcdata[config] = parsed_mcdata
             if multiconfig:
@@ -369,6 +387,7 @@ class CookerDataBuilder(object):
             data = parse_config_file(f, data)
 
         layerconf = self._findLayerConf(data)
+        layerdata = {}
         if layerconf:
             parselog.debug2("Found bblayers.conf (%s)", layerconf)
             # By definition bblayers.conf is in conf/ of TOPDIR.
@@ -402,77 +421,215 @@ class CookerDataBuilder(object):
                 parselog.critical("Please check BBLAYERS in %s" % (layerconf))
                 raise bb.BBHandledException()
 
+            bitbakedir = os.path.realpath(os.path.dirname(__file__) + "/../../")
+            data.setVar("BITBAKEDIR", bitbakedir)
+            data.setVarFlag("BITBAKEDIR", "vardepvalue", "")
+
             layerseries = None
-            compat_entries = {}
+            layer_safevars = tuple()
+            layer_filterfunc = None
+            errors = []
+            datastores = {}
             for layer in layers:
-                parselog.debug2("Adding layer %s", layer)
+                parselog.debug2("Adding layer %s" % layer)
                 if 'HOME' in approved and '~' in layer:
                     layer = os.path.expanduser(layer)
                 if layer.endswith('/'):
                     layer = layer.rstrip('/')
-                data.setVar('LAYERDIR', layer)
-                data.setVar('LAYERDIR_RE', re.escape(layer))
-                data = parse_config_file(os.path.join(layer, "conf", "layer.conf"), data)
-                data.expandVarref('LAYERDIR')
-                data.expandVarref('LAYERDIR_RE')
-
-                # Sadly we can't have nice things.
-                # Some layers think they're going to be 'clever' and copy the values from
-                # another layer, e.g. using ${LAYERSERIES_COMPAT_core}. The whole point of
-                # this mechanism is to make it clear which releases a layer supports and
-                # show when a layer master branch is bitrotting and is unmaintained.
-                # We therefore avoid people doing this here.
-                collections = (data.getVar('BBFILE_COLLECTIONS') or "").split()
-                for c in collections:
-                    compat_entry = data.getVar("LAYERSERIES_COMPAT_%s" % c)
-                    if compat_entry:
-                        compat_entries[c] = set(compat_entry.split())
-                        data.delVar("LAYERSERIES_COMPAT_%s" % c)
-                if not layerseries:
-                    layerseries = set((data.getVar("LAYERSERIES_CORENAMES") or "").split())
-                    if layerseries:
-                        data.delVar("LAYERSERIES_CORENAMES")
-
-            data.delVar('LAYERDIR_RE')
-            data.delVar('LAYERDIR')
-            for c in compat_entries:
-                data.setVar("LAYERSERIES_COMPAT_%s" % c, " ".join(sorted(compat_entries[c])))
-
-            bbfiles_dynamic = (data.getVar('BBFILES_DYNAMIC') or "").split()
-            collections = (data.getVar('BBFILE_COLLECTIONS') or "").split()
-            invalid = []
-            for entry in bbfiles_dynamic:
-                parts = entry.split(":", 1)
-                if len(parts) != 2:
-                    invalid.append(entry)
+                layer = os.path.realpath(layer)
+
+                ld = data.createCopy()
+                ld.setVar('LAYERDIR', layer)
+                #ld.setVar('LAYERDIR_RE', re.escape(layer))
+                layerfile = os.path.join(layer, "conf", "layer.conf")
+                ld = parse_config_file(layerfile, ld)
+                bb.parse.mark_dependency(data, layerfile)
+
+                layername = ld.getVar("LAYERNAME")
+                if not layername:
+                    errors.append("Layer %s does not set LAYERNAME" % layer)
+                    continue
+                if layername in layerdata:
+                    errors.append("LAYERNAME %s is used by both %s and %s" % (layername, layer, layerdata[layername].path))
                     continue
-                l, f = parts
-                invert = l[0] == "!"
-                if invert:
-                    l = l[1:]
-                if (l in collections and not invert) or (l not in collections and invert):
-                    data.appendVar("BBFILES", " " + f)
-            if invalid:
-                bb.fatal("BBFILES_DYNAMIC entries must be of the form {!}<collection name>:<filename pattern>, not:\n    %s" % "\n    ".join(invalid))
-
-            collections_tmp = collections[:]
-            for c in collections:
-                collections_tmp.remove(c)
-                if c in collections_tmp:
-                    bb.fatal("Found duplicated BBFILE_COLLECTIONS '%s', check bblayers.conf or layer.conf to fix it." % c)
-
-                compat = set()
-                if c in compat_entries:
-                    compat = compat_entries[c]
-                if compat and not layerseries:
-                    bb.fatal("No core layer found to work with layer '%s'. Missing entry in bblayers.conf?" % c)
-                if compat and not (compat & layerseries):
-                    bb.fatal("Layer %s is not compatible with the core layer which only supports these series: %s (layer is compatible with %s)"
-                              % (c, " ".join(layerseries), " ".join(compat)))
-                elif not compat and not data.getVar("BB_WORKERCONTEXT"):
-                    bb.warn("Layer %s should set LAYERSERIES_COMPAT_%s in its conf/layer.conf file to list the core layer names it is compatible with." % (c, c))
 
+                nested = False
+                for pathcheck in layerdata:
+                    otherpath = layerdata[pathcheck].path
+                    if layer.startswith(otherpath + "/") or otherpath.startswith(layer + "/"):
+                        errors.append("Layer path %s (layer %s) conflicts with path %s from layer %s. Layers can't nest." % (layer, layername, otherpath, pathcheck))
+                        nested = True
+                if nested:
+                    continue
+
+                def getVar(var, layername, ld):
+                    value = ld.getVar(var)
+                    if not value:
+                        value = ld.getVar("%s_%s" % (var, layername))
+                    return value
+
+                layerdata[layername] = Layer(
+                    path=layer,
+                    version=getVar("LAYERVERSION", layername, ld) or "1",
+                    compat=set((getVar("LAYERSERIES_COMPAT", layername, ld) or "").split()),
+                    depends=bb.utils.explode_dep_versions2(getVar("LAYERDEPENDS", layername, ld) or ""),
+                    recommends=bb.utils.explode_dep_versions2(getVar("LAYERRECOMMENDS", layername, ld) or ""),
+                    fragment_recommends_any=set((getVar("LAYER_FRAGMENT_RECOMMENDS_ANY", layername, ld) or "").split()),
+                )
+
+                if not layerdata[layername].compat:
+                    errors.append("Layer %s should set LAYERSERIES_COMPAT in its conf/layer.conf file to list the core layer names it is compatible with." % (layername))
+
+                if not layerseries:
+                    layerseries = set((ld.getVar("LAYERSERIES_CORENAMES") or "").split())
+                if not layer_safevars:
+                    layer_safevars = tuple((ld.getVar("LAYER_PASSTHROUGH_VARS_PREFIXES") or "").split())
+                if not layer_filterfunc:
+                    layer_filterfunc = ld.getVar("BB_LAYER_FILTER_FUNC")
+                datastores[layer] = ld
+
+            for layername in layerdata:
+                data.setVar("LAYERDIR_%s" % layername, layerdata[layername].path)
+                data.setVarFlag("LAYERDIR_%s" % layername, "vardepvalue", "")
+
+            def copy_layer_history(var, data, ld):
+                base = len(initial.varhistory.variable(var))
+                for entry in ld.varhistory.variable(var)[base:]:
+                     if "flag" not in entry:
+                        data.varhistory.record(**entry)
+
+            initial = data
+            data = data.createCopy()
+            for layer in sorted(datastores):
+                ld = datastores[layer]
+                for var in ld:
+                    if var.startswith(("LAYERNAME", "LAYERDEPENDS", "LAYERRECOMMENDS", "LAYERVERSION", "LAYERSERIES_COMPAT", "LAYERSERIES_CORENAMES", "LAYERDIR",  "LAYER_FRAGMENT_RECOMMENDS_ANY", "LAYER_PASSTHROUGH_VARS_PREFIXES")):
+                        continue
+                    if var.startswith(("BBFILE_COLLECTIONS", "BBFILE_PRIORITY", "BBFILE_PATTERN")):
+                        bb.warn("Support for %s was removed and the variable is being ignored but is set by layer %s" % (var, layer))
+                        continue
+                    if var in ["__depends"]:
+                        continue
+                    if var in ["BBPATH", "BBFILES", "BBFILES_DYNAMIC"]:
+                        if ld.getVar(var) != data.getVar(var):
+                            bb.warn("%s now set automatically, the variable is being ignored but is set by layer %s" % (var, layer))
+                            bb.warn(str(ld.getVar(var, expand=False)))
+                        continue
+                    append = None
+                    if var in initial:
+                        orig = initial.getVar(var, False)
+                        new = ld.getVar(var, False)
+                        if orig == new:
+                            continue
+                        if not new.startswith(orig):
+                            errors.append("Layer %s is overwriting variable %s, it should only append to it" % (layer, var))
+                            continue
+                        append = new.removeprefix(orig)
+                    if var.startswith(layer_safevars):
+                        pass
+                    elif var.startswith(("BBLAYERS_LAYERINDEX_NAME", "BB_GLOBAL_PYMODULES")):
+                        pass
+                    else:
+                        bb.warn("Variable %s is set by %s but it will be ignored" % (var, layer))
+                        continue
+
+                    copy_layer_history(var, data, ld)
+                    if append:
+                        data.appendVar(var, append)
+                    elif var in data:
+                        # Assume that if multiple layers set it, it should be space separated.
+                        data.appendVar(var, " " + ld.getVar(var, False))
+                    else:
+                        data.setVar(var, ld.getVar(var, False))
+            if not layerseries:
+                errors.append("No layer sets LAYERSERIES_CORENAMES")
             data.setVar("LAYERSERIES_CORENAMES", " ".join(sorted(layerseries)))
+            data.setVar("LAYER_PASSTHROUGH_VARS_PREFIXES", " ".join(layer_safevars))
+
+            layers = set(layerdata)
+            for layer in layerdata:
+                if not (layerdata[layer].compat & layerseries):
+                    errors.append("Layer %s is not compatible with the core layer which only supports these series: %s (layer is compatible with %s)"
+                              % (layer, " ".join(layerseries), " ".join(layerdata[layer].compat)))
+
+                # Check dependencies
+                if not set(layerdata[layer].depends).issubset(layers):
+                    errors.append("Layer %s depends on %s but that layer isn't configured" % (layer, " ".join(set(layerdata[layer].depends) - layers)))
+                    continue
+
+                # Check dependency versions
+                for dep in layerdata[layer].depends:
+                    for verop in layerdata[layer].depends[dep]:
+                        (op, depver) = verop.split()
+                        layerver = layerdata[dep].version
+                        if not layerver:
+                            errors.append("Layer '%s' depends on version %s of layer '%s', which exists in your configuration but does not specify a version. Check that you are using the correct matching versions/branches of these two layers." % (layer, verop, dep))
+                            continue
+                        try:
+                            res = bb.utils.vercmp_string_op(layerver, depver, op)
+                        except bb.utils.VersionStringException as vse:
+                            bb.fatal('Error parsing LAYERDEPENDS for layer %s: %s' % (layer, str(vse)))
+                        if not res:
+                            errors.append("Layer '%s' depends on version %s of layer '%s', but version %s is currently enabled in your configuration. Check that you are using the correct matching versions/branches of these two layers." % (layer, verop, dep, layerver))
+
+                # Check recommends versions
+                for dep in layerdata[layer].recommends:
+                    for verop in layerdata[layer].recommends[dep]:
+                        if dep not in layerdata:
+                            continue
+                        (op, depver) = verop.split()
+                        layerver = layerdata[dep].version
+                        if not layerver:
+                            errors.append("Layer '%s' recommends version %s of layer '%s', which exists in your configuration but does not specify a version. Check that you are using the correct matching versions/branches of these two layers." % (layer, verop, dep))
+                            continue
+                        try:
+                            res = bb.utils.vercmp_string_op(layerver, depver, op)
+                        except bb.utils.VersionStringException as vse:
+                            bb.fatal('Error parsing LAYERRECOMMENDS for layer %s: %s' % (layer, str(vse)))
+                        if not res:
+                            errors.append("Layer '%s' recommends version %s of layer '%s', but version %s is currently enabled in your configuration. Check that you are using the correct matching versions/branches of these two layers." % (layer, verop, dep, layerver))
+
+            data.setVar("layerdata", layerdata)
+
+            if errors:
+                for error in errors:
+                    bb.error(error)
+                bb.fatal("Layer errors found, parsing stopped")
+
+            # Using the layer dependencies, work out the order layers should be listed
+            # in BBPATH and searched for BBFILES
+            layerorder = graphlib.TopologicalSorter()
+            for layer in sorted(layerdata.keys()):
+                layerorder.add(layer)
+                for dep in layerdata[layer].depends:
+                    layerorder.add(layer, dep)
+
+            try:
+                ordering = list(layerorder.static_order())
+            except graphlib.CycleError as exc:
+                bb.fatal("Circular dependencies found from LAYERDEPENDS, can't continue. (%s)" % str(exc))
+
+            # Construct BBPATH
+            data.setVar("BBPATH", ":".join(["${TOPDIR}"] + [layerdata[layer].path for layer in ordering[::-1]]))
+
+            # Construct BBFILES
+            #  - any recipes subdirs are added through a glob
+            #  - any /dynamic-recipes/<layername>/ are added if the named layer is present
+            bbfiles = []
+            for layer in ordering:
+                recipes = layerdata[layer].path + "/recipes*"
+                bbfiles.append(recipes)
+                dynamic_recipes = layerdata[layer].path + "/dynamic-recipes"
+                if os.path.isdir(dynamic_recipes):
+                    for deplayer in os.listdir(dynamic_recipes):
+                        if not os.path.isdir(dynamic_recipes + "/" + deplayer):
+                            continue
+                        if deplayer in layerdata:
+                            bbfiles.append(dynamic_recipes + "/" + deplayer)
+            data.setVar("BBFILES", " ".join(bbfiles))
+
+            if layer_filterfunc:
+                bb.utils.better_eval("%s(d)" % layer_filterfunc, {"d": data})
 
         if not data.getVar("BBPATH"):
             msg = "The BBPATH variable is not set"
@@ -523,7 +680,7 @@ class CookerDataBuilder(object):
 
         data.setVar('BBINCLUDED',bb.parse.get_file_depends(data))
 
-        return data
+        return data, layerdata
 
     @staticmethod
     def _parse_recipe(bb_data, bbfile, appends, mc, layername):
@@ -538,6 +695,19 @@ class CookerDataBuilder(object):
         if appends:
             bb_data.setVar('__BBAPPEND', " ".join(appends))
 
+        layerdir = bb_data.getVar("LAYERDIR_%s" % layername)
+        if layerdir:
+             conffile = layerdir + "/conf/layervars.conf"
+             bb.parse.mark_dependency(bb_data, conffile)
+             if os.path.exists(conffile):
+                 bb.parse.handle(conffile, bb_data, True, baseconfig=True)
+                 # Handle any added INHERITs
+                 bbclasses = (bb_data.getVar('INHERIT') or "").split()
+                 bb_data.setVar("__bbclasstype", "global")
+                 for bbclass in bbclasses:
+                     bb_data = _inherit(bbclass, bb_data)
+                 bb_data.setVar("__bbclasstype", "recipe")
+
         return bb.parse.handle(bbfile, bb_data)
 
     def parseRecipeVariants(self, bbfile, appends, virtonly=False, mc=None, layername=None):
diff --git a/lib/bb/parse/ast.py b/lib/bb/parse/ast.py
index d5d53a7c712..c26632b8b63 100644
--- a/lib/bb/parse/ast.py
+++ b/lib/bb/parse/ast.py
@@ -359,10 +359,11 @@ class AddFragmentsNode(AstNode):
         # No need to use mark_dependency since we would only match a fragment
         # from a specific layer and there can only be a single layer with a
         # given namespace.
-        def find_fragment(layers, layerid, full_fragment_name):
-           for layerpath in layers.split():
+        def find_fragment(layerdata, layerid, full_fragment_name):
+           if layerid in layerdata:
+               layerpath = layerdata[layerid].path
                candidate_fragment_path = os.path.join(layerpath, full_fragment_name)
-               if os.path.exists(candidate_fragment_path) and bb.utils.get_file_layer(candidate_fragment_path, data) == layerid:
+               if os.path.exists(candidate_fragment_path):
                    return candidate_fragment_path
            return None
 
@@ -388,11 +389,17 @@ class AddFragmentsNode(AstNode):
                 return True
             return False
 
-        fragments = data.getVar(self.fragments_variable)
-        layers = data.getVar('BBLAYERS')
+        fragments = (data.getVar(self.fragments_variable) or "").split()
         flagged_variables = data.getVar(self.flagged_variables_list_variable).split()
         builtin_fragments = {f[0]:f[1] for f in [f.split(':') for f in data.getVar(self.builtin_fragments_variable).split()] }
 
+        layerdata = data.getVar("layerdata", expand=False)
+        optedout = set((data.getVar("LAYER_FRAGMENTS_OPTED_OUT") or "").split())
+        for layer in layerdata:
+            wanted = layerdata[layer].fragment_recommends_any - optedout
+            if wanted and not (wanted & set(fragments)):
+                bb.warn("Layer %s recommends one of the fragments %s to be enabled but none are" % (layer, str(wanted)))
+
         if not fragments:
             return
 
@@ -401,7 +408,7 @@ class AddFragmentsNode(AstNode):
             builtin_fragments_list = list(
                 filter(
                     lambda f: f.startswith(builtin_fragment_key + "/"),
-                    fragments.split(),
+                    fragments,
                 )
             )
             if len(builtin_fragments_list) > 1:
@@ -416,12 +423,12 @@ class AddFragmentsNode(AstNode):
                     )
                 )
 
-        for f in fragments.split():
+        for f in fragments:
             if check_and_set_builtin_fragment(f, data, builtin_fragments):
                 continue
             layerid, fragment_name = f.split('/', 1)
             full_fragment_name = data.expand("{}/{}.conf".format(self.fragments_path_prefix, fragment_name))
-            fragment_path = find_fragment(layers, layerid, full_fragment_name)
+            fragment_path = find_fragment(layerdata, layerid, full_fragment_name)
             if fragment_path:
                 bb.parse.ConfHandler.include(self.filename, fragment_path, self.lineno, data, "include fragment")
                 for flagged_var in flagged_variables:
@@ -429,7 +436,8 @@ class AddFragmentsNode(AstNode):
                     data.setVarFlag(flagged_var, f, val)
                     data.setVar(flagged_var, None)
             else:
-                bb.fatal("Could not find fragment {} in enabled layers:\n\t{}".format(f, "\n\t".join(layers.split())))
+                paths = [layerdata[layer].path for layer in layerdata]
+                bb.fatal("Could not find fragment {} in enabled layers:\n\t{}".format(f, "\n\t".join(paths)))
 
 def handleInclude(statements, filename, lineno, m, force):
     statements.append(IncludeNode(filename, lineno, m.group(1), force))
