summaryrefslogtreecommitdiffstats
path: root/Documentation/sphinx/maintainers_include.py
diff options
context:
space:
mode:
authorLinus Torvalds <torvalds@linux-foundation.org>2026-09-13 12:27:00 -0700
committerLinus Torvalds <torvalds@linux-foundation.org>2026-09-13 12:27:00 -0700
commit22098763a10d9c1340827fcf6edab66f153b27f0 (patch)
tree3962f95a34df034652ff93686cdd156c7197f2d9 /Documentation/sphinx/maintainers_include.py
downloadlinux-stable-22098763a10d9c1340827fcf6edab66f153b27f0.tar.gz
linux-stable-22098763a10d9c1340827fcf6edab66f153b27f0.zip
Merge tag 'trace-v7.3-rc2' of git://git.kernel.org/pub/scm/linux/kernel/git/trace/linux-tracegrafted
Pull tracing fixes from Steven Rostedt: - Don't destroy user event fields when removal fails User event fields are destroyed before the event is removed from visibility. But that can fail leaving the still visible event with no fields. Move the destroying of the fields to after the event is successfully removed from visibility. - Initialize function graph state is fork before calling copy_exec_state() For non-CLONE_VM forks, copy_exec_state() allocates a new task_exec_state. If that allocation fails, ftrace_graph_exit_task() will free the tasks ret_stack pointer. Since that pointer is still using the parent's ret_stack, it mistakenly frees the parent's pointer too. Call ftrace_graph_init() on the task first which will NULL out the new tasks's ret_stack and if the copy fails, it will not free anything. - Remove FGRAPH_MAX_INDEX The macro FGRAPH_MAX_INDEX was added but never used. Remove it. - Save ent_size in function graph printing of nested functions The function graph tracer needs to look at the next event to see if the next event is the return of the current function entry. If it is, it prints a single line: ktime_get(); Otherwise it prints it like a nested function: tick_nohz_irq_exit() { ktime_get(); kcpustat_irq_exit(); } In order to look at the next event, it must save the current event so that it has the information to print from it. It saves the event in the iterator descriptor called "ent". What it doesn't save is the ent_size of the event which is now used to know if the function graph arguments are to be printed. The peek doesn't save the size so the size used happens to be that of the size of the last event that was seen. Save the entry event size in the iterator descriptor so that the correct size is used. - Fix several errors with freeing data in the histogram code The histogram code had a lot of leaked or or incorrect accounting when failures happen. Correct them. - Fix histogram regression of .percent and .graph modifiers Up until 6.3 histogram values could have "percent" or "graph" modifiers that changed how they were printed. But a change that added restricting histograms values from being strings, stack traces and other modifiers inadvertently prevented them from using the percent and graph modifiers, which were legal use cases for values. Put back the percent and graph modifiers. - Fix various typos in the comments - Set the trace_clock before initializing a histogram with clock argument The histogram API allows the user to specific which trace clock to use via a "clock=" string. The histogram is set up first before the clock is checked. If the passed in clock is not valid, it exits without fully fixing up the histogram leaving it on the list and a use-after-free can trigger. Update the clock argument first and if it fails then exit gracefully before the histogram trigger is placed on any lists. - Restore :mod: trailer after parsing in ftrace_set_clr_event The function ftrace_set_clr_event() modifies the parse string and needs to put it back to what was passed in. It searches for ":mod:" via a strsep() but fails to put back the first ':' in the string. Add back the ':' in the passed in string. - Take trace_array reference when opening a tracer options file The options files are dynamically created and some tracers add their own options. When a tracer adds their own list of options, the trace_array holding them has an array to hold the list of options for each tracer. This array increases in size via a krealloc(), and the new entry gets a newly allocated array to hold the options of the new tracer being added. The element in each entry of the tracer's option array holds a pointer back to the trace_array, a pointer to the tracer it is associated to, a pointer to the flags of the option. The issue is that these arrays are freed when the trace_array is freed when its instance it represents is removed from the instances directory. There's a race that an open of one of these options files can happen when the instance is being removed. Add a new helper function to be called by the open function of the options file to iterate all existing trace_arrays under a lock and find the one that has the given option element in one of it's tracer arrays. If found, then update the associated trace_array's reference counter to keep it from being freed. If not found, have the open call return -ENODEV. - Disable interrupts when acquiring the lock in rb_wake_up_waiters() The function rb_wake_up_waiters() assumes it will be called in interrupt context and does not disable irqs when taking cpu_buffer->reader_lock, which can be called in hard interrupt context. The issue is in PREEMPT_RT, this function is called in thread context leaving this lock open to a deadlock. Take the lock with interrupts disabled. - Use rcu_assign_pointer() for tmp_ops filter hash The tmp_ops used in update_ftrace_direct_mod() assigns its filter_hash field directly, but that field is annotated as __rcu and sparse complains. Assign it with rcu_assign_pointer() - Fix use-after-free in enable_trigger_private_data_free() The trace_event_call is accessed through the event_trigger_data's trace_event_file pointer to put the trace_event_call on freeing. The issue is that the trace_event_file data may have been freed already causing a use-after-free. Add a field to the event_trigger_data that points directly to the trace_event_call so that it can decrement its reference directly without needing to go through the trace_event_file. - Fix accounting of buffer data remote headers trace_buffer_desc_size() and trace_remote_alloc_buffer() undercount the number of pages is needed for the asked for size as it doesn't take into account the meta data on each page. Add a helper function to do the calculation properly and use that in these functions. - Catch nr_page_va overflow in ring_buffer_desc sizing The number of pages per remote ring buffer is capped by ring_buffer_desc::nr_page_va (32 bits). A buffer_size large enough to overflow that field would silently allocate a descriptor smaller than what was asked for. - Do not resize the subbuf order if any per_cpu buffer is disabled The mmapping of ring buffers disables resizing the subbuffers, but it is done per-cpu whereas the subbuf size change is done for all the per_cpu buffers under the buffer->mutex. It could change the size of some while the mapping is happening on others. Have the resize of the subbuf order check all the per_cpu buffers under the lock to see if any of them is disabled before starting and causing an inconsistency between buffers that are being mapped. * tag 'trace-v7.3-rc2' of git://git.kernel.org/pub/scm/linux/kernel/git/trace/linux-trace: (25 commits) ring-buffer: Check resize_disabled before publishing the new subbuf order tracing/remotes: Catch nr_page_va overflow in ring_buffer_desc sizing tracing/remotes: Account for ring buffer page header in size calculation tracing: Don't dereference trace_event_file in deferred trigger free ftrace: Use rcu_assign_pointer() for tmp_ops filter hash ring-buffer: Acquire the lock with irqsave in rb_wake_up_waiters() tracing: Take trace_array reference when opening a tracer options file tracing: Fix ring_buffer_read_page_size() kernel-doc tracing: Restore :mod: trailer after parsing in ftrace_set_clr_event() tracing: Fix memory corruption from a "STACKTRACE" histogram key tracing: Fix memory corruption from the histogram stacktrace modifier tracing: Undo the registration when enabling the histogram trigger fails tracing: Take the reference before publishing the named histogram trigger tracing: Set the trace clock before registering the histogram trigger tracing: Fix typo "preceeded" in comment tracing: Fix typo "availabe" in comment tracing: Let histogram values keep the percent and graph modifiers tracing: Keep the entry count when the histogram stats allocation fails tracing: Free histogram the field rejected for a bad modifier tracing: Free histogram the var ref when its initialization fails ...
Diffstat (limited to 'Documentation/sphinx/maintainers_include.py')
-rwxr-xr-xDocumentation/sphinx/maintainers_include.py418
1 files changed, 418 insertions, 0 deletions
diff --git a/Documentation/sphinx/maintainers_include.py b/Documentation/sphinx/maintainers_include.py
new file mode 100755
index 000000000..7ffe19b5e
--- /dev/null
+++ b/Documentation/sphinx/maintainers_include.py
@@ -0,0 +1,418 @@
+#!/usr/bin/env python
+# SPDX-License-Identifier: GPL-2.0
+# -*- coding: utf-8; mode: python -*-
+# pylint: disable=C0209, C0301, E0401, R0022, R0902, R0903, R0912, R0914
+
+"""
+Implementation of the ``maintainers-include`` reST-directive.
+
+:copyright: Copyright (C) 2019 Kees Cook <keescook@chromium.org>
+:license: GPL Version 2, June 1991 see linux/COPYING for details.
+
+The ``maintainers-include`` reST-directive performs extensive parsing
+specific to the Linux kernel's standard "MAINTAINERS" file, in an
+effort to avoid needing to heavily mark up the original plain text.
+"""
+
+import os.path
+import re
+
+from glob import glob
+
+from docutils import statemachine
+from docutils.parsers.rst.directives.misc import Include
+
+#
+# Base URL for intersphinx-like links to maintainer profiles
+#
+KERNELDOC_URL = "https://docs.kernel.org/"
+
+__version__ = "1.0"
+
+maint_parser = None # pylint: disable=C0103
+
+JS_FILTER = """
+(function() {
+ function filterTable(table) {
+ const filter = document.getElementById("filter-table").value.trim();
+ const rows = table.querySelectorAll("tbody tr");
+ for (let i = 0; i < rows.length; i++) {
+ const tds = rows[i].getElementsByTagName("td");
+ let match = false;
+ for (let j = 0; j < tds.length; j++) {
+ const cellText = (tds[j].textContent || tds[j].innerText);
+ if (cellText.includes(filter)) {
+ match = true;
+ break;
+ }
+ }
+ rows[i].style.display = match ? "table-row" : "none";
+ }
+ }
+ function addInput() {
+ const table = document.getElementById("maintainers-table");
+ if (!table) return;
+ let input = document.getElementById("filter-table");
+ if (!input) {
+ const filt_div = document.createElement('div');
+ filt_div.innerHTML = `
+ <p>Filter:
+ <input type="search" id="filter-table" placeholder="search string"/>
+ subsystem or property (case-sensitive)
+ </p>
+ `;
+ table.parentNode.insertBefore(filt_div, table);
+ const input = document.getElementById("filter-table")
+ input.addEventListener('input', () => filterTable(table));
+ }
+ }
+ if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', addInput);
+ } else {
+ addInput();
+ }
+})();
+"""
+
+
+# Shamelessly stolen from docutils
+def ErrorString(exc): # pylint: disable=C0103, C0116
+ return f"{exc.__class__.__name}: {exc}" # pylint: disable=W0212
+
+class MaintainersParser:
+ """Parse MAINTAINERS file(s) content"""
+
+ def __init__(self, base_dir, app_dir, path):
+ self.path = path
+
+ # Poor man's state machine.
+ self.descriptions = False
+ self.maintainers = False
+ self.subsystems = False
+
+ self.subsystem_name = None
+
+ self.base_dir = base_dir
+ self.app_dir = app_dir
+
+ self.re_doc = re.compile(r'(Documentation/(\S*)\.rst)')
+
+ #
+ # Output variables with maintainers content to be stored
+ #
+ self.profile_toc = set()
+ self.profile_entries = {}
+ self.header = ""
+ self.maint_entries = {}
+ self.fields = {}
+
+ prev = None
+ with open(path, "r", encoding="utf-8") as fp:
+ for line in fp:
+ if self.descriptions:
+ self.parse_descriptions(line)
+ elif self.maintainers and not self.subsystems:
+ if re.search('^[A-Z0-9]', line):
+ self.subsystems = True
+ self.parse_subsystems(line)
+ else:
+ self.header += line
+ elif self.subsystems:
+ self.parse_subsystems(line)
+ else:
+ self.header += line
+
+ # Update the state machine when we find heading separators.
+ if line.startswith("----------"):
+ if prev.startswith("Descriptions"):
+ self.descriptions = True
+ if prev.startswith("Maintainers"):
+ self.maintainers = True
+
+ # Retain previous line for state machine transitions.
+ prev = line
+
+ def get_entries(self, text):
+ """Generate refs to ReST files in Documentation/"""
+
+ if "Documentation/" not in text:
+ return None
+
+ if "*" in text or "?" in text:
+ m = self.re_doc.search(text)
+ if not m:
+ return None
+
+ doc_list = glob(os.path.join(self.base_dir, m.group(1)))
+ else:
+ doc_list = [text]
+
+ entries = {}
+ for doc in doc_list:
+ m = self.re_doc.search(doc)
+ if m:
+ fname = m.group(1)
+ ename = m.group(2)
+
+ entry = os.path.relpath(self.base_dir + fname, self.app_dir)
+ entry = entry.removesuffix(".rst")
+
+ if entry.startswith("../"):
+ html = KERNELDOC_URL + ename + ".html"
+ entries[entry] = f'`{ename} <{html}>`_'
+ else:
+ entries[entry] = f'/{entry}'
+
+ return entries
+
+ def linkify(self, text):
+ """Return a list of doc files converted to cross-references"""
+
+ entries = self.get_entries(text)
+ if not entries:
+ return text
+
+ return self.re_doc.sub(", ".join(entries.values()), text)
+
+ def parse_descriptions(self, line):
+ """Handle contents of the descriptions section."""
+
+ # Have we reached the end of the preformatted Descriptions text?
+ if line.startswith("Maintainers"):
+ self.descriptions = False
+ self.header += "\n" + line
+ return
+
+ # Look for and record field letter to field name mappings:
+ # R: Designated *reviewer*: FullName <address@domain>
+ m = re.match(r"\s+(\S):\s+(\S+)", line)
+ if m:
+ field = m.group(1)
+ details = m.group(2)
+
+ if field not in self.fields:
+ m = re.search(r"\*([^\*]+)\*", line)
+ if m:
+ self.fields[field] = m.group(1)
+ elif field in ['F', 'N', 'X', 'K']:
+ line = line.replace(details, f'``{details}``')
+
+ self.header += "| " + self.linkify(line)
+
+
+ def parse_subsystems(self, line):
+ """Handle contents of the per-subsystem sections."""
+
+ # Drop needless input whitespace.
+ line = line.rstrip()
+
+ # Skip empty lines: subsystem parser adds them as needed.
+ if not line:
+ return
+
+ if line[1] != ':':
+ self.subsystem_name = re.sub(r"\s+", " ", self.linkify(line))
+ return
+
+ # Render a subsystem field as:
+ # :Field: entry
+ # entry...
+ field, details = line.split(":", 1)
+ details = details.strip()
+
+ #
+ # Handle profile entries - either as files or as https refs
+ #
+ if field == "P":
+ entries = self.get_entries(details)
+ if entries:
+ for e, link in entries.items():
+ if "html" not in link:
+ self.profile_toc.add(e)
+
+ self.profile_entries[self.subsystem_name] = link
+
+ details = ", ".join(entries.values())
+ else:
+ match = re.match(r"(https?://.*)", details)
+ if match:
+ entry = match.group(1).strip()
+ self.profile_entries[self.subsystem_name] = entry
+ else:
+ self.profile_entries[self.subsystem_name] = f"``{details}``"
+
+ details = self.linkify(details)
+ else:
+ details = self.linkify(details)
+
+ #
+ # Mark paths (and regexes) as literal text for improved
+ # readability and to escape any escapes.
+ #
+ if field in ['F', 'N', 'X', 'K']:
+ # But only if not already marked :)
+ if ':doc:' not in details and "http" not in details:
+ details = '``%s``' % (details)
+
+ if self.subsystem_name not in self.maint_entries:
+ self.maint_entries[self.subsystem_name] = {}
+
+ if field not in self.maint_entries[self.subsystem_name]:
+ self.maint_entries[self.subsystem_name][field] = []
+
+ self.maint_entries[self.subsystem_name][field].append(details)
+
+ self.field_prev = field
+
+
+class MaintainersInclude(Include):
+ """MaintainersInclude (``maintainers-include``) directive"""
+
+ required_arguments = 0
+
+ def emit(self):
+ """Parse all the MAINTAINERS lines into ReST for human-readability"""
+ path = maint_parser.path
+ output = ".. _maintainers:\n\n"
+ output += maint_parser.header
+
+ output += ".. _maintainers_table:\n\n"
+ output += ".. flat-table::\n"
+ output += " :header-rows: 1\n\n"
+ output += " * - Subsystem\n"
+ output += " - Properties\n\n"
+
+ self.state.document['maintainers_included'] = True
+
+ # Keep the last entry ("THE REST") in the end
+ entries = list(maint_parser.maint_entries.keys())
+ entries = sorted(entries[:-1], key=str.casefold) + [entries[-1]]
+
+ for name in entries:
+ fields = maint_parser.maint_entries[name]
+ output += f" * - {name}\n"
+ tag = "-"
+ for field, lines in fields.items():
+ field_name = maint_parser.fields.get(field, field)
+
+ output += f" {tag} :{field_name}:\n "
+ output += ",\n ".join(lines) + "\n"
+ tag = " "
+
+ output += "\n"
+
+ # For debugging the pre-rendered results...
+ #print(output, file=open("/tmp/MAINTAINERS.rst", "w"))
+
+ self.state.document.settings.record_dependencies.add(path)
+ self.state_machine.insert_input(statemachine.string2lines(output), path)
+
+ def run(self):
+ """Include the MAINTAINERS file as part of this reST file."""
+ if not self.state.document.settings.file_insertion_enabled:
+ raise self.warning('"%s" directive disabled.' % self.name)
+
+ try:
+ self.emit()
+ except IOError as error:
+ raise self.severe('Problems with "%s" directive path:\n%s.' %
+ (self.name, ErrorString(error)))
+
+ return []
+
+
+class MaintainersProfile(Include):
+ """Generate a list with all maintainer's profiles"""
+
+ required_arguments = 0
+
+ def emit(self):
+ """Parse all the MAINTAINERS lines looking for profile entries"""
+ env = self.state.document.settings.env
+ docdir = os.path.dirname(os.path.join(env.srcdir, env.docname))
+ path = maint_parser.path
+
+ #
+ # Produce a list with all maintainer profiles, sorted by subsystem name
+ #
+ output = ""
+ for profile, entry in sorted(maint_parser.profile_entries.items()):
+ name = profile.title()
+
+ if entry.startswith("http"):
+ output += f"- `{name} <{entry}>`_\n"
+ elif entry.startswith("`"):
+ output += f"- {name}: {entry}\n"
+ self.warning(f"{profile}: Invalid 'P' tag: {entry}\n")
+ else:
+ if not name:
+ name = entry
+
+ output += f"- :doc:`{name} <{entry}>`\n"
+
+ #
+ # Create a hidden TOC table with all profiles. That allows adding
+ # profiles without needing to add them on any index.rst file.
+ #
+ output += "\n.. toctree::\n"
+ output += " :hidden:\n\n"
+
+ for f in sorted(maint_parser.profile_toc):
+ fname = os.path.join(maint_parser.base_dir, "Documentation", f)
+ fname = os.path.relpath(fname, docdir)
+ output += f" {fname}\n"
+
+ output += "\n"
+
+ # For debugging the pre-rendered results...
+ #print(output, file=open("/tmp/profiles.rst", "w"))
+
+ self.state.document.settings.record_dependencies.add(path)
+ self.state_machine.insert_input(statemachine.string2lines(output), path)
+
+ def run(self):
+ """Include the MAINTAINERS file as part of this reST file."""
+ if not self.state.document.settings.file_insertion_enabled:
+ raise self.warning('"%s" directive disabled.' % self.name)
+
+ try:
+ self.emit()
+ except IOError as error:
+ raise self.severe('Problems with "%s" directive path:\n%s.' %
+ (self.name, ErrorString(error)))
+
+ return []
+
+
+# pylint: disable=W0613
+def add_filter_script(app, pagename, templatename, context, doctree):
+ """Add Filter javascript only to maintainers page"""
+
+ if doctree and doctree.get('maintainers_included'):
+ app.add_js_file(None, body=JS_FILTER)
+
+
+def setup(app):
+ """Setup Sphinx extension"""
+ global maint_parser # pylint: disable=W0603
+
+ app_dir = os.path.abspath(app.srcdir)
+ match = re.match(r"(.*/)Documentation", app_dir)
+ if not match:
+ raise ValueError('Documentation directory not found.')
+
+ base_dir = match.group(1)
+ path = os.path.join(base_dir, "MAINTAINERS")
+
+ maint_parser = MaintainersParser(base_dir, app_dir, path)
+
+ app.add_directive("maintainers-include", MaintainersInclude)
+ app.add_directive("maintainers-profile-toc", MaintainersProfile)
+
+ app.connect("html-page-context", add_filter_script)
+
+ return {
+ "version": __version__,
+ "parallel_read_safe": True,
+ "parallel_write_safe": True,
+ }