diff --git a/.gitignore b/.gitignore
index dee574a..3d96541 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,6 +1,5 @@
-.idea/
-target/
-bin/
-.classpath
-.project
-*.iml
+.texpadtmp
+*.aux
+*.log
+*.pdf
+
diff --git a/Bibliography.bib b/Bibliography.bib
new file mode 100644
index 0000000..abcf753
--- /dev/null
+++ b/Bibliography.bib
@@ -0,0 +1,38 @@
+@article{Ukkonen95,
+ author = {Ukkonen, Esko},
+ journal = {Algorithmica},
+ keywords = {string\_matching, suffix\_trees},
+ number = {3},
+ pages = {249--260},
+ posted-at = {2008-06-08 04:09:56},
+ title = {{On-Line Construction of Suffix Trees}},
+ volume = {14},
+ year = {1995}
+}
+
+@misc{javolution,
+ title = {{javolution - The Java \texttrademark Solution for Real-Time and Embedded Systems}},
+ url = {{http://javolution.org/}}
+}
+
+@misc{guava,
+ author = {{Google, inc.}},
+ title = {{guava-libraries}},
+ url = {{http://code.google.com/p/guava-libraries/}}
+}
+
+@misc{hamcrest,
+ title = {{Hamcrest - library of matchers for building test expressions}},
+ url = {{http://code.google.com/p/hamcrest/}}
+}
+
+@misc{testng,
+ title = {{TestNG}},
+ url = {{http://www.testng.org}}
+}
+
+@misc{caliper,
+ author = {{Google, inc.}},
+ title = {{Caliper - Google's open-source framework for writing, running and viewing the results of Java Microbenchmarks}},
+ url = {{http://code.google.com/p/caliper/}}
+}
\ No newline at end of file
diff --git a/INSTALL b/INSTALL
deleted file mode 100644
index d7cc29f..0000000
--- a/INSTALL
+++ /dev/null
@@ -1,5 +0,0 @@
-To build, please install an up-to-date version of maven and run the following commands.
-In the project root directory: mvn clean install
-Then, in the assembly directory: mvn clean install assembly:single
-This will generate a tar.gz and a .zip containing the diffr jar, and a bash script each for diff and patch.
-
diff --git a/README b/README
deleted file mode 100644
index 183d85f..0000000
--- a/README
+++ /dev/null
@@ -1,2 +0,0 @@
-Intelligent DIFF/PATCH tool that knows copy and move, and has an 'R' at the end of its name.
-
diff --git a/assembly/pom.xml b/assembly/pom.xml
deleted file mode 100644
index 9da8f42..0000000
--- a/assembly/pom.xml
+++ /dev/null
@@ -1,60 +0,0 @@
-
-
- 4.0.0
-
-
- diffr
- parent
- 1.0-SNAPSHOT
-
-
- diffr
- assembly
- 1.0-SNAPSHOT
- jar
- ${project.groupId}.${project.artifactId}
- Assembles diffr and patchr into a single jar.
-
-
-
- diffr
- diff
- ${current.version}
-
-
- diffr
- patch
- ${current.version}
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-shade-plugin
- 1.6
-
-
- package
-
- shade
-
-
-
-
-
- org.apache.maven.plugins
- maven-assembly-plugin
- ${assembly.version}
-
-
- src/main/assembly/assembly.xml
-
-
-
-
-
-
diff --git a/assembly/src/main/assembly/assembly.xml b/assembly/src/main/assembly/assembly.xml
deleted file mode 100644
index 190f656..0000000
--- a/assembly/src/main/assembly/assembly.xml
+++ /dev/null
@@ -1,31 +0,0 @@
-
- diffr-assembly
-
- zip
- tar.gz
-
- false
-
-
- true
-
- diffr:assembly:jar
-
-
-
-
-
-
- /
- src/main/bin/diffr.sh
- 755
-
-
- /
- src/main/bin/patchr.sh
- 755
-
-
-
diff --git a/assembly/src/main/bin/diffr.sh b/assembly/src/main/bin/diffr.sh
deleted file mode 100644
index 5403782..0000000
--- a/assembly/src/main/bin/diffr.sh
+++ /dev/null
@@ -1,2 +0,0 @@
-#!/bin/bash
-java -cp "*" diffr.diff.Main $@
diff --git a/assembly/src/main/bin/patchr.sh b/assembly/src/main/bin/patchr.sh
deleted file mode 100644
index f4ef357..0000000
--- a/assembly/src/main/bin/patchr.sh
+++ /dev/null
@@ -1,2 +0,0 @@
-#!/bin/bash
-java -cp "*" diffr.patch.Main $@
diff --git a/conclusion/conclusion.tex b/conclusion/conclusion.tex
new file mode 100644
index 0000000..1f5fc94
--- /dev/null
+++ b/conclusion/conclusion.tex
@@ -0,0 +1,7 @@
+\section{Conclusion}
+
+Overall, the project was a success. The team as a whole had the opportunity to use tools that allowed us to streamline our work quite effectively. As some members were more familiar than others on a particular tool or technology, communication was essential. We relied heavily on \texttt{bitbucket.org} to store code, track and assign issues to each other. A post-meeting email was systematically sent with goals for each member of the team, even when all team members were physically present at the meeting.
+
+The final sprints were conducted when all team members were physically separated in locations that spanned 6 different timezones (from the East Coast USA to Poland). This proves that while distance certainly can hinder efficiency, remote development teams can still function well. Correct and up-to-date commit messages, distributed version control, and frequent communication were key to overcoming glitches and ensuring our success.
+
+In this project we have learned about how \texttt{DIFF} and \texttt{PATCH} tools work, and why they are so important. We have also gained experience in working with clone detection techniques such as suffix trees, which proved a very effective addition to the \texttt{diffr} tool. The tools we produced performed well against the oft-used \texttt{GNU DIFF}; the result was a slightly slower, but well scaling tool that outputs significantly smaller patch files. As an additional challenge, the group plans to port this tool to \texttt{C/C++} over the summer, in order to improve the runtime.
diff --git a/design/design.tex b/design/design.tex
new file mode 100644
index 0000000..9e82632
--- /dev/null
+++ b/design/design.tex
@@ -0,0 +1,45 @@
+\section{UML Diagram}
+
+Below are the UML diagrams for each module in the system, and one to show the interactions between them.
+
+\begin{figure}[H]
+\begin{center}
+\includegraphics[width=\textwidth]{design/diffrUML-util.png}
+\end{center}
+\caption{UML diagram for the Util module.}
+\label{fig:utilUML}
+\end{figure}
+
+\begin{figure}[H]
+\begin{center}
+\includegraphics[width=\textwidth]{design/diffrUML-suffixtree.png}
+\end{center}
+\caption{UML diagram for the SuffixTree module.}
+\label{fig:suffixTreeUML}
+\end{figure}
+
+\begin{figure}[H]
+\begin{center}
+\includegraphics[width=\textwidth]{design/diffrUML-diffR.png}
+\end{center}
+\caption{UML diagram for the DiffR module.}
+\label{fig:diffrUML}
+\end{figure}
+
+\begin{figure}[H]
+\begin{center}
+\includegraphics[width=\textwidth]{design/diffrUML-patchR.png}
+\end{center}
+\caption{UML diagram for the PatchR module.}
+\label{fig:patchrUML}
+\end{figure}
+
+\begin{figure}[H]
+\begin{center}
+\includegraphics[width=\textwidth]{design/diffrUML-packages.png}
+\end{center}
+\caption{UML diagram to show module interaction.}
+\label{fig:packagesUML}
+\end{figure}
+
+
diff --git a/design/diffRUML-diffR.png b/design/diffRUML-diffR.png
new file mode 100644
index 0000000..fbe0e52
Binary files /dev/null and b/design/diffRUML-diffR.png differ
diff --git a/design/diffRUML-packages.png b/design/diffRUML-packages.png
new file mode 100644
index 0000000..4fc9839
Binary files /dev/null and b/design/diffRUML-packages.png differ
diff --git a/design/diffRUML-patchR.png b/design/diffRUML-patchR.png
new file mode 100644
index 0000000..9b475b3
Binary files /dev/null and b/design/diffRUML-patchR.png differ
diff --git a/design/diffRUML-suffixtree.png b/design/diffRUML-suffixtree.png
new file mode 100644
index 0000000..cc026cf
Binary files /dev/null and b/design/diffRUML-suffixtree.png differ
diff --git a/design/diffRUML-util.png b/design/diffRUML-util.png
new file mode 100644
index 0000000..1049931
Binary files /dev/null and b/design/diffRUML-util.png differ
diff --git a/diff/pom.xml b/diff/pom.xml
deleted file mode 100644
index 3bb6e95..0000000
--- a/diff/pom.xml
+++ /dev/null
@@ -1,56 +0,0 @@
-
-
- 4.0.0
-
-
- diffr
- parent
- 1.0-SNAPSHOT
-
-
- diffr
- diff
- 1.0-SNAPSHOT
- jar
- ${project.groupId}.${project.artifactId}
- Diff for diffr.
-
-
-
- diffr
- suffix-tree
- ${current.version}
-
-
- diffr
- util
- ${current.version}
-
-
- com.google.guava
- guava
- ${guava.version}
-
-
- diffr
- util
- ${current.version}
- test
- tests
-
-
- org.testng
- testng
- ${testng.version}
- test
-
-
- org.hamcrest
- hamcrest-all
- ${hamcrest.version}
- test
-
-
-
diff --git a/diff/src/main/java/diffr/diff/Diffr.java b/diff/src/main/java/diffr/diff/Diffr.java
deleted file mode 100644
index 9600711..0000000
--- a/diff/src/main/java/diffr/diff/Diffr.java
+++ /dev/null
@@ -1,71 +0,0 @@
-package diffr.diff;
-
-import com.google.common.collect.Lists;
-import diffr.suffixtree.SuffixTree;
-import diffr.suffixtree.SuffixTree.Matcher;
-import diffr.suffixtree.SuffixTrees;
-import diffr.util.instruction.CopyInstruction;
-import diffr.util.instruction.InsertInstruction;
-import diffr.util.instruction.Instruction;
-
-import java.util.List;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-/**
- * Generates a list of {@link Instruction}s to transform original file into a new file.
- *
- * @author Sarina Gurung
- * @author Jakub D Kozlowski
- * @since 0.3
- */
-public final class Diffr {
-
- private final List originalFile;
-
- private final List newFile;
-
- /**
- * Default constructor.
- *
- * @param originalFile original file to be transform.
- * @param newFile new file to transform {@code originalFile} to.
- *
- * @throws NullPointerException if any parameter is null.
- */
- public Diffr(final List originalFile, final List newFile) {
- this.originalFile = checkNotNull(originalFile);
- this.newFile = checkNotNull(newFile);
- }
-
- /**
- * Gets the list of {@link Instruction}s to transform {@code originalFile} to {@code newFile}.
- *
- * @return list of {@link Instruction}s.
- */
- public List diff() {
-
- final List instructions = Lists.newArrayList();
- final SuffixTree suffixTree = SuffixTrees.newSuffixTree(this.originalFile);
-
- Matcher matcher = suffixTree.matcher();
-
- for (final String newFileLine : newFile) {
-
- if (!matcher.matchNext(newFileLine).isMatched()) {
- if (!matcher.isRoot()) {
- instructions.add(new CopyInstruction(matcher.range()));
- }
- instructions.add(new InsertInstruction(newFileLine));
- matcher = suffixTree.matcher();
- }
- }
-
- if (!matcher.isRoot()) {
- instructions.add(new CopyInstruction(matcher.range()));
- }
-
- return instructions;
- }
-
-}
diff --git a/diff/src/main/java/diffr/diff/Main.java b/diff/src/main/java/diffr/diff/Main.java
deleted file mode 100644
index 2555a76..0000000
--- a/diff/src/main/java/diffr/diff/Main.java
+++ /dev/null
@@ -1,112 +0,0 @@
-package diffr.diff;
-
-import com.google.common.base.Optional;
-import com.google.common.io.Files;
-import diffr.util.ArgumentsProcessor;
-import diffr.util.instruction.Instruction;
-import diffr.util.instruction.InstructionComposer;
-import diffr.util.instruction.Instructions;
-
-import java.io.BufferedWriter;
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.nio.charset.Charset;
-import java.util.List;
-
-/**
- * Main entry point to diffr's DIFF tool.
- *
- *
- * Expects two arguments:
- *
- * <original-file> - The original file to diff.
- * <new-file> - The new version of the original file to diff.
- *
- *
- *
- * @author Jakub D Kozlowski
- * @author Sarina Gurung
- * @since 0.1
- */
-public final class Main {
-
- /**
- * Prints the usage of this tool.
- */
- private static void printUsage() {
- System.out.println("Usage: \n" +
- " diffr \n" +
- " diffr -o ");
- }
-
- /**
- * Runs the diff tool on two files.
- *
- * @param args arguments to this tool.
- *
- * @return exit code.
- */
- public static int run(String... args) {
- try {
- if (ArgumentsProcessor.containsHelpArgument(args)
- || (2 != args.length
- && 4 != args.length)) {
- printUsage();
- return -1;
- }
-
- final File firstFile = new File(args[0]);
- final File secondFile = new File(args[1]);
-
- if (!firstFile.exists()) {
- System.err.println("File " + firstFile + " not found.");
- return -1;
- }
-
- if (!secondFile.exists()) {
- System.err.println("File " + secondFile + " not found.");
- return -1;
- }
-
- final List originalFile = Files.readLines(firstFile, Charset.defaultCharset());
- final List newFile = Files.readLines(secondFile, Charset.defaultCharset());
-
- final List instructions = new Diffr(originalFile, newFile).diff();
-
- final Optional outputFile = ArgumentsProcessor.extractOutputFile(args);
-
- if (4 == args.length
- && outputFile.isPresent()) {
-
- final File file = new File(outputFile.get());
- final BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
- for (final Instruction instruction : instructions) {
- Instructions.writeInstruction(instruction, bufferedWriter);
- }
- bufferedWriter.close();
- }
- else {
- for (final Instruction instruction : instructions) {
- System.out.println(InstructionComposer.composeString(instruction));
- }
- System.out.flush();
- }
-
- return 0;
- }
- catch (final IOException io) {
- System.err.println("There was a problem reading the files: " + io);
- return -1;
- }
- }
-
- /**
- * Invokes {@link #run(String...)} and calls {@link System#exit(int)}.
- *
- * @param args arguments to this tool.
- */
- public static void main(String... args) {
- System.exit(run(args));
- }
-}
diff --git a/diff/src/test/java/diffr/diff/DiffrTest.java b/diff/src/test/java/diffr/diff/DiffrTest.java
deleted file mode 100644
index 356fb0c..0000000
--- a/diff/src/test/java/diffr/diff/DiffrTest.java
+++ /dev/null
@@ -1,95 +0,0 @@
-package diffr.diff;
-
-import com.google.common.collect.Lists;
-import com.google.common.io.Files;
-import com.google.common.io.LineProcessor;
-import com.google.common.io.Resources;
-import diffr.util.instruction.Instruction;
-import diffr.util.instruction.InstructionComposer;
-import diffr.util.instruction.InstructionParser;
-import org.testng.annotations.DataProvider;
-import org.testng.annotations.Test;
-
-import java.io.File;
-import java.io.IOException;
-import java.net.URISyntaxException;
-import java.nio.charset.Charset;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.is;
-
-/**
- * Tests {@link Diffr}.
- *
- * @author Sarina Gurung
- * @author Jakub D Kozlowski
- * @since 0.3
- */
-public class DiffrTest {
-
- private static final String DEFAULT_PROVIDER = "default-provider";
-
- @DataProvider(name = "default-provider")
- public Object[][] getFiles() throws URISyntaxException, IOException {
-
- final List files = Lists.newArrayList();
-
- final File originalDir = new File(Resources.getResource("original").toURI());
- for (final File originalFile : originalDir.listFiles()) {
- final File newFile = new File(Resources.getResource("new/" + originalFile.getName()).toURI());
- final File patchFile = new File(Resources.getResource("patch/" + originalFile.getName()).toURI());
- files.add(new Object[]{
- Files.readLines(originalFile, Charset.defaultCharset()),
- Files.readLines(newFile, Charset.defaultCharset()),
- Files.readLines(patchFile, Charset.defaultCharset(), new LineProcessor>() {
-
- private List instructions = Lists.newArrayList();
-
- @Override
- public boolean processLine(String s) throws IOException {
- instructions.add(InstructionParser.parseInstruction(s).get());
- return true;
- }
-
- @Override
- public List getResult() {
- return instructions;
- }
- })
- });
- }
-
- return files.toArray(new Object[][]{});
- }
-
- @Test(expectedExceptions = NullPointerException.class)
- public void testConstructorNullOriginalFile() {
- new Diffr(null, Collections.EMPTY_LIST);
- }
-
- @Test(expectedExceptions = NullPointerException.class)
- public void testConstructorNullNewFile() {
- new Diffr(Collections.EMPTY_LIST, null);
- }
-
- @Test(dataProvider = DEFAULT_PROVIDER)
- public void testDiff(final List originalFile,
- final List newFile,
- final List patchFile)
- throws IOException, URISyntaxException {
-
-
- final Diffr d = new Diffr(originalFile, newFile);
-
- final Iterator actualInstructions = d.diff().iterator();
-
- for (final Instruction expected : patchFile) {
- final Instruction actual = actualInstructions.next();
- assertThat(InstructionComposer.composeString(actual),
- is(InstructionComposer.composeString(expected)));
- }
- }
-}
diff --git a/diff/src/test/resources/new/test1 b/diff/src/test/resources/new/test1
deleted file mode 100644
index 20e4817..0000000
--- a/diff/src/test/resources/new/test1
+++ /dev/null
@@ -1,5 +0,0 @@
-One
-Two
-Three
-Five
-Seven
\ No newline at end of file
diff --git a/diff/src/test/resources/new/test2 b/diff/src/test/resources/new/test2
deleted file mode 100644
index 2ab6864..0000000
--- a/diff/src/test/resources/new/test2
+++ /dev/null
@@ -1,7 +0,0 @@
-One
-Two
-Three
-Five
-Seven
-Eight
-Nine
\ No newline at end of file
diff --git a/diff/src/test/resources/new/test3 b/diff/src/test/resources/new/test3
deleted file mode 100644
index c86d140..0000000
--- a/diff/src/test/resources/new/test3
+++ /dev/null
@@ -1,8 +0,0 @@
-One
-Two
-Three
-Five
-Seven
-Eight
-Nine
-Ten
\ No newline at end of file
diff --git a/diff/src/test/resources/new/test4 b/diff/src/test/resources/new/test4
deleted file mode 100644
index 2b10312..0000000
--- a/diff/src/test/resources/new/test4
+++ /dev/null
@@ -1,10 +0,0 @@
-One
-Two
-Three
-Five
-Seven
-Eight
-Nine
-Ten
-Twelve
-Thirteen
\ No newline at end of file
diff --git a/diff/src/test/resources/new/test5 b/diff/src/test/resources/new/test5
deleted file mode 100644
index 582b92b..0000000
--- a/diff/src/test/resources/new/test5
+++ /dev/null
@@ -1,11 +0,0 @@
-One
-Two
-Three
-Five
-Seven
-Eight
-Nine
-Ten
-Twelve
-Thirteen
-Fifteen
\ No newline at end of file
diff --git a/diff/src/test/resources/new/test6 b/diff/src/test/resources/new/test6
deleted file mode 100644
index 40816a2..0000000
--- a/diff/src/test/resources/new/test6
+++ /dev/null
@@ -1 +0,0 @@
-Hi
\ No newline at end of file
diff --git a/diff/src/test/resources/new/test7 b/diff/src/test/resources/new/test7
deleted file mode 100644
index 40816a2..0000000
--- a/diff/src/test/resources/new/test7
+++ /dev/null
@@ -1 +0,0 @@
-Hi
\ No newline at end of file
diff --git a/diff/src/test/resources/new/test9 b/diff/src/test/resources/new/test9
deleted file mode 100644
index c7c85c9..0000000
--- a/diff/src/test/resources/new/test9
+++ /dev/null
@@ -1,7 +0,0 @@
-January
-February
-March
-
-April
-May
-June
\ No newline at end of file
diff --git a/diff/src/test/resources/original/test1 b/diff/src/test/resources/original/test1
deleted file mode 100644
index 2402b58..0000000
--- a/diff/src/test/resources/original/test1
+++ /dev/null
@@ -1,5 +0,0 @@
-One
-Two
-Three
-Four
-Six
\ No newline at end of file
diff --git a/diff/src/test/resources/original/test2 b/diff/src/test/resources/original/test2
deleted file mode 100644
index ba63efe..0000000
--- a/diff/src/test/resources/original/test2
+++ /dev/null
@@ -1,7 +0,0 @@
-One
-Two
-Three
-Four
-Six
-Eight
-Nine
\ No newline at end of file
diff --git a/diff/src/test/resources/original/test3 b/diff/src/test/resources/original/test3
deleted file mode 100644
index 945d8c5..0000000
--- a/diff/src/test/resources/original/test3
+++ /dev/null
@@ -1,8 +0,0 @@
-Some other line
-Two
-Three
-Four
-Six
-Eight
-Nine
-Elevan
diff --git a/diff/src/test/resources/original/test4 b/diff/src/test/resources/original/test4
deleted file mode 100644
index f790a2e..0000000
--- a/diff/src/test/resources/original/test4
+++ /dev/null
@@ -1,10 +0,0 @@
-One
-Two
-Three
-Four
-Six
-Eight
-Nine
-Elevan
-Twelve
-Thirteen
\ No newline at end of file
diff --git a/diff/src/test/resources/original/test5 b/diff/src/test/resources/original/test5
deleted file mode 100644
index abfb0ce..0000000
--- a/diff/src/test/resources/original/test5
+++ /dev/null
@@ -1,11 +0,0 @@
-One
-Two
-Three
-Four
-Six
-Eight
-Nine
-Elevan
-Twelve
-Thirteen
-Fourteen
\ No newline at end of file
diff --git a/diff/src/test/resources/original/test6 b/diff/src/test/resources/original/test6
deleted file mode 100644
index 5ab2f8a..0000000
--- a/diff/src/test/resources/original/test6
+++ /dev/null
@@ -1 +0,0 @@
-Hello
\ No newline at end of file
diff --git a/diff/src/test/resources/original/test7 b/diff/src/test/resources/original/test7
deleted file mode 100644
index 40816a2..0000000
--- a/diff/src/test/resources/original/test7
+++ /dev/null
@@ -1 +0,0 @@
-Hi
\ No newline at end of file
diff --git a/diff/src/test/resources/original/test9 b/diff/src/test/resources/original/test9
deleted file mode 100644
index 6d45f45..0000000
--- a/diff/src/test/resources/original/test9
+++ /dev/null
@@ -1,7 +0,0 @@
-April
-May
-June
-
-April
-May
-June
\ No newline at end of file
diff --git a/diff/src/test/resources/patch/test1 b/diff/src/test/resources/patch/test1
deleted file mode 100644
index 8ef175c..0000000
--- a/diff/src/test/resources/patch/test1
+++ /dev/null
@@ -1,3 +0,0 @@
-0,2
-> Five
-> Seven
diff --git a/diff/src/test/resources/patch/test2 b/diff/src/test/resources/patch/test2
deleted file mode 100644
index 237a1c9..0000000
--- a/diff/src/test/resources/patch/test2
+++ /dev/null
@@ -1,4 +0,0 @@
-0,2
-> Five
-> Seven
-5,6
\ No newline at end of file
diff --git a/diff/src/test/resources/patch/test3 b/diff/src/test/resources/patch/test3
deleted file mode 100644
index f5d419f..0000000
--- a/diff/src/test/resources/patch/test3
+++ /dev/null
@@ -1,6 +0,0 @@
-> One
-1,2
-> Five
-> Seven
-5,6
-> Ten
diff --git a/diff/src/test/resources/patch/test4 b/diff/src/test/resources/patch/test4
deleted file mode 100644
index cac32de..0000000
--- a/diff/src/test/resources/patch/test4
+++ /dev/null
@@ -1,6 +0,0 @@
-0,2
-> Five
-> Seven
-5,6
-> Ten
-8,9
\ No newline at end of file
diff --git a/diff/src/test/resources/patch/test5 b/diff/src/test/resources/patch/test5
deleted file mode 100644
index ff337de..0000000
--- a/diff/src/test/resources/patch/test5
+++ /dev/null
@@ -1,7 +0,0 @@
-0,2
-> Five
-> Seven
-5,6
-> Ten
-8,9
-> Fifteen
\ No newline at end of file
diff --git a/diff/src/test/resources/patch/test6 b/diff/src/test/resources/patch/test6
deleted file mode 100644
index c7eb67a..0000000
--- a/diff/src/test/resources/patch/test6
+++ /dev/null
@@ -1 +0,0 @@
-> Hi
\ No newline at end of file
diff --git a/diff/src/test/resources/patch/test7 b/diff/src/test/resources/patch/test7
deleted file mode 100644
index 7de346d..0000000
--- a/diff/src/test/resources/patch/test7
+++ /dev/null
@@ -1 +0,0 @@
-0,0
\ No newline at end of file
diff --git a/diff/src/test/resources/patch/test9 b/diff/src/test/resources/patch/test9
deleted file mode 100644
index 71432c4..0000000
--- a/diff/src/test/resources/patch/test9
+++ /dev/null
@@ -1,4 +0,0 @@
-> January
-> February
-> March
-3,6
\ No newline at end of file
diff --git a/implementation/implementation.tex b/implementation/implementation.tex
new file mode 100644
index 0000000..31305f0
--- /dev/null
+++ b/implementation/implementation.tex
@@ -0,0 +1,47 @@
+\section{Implementation}
+
+In this chapter we will describe the overall architecture of \texttt{diffr} and \texttt{patchr} and provide a few implementation details. Then we will move on to describe the tools we used during the implementation.
+
+\subsection{Modules}
+
+\paragraph{diffr.suffix-tree (suffix-tree/)}
+This module contains the Suffix Tree implementation. It is a generic Suffix Tree based on the implementation suggested in \cite{Ukkonen95} and optimised for quickly matching suffixes of elements. The implementation details are completely hidden from the user behind the \\ \texttt{diffr.suffixtree.SuffixTree} interface and \\ \texttt{diffr.suffixtree.SuffixTrees} factory. Using the \texttt{SuffixTree} for matching sequences of elements can be accomplished through an implementation of \texttt{diffr.suffixtree.SuffixTree.Matcher} interface returned from \\ \texttt{SuffixTree\#matcher()} method. Internally the Suffix Tree uses high-performance, real-time \texttt{java.util.List} and \texttt{java.util.Map} implementations from the \texttt{javolution library} (\texttt{javolution.util.FastTable} and \texttt{javolution.util.FastMap})~\cite{javolution}.
+
+The hashcode of each of line of the first document is computed and used first before a deep comparison of lines when attempting to find clones in the tree.
+This improves performance slightly.
+
+\paragraph{diffr.util (util/)}
+This module contains various domain objects and utility classes. The main classes that encapsulate the two possible instructions output by \texttt{diffr} and are located in the \texttt{diffr.util.instruction} package. Also in this package, we have implemented classes that deal with transforming instructions to/from text and writing them to streams.
+
+\paragraph{diffr.patch (patch/)}
+This module contains the patch implementation. The algorithm is implemented in \texttt{diffr.patch.Patchr}: it reads both the original file and the patch file into memory. In then uses the classes from the \texttt{util/} module to parse and validate the patch file for existence of incorrect instructions and terminates with an error message if the validation fails. It then iterates through instructions and transforms them into appropriate text. The instruction text is collected in a list and returned. It is the \texttt{diffr.patch.Main} class that outputs the transformed file. This separation of concerns allows us to choose between writing to file and standard output, depending on a flag specified by the user.
+
+Additionally, the patch tool will exit and print a relevant error message if one of the files cannot be read, or if any sort of exception is thrown.
+
+\paragraph{diffr.diff (diff/)}
+
+This module contains the diff implementation. The algorithm is implemented in \texttt{diffr.diff.Diffr}: it builds the \texttt{SuffixTree} or the original file and then iterates through the new file in order to collect in a list the longest sequences of clones and holes between the two files, and return this list. Similarly to \texttt{patch/}, it is the \texttt{diffr.diff.Main} class that outputs the instructions. Again, this separation of concerns allows us to choose between writing to file and standard output, depending on a flag specified by the user.
+
+Also, relevant error messages are printed if any error condition occurs.
+
+\paragraph{diffr.assembly (assembly/)}
+This module builds a jar file with all the \texttt{diffr.patch}, \texttt{diffr.diff} classes and their dependencies. The jar file is then aggregated together with bash scripts for running \texttt{diff} and \texttt{patch} in \texttt{.zip} and \texttt{.tar.gz} archives.
+
+\paragraph{diffr.integration-tests (integration-tests/)}
+This module contains the integration tests, further described in~\Cref{IntegrationTesting}.
+
+\subsection{Tools}
+
+\paragraph{Build Management}
+
+We used \textit{Maven3} as our build tool. The main advantage of \textit{Maven3} over the more traditional \textit{Ant} is automatic dependency management and default build configuration that suits most of the projects well.
+
+\paragraph{Version Control}
+We decided to use \textit{git} as our version control system, as most of our group were already familiar with it. \texttt{git} is great for doing distributed, offline development and the first-class support for branching means we can all safely work in separate branches and freely share code, without polluting the history in the main branch. We also decided to use \textit{bitbucket.org} to host our repository due to the built-in support for issues and pull requests, that we used extensively for planning iterations, tracking tasks and code review.
+
+\paragraph{IDE}
+Because we used \textit{Maven3} as our build tool, our team members were free to choose any IDE they wished. Our team members used \textit{IntelliJ IDEA} and \textit{Eclipse}.
+
+\paragraph{Libraries}
+We mainly used two open source libraries in the production code: \texttt{javolution}~\cite{javolution} and \texttt{guava-libraries}~\cite{guava}. The already mentioned~\cite{javolution} provided high-performance, real-time replacements for \texttt{Java Collections} classes and~\cite{guava} useful utilities for idiomatically reading/writing files, validating input etc.
+
diff --git a/integration-tests/pom.xml b/integration-tests/pom.xml
deleted file mode 100644
index e27b375..0000000
--- a/integration-tests/pom.xml
+++ /dev/null
@@ -1,53 +0,0 @@
-
-
- 4.0.0
-
-
- diffr
- parent
- 1.0-SNAPSHOT
-
-
- diffr
- integration-tests
- 1.0-SNAPSHOT
- jar
- ${project.groupId}.${project.artifactId}
- Integration tests for patchr and diffr.
-
-
-
- diffr
- util
- ${current.version}
- test
- tests
-
-
- diffr
- diff
- ${current.version}
- test
-
-
- diffr
- patch
- ${current.version}
- test
-
-
- org.testng
- testng
- ${testng.version}
- test
-
-
- org.hamcrest
- hamcrest-all
- ${hamcrest.version}
- test
-
-
-
diff --git a/integration-tests/src/test/java/diffr/integration/DiffPatchIntegrationTest.java b/integration-tests/src/test/java/diffr/integration/DiffPatchIntegrationTest.java
deleted file mode 100644
index 539275f..0000000
--- a/integration-tests/src/test/java/diffr/integration/DiffPatchIntegrationTest.java
+++ /dev/null
@@ -1,91 +0,0 @@
-package diffr.integration;
-
-import com.google.common.io.Files;
-import com.google.common.io.Resources;
-import diffr.patch.IllegalPatchFileException;
-import org.testng.annotations.Test;
-
-import java.io.File;
-import java.io.IOException;
-import java.net.URISyntaxException;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.is;
-
-/**
- * Tests diff/patch integration.
- *
- * @author Jakub D Kozlowski
- * @since 1.0
- */
-public class DiffPatchIntegrationTest {
-
- @Test
- public void testKernel01ToKernel26() throws IllegalPatchFileException, URISyntaxException, IOException {
- testDiffrPatchr("kernel01.txt", "kernel26.txt");
- }
-
- @Test
- public void testKernel26ToKernel01() throws IllegalPatchFileException, URISyntaxException, IOException {
- testDiffrPatchr("kernel26.txt", "kernel01.txt");
- }
-
- @Test
- public void testKernel01ToKernel33() throws IllegalPatchFileException, URISyntaxException, IOException {
- testDiffrPatchr("kernel01.txt", "kernel33.txt");
- }
-
- @Test
- public void testKernel33ToKernel01() throws IllegalPatchFileException, URISyntaxException, IOException {
- testDiffrPatchr("kernel33.txt", "kernel01.txt");
- }
-
- @Test
- public void testKernel26ToKernel33() throws IllegalPatchFileException, URISyntaxException, IOException {
- testDiffrPatchr("kernel26.txt", "kernel33.txt");
- }
-
- @Test
- public void testKernel33ToKernel26() throws IllegalPatchFileException, URISyntaxException, IOException {
- testDiffrPatchr("kernel33.txt", "kernel26.txt");
- }
-
- /**
- * Runs diffr on {@code originalFileName} and {@code newFileName}, runs patchr on the resulting patch file and
- * {@code originalFileName} and compares the result to {@code newFileName}.
- *
- * @param originalFileName file name of the original file.
- * @param newFileName file name of the new file.
- *
- * @throws IOException if there is a problem reading or writing the files.
- * @throws URISyntaxException if the file names cannot be found.
- */
- public static void testDiffrPatchr(final String originalFileName, final String newFileName)
- throws IOException, URISyntaxException {
-
- final File originalFile = getFile(originalFileName);
- final File newFile = getFile(newFileName);
-
- final File tmpPatchFile = File.createTempFile("diffr", "patch", Files.createTempDir());
- final File tmpNewFile = File.createTempFile("diffr", "new", Files.createTempDir());
-
- diffr.diff.Main.run(originalFile.getAbsolutePath(), newFile.getAbsolutePath(), "-o",
- tmpPatchFile.getAbsolutePath());
-
- diffr.patch.Main.run(originalFile.getAbsolutePath(), tmpPatchFile.getAbsolutePath(), "-o",
- tmpNewFile.getAbsolutePath());
-
- assertThat(Files.equal(newFile, tmpNewFile), is(true));
- }
-
- /**
- * Gets the {@code fileName} from the classloader.
- *
- * @param fileName name of file to get.
- *
- * @return {@code fileName} from the classloader.
- */
- public static File getFile(final String fileName) throws URISyntaxException, IOException {
- return new File(Resources.getResource(fileName).toURI());
- }
-}
diff --git a/integration-tests/src/test/resources/kernel01.txt b/integration-tests/src/test/resources/kernel01.txt
deleted file mode 100644
index 26d2bda..0000000
--- a/integration-tests/src/test/resources/kernel01.txt
+++ /dev/null
@@ -1,2585 +0,0 @@
-/*
- * console.c
- *
- * This module implements the console io functions
- * 'void con_init(void)'
- * 'void con_write(struct tty_queue * queue)'
- * Hopefully this will be a rather complete VT102 implementation.
- *
- */
-
-/*
- * NOTE!!! We sometimes disable and enable interrupts for a short while
- * (to put a word in video IO), but this will work even for keyboard
- * interrupts. We know interrupts aren't enabled when getting a keyboard
- * interrupt, as we use trap-gates. Hopefully all is well.
- */
-
-#include
-#include
-#include
-#include
-
-#define SCREEN_START 0xb8000
-#define SCREEN_END 0xc0000
-#define LINES 25
-#define COLUMNS 80
-#define NPAR 16
-
-extern void keyboard_interrupt(void);
-
-static unsigned long origin=SCREEN_START;
-static unsigned long scr_end=SCREEN_START+LINES*COLUMNS*2;
-static unsigned long pos;
-static unsigned long x,y;
-static unsigned long top=0,bottom=LINES;
-static unsigned long lines=LINES,columns=COLUMNS;
-static unsigned long state=0;
-static unsigned long npar,par[NPAR];
-static unsigned long ques=0;
-static unsigned char attr=0x07;
-
-/*
- * this is what the terminal answers to a ESC-Z or csi0c
- * query (= vt100 response).
- */
-#define RESPONSE "\033[?1;2c"
-
-static inline void gotoxy(unsigned int new_x,unsigned int new_y)
-{
- if (new_x>=columns || new_y>=lines)
- return;
- x=new_x;
- y=new_y;
- pos=origin+((y*columns+x)<<1);
-}
-
-static inline void set_origin(void)
-{
- cli();
- outb_p(12,0x3d4);
- outb_p(0xff&((origin-SCREEN_START)>>9),0x3d5);
- outb_p(13,0x3d4);
- outb_p(0xff&((origin-SCREEN_START)>>1),0x3d5);
- sti();
-}
-
-static void scrup(void)
-{
- if (!top && bottom==lines) {
- origin += columns<<1;
- pos += columns<<1;
- scr_end += columns<<1;
- if (scr_end>SCREEN_END) {
- __asm__("cld\n\t"
- "rep\n\t"
- "movsl\n\t"
- "movl _columns,%1\n\t"
- "rep\n\t"
- "stosw"
- ::"a" (0x0720),
- "c" ((lines-1)*columns>>1),
- "D" (SCREEN_START),
- "S" (origin)
- :"cx","di","si");
- scr_end -= origin-SCREEN_START;
- pos -= origin-SCREEN_START;
- origin = SCREEN_START;
- } else {
- __asm__("cld\n\t"
- "rep\n\t"
- "stosl"
- ::"a" (0x07200720),
- "c" (columns>>1),
- "D" (scr_end-(columns<<1))
- :"cx","di");
- }
- set_origin();
- } else {
- __asm__("cld\n\t"
- "rep\n\t"
- "movsl\n\t"
- "movl _columns,%%ecx\n\t"
- "rep\n\t"
- "stosw"
- ::"a" (0x0720),
- "c" ((bottom-top-1)*columns>>1),
- "D" (origin+(columns<<1)*top),
- "S" (origin+(columns<<1)*(top+1))
- :"cx","di","si");
- }
-}
-
-static void scrdown(void)
-{
- __asm__("std\n\t"
- "rep\n\t"
- "movsl\n\t"
- "addl $2,%%edi\n\t" /* %edi has been decremented by 4 */
- "movl _columns,%%ecx\n\t"
- "rep\n\t"
- "stosw"
- ::"a" (0x0720),
- "c" ((bottom-top-1)*columns>>1),
- "D" (origin+(columns<<1)*bottom-4),
- "S" (origin+(columns<<1)*(bottom-1)-4)
- :"ax","cx","di","si");
-}
-
-static void lf(void)
-{
- if (y+1top) {
- y--;
- pos -= columns<<1;
- return;
- }
- scrdown();
-}
-
-static void cr(void)
-{
- pos -= x<<1;
- x=0;
-}
-
-static void del(void)
-{
- if (x) {
- pos -= 2;
- x--;
- *(unsigned short *)pos = 0x0720;
- }
-}
-
-static void csi_J(int par)
-{
- long count __asm__("cx");
- long start __asm__("di");
-
- switch (par) {
- case 0: /* erase from cursor to end of display */
- count = (scr_end-pos)>>1;
- start = pos;
- break;
- case 1: /* erase from start to cursor */
- count = (pos-origin)>>1;
- start = origin;
- break;
- case 2: /* erase whole display */
- count = columns*lines;
- start = origin;
- break;
- default:
- return;
- }
- __asm__("cld\n\t"
- "rep\n\t"
- "stosw\n\t"
- ::"c" (count),
- "D" (start),"a" (0x0720)
- :"cx","di");
-}
-
-static void csi_K(int par)
-{
- long count __asm__("cx");
- long start __asm__("di");
-
- switch (par) {
- case 0: /* erase from cursor to end of line */
- if (x>=columns)
- return;
- count = columns-x;
- start = pos;
- break;
- case 1: /* erase from start of line to cursor */
- start = pos - (x<<1);
- count = (x>9),0x3d5);
- outb_p(15,0x3d4);
- outb_p(0xff&((pos-SCREEN_START)>>1),0x3d5);
- sti();
-}
-
-static void respond(struct tty_struct * tty)
-{
- char * p = RESPONSE;
-
- cli();
- while (*p) {
- PUTCH(*p,tty->read_q);
- p++;
- }
- sti();
- copy_to_cooked(tty);
-}
-
-static void insert_char(void)
-{
- int i=x;
- unsigned short tmp,old=0x0720;
- unsigned short * p = (unsigned short *) pos;
-
- while (i++=columns)
- return;
- i = x;
- while (++i < columns) {
- *p = *(p+1);
- p++;
- }
- *p=0x0720;
-}
-
-static void delete_line(void)
-{
- int oldtop,oldbottom;
-
- oldtop=top;
- oldbottom=bottom;
- top=y;
- bottom=lines;
- scrup();
- top=oldtop;
- bottom=oldbottom;
-}
-
-static void csi_at(int nr)
-{
- if (nr>columns)
- nr=columns;
- else if (!nr)
- nr=1;
- while (nr--)
- insert_char();
-}
-
-static void csi_L(int nr)
-{
- if (nr>lines)
- nr=lines;
- else if (!nr)
- nr=1;
- while (nr--)
- insert_line();
-}
-
-static void csi_P(int nr)
-{
- if (nr>columns)
- nr=columns;
- else if (!nr)
- nr=1;
- while (nr--)
- delete_char();
-}
-
-static void csi_M(int nr)
-{
- if (nr>lines)
- nr=lines;
- else if (!nr)
- nr=1;
- while (nr--)
- delete_line();
-}
-
-static int saved_x=0;
-static int saved_y=0;
-
-static void save_cur(void)
-{
- saved_x=x;
- saved_y=y;
-}
-
-static void restore_cur(void)
-{
- x=saved_x;
- y=saved_y;
- pos=origin+((y*columns+x)<<1);
-}
-
-void con_write(struct tty_struct * tty)
-{
- int nr;
- char c;
-
- nr = CHARS(tty->write_q);
- while (nr--) {
- GETCH(tty->write_q,c);
- switch(state) {
- case 0:
- if (c>31 && c<127) {
- if (x>=columns) {
- x -= columns;
- pos -= columns<<1;
- lf();
- }
- __asm__("movb _attr,%%ah\n\t"
- "movw %%ax,%1\n\t"
- ::"a" (c),"m" (*(short *)pos)
- :"ax");
- pos += 2;
- x++;
- } else if (c==27)
- state=1;
- else if (c==10 || c==11 || c==12)
- lf();
- else if (c==13)
- cr();
- else if (c==ERASE_CHAR(tty))
- del();
- else if (c==8) {
- if (x) {
- x--;
- pos -= 2;
- }
- } else if (c==9) {
- c=8-(x&7);
- x += c;
- pos += c<<1;
- if (x>columns) {
- x -= columns;
- pos -= columns<<1;
- lf();
- }
- c=9;
- }
- break;
- case 1:
- state=0;
- if (c=='[')
- state=2;
- else if (c=='E')
- gotoxy(0,y+1);
- else if (c=='M')
- ri();
- else if (c=='D')
- lf();
- else if (c=='Z')
- respond(tty);
- else if (x=='7')
- save_cur();
- else if (x=='8')
- restore_cur();
- break;
- case 2:
- for(npar=0;npar='0' && c<='9') {
- par[npar]=10*par[npar]+c-'0';
- break;
- } else state=4;
- case 4:
- state=0;
- switch(c) {
- case 'G': case '`':
- if (par[0]) par[0]--;
- gotoxy(par[0],y);
- break;
- case 'A':
- if (!par[0]) par[0]++;
- gotoxy(x,y-par[0]);
- break;
- case 'B': case 'e':
- if (!par[0]) par[0]++;
- gotoxy(x,y+par[0]);
- break;
- case 'C': case 'a':
- if (!par[0]) par[0]++;
- gotoxy(x+par[0],y);
- break;
- case 'D':
- if (!par[0]) par[0]++;
- gotoxy(x-par[0],y);
- break;
- case 'E':
- if (!par[0]) par[0]++;
- gotoxy(0,y+par[0]);
- break;
- case 'F':
- if (!par[0]) par[0]++;
- gotoxy(0,y-par[0]);
- break;
- case 'd':
- if (par[0]) par[0]--;
- gotoxy(x,par[0]);
- break;
- case 'H': case 'f':
- if (par[0]) par[0]--;
- if (par[1]) par[1]--;
- gotoxy(par[1],par[0]);
- break;
- case 'J':
- csi_J(par[0]);
- break;
- case 'K':
- csi_K(par[0]);
- break;
- case 'L':
- csi_L(par[0]);
- break;
- case 'M':
- csi_M(par[0]);
- break;
- case 'P':
- csi_P(par[0]);
- break;
- case '@':
- csi_at(par[0]);
- break;
- case 'm':
- csi_m();
- break;
- case 'r':
- if (par[0]) par[0]--;
- if (!par[1]) par[1]=lines;
- if (par[0] < par[1] &&
- par[1] <= lines) {
- top=par[0];
- bottom=par[1];
- }
- break;
- case 's':
- save_cur();
- break;
- case 'u':
- restore_cur();
- break;
- }
- }
- }
- set_cursor();
-}
-
-/*
- * void con_init(void);
- *
- * This routine initalizes console interrupts, and does nothing
- * else. If you want the screen to clear, call tty_write with
- * the appropriate escape-sequece.
- */
-void con_init(void)
-{
- register unsigned char a;
-
- gotoxy(*(unsigned char *)(0x90000+510),*(unsigned char *)(0x90000+511));
- set_trap_gate(0x21,&keyboard_interrupt);
- outb_p(inb_p(0x21)&0xfd,0x21);
- a=inb_p(0x61);
- outb_p(a|0x80,0x61);
- outb(a,0x61);
-}
-#include
-#include
-#include
-
-#include
-#include
-#include
-#include
-
-int sys_pause(void);
-int sys_close(int fd);
-
-void release(struct task_struct * p)
-{
- int i;
-
- if (!p)
- return;
- for (i=1 ; i32)
- return;
- if (priv ||
- current->uid==p->uid ||
- current->euid==p->uid ||
- current->uid==p->euid ||
- current->euid==p->euid)
- p->signal |= (1<<(sig-1));
-}
-
-void do_kill(long pid,long sig,int priv)
-{
- struct task_struct **p = NR_TASKS + task;
-
- if (!pid) while (--p > &FIRST_TASK) {
- if (*p && (*p)->pgrp == current->pid)
- send_sig(sig,*p,priv);
- } else if (pid>0) while (--p > &FIRST_TASK) {
- if (*p && (*p)->pid == pid)
- send_sig(sig,*p,priv);
- } else if (pid == -1) while (--p > &FIRST_TASK)
- send_sig(sig,*p,priv);
- else while (--p > &FIRST_TASK)
- if (*p && (*p)->pgrp == -pid)
- send_sig(sig,*p,priv);
-}
-
-int sys_kill(int pid,int sig)
-{
- do_kill(pid,sig,!(current->uid || current->euid));
- return 0;
-}
-
-int do_exit(long code)
-{
- int i;
-
- free_page_tables(get_base(current->ldt[1]),get_limit(0x0f));
- free_page_tables(get_base(current->ldt[2]),get_limit(0x17));
- for (i=0 ; ifather == current->pid)
- task[i]->father = 0;
- for (i=0 ; ifilp[i])
- sys_close(i);
- iput(current->pwd);
- current->pwd=NULL;
- iput(current->root);
- current->root=NULL;
- if (current->leader && current->tty >= 0)
- tty_table[current->tty].pgrp = 0;
- if (last_task_used_math == current)
- last_task_used_math = NULL;
- if (current->father) {
- current->state = TASK_ZOMBIE;
- do_kill(current->father,SIGCHLD,1);
- current->exit_code = code;
- } else
- release(current);
- schedule();
- return (-1); /* just to suppress warnings */
-}
-
-int sys_exit(int error_code)
-{
- return do_exit((error_code&0xff)<<8);
-}
-
-int sys_waitpid(pid_t pid,int * stat_addr, int options)
-{
- int flag=0;
- struct task_struct ** p;
-
- verify_area(stat_addr,4);
-repeat:
- for(p = &LAST_TASK ; p > &FIRST_TASK ; --p)
- if (*p && *p != current &&
- (pid==-1 || (*p)->pid==pid ||
- (pid==0 && (*p)->pgrp==current->pgrp) ||
- (pid<0 && (*p)->pgrp==-pid)))
- if ((*p)->father == current->pid) {
- flag=1;
- if ((*p)->state==TASK_ZOMBIE) {
- put_fs_long((*p)->exit_code,
- (unsigned long *) stat_addr);
- current->cutime += (*p)->utime;
- current->cstime += (*p)->stime;
- flag = (*p)->pid;
- release(*p);
- return flag;
- }
- }
- if (flag) {
- if (options & WNOHANG)
- return 0;
- sys_pause();
- if (!(current->signal &= ~(1<<(SIGCHLD-1))))
- goto repeat;
- else
- return -EINTR;
- }
- return -ECHILD;
-}
-
-
-/*
- * 'fork.c' contains the help-routines for the 'fork' system call
- * (see also system_call.s), and some misc functions ('verify_area').
- * Fork is rather simple, once you get the hang of it, but the memory
- * management can be a bitch. See 'mm/mm.c': 'copy_page_tables()'
- */
-#include
-
-#include
-#include
-#include
-#include
-
-extern void write_verify(unsigned long address);
-
-long last_pid=0;
-
-void verify_area(void * addr,int size)
-{
- unsigned long start;
-
- start = (unsigned long) addr;
- size += start & 0xfff;
- start &= 0xfffff000;
- start += get_base(current->ldt[2]);
- while (size>0) {
- size -= 4096;
- write_verify(start);
- start += 4096;
- }
-}
-
-int copy_mem(int nr,struct task_struct * p)
-{
- unsigned long old_data_base,new_data_base,data_limit;
- unsigned long old_code_base,new_code_base,code_limit;
-
- code_limit=get_limit(0x0f);
- data_limit=get_limit(0x17);
- old_code_base = get_base(current->ldt[1]);
- old_data_base = get_base(current->ldt[2]);
- if (old_data_base != old_code_base)
- panic("We don't support separate I&D");
- if (data_limit < code_limit)
- panic("Bad data_limit");
- new_data_base = new_code_base = nr * 0x4000000;
- set_base(p->ldt[1],new_code_base);
- set_base(p->ldt[2],new_data_base);
- if (copy_page_tables(old_data_base,new_data_base,data_limit)) {
- free_page_tables(new_data_base,data_limit);
- return -ENOMEM;
- }
- return 0;
-}
-
-/*
- * Ok, this is the main fork-routine. It copies the system process
- * information (task[nr]) and sets up the necessary registers. It
- * also copies the data segment in it's entirety.
- */
-int copy_process(int nr,long ebp,long edi,long esi,long gs,long none,
- long ebx,long ecx,long edx,
- long fs,long es,long ds,
- long eip,long cs,long eflags,long esp,long ss)
-{
- struct task_struct *p;
- int i;
- struct file *f;
-
- p = (struct task_struct *) get_free_page();
- if (!p)
- return -EAGAIN;
- *p = *current; /* NOTE! this doesn't copy the supervisor stack */
- p->state = TASK_RUNNING;
- p->pid = last_pid;
- p->father = current->pid;
- p->counter = p->priority;
- p->signal = 0;
- p->alarm = 0;
- p->leader = 0; /* process leadership doesn't inherit */
- p->utime = p->stime = 0;
- p->cutime = p->cstime = 0;
- p->start_time = jiffies;
- p->tss.back_link = 0;
- p->tss.esp0 = PAGE_SIZE + (long) p;
- p->tss.ss0 = 0x10;
- p->tss.eip = eip;
- p->tss.eflags = eflags;
- p->tss.eax = 0;
- p->tss.ecx = ecx;
- p->tss.edx = edx;
- p->tss.ebx = ebx;
- p->tss.esp = esp;
- p->tss.ebp = ebp;
- p->tss.esi = esi;
- p->tss.edi = edi;
- p->tss.es = es & 0xffff;
- p->tss.cs = cs & 0xffff;
- p->tss.ss = ss & 0xffff;
- p->tss.ds = ds & 0xffff;
- p->tss.fs = fs & 0xffff;
- p->tss.gs = gs & 0xffff;
- p->tss.ldt = _LDT(nr);
- p->tss.trace_bitmap = 0x80000000;
- if (last_task_used_math == current)
- __asm__("fnsave %0"::"m" (p->tss.i387));
- if (copy_mem(nr,p)) {
- free_page((long) p);
- return -EAGAIN;
- }
- for (i=0; ifilp[i])
- f->f_count++;
- if (current->pwd)
- current->pwd->i_count++;
- if (current->root)
- current->root->i_count++;
- set_tss_desc(gdt+(nr<<1)+FIRST_TSS_ENTRY,&(p->tss));
- set_ldt_desc(gdt+(nr<<1)+FIRST_LDT_ENTRY,&(p->ldt));
- task[nr] = p; /* do this last, just in case */
- return last_pid;
-}
-
-int find_empty_process(void)
-{
- int i;
-
- repeat:
- if ((++last_pid)<0) last_pid=1;
- for(i=0 ; ipid == last_pid) goto repeat;
- for(i=1 ; i
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-
-/*
- * This code handles all hd-interrupts, and read/write requests to
- * the hard-disk. It is relatively straigthforward (not obvious maybe,
- * but interrupts never are), while still being efficient, and never
- * disabling interrupts (except to overcome possible race-condition).
- * The elevator block-seek algorithm doesn't need to disable interrupts
- * due to clever programming.
- */
-
-/* Max read/write errors/sector */
-#define MAX_ERRORS 5
-#define MAX_HD 2
-#define NR_REQUEST 32
-
-/*
- * This struct defines the HD's and their types.
- * Currently defined for CP3044's, ie a modified
- * type 17.
- */
-static struct hd_i_struct{
- int head,sect,cyl,wpcom,lzone,ctl;
- } hd_info[]= { HD_TYPE };
-
-#define NR_HD ((sizeof (hd_info))/(sizeof (struct hd_i_struct)))
-
-static struct hd_struct {
- long start_sect;
- long nr_sects;
-} hd[5*MAX_HD]={{0,0},};
-
-static struct hd_request {
- int hd; /* -1 if no request */
- int nsector;
- int sector;
- int head;
- int cyl;
- int cmd;
- int errors;
- struct buffer_head * bh;
- struct hd_request * next;
-} request[NR_REQUEST];
-
-#define IN_ORDER(s1,s2) \
-((s1)->hd<(s2)->hd || (s1)->hd==(s2)->hd && \
-((s1)->cyl<(s2)->cyl || (s1)->cyl==(s2)->cyl && \
-((s1)->head<(s2)->head || (s1)->head==(s2)->head && \
-((s1)->sector<(s2)->sector))))
-
-static struct hd_request * this_request = NULL;
-
-static int sorting=0;
-
-static void do_request(void);
-static void reset_controller(void);
-static void rw_abs_hd(int rw,unsigned int nr,unsigned int sec,unsigned int head,
- unsigned int cyl,struct buffer_head * bh);
-void hd_init(void);
-
-#define port_read(port,buf,nr) \
-__asm__("cld;rep;insw"::"d" (port),"D" (buf),"c" (nr):"cx","di")
-
-#define port_write(port,buf,nr) \
-__asm__("cld;rep;outsw"::"d" (port),"S" (buf),"c" (nr):"cx","si")
-
-extern void hd_interrupt(void);
-
-static struct task_struct * wait_for_request=NULL;
-
-static inline void lock_buffer(struct buffer_head * bh)
-{
- if (bh->b_lock)
- printk("hd.c: buffer multiply locked\n");
- bh->b_lock=1;
-}
-
-static inline void unlock_buffer(struct buffer_head * bh)
-{
- if (!bh->b_lock)
- printk("hd.c: free buffer being unlocked\n");
- bh->b_lock=0;
- wake_up(&bh->b_wait);
-}
-
-static inline void wait_on_buffer(struct buffer_head * bh)
-{
- cli();
- while (bh->b_lock)
- sleep_on(&bh->b_wait);
- sti();
-}
-
-void rw_hd(int rw, struct buffer_head * bh)
-{
- unsigned int block,dev;
- unsigned int sec,head,cyl;
-
- block = bh->b_blocknr << 1;
- dev = MINOR(bh->b_dev);
- if (dev >= 5*NR_HD || block+2 > hd[dev].nr_sects)
- return;
- block += hd[dev].start_sect;
- dev /= 5;
- __asm__("divl %4":"=a" (block),"=d" (sec):"0" (block),"1" (0),
- "r" (hd_info[dev].sect));
- __asm__("divl %4":"=a" (cyl),"=d" (head):"0" (block),"1" (0),
- "r" (hd_info[dev].head));
- rw_abs_hd(rw,dev,sec+1,head,cyl,bh);
-}
-
-/* This may be used only once, enforced by 'static int callable' */
-int sys_setup(void)
-{
- static int callable = 1;
- int i,drive;
- struct partition *p;
-
- if (!callable)
- return -1;
- callable = 0;
- for (drive=0 ; driveb_uptodate) {
- printk("Unable to read partition table of drive %d\n\r",
- drive);
- panic("");
- }
- if (start_buffer->b_data[510] != 0x55 || (unsigned char)
- start_buffer->b_data[511] != 0xAA) {
- printk("Bad partition table on drive %d\n\r",drive);
- panic("");
- }
- p = 0x1BE + (void *)start_buffer->b_data;
- for (i=1;i<5;i++,p++) {
- hd[i+5*drive].start_sect = p->start_sect;
- hd[i+5*drive].nr_sects = p->nr_sects;
- }
- }
- printk("Partition table%s ok.\n\r",(NR_HD>1)?"s":"");
- mount_root();
- return (0);
-}
-
-/*
- * This is the pointer to a routine to be executed at every hd-interrupt.
- * Interesting way of doing things, but should be rather practical.
- */
-void (*do_hd)(void) = NULL;
-
-static int controller_ready(void)
-{
- int retries=1000;
-
- while (--retries && (inb(HD_STATUS)&0xc0)!=0x40);
- return (retries);
-}
-
-static int win_result(void)
-{
- int i=inb(HD_STATUS);
-
- if ((i & (BUSY_STAT | READY_STAT | WRERR_STAT | SEEK_STAT | ERR_STAT))
- == (READY_STAT | SEEK_STAT))
- return(0); /* ok */
- if (i&1) i=inb(HD_ERROR);
- return (1);
-}
-
-static void hd_out(unsigned int drive,unsigned int nsect,unsigned int sect,
- unsigned int head,unsigned int cyl,unsigned int cmd,
- void (*intr_addr)(void))
-{
- register int port asm("dx");
-
- if (drive>1 || head>15)
- panic("Trying to write bad sector");
- if (!controller_ready())
- panic("HD controller not ready");
- do_hd = intr_addr;
- outb(_CTL,HD_CMD);
- port=HD_DATA;
- outb_p(_WPCOM,++port);
- outb_p(nsect,++port);
- outb_p(sect,++port);
- outb_p(cyl,++port);
- outb_p(cyl>>8,++port);
- outb_p(0xA0|(drive<<4)|head,++port);
- outb(cmd,++port);
-}
-
-static int drive_busy(void)
-{
- unsigned int i;
-
- for (i = 0; i < 100000; i++)
- if (READY_STAT == (inb(HD_STATUS) & (BUSY_STAT | READY_STAT)))
- break;
- i = inb(HD_STATUS);
- i &= BUSY_STAT | READY_STAT | SEEK_STAT;
- if (i == READY_STAT | SEEK_STAT)
- return(0);
- printk("HD controller times out\n\r");
- return(1);
-}
-
-static void reset_controller(void)
-{
- int i;
-
- outb(4,HD_CMD);
- for(i = 0; i < 1000; i++) nop();
- outb(0,HD_CMD);
- for(i = 0; i < 10000 && drive_busy(); i++) /* nothing */;
- if (drive_busy())
- printk("HD-controller still busy\n\r");
- if((i = inb(ERR_STAT)) != 1)
- printk("HD-controller reset failed: %02x\n\r",i);
-}
-
-static void reset_hd(int nr)
-{
- reset_controller();
- hd_out(nr,_SECT,_SECT,_HEAD-1,_CYL,WIN_SPECIFY,&do_request);
-}
-
-void unexpected_hd_interrupt(void)
-{
- panic("Unexpected HD interrupt\n\r");
-}
-
-static void bad_rw_intr(void)
-{
- int i = this_request->hd;
-
- if (this_request->errors++ >= MAX_ERRORS) {
- this_request->bh->b_uptodate = 0;
- unlock_buffer(this_request->bh);
- wake_up(&wait_for_request);
- this_request->hd = -1;
- this_request=this_request->next;
- }
- reset_hd(i);
-}
-
-static void read_intr(void)
-{
- if (win_result()) {
- bad_rw_intr();
- return;
- }
- port_read(HD_DATA,this_request->bh->b_data+
- 512*(this_request->nsector&1),256);
- this_request->errors = 0;
- if (--this_request->nsector)
- return;
- this_request->bh->b_uptodate = 1;
- this_request->bh->b_dirt = 0;
- wake_up(&wait_for_request);
- unlock_buffer(this_request->bh);
- this_request->hd = -1;
- this_request=this_request->next;
- do_request();
-}
-
-static void write_intr(void)
-{
- if (win_result()) {
- bad_rw_intr();
- return;
- }
- if (--this_request->nsector) {
- port_write(HD_DATA,this_request->bh->b_data+512,256);
- return;
- }
- this_request->bh->b_uptodate = 1;
- this_request->bh->b_dirt = 0;
- wake_up(&wait_for_request);
- unlock_buffer(this_request->bh);
- this_request->hd = -1;
- this_request=this_request->next;
- do_request();
-}
-
-static void do_request(void)
-{
- int i,r;
-
- if (sorting)
- return;
- if (!this_request) {
- do_hd=NULL;
- return;
- }
- if (this_request->cmd == WIN_WRITE) {
- hd_out(this_request->hd,this_request->nsector,this_request->
- sector,this_request->head,this_request->cyl,
- this_request->cmd,&write_intr);
- for(i=0 ; i<3000 && !(r=inb_p(HD_STATUS)&DRQ_STAT) ; i++)
- /* nothing */ ;
- if (!r) {
- reset_hd(this_request->hd);
- return;
- }
- port_write(HD_DATA,this_request->bh->b_data+
- 512*(this_request->nsector&1),256);
- } else if (this_request->cmd == WIN_READ) {
- hd_out(this_request->hd,this_request->nsector,this_request->
- sector,this_request->head,this_request->cyl,
- this_request->cmd,&read_intr);
- } else
- panic("unknown hd-command");
-}
-
-/*
- * add-request adds a request to the linked list.
- * It sets the 'sorting'-variable when doing something
- * that interrupts shouldn't touch.
- */
-static void add_request(struct hd_request * req)
-{
- struct hd_request * tmp;
-
- if (req->nsector != 2)
- panic("nsector!=2 not implemented");
-/*
- * Not to mess up the linked lists, we never touch the two first
- * entries (not this_request, as it is used by current interrups,
- * and not this_request->next, as it can be assigned to this_request).
- * This is not too high a price to pay for the ability of not
- * disabling interrupts.
- */
- sorting=1;
- if (!(tmp=this_request))
- this_request=req;
- else {
- if (!(tmp->next))
- tmp->next=req;
- else {
- tmp=tmp->next;
- for ( ; tmp->next ; tmp=tmp->next)
- if ((IN_ORDER(tmp,req) ||
- !IN_ORDER(tmp,tmp->next)) &&
- IN_ORDER(req,tmp->next))
- break;
- req->next=tmp->next;
- tmp->next=req;
- }
- }
- sorting=0;
-/*
- * NOTE! As a result of sorting, the interrupts may have died down,
- * as they aren't redone due to locking with sorting=1. They might
- * also never have started, if this is the first request in the queue,
- * so we restart them if necessary.
- */
- if (!do_hd)
- do_request();
-}
-
-void rw_abs_hd(int rw,unsigned int nr,unsigned int sec,unsigned int head,
- unsigned int cyl,struct buffer_head * bh)
-{
- struct hd_request * req;
-
- if (rw!=READ && rw!=WRITE)
- panic("Bad hd command, must be R/W");
- lock_buffer(bh);
-repeat:
- for (req=0+request ; reqhd<0)
- break;
- if (req==NR_REQUEST+request) {
- sleep_on(&wait_for_request);
- goto repeat;
- }
- req->hd=nr;
- req->nsector=2;
- req->sector=sec;
- req->head=head;
- req->cyl=cyl;
- req->cmd = ((rw==READ)?WIN_READ:WIN_WRITE);
- req->bh=bh;
- req->errors=0;
- req->next=NULL;
- add_request(req);
- wait_on_buffer(bh);
-}
-
-void hd_init(void)
-{
- int i;
-
- for (i=0 ; i
-
-/*
- * This isn't the library routine, it is only used in the kernel.
- * as such, we don't care about years<1970 etc, but assume everything
- * is ok. Similarly, TZ etc is happily ignored. We just do everything
- * as easily as possible. Let's find something public for the library
- * routines (although I think minix times is public).
- */
-/*
- * PS. I hate whoever though up the year 1970 - couldn't they have gotten
- * a leap-year instead? I also hate Gregorius, pope or no. I'm grumpy.
- */
-#define MINUTE 60
-#define HOUR (60*MINUTE)
-#define DAY (24*HOUR)
-#define YEAR (365*DAY)
-
-/* interestingly, we assume leap-years */
-static int month[12] = {
- 0,
- DAY*(31),
- DAY*(31+29),
- DAY*(31+29+31),
- DAY*(31+29+31+30),
- DAY*(31+29+31+30+31),
- DAY*(31+29+31+30+31+30),
- DAY*(31+29+31+30+31+30+31),
- DAY*(31+29+31+30+31+30+31+31),
- DAY*(31+29+31+30+31+30+31+31+30),
- DAY*(31+29+31+30+31+30+31+31+30+31),
- DAY*(31+29+31+30+31+30+31+31+30+31+30)
-};
-
-long kernel_mktime(struct tm * tm)
-{
- long res;
- int year;
-
- year = tm->tm_year - 70;
-/* magic offsets (y+1) needed to get leapyears right.*/
- res = YEAR*year + DAY*((year+1)/4);
- res += month[tm->tm_mon];
-/* and (y+2) here. If it wasn't a leap-year, we have to adjust */
- if (tm->tm_mon>1 && ((year+2)%4))
- res -= DAY;
- res += DAY*(tm->tm_mday-1);
- res += HOUR*tm->tm_hour;
- res += MINUTE*tm->tm_min;
- res += tm->tm_sec;
- return res;
-}
-/*
- * This function is used through-out the kernel (includeinh mm and fs)
- * to indicate a major problem.
- */
-#include
-
-volatile void panic(const char * s)
-{
- printk("Kernel panic: %s\n\r",s);
- for(;;);
-}
-/*
- * When in kernel-mode, we cannot use printf, as fs is liable to
- * point to 'interesting' things. Make a printf with fs-saving, and
- * all is well.
- */
-#include
-#include
-
-#include
-
-static char buf[1024];
-
-int printk(const char *fmt, ...)
-{
- va_list args;
- int i;
-
- va_start(args, fmt);
- i=vsprintf(buf,fmt,args);
- va_end(args);
- __asm__("push %%fs\n\t"
- "push %%ds\n\t"
- "pop %%fs\n\t"
- "pushl %0\n\t"
- "pushl $_buf\n\t"
- "pushl $0\n\t"
- "call _tty_write\n\t"
- "addl $8,%%esp\n\t"
- "popl %0\n\t"
- "pop %%fs"
- ::"r" (i):"ax","cx","dx");
- return i;
-}
-/*
- * 'sched.c' is the main kernel file. It contains scheduling primitives
- * (sleep_on, wakeup, schedule etc) as well as a number of simple system
- * call functions (type getpid(), which just extracts a field from
- * current-task
- */
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-
-#define LATCH (1193180/HZ)
-
-extern void mem_use(void);
-
-extern int timer_interrupt(void);
-extern int system_call(void);
-
-union task_union {
- struct task_struct task;
- char stack[PAGE_SIZE];
-};
-
-static union task_union init_task = {INIT_TASK,};
-
-long volatile jiffies=0;
-long startup_time=0;
-struct task_struct *current = &(init_task.task), *last_task_used_math = NULL;
-
-struct task_struct * task[NR_TASKS] = {&(init_task.task), };
-
-long user_stack [ PAGE_SIZE>>2 ] ;
-
-struct {
- long * a;
- short b;
- } stack_start = { & user_stack [PAGE_SIZE>>2] , 0x10 };
-/*
- * 'math_state_restore()' saves the current math information in the
- * old math state array, and gets the new ones from the current task
- */
-void math_state_restore()
-{
- if (last_task_used_math)
- __asm__("fnsave %0"::"m" (last_task_used_math->tss.i387));
- if (current->used_math)
- __asm__("frstor %0"::"m" (current->tss.i387));
- else {
- __asm__("fninit"::);
- current->used_math=1;
- }
- last_task_used_math=current;
-}
-
-/*
- * 'schedule()' is the scheduler function. This is GOOD CODE! There
- * probably won't be any reason to change this, as it should work well
- * in all circumstances (ie gives IO-bound processes good response etc).
- * The one thing you might take a look at is the signal-handler code here.
- *
- * NOTE!! Task 0 is the 'idle' task, which gets called when no other
- * tasks can run. It can not be killed, and it cannot sleep. The 'state'
- * information in task[0] is never used.
- */
-void schedule(void)
-{
- int i,next,c;
- struct task_struct ** p;
-
-/* check alarm, wake up any interruptible tasks that have got a signal */
-
- for(p = &LAST_TASK ; p > &FIRST_TASK ; --p)
- if (*p) {
- if ((*p)->alarm && (*p)->alarm < jiffies) {
- (*p)->signal |= (1<<(SIGALRM-1));
- (*p)->alarm = 0;
- }
- if ((*p)->signal && (*p)->state==TASK_INTERRUPTIBLE)
- (*p)->state=TASK_RUNNING;
- }
-
-/* this is the scheduler proper: */
-
- while (1) {
- c = -1;
- next = 0;
- i = NR_TASKS;
- p = &task[NR_TASKS];
- while (--i) {
- if (!*--p)
- continue;
- if ((*p)->state == TASK_RUNNING && (*p)->counter > c)
- c = (*p)->counter, next = i;
- }
- if (c) break;
- for(p = &LAST_TASK ; p > &FIRST_TASK ; --p)
- if (*p)
- (*p)->counter = ((*p)->counter >> 1) +
- (*p)->priority;
- }
- switch_to(next);
-}
-
-int sys_pause(void)
-{
- current->state = TASK_INTERRUPTIBLE;
- schedule();
- return 0;
-}
-
-void sleep_on(struct task_struct **p)
-{
- struct task_struct *tmp;
-
- if (!p)
- return;
- if (current == &(init_task.task))
- panic("task[0] trying to sleep");
- tmp = *p;
- *p = current;
- current->state = TASK_UNINTERRUPTIBLE;
- schedule();
- if (tmp)
- tmp->state=0;
-}
-
-void interruptible_sleep_on(struct task_struct **p)
-{
- struct task_struct *tmp;
-
- if (!p)
- return;
- if (current == &(init_task.task))
- panic("task[0] trying to sleep");
- tmp=*p;
- *p=current;
-repeat: current->state = TASK_INTERRUPTIBLE;
- schedule();
- if (*p && *p != current) {
- (**p).state=0;
- goto repeat;
- }
- *p=NULL;
- if (tmp)
- tmp->state=0;
-}
-
-void wake_up(struct task_struct **p)
-{
- if (p && *p) {
- (**p).state=0;
- *p=NULL;
- }
-}
-
-void do_timer(long cpl)
-{
- if (cpl)
- current->utime++;
- else
- current->stime++;
- if ((--current->counter)>0) return;
- current->counter=0;
- if (!cpl) return;
- schedule();
-}
-
-int sys_alarm(long seconds)
-{
- current->alarm = (seconds>0)?(jiffies+HZ*seconds):0;
- return seconds;
-}
-
-int sys_getpid(void)
-{
- return current->pid;
-}
-
-int sys_getppid(void)
-{
- return current->father;
-}
-
-int sys_getuid(void)
-{
- return current->uid;
-}
-
-int sys_geteuid(void)
-{
- return current->euid;
-}
-
-int sys_getgid(void)
-{
- return current->gid;
-}
-
-int sys_getegid(void)
-{
- return current->egid;
-}
-
-int sys_nice(long increment)
-{
- if (current->priority-increment>0)
- current->priority -= increment;
- return 0;
-}
-
-int sys_signal(long signal,long addr,long restorer)
-{
- long i;
-
- switch (signal) {
- case SIGHUP: case SIGINT: case SIGQUIT: case SIGILL:
- case SIGTRAP: case SIGABRT: case SIGFPE: case SIGUSR1:
- case SIGSEGV: case SIGUSR2: case SIGPIPE: case SIGALRM:
- case SIGCHLD:
- i=(long) current->sig_fn[signal-1];
- current->sig_fn[signal-1] = (fn_ptr) addr;
- current->sig_restorer = (fn_ptr) restorer;
- return i;
- default: return -1;
- }
-}
-
-void sched_init(void)
-{
- int i;
- struct desc_struct * p;
-
- set_tss_desc(gdt+FIRST_TSS_ENTRY,&(init_task.task.tss));
- set_ldt_desc(gdt+FIRST_LDT_ENTRY,&(init_task.task.ldt));
- p = gdt+2+FIRST_TSS_ENTRY;
- for(i=1;ia=p->b=0;
- p++;
- p->a=p->b=0;
- p++;
- }
- ltr(0);
- lldt(0);
- outb_p(0x36,0x43); /* binary, mode 3, LSB/MSB, ch 0 */
- outb_p(LATCH & 0xff , 0x40); /* LSB */
- outb(LATCH >> 8 , 0x40); /* MSB */
- set_intr_gate(0x20,&timer_interrupt);
- outb(inb_p(0x21)&~0x01,0x21);
- set_system_gate(0x80,&system_call);
-}
-/*
- * serial.c
- *
- * This module implements the rs232 io functions
- * void rs_write(struct tty_struct * queue);
- * void rs_init(void);
- * and all interrupts pertaining to serial IO.
- */
-
-#include
-#include
-#include
-#include
-
-#define WAKEUP_CHARS (TTY_BUF_SIZE/4)
-
-extern void rs1_interrupt(void);
-extern void rs2_interrupt(void);
-
-static void init(int port)
-{
- outb_p(0x80,port+3); /* set DLAB of line control reg */
- outb_p(0x30,port); /* LS of divisor (48 -> 2400 bps */
- outb_p(0x00,port+1); /* MS of divisor */
- outb_p(0x03,port+3); /* reset DLAB */
- outb_p(0x0b,port+4); /* set DTR,RTS, OUT_2 */
- outb_p(0x0d,port+1); /* enable all intrs but writes */
- (void)inb(port); /* read data port to reset things (?) */
-}
-
-void rs_init(void)
-{
- set_intr_gate(0x24,rs1_interrupt);
- set_intr_gate(0x23,rs2_interrupt);
- init(tty_table[1].read_q.data);
- init(tty_table[2].read_q.data);
- outb(inb_p(0x21)&0xE7,0x21);
-}
-
-/*
- * This routine gets called when tty_write has put something into
- * the write_queue. It must check wheter the queue is empty, and
- * set the interrupt register accordingly
- *
- * void _rs_write(struct tty_struct * tty);
- */
-void rs_write(struct tty_struct * tty)
-{
- cli();
- if (!EMPTY(tty->write_q))
- outb(inb_p(tty->write_q.data+1)|0x02,tty->write_q.data+1);
- sti();
-}
-#include
-
-#include
-#include
-#include
-#include
-#include
-#include
-
-int sys_ftime()
-{
- return -ENOSYS;
-}
-
-int sys_mknod()
-{
- return -ENOSYS;
-}
-
-int sys_break()
-{
- return -ENOSYS;
-}
-
-int sys_mount()
-{
- return -ENOSYS;
-}
-
-int sys_umount()
-{
- return -ENOSYS;
-}
-
-int sys_ustat(int dev,struct ustat * ubuf)
-{
- return -1;
-}
-
-int sys_ptrace()
-{
- return -ENOSYS;
-}
-
-int sys_stty()
-{
- return -ENOSYS;
-}
-
-int sys_gtty()
-{
- return -ENOSYS;
-}
-
-int sys_rename()
-{
- return -ENOSYS;
-}
-
-int sys_prof()
-{
- return -ENOSYS;
-}
-
-int sys_setgid(int gid)
-{
- if (current->euid && current->uid)
- if (current->gid==gid || current->sgid==gid)
- current->egid=gid;
- else
- return -EPERM;
- else
- current->gid=current->egid=gid;
- return 0;
-}
-
-int sys_acct()
-{
- return -ENOSYS;
-}
-
-int sys_phys()
-{
- return -ENOSYS;
-}
-
-int sys_lock()
-{
- return -ENOSYS;
-}
-
-int sys_mpx()
-{
- return -ENOSYS;
-}
-
-int sys_ulimit()
-{
- return -ENOSYS;
-}
-
-int sys_time(long * tloc)
-{
- int i;
-
- i = CURRENT_TIME;
- if (tloc) {
- verify_area(tloc,4);
- put_fs_long(i,(unsigned long *)tloc);
- }
- return i;
-}
-
-int sys_setuid(int uid)
-{
- if (current->euid && current->uid)
- if (uid==current->uid || current->suid==current->uid)
- current->euid=uid;
- else
- return -EPERM;
- else
- current->euid=current->uid=uid;
- return 0;
-}
-
-int sys_stime(long * tptr)
-{
- if (current->euid && current->uid)
- return -1;
- startup_time = get_fs_long((unsigned long *)tptr) - jiffies/HZ;
- return 0;
-}
-
-int sys_times(struct tms * tbuf)
-{
- if (!tbuf)
- return jiffies;
- verify_area(tbuf,sizeof *tbuf);
- put_fs_long(current->utime,(unsigned long *)&tbuf->tms_utime);
- put_fs_long(current->stime,(unsigned long *)&tbuf->tms_stime);
- put_fs_long(current->cutime,(unsigned long *)&tbuf->tms_cutime);
- put_fs_long(current->cstime,(unsigned long *)&tbuf->tms_cstime);
- return jiffies;
-}
-
-int sys_brk(unsigned long end_data_seg)
-{
- if (end_data_seg >= current->end_code &&
- end_data_seg < current->start_stack - 16384)
- current->brk = end_data_seg;
- return current->brk;
-}
-
-/*
- * This needs some heave checking ...
- * I just haven't get the stomach for it. I also don't fully
- * understand sessions/pgrp etc. Let somebody who does explain it.
- */
-int sys_setpgid(int pid, int pgid)
-{
- int i;
-
- if (!pid)
- pid = current->pid;
- if (!pgid)
- pgid = pid;
- for (i=0 ; ipid==pid) {
- if (task[i]->leader)
- return -EPERM;
- if (task[i]->session != current->session)
- return -EPERM;
- task[i]->pgrp = pgid;
- return 0;
- }
- return -ESRCH;
-}
-
-int sys_getpgrp(void)
-{
- return current->pgrp;
-}
-
-int sys_setsid(void)
-{
- if (current->uid && current->euid)
- return -EPERM;
- if (current->leader)
- return -EPERM;
- current->leader = 1;
- current->session = current->pgrp = current->pid;
- current->tty = -1;
- return current->pgrp;
-}
-
-int sys_uname(struct utsname * name)
-{
- static struct utsname thisname = {
- "linux .0","nodename","release ","version ","machine "
- };
- int i;
-
- if (!name) return -1;
- verify_area(name,sizeof *name);
- for(i=0;iumask;
-
- current->umask = mask & 0777;
- return (old);
-}
-/*
- * 'Traps.c' handles hardware traps and faults after we have saved some
- * state in 'asm.s'. Currently mostly a debugging-aid, will be extended
- * to mainly kill the offending process (probably by giving it a signal,
- * but possibly by killing it outright if necessary).
- */
-#include
-
-#include
-#include
-#include
-#include
-#include
-
-#define get_seg_byte(seg,addr) ({ \
-register char __res; \
-__asm__("push %%fs;mov %%ax,%%fs;movb %%fs:%2,%%al;pop %%fs" \
- :"=a" (__res):"0" (seg),"m" (*(addr))); \
-__res;})
-
-#define get_seg_long(seg,addr) ({ \
-register unsigned long __res; \
-__asm__("push %%fs;mov %%ax,%%fs;movl %%fs:%2,%%eax;pop %%fs" \
- :"=a" (__res):"0" (seg),"m" (*(addr))); \
-__res;})
-
-#define _fs() ({ \
-register unsigned short __res; \
-__asm__("mov %%fs,%%ax":"=a" (__res):); \
-__res;})
-
-int do_exit(long code);
-
-void page_exception(void);
-
-void divide_error(void);
-void debug(void);
-void nmi(void);
-void int3(void);
-void overflow(void);
-void bounds(void);
-void invalid_op(void);
-void device_not_available(void);
-void double_fault(void);
-void coprocessor_segment_overrun(void);
-void invalid_TSS(void);
-void segment_not_present(void);
-void stack_segment(void);
-void general_protection(void);
-void page_fault(void);
-void coprocessor_error(void);
-void reserved(void);
-
-static void die(char * str,long esp_ptr,long nr)
-{
- long * esp = (long *) esp_ptr;
- int i;
-
- printk("%s: %04x\n\r",str,nr&0xffff);
- printk("EIP:\t%04x:%p\nEFLAGS:\t%p\nESP:\t%04x:%p\n",
- esp[1],esp[0],esp[2],esp[4],esp[3]);
- printk("fs: %04x\n",_fs());
- printk("base: %p, limit: %p\n",get_base(current->ldt[1]),get_limit(0x17));
- if (esp[4] == 0x17) {
- printk("Stack: ");
- for (i=0;i<4;i++)
- printk("%p ",get_seg_long(0x17,i+(long *)esp[3]));
- printk("\n");
- }
- str(i);
- printk("Pid: %d, process nr: %d\n\r",current->pid,0xffff & i);
- for(i=0;i<10;i++)
- printk("%02x ",0xff & get_seg_byte(esp[1],(i+(char *)esp[0])));
- printk("\n\r");
- do_exit(11); /* play segment exception */
-}
-
-void do_double_fault(long esp, long error_code)
-{
- die("double fault",esp,error_code);
-}
-
-void do_general_protection(long esp, long error_code)
-{
- die("general protection",esp,error_code);
-}
-
-void do_divide_error(long esp, long error_code)
-{
- die("divide error",esp,error_code);
-}
-
-void do_int3(long * esp, long error_code,
- long fs,long es,long ds,
- long ebp,long esi,long edi,
- long edx,long ecx,long ebx,long eax)
-{
- int tr;
-
- __asm__("str %%ax":"=a" (tr):"0" (0));
- printk("eax\t\tebx\t\tecx\t\tedx\n\r%8x\t%8x\t%8x\t%8x\n\r",
- eax,ebx,ecx,edx);
- printk("esi\t\tedi\t\tebp\t\tesp\n\r%8x\t%8x\t%8x\t%8x\n\r",
- esi,edi,ebp,(long) esp);
- printk("\n\rds\tes\tfs\ttr\n\r%4x\t%4x\t%4x\t%4x\n\r",
- ds,es,fs,tr);
- printk("EIP: %8x CS: %4x EFLAGS: %8x\n\r",esp[0],esp[1],esp[2]);
-}
-
-void do_nmi(long esp, long error_code)
-{
- die("nmi",esp,error_code);
-}
-
-void do_debug(long esp, long error_code)
-{
- die("debug",esp,error_code);
-}
-
-void do_overflow(long esp, long error_code)
-{
- die("overflow",esp,error_code);
-}
-
-void do_bounds(long esp, long error_code)
-{
- die("bounds",esp,error_code);
-}
-
-void do_invalid_op(long esp, long error_code)
-{
- die("invalid operand",esp,error_code);
-}
-
-void do_device_not_available(long esp, long error_code)
-{
- die("device not available",esp,error_code);
-}
-
-void do_coprocessor_segment_overrun(long esp, long error_code)
-{
- die("coprocessor segment overrun",esp,error_code);
-}
-
-void do_invalid_TSS(long esp,long error_code)
-{
- die("invalid TSS",esp,error_code);
-}
-
-void do_segment_not_present(long esp,long error_code)
-{
- die("segment not present",esp,error_code);
-}
-
-void do_stack_segment(long esp,long error_code)
-{
- die("stack segment",esp,error_code);
-}
-
-void do_coprocessor_error(long esp, long error_code)
-{
- die("coprocessor error",esp,error_code);
-}
-
-void do_reserved(long esp, long error_code)
-{
- die("reserved (15,17-31) error",esp,error_code);
-}
-
-void trap_init(void)
-{
- int i;
-
- set_trap_gate(0,÷_error);
- set_trap_gate(1,&debug);
- set_trap_gate(2,&nmi);
- set_system_gate(3,&int3); /* int3-5 can be called from all */
- set_system_gate(4,&overflow);
- set_system_gate(5,&bounds);
- set_trap_gate(6,&invalid_op);
- set_trap_gate(7,&device_not_available);
- set_trap_gate(8,&double_fault);
- set_trap_gate(9,&coprocessor_segment_overrun);
- set_trap_gate(10,&invalid_TSS);
- set_trap_gate(11,&segment_not_present);
- set_trap_gate(12,&stack_segment);
- set_trap_gate(13,&general_protection);
- set_trap_gate(14,&page_fault);
- set_trap_gate(15,&reserved);
- set_trap_gate(16,&coprocessor_error);
- for (i=17;i<32;i++)
- set_trap_gate(i,&reserved);
-/* __asm__("movl $0x3ff000,%%eax\n\t"
- "movl %%eax,%%db0\n\t"
- "movl $0x000d0303,%%eax\n\t"
- "movl %%eax,%%db7"
- :::"ax");*/
-}
-
-/*
- * 'tty_io.c' gives an orthogonal feeling to tty's, be they consoles
- * or rs-channels. It also implements echoing, cooked mode etc (well,
- * not currently, but ...)
- */
-#include
-#include
-#include
-
-#define ALRMMASK (1<<(SIGALRM-1))
-
-#include
-#include
-#include
-#include
-
-#define _L_FLAG(tty,f) ((tty)->termios.c_lflag & f)
-#define _I_FLAG(tty,f) ((tty)->termios.c_iflag & f)
-#define _O_FLAG(tty,f) ((tty)->termios.c_oflag & f)
-
-#define L_CANON(tty) _L_FLAG((tty),ICANON)
-#define L_ISIG(tty) _L_FLAG((tty),ISIG)
-#define L_ECHO(tty) _L_FLAG((tty),ECHO)
-#define L_ECHOE(tty) _L_FLAG((tty),ECHOE)
-#define L_ECHOK(tty) _L_FLAG((tty),ECHOK)
-#define L_ECHOCTL(tty) _L_FLAG((tty),ECHOCTL)
-#define L_ECHOKE(tty) _L_FLAG((tty),ECHOKE)
-
-#define I_UCLC(tty) _I_FLAG((tty),IUCLC)
-#define I_NLCR(tty) _I_FLAG((tty),INLCR)
-#define I_CRNL(tty) _I_FLAG((tty),ICRNL)
-#define I_NOCR(tty) _I_FLAG((tty),IGNCR)
-
-#define O_POST(tty) _O_FLAG((tty),OPOST)
-#define O_NLCR(tty) _O_FLAG((tty),ONLCR)
-#define O_CRNL(tty) _O_FLAG((tty),OCRNL)
-#define O_NLRET(tty) _O_FLAG((tty),ONLRET)
-#define O_LCUC(tty) _O_FLAG((tty),OLCUC)
-
-struct tty_struct tty_table[] = {
- {
- {0,
- OPOST|ONLCR, /* change outgoing NL to CRNL */
- 0,
- ICANON | ECHO | ECHOCTL | ECHOKE,
- 0, /* console termio */
- INIT_C_CC},
- 0, /* initial pgrp */
- 0, /* initial stopped */
- con_write,
- {0,0,0,0,""}, /* console read-queue */
- {0,0,0,0,""}, /* console write-queue */
- {0,0,0,0,""} /* console secondary queue */
- },{
- {0, /*IGNCR*/
- OPOST | ONLRET, /* change outgoing NL to CR */
- B2400 | CS8,
- 0,
- 0,
- INIT_C_CC},
- 0,
- 0,
- rs_write,
- {0x3f8,0,0,0,""}, /* rs 1 */
- {0x3f8,0,0,0,""},
- {0,0,0,0,""}
- },{
- {0, /*IGNCR*/
- OPOST | ONLRET, /* change outgoing NL to CR */
- B2400 | CS8,
- 0,
- 0,
- INIT_C_CC},
- 0,
- 0,
- rs_write,
- {0x2f8,0,0,0,""}, /* rs 2 */
- {0x2f8,0,0,0,""},
- {0,0,0,0,""}
- }
-};
-
-/*
- * these are the tables used by the machine code handlers.
- * you can implement pseudo-tty's or something by changing
- * them. Currently not done.
- */
-struct tty_queue * table_list[]={
- &tty_table[0].read_q, &tty_table[0].write_q,
- &tty_table[1].read_q, &tty_table[1].write_q,
- &tty_table[2].read_q, &tty_table[2].write_q
- };
-
-void tty_init(void)
-{
- rs_init();
- con_init();
-}
-
-void tty_intr(struct tty_struct * tty, int signal)
-{
- int i;
-
- if (tty->pgrp <= 0)
- return;
- for (i=0;ipgrp==tty->pgrp)
- task[i]->signal |= 1<<(signal-1);
-}
-
-static void sleep_if_empty(struct tty_queue * queue)
-{
- cli();
- while (!current->signal && EMPTY(*queue))
- interruptible_sleep_on(&queue->proc_list);
- sti();
-}
-
-static void sleep_if_full(struct tty_queue * queue)
-{
- if (!FULL(*queue))
- return;
- cli();
- while (!current->signal && LEFT(*queue)<128)
- interruptible_sleep_on(&queue->proc_list);
- sti();
-}
-
-void copy_to_cooked(struct tty_struct * tty)
-{
- signed char c;
-
- while (!EMPTY(tty->read_q) && !FULL(tty->secondary)) {
- GETCH(tty->read_q,c);
- if (c==13)
- if (I_CRNL(tty))
- c=10;
- else if (I_NOCR(tty))
- continue;
- else ;
- else if (c==10 && I_NLCR(tty))
- c=13;
- if (I_UCLC(tty))
- c=tolower(c);
- if (L_CANON(tty)) {
- if (c==ERASE_CHAR(tty)) {
- if (EMPTY(tty->secondary) ||
- (c=LAST(tty->secondary))==10 ||
- c==EOF_CHAR(tty))
- continue;
- if (L_ECHO(tty)) {
- if (c<32)
- PUTCH(127,tty->write_q);
- PUTCH(127,tty->write_q);
- tty->write(tty);
- }
- DEC(tty->secondary.head);
- continue;
- }
- if (c==STOP_CHAR(tty)) {
- tty->stopped=1;
- continue;
- }
- if (c==START_CHAR(tty)) {
- tty->stopped=0;
- continue;
- }
- }
- if (!L_ISIG(tty)) {
- if (c==INTR_CHAR(tty)) {
- tty_intr(tty,SIGINT);
- continue;
- }
- }
- if (c==10 || c==EOF_CHAR(tty))
- tty->secondary.data++;
- if (L_ECHO(tty)) {
- if (c==10) {
- PUTCH(10,tty->write_q);
- PUTCH(13,tty->write_q);
- } else if (c<32) {
- if (L_ECHOCTL(tty)) {
- PUTCH('^',tty->write_q);
- PUTCH(c+64,tty->write_q);
- }
- } else
- PUTCH(c,tty->write_q);
- tty->write(tty);
- }
- PUTCH(c,tty->secondary);
- }
- wake_up(&tty->secondary.proc_list);
-}
-
-int tty_read(unsigned channel, char * buf, int nr)
-{
- struct tty_struct * tty;
- char c, * b=buf;
- int minimum,time,flag=0;
- long oldalarm;
-
- if (channel>2 || nr<0) return -1;
- tty = &tty_table[channel];
- oldalarm = current->alarm;
- time = (unsigned) 10*tty->termios.c_cc[VTIME];
- minimum = (unsigned) tty->termios.c_cc[VMIN];
- if (time && !minimum) {
- minimum=1;
- if (flag=(!oldalarm || time+jiffiesalarm = time+jiffies;
- }
- if (minimum>nr)
- minimum=nr;
- while (nr>0) {
- if (flag && (current->signal & ALRMMASK)) {
- current->signal &= ~ALRMMASK;
- break;
- }
- if (current->signal)
- break;
- if (EMPTY(tty->secondary) || (L_CANON(tty) &&
- !tty->secondary.data && LEFT(tty->secondary)>20)) {
- sleep_if_empty(&tty->secondary);
- continue;
- }
- do {
- GETCH(tty->secondary,c);
- if (c==EOF_CHAR(tty) || c==10)
- tty->secondary.data--;
- if (c==EOF_CHAR(tty) && L_CANON(tty))
- return (b-buf);
- else {
- put_fs_byte(c,b++);
- if (!--nr)
- break;
- }
- } while (nr>0 && !EMPTY(tty->secondary));
- if (time && !L_CANON(tty))
- if (flag=(!oldalarm || time+jiffiesalarm = time+jiffies;
- else
- current->alarm = oldalarm;
- if (L_CANON(tty)) {
- if (b-buf)
- break;
- } else if (b-buf >= minimum)
- break;
- }
- current->alarm = oldalarm;
- if (current->signal && !(b-buf))
- return -EINTR;
- return (b-buf);
-}
-
-int tty_write(unsigned channel, char * buf, int nr)
-{
- static cr_flag=0;
- struct tty_struct * tty;
- char c, *b=buf;
-
- if (channel>2 || nr<0) return -1;
- tty = channel + tty_table;
- while (nr>0) {
- sleep_if_full(&tty->write_q);
- if (current->signal)
- break;
- while (nr>0 && !FULL(tty->write_q)) {
- c=get_fs_byte(b);
- if (O_POST(tty)) {
- if (c=='\r' && O_CRNL(tty))
- c='\n';
- else if (c=='\n' && O_NLRET(tty))
- c='\r';
- if (c=='\n' && !cr_flag && O_NLCR(tty)) {
- cr_flag = 1;
- PUTCH(13,tty->write_q);
- continue;
- }
- if (O_LCUC(tty))
- c=toupper(c);
- }
- b++; nr--;
- cr_flag = 0;
- PUTCH(c,tty->write_q);
- }
- tty->write(tty);
- if (nr>0)
- schedule();
- }
- return (b-buf);
-}
-
-/*
- * Jeh, sometimes I really like the 386.
- * This routine is called from an interrupt,
- * and there should be absolutely no problem
- * with sleeping even in an interrupt (I hope).
- * Of course, if somebody proves me wrong, I'll
- * hate intel for all time :-). We'll have to
- * be careful and see to reinstating the interrupt
- * chips before calling this, though.
- */
-void do_tty_interrupt(int tty)
-{
- copy_to_cooked(tty_table+tty);
-}
-/* vsprintf.c -- Lars Wirzenius & Linus Torvalds. */
-/*
- * Wirzenius wrote this portably, Torvalds fucked it up :-)
- */
-
-#include
-#include
-
-/* we use this so that we can do without the ctype library */
-#define is_digit(c) ((c) >= '0' && (c) <= '9')
-
-static int skip_atoi(const char **s)
-{
- int i=0;
-
- while (is_digit(**s))
- i = i*10 + *((*s)++) - '0';
- return i;
-}
-
-#define ZEROPAD 1 /* pad with zero */
-#define SIGN 2 /* unsigned/signed long */
-#define PLUS 4 /* show plus */
-#define SPACE 8 /* space if plus */
-#define LEFT 16 /* left justified */
-#define SPECIAL 32 /* 0x */
-#define SMALL 64 /* use 'abcdef' instead of 'ABCDEF' */
-
-#define do_div(n,base) ({ \
-int __res; \
-__asm__("divl %4":"=a" (n),"=d" (__res):"0" (n),"1" (0),"r" (base)); \
-__res; })
-
-static char * number(char * str, int num, int base, int size, int precision
- ,int type)
-{
- char c,sign,tmp[36];
- const char *digits="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
- int i;
-
- if (type&SMALL) digits="0123456789abcdefghijklmnopqrstuvwxyz";
- if (type&LEFT) type &= ~ZEROPAD;
- if (base<2 || base>36)
- return 0;
- c = (type & ZEROPAD) ? '0' : ' ' ;
- if (type&SIGN && num<0) {
- sign='-';
- num = -num;
- } else
- sign=(type&PLUS) ? '+' : ((type&SPACE) ? ' ' : 0);
- if (sign) size--;
- if (type&SPECIAL)
- if (base==16) size -= 2;
- else if (base==8) size--;
- i=0;
- if (num==0)
- tmp[i++]='0';
- else while (num!=0)
- tmp[i++]=digits[do_div(num,base)];
- if (i>precision) precision=i;
- size -= precision;
- if (!(type&(ZEROPAD+LEFT)))
- while(size-->0)
- *str++ = ' ';
- if (sign)
- *str++ = sign;
- if (type&SPECIAL)
- if (base==8)
- *str++ = '0';
- else if (base==16) {
- *str++ = '0';
- *str++ = digits[33];
- }
- if (!(type&LEFT))
- while(size-->0)
- *str++ = c;
- while(i0)
- *str++ = tmp[i];
- while(size-->0)
- *str++ = ' ';
- return str;
-}
-
-int vsprintf(char *buf, const char *fmt, va_list args)
-{
- int len;
- int i;
- char * str;
- char *s;
- int *ip;
-
- int flags; /* flags to number() */
-
- int field_width; /* width of output field */
- int precision; /* min. # of digits for integers; max
- number of chars for from string */
- int qualifier; /* 'h', 'l', or 'L' for integer fields */
-
- for (str=buf ; *fmt ; ++fmt) {
- if (*fmt != '%') {
- *str++ = *fmt;
- continue;
- }
-
- /* process flags */
- flags = 0;
- repeat:
- ++fmt; /* this also skips first '%' */
- switch (*fmt) {
- case '-': flags |= LEFT; goto repeat;
- case '+': flags |= PLUS; goto repeat;
- case ' ': flags |= SPACE; goto repeat;
- case '#': flags |= SPECIAL; goto repeat;
- case '0': flags |= ZEROPAD; goto repeat;
- }
-
- /* get field width */
- field_width = -1;
- if (is_digit(*fmt))
- field_width = skip_atoi(&fmt);
- else if (*fmt == '*') {
- /* it's the next argument */
- field_width = va_arg(args, int);
- if (field_width < 0) {
- field_width = -field_width;
- flags |= LEFT;
- }
- }
-
- /* get the precision */
- precision = -1;
- if (*fmt == '.') {
- ++fmt;
- if (is_digit(*fmt))
- precision = skip_atoi(&fmt);
- else if (*fmt == '*') {
- /* it's the next argument */
- precision = va_arg(args, int);
- }
- if (precision < 0)
- precision = 0;
- }
-
- /* get the conversion qualifier */
- qualifier = -1;
- if (*fmt == 'h' || *fmt == 'l' || *fmt == 'L') {
- qualifier = *fmt;
- ++fmt;
- }
-
- switch (*fmt) {
- case 'c':
- if (!(flags & LEFT))
- while (--field_width > 0)
- *str++ = ' ';
- *str++ = (unsigned char) va_arg(args, int);
- while (--field_width > 0)
- *str++ = ' ';
- break;
-
- case 's':
- s = va_arg(args, char *);
- len = strlen(s);
- if (precision < 0)
- precision = len;
- else if (len > precision)
- len = precision;
-
- if (!(flags & LEFT))
- while (len < field_width--)
- *str++ = ' ';
- for (i = 0; i < len; ++i)
- *str++ = *s++;
- while (len < field_width--)
- *str++ = ' ';
- break;
-
- case 'o':
- str = number(str, va_arg(args, unsigned long), 8,
- field_width, precision, flags);
- break;
-
- case 'p':
- if (field_width == -1) {
- field_width = 8;
- flags |= ZEROPAD;
- }
- str = number(str,
- (unsigned long) va_arg(args, void *), 16,
- field_width, precision, flags);
- break;
-
- case 'x':
- flags |= SMALL;
- case 'X':
- str = number(str, va_arg(args, unsigned long), 16,
- field_width, precision, flags);
- break;
-
- case 'd':
- case 'i':
- flags |= SIGN;
- case 'u':
- str = number(str, va_arg(args, unsigned long), 10,
- field_width, precision, flags);
- break;
-
- case 'n':
- ip = va_arg(args, int *);
- *ip = (str - buf);
- break;
-
- default:
- if (*fmt != '%')
- *str++ = '%';
- if (*fmt)
- *str++ = *fmt;
- else
- --fmt;
- break;
- }
- }
- *str = '\0';
- return str-buf;
-}
diff --git a/integration-tests/src/test/resources/kernel26.txt b/integration-tests/src/test/resources/kernel26.txt
deleted file mode 100644
index 54016b6..0000000
--- a/integration-tests/src/test/resources/kernel26.txt
+++ /dev/null
@@ -1,106086 +0,0 @@
-./acct.c
-./audit.c
-./audit_tree.c
-./auditfilter.c
-./auditsc.c
-./backtracetest.c
-./bounds.c
-./capability.c
-./cgroup.c
-./cgroup_debug.c
-./compat.c
-./configs.c
-./cpu.c
-./cpuset.c
-./delayacct.c
-./dma-coherent.c
-./dma.c
-./exec_domain.c
-./exit.c
-./extable.c
-./fork.c
-./futex.c
-./futex_compat.c
-./hrtimer.c
-./irq/autoprobe.c
-./irq/chip.c
-./irq/devres.c
-./irq/handle.c
-./irq/manage.c
-./irq/migration.c
-./irq/proc.c
-./irq/resend.c
-./irq/spurious.c
-./itimer.c
-./kallsyms.c
-./kexec.c
-./kfifo.c
-./kgdb.c
-./kmod.c
-./kprobes.c
-./ksysfs.c
-./kthread.c
-./latencytop.c
-./lockdep.c
-./lockdep_proc.c
-./marker.c
-./module.c
-./mutex-debug.c
-./mutex.c
-./notifier.c
-./ns_cgroup.c
-./nsproxy.c
-./panic.c
-./params.c
-./pid.c
-./pid_namespace.c
-./pm_qos_params.c
-./posix-cpu-timers.c
-./posix-timers.c
-./power/console.c
-./power/disk.c
-./power/main.c
-./power/poweroff.c
-./power/process.c
-./power/snapshot.c
-./power/swap.c
-./power/swsusp.c
-./power/user.c
-./printk.c
-./profile.c
-./ptrace.c
-./rcuclassic.c
-./rcupdate.c
-./rcupreempt.c
-./rcupreempt_trace.c
-./rcutorture.c
-./relay.c
-./res_counter.c
-./resource.c
-./rtmutex-debug.c
-./rtmutex-tester.c
-./rtmutex.c
-./rwsem.c
-./sched.c
-./sched_clock.c
-./sched_cpupri.c
-./sched_debug.c
-./sched_fair.c
-./sched_idletask.c
-./sched_rt.c
-./seccomp.c
-./semaphore.c
-./signal.c
-./smp.c
-./softirq.c
-./softlockup.c
-./spinlock.c
-./srcu.c
-./stacktrace.c
-./stop_machine.c
-./sys.c
-./sys_ni.c
-./sysctl.c
-./sysctl_check.c
-./taskstats.c
-./test_kprobes.c
-./time/clockevents.c
-./time/clocksource.c
-./time/jiffies.c
-./time/ntp.c
-./time/tick-broadcast.c
-./time/tick-common.c
-./time/tick-oneshot.c
-./time/tick-sched.c
-./time/timekeeping.c
-./time/timer_list.c
-./time/timer_stats.c
-./time.c
-./timer.c
-./trace/ftrace.c
-./trace/trace.c
-./trace/trace_functions.c
-./trace/trace_irqsoff.c
-./trace/trace_mmiotrace.c
-./trace/trace_sched_switch.c
-./trace/trace_sched_wakeup.c
-./trace/trace_selftest.c
-./trace/trace_selftest_dynamic.c
-./trace/trace_sysprof.c
-./tsacct.c
-./uid16.c
-./user.c
-./user_namespace.c
-./utsname.c
-./utsname_sysctl.c
-./wait.c
-./workqueue.c
-/*
- * linux/kernel/acct.c
- *
- * BSD Process Accounting for Linux
- *
- * Author: Marco van Wieringen
- *
- * Some code based on ideas and code from:
- * Thomas K. Dyas
- *
- * This file implements BSD-style process accounting. Whenever any
- * process exits, an accounting record of type "struct acct" is
- * written to the file specified with the acct() system call. It is
- * up to user-level programs to do useful things with the accounting
- * log. The kernel just provides the raw accounting information.
- *
- * (C) Copyright 1995 - 1997 Marco van Wieringen - ELM Consultancy B.V.
- *
- * Plugged two leaks. 1) It didn't return acct_file into the free_filps if
- * the file happened to be read-only. 2) If the accounting was suspended
- * due to the lack of space it happily allowed to reopen it and completely
- * lost the old acct_file. 3/10/98, Al Viro.
- *
- * Now we silently close acct_file on attempt to reopen. Cleaned sys_acct().
- * XTerms and EMACS are manifestations of pure evil. 21/10/98, AV.
- *
- * Fixed a nasty interaction with with sys_umount(). If the accointing
- * was suspeneded we failed to stop it on umount(). Messy.
- * Another one: remount to readonly didn't stop accounting.
- * Question: what should we do if we have CAP_SYS_ADMIN but not
- * CAP_SYS_PACCT? Current code does the following: umount returns -EBUSY
- * unless we are messing with the root. In that case we are getting a
- * real mess with do_remount_sb(). 9/11/98, AV.
- *
- * Fixed a bunch of races (and pair of leaks). Probably not the best way,
- * but this one obviously doesn't introduce deadlocks. Later. BTW, found
- * one race (and leak) in BSD implementation.
- * OK, that's better. ANOTHER race and leak in BSD variant. There always
- * is one more bug... 10/11/98, AV.
- *
- * Oh, fsck... Oopsable SMP race in do_process_acct() - we must hold
- * ->mmap_sem to walk the vma list of current->mm. Nasty, since it leaks
- * a struct file opened for write. Fixed. 2/6/2000, AV.
- */
-
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include /* sector_div */
-#include
-
-/*
- * These constants control the amount of freespace that suspend and
- * resume the process accounting system, and the time delay between
- * each check.
- * Turned into sysctl-controllable parameters. AV, 12/11/98
- */
-
-int acct_parm[3] = {4, 2, 30};
-#define RESUME (acct_parm[0]) /* >foo% free space - resume */
-#define SUSPEND (acct_parm[1]) /* needcheck = 1;
-}
-
-/*
- * Check the amount of free space and suspend/resume accordingly.
- */
-static int check_free_space(struct bsd_acct_struct *acct, struct file *file)
-{
- struct kstatfs sbuf;
- int res;
- int act;
- sector_t resume;
- sector_t suspend;
-
- spin_lock(&acct_lock);
- res = acct->active;
- if (!file || !acct->needcheck)
- goto out;
- spin_unlock(&acct_lock);
-
- /* May block */
- if (vfs_statfs(file->f_path.dentry, &sbuf))
- return res;
- suspend = sbuf.f_blocks * SUSPEND;
- resume = sbuf.f_blocks * RESUME;
-
- sector_div(suspend, 100);
- sector_div(resume, 100);
-
- if (sbuf.f_bavail <= suspend)
- act = -1;
- else if (sbuf.f_bavail >= resume)
- act = 1;
- else
- act = 0;
-
- /*
- * If some joker switched acct->file under us we'ld better be
- * silent and _not_ touch anything.
- */
- spin_lock(&acct_lock);
- if (file != acct->file) {
- if (act)
- res = act>0;
- goto out;
- }
-
- if (acct->active) {
- if (act < 0) {
- acct->active = 0;
- printk(KERN_INFO "Process accounting paused\n");
- }
- } else {
- if (act > 0) {
- acct->active = 1;
- printk(KERN_INFO "Process accounting resumed\n");
- }
- }
-
- del_timer(&acct->timer);
- acct->needcheck = 0;
- acct->timer.expires = jiffies + ACCT_TIMEOUT*HZ;
- add_timer(&acct->timer);
- res = acct->active;
-out:
- spin_unlock(&acct_lock);
- return res;
-}
-
-/*
- * Close the old accounting file (if currently open) and then replace
- * it with file (if non-NULL).
- *
- * NOTE: acct_lock MUST be held on entry and exit.
- */
-static void acct_file_reopen(struct bsd_acct_struct *acct, struct file *file,
- struct pid_namespace *ns)
-{
- struct file *old_acct = NULL;
- struct pid_namespace *old_ns = NULL;
-
- if (acct->file) {
- old_acct = acct->file;
- old_ns = acct->ns;
- del_timer(&acct->timer);
- acct->active = 0;
- acct->needcheck = 0;
- acct->file = NULL;
- acct->ns = NULL;
- list_del(&acct->list);
- }
- if (file) {
- acct->file = file;
- acct->ns = ns;
- acct->needcheck = 0;
- acct->active = 1;
- list_add(&acct->list, &acct_list);
- /* It's been deleted if it was used before so this is safe */
- setup_timer(&acct->timer, acct_timeout, (unsigned long)acct);
- acct->timer.expires = jiffies + ACCT_TIMEOUT*HZ;
- add_timer(&acct->timer);
- }
- if (old_acct) {
- mnt_unpin(old_acct->f_path.mnt);
- spin_unlock(&acct_lock);
- do_acct_process(acct, old_ns, old_acct);
- filp_close(old_acct, NULL);
- spin_lock(&acct_lock);
- }
-}
-
-static int acct_on(char *name)
-{
- struct file *file;
- struct vfsmount *mnt;
- int error;
- struct pid_namespace *ns;
- struct bsd_acct_struct *acct = NULL;
-
- /* Difference from BSD - they don't do O_APPEND */
- file = filp_open(name, O_WRONLY|O_APPEND|O_LARGEFILE, 0);
- if (IS_ERR(file))
- return PTR_ERR(file);
-
- if (!S_ISREG(file->f_path.dentry->d_inode->i_mode)) {
- filp_close(file, NULL);
- return -EACCES;
- }
-
- if (!file->f_op->write) {
- filp_close(file, NULL);
- return -EIO;
- }
-
- ns = task_active_pid_ns(current);
- if (ns->bacct == NULL) {
- acct = kzalloc(sizeof(struct bsd_acct_struct), GFP_KERNEL);
- if (acct == NULL) {
- filp_close(file, NULL);
- return -ENOMEM;
- }
- }
-
- error = security_acct(file);
- if (error) {
- kfree(acct);
- filp_close(file, NULL);
- return error;
- }
-
- spin_lock(&acct_lock);
- if (ns->bacct == NULL) {
- ns->bacct = acct;
- acct = NULL;
- }
-
- mnt = file->f_path.mnt;
- mnt_pin(mnt);
- acct_file_reopen(ns->bacct, file, ns);
- spin_unlock(&acct_lock);
-
- mntput(mnt); /* it's pinned, now give up active reference */
- kfree(acct);
-
- return 0;
-}
-
-/**
- * sys_acct - enable/disable process accounting
- * @name: file name for accounting records or NULL to shutdown accounting
- *
- * Returns 0 for success or negative errno values for failure.
- *
- * sys_acct() is the only system call needed to implement process
- * accounting. It takes the name of the file where accounting records
- * should be written. If the filename is NULL, accounting will be
- * shutdown.
- */
-SYSCALL_DEFINE1(acct, const char __user *, name)
-{
- int error;
-
- if (!capable(CAP_SYS_PACCT))
- return -EPERM;
-
- if (name) {
- char *tmp = getname(name);
- if (IS_ERR(tmp))
- return (PTR_ERR(tmp));
- error = acct_on(tmp);
- putname(tmp);
- } else {
- struct bsd_acct_struct *acct;
-
- acct = task_active_pid_ns(current)->bacct;
- if (acct == NULL)
- return 0;
-
- error = security_acct(NULL);
- if (!error) {
- spin_lock(&acct_lock);
- acct_file_reopen(acct, NULL, NULL);
- spin_unlock(&acct_lock);
- }
- }
- return error;
-}
-
-/**
- * acct_auto_close - turn off a filesystem's accounting if it is on
- * @m: vfsmount being shut down
- *
- * If the accounting is turned on for a file in the subtree pointed to
- * to by m, turn accounting off. Done when m is about to die.
- */
-void acct_auto_close_mnt(struct vfsmount *m)
-{
- struct bsd_acct_struct *acct;
-
- spin_lock(&acct_lock);
-restart:
- list_for_each_entry(acct, &acct_list, list)
- if (acct->file && acct->file->f_path.mnt == m) {
- acct_file_reopen(acct, NULL, NULL);
- goto restart;
- }
- spin_unlock(&acct_lock);
-}
-
-/**
- * acct_auto_close - turn off a filesystem's accounting if it is on
- * @sb: super block for the filesystem
- *
- * If the accounting is turned on for a file in the filesystem pointed
- * to by sb, turn accounting off.
- */
-void acct_auto_close(struct super_block *sb)
-{
- struct bsd_acct_struct *acct;
-
- spin_lock(&acct_lock);
-restart:
- list_for_each_entry(acct, &acct_list, list)
- if (acct->file && acct->file->f_path.mnt->mnt_sb == sb) {
- acct_file_reopen(acct, NULL, NULL);
- goto restart;
- }
- spin_unlock(&acct_lock);
-}
-
-void acct_exit_ns(struct pid_namespace *ns)
-{
- struct bsd_acct_struct *acct;
-
- spin_lock(&acct_lock);
- acct = ns->bacct;
- if (acct != NULL) {
- if (acct->file != NULL)
- acct_file_reopen(acct, NULL, NULL);
-
- kfree(acct);
- }
- spin_unlock(&acct_lock);
-}
-
-/*
- * encode an unsigned long into a comp_t
- *
- * This routine has been adopted from the encode_comp_t() function in
- * the kern_acct.c file of the FreeBSD operating system. The encoding
- * is a 13-bit fraction with a 3-bit (base 8) exponent.
- */
-
-#define MANTSIZE 13 /* 13 bit mantissa. */
-#define EXPSIZE 3 /* Base 8 (3 bit) exponent. */
-#define MAXFRACT ((1 << MANTSIZE) - 1) /* Maximum fractional value. */
-
-static comp_t encode_comp_t(unsigned long value)
-{
- int exp, rnd;
-
- exp = rnd = 0;
- while (value > MAXFRACT) {
- rnd = value & (1 << (EXPSIZE - 1)); /* Round up? */
- value >>= EXPSIZE; /* Base 8 exponent == 3 bit shift. */
- exp++;
- }
-
- /*
- * If we need to round up, do it (and handle overflow correctly).
- */
- if (rnd && (++value > MAXFRACT)) {
- value >>= EXPSIZE;
- exp++;
- }
-
- /*
- * Clean it up and polish it off.
- */
- exp <<= MANTSIZE; /* Shift the exponent into place */
- exp += value; /* and add on the mantissa. */
- return exp;
-}
-
-#if ACCT_VERSION==1 || ACCT_VERSION==2
-/*
- * encode an u64 into a comp2_t (24 bits)
- *
- * Format: 5 bit base 2 exponent, 20 bits mantissa.
- * The leading bit of the mantissa is not stored, but implied for
- * non-zero exponents.
- * Largest encodable value is 50 bits.
- */
-
-#define MANTSIZE2 20 /* 20 bit mantissa. */
-#define EXPSIZE2 5 /* 5 bit base 2 exponent. */
-#define MAXFRACT2 ((1ul << MANTSIZE2) - 1) /* Maximum fractional value. */
-#define MAXEXP2 ((1 < (MAXFRACT2>>1));
- rnd = 0;
- while (value > MAXFRACT2) {
- rnd = value & 1;
- value >>= 1;
- exp++;
- }
-
- /*
- * If we need to round up, do it (and handle overflow correctly).
- */
- if (rnd && (++value > MAXFRACT2)) {
- value >>= 1;
- exp++;
- }
-
- if (exp > MAXEXP2) {
- /* Overflow. Return largest representable number instead. */
- return (1ul << (MANTSIZE2+EXPSIZE2-1)) - 1;
- } else {
- return (value & (MAXFRACT2>>1)) | (exp << (MANTSIZE2-1));
- }
-}
-#endif
-
-#if ACCT_VERSION==3
-/*
- * encode an u64 into a 32 bit IEEE float
- */
-static u32 encode_float(u64 value)
-{
- unsigned exp = 190;
- unsigned u;
-
- if (value==0) return 0;
- while ((s64)value > 0){
- value <<= 1;
- exp--;
- }
- u = (u32)(value >> 40) & 0x7fffffu;
- return u | (exp << 23);
-}
-#endif
-
-/*
- * Write an accounting entry for an exiting process
- *
- * The acct_process() call is the workhorse of the process
- * accounting system. The struct acct is built here and then written
- * into the accounting file. This function should only be called from
- * do_exit() or when switching to a different output file.
- */
-
-/*
- * do_acct_process does all actual work. Caller holds the reference to file.
- */
-static void do_acct_process(struct bsd_acct_struct *acct,
- struct pid_namespace *ns, struct file *file)
-{
- struct pacct_struct *pacct = ¤t->signal->pacct;
- acct_t ac;
- mm_segment_t fs;
- unsigned long flim;
- u64 elapsed;
- u64 run_time;
- struct timespec uptime;
- struct tty_struct *tty;
-
- /*
- * First check to see if there is enough free_space to continue
- * the process accounting system.
- */
- if (!check_free_space(acct, file))
- return;
-
- /*
- * Fill the accounting struct with the needed info as recorded
- * by the different kernel functions.
- */
- memset((caddr_t)&ac, 0, sizeof(acct_t));
-
- ac.ac_version = ACCT_VERSION | ACCT_BYTEORDER;
- strlcpy(ac.ac_comm, current->comm, sizeof(ac.ac_comm));
-
- /* calculate run_time in nsec*/
- do_posix_clock_monotonic_gettime(&uptime);
- run_time = (u64)uptime.tv_sec*NSEC_PER_SEC + uptime.tv_nsec;
- run_time -= (u64)current->group_leader->start_time.tv_sec * NSEC_PER_SEC
- + current->group_leader->start_time.tv_nsec;
- /* convert nsec -> AHZ */
- elapsed = nsec_to_AHZ(run_time);
-#if ACCT_VERSION==3
- ac.ac_etime = encode_float(elapsed);
-#else
- ac.ac_etime = encode_comp_t(elapsed < (unsigned long) -1l ?
- (unsigned long) elapsed : (unsigned long) -1l);
-#endif
-#if ACCT_VERSION==1 || ACCT_VERSION==2
- {
- /* new enlarged etime field */
- comp2_t etime = encode_comp2_t(elapsed);
- ac.ac_etime_hi = etime >> 16;
- ac.ac_etime_lo = (u16) etime;
- }
-#endif
- do_div(elapsed, AHZ);
- ac.ac_btime = get_seconds() - elapsed;
- /* we really need to bite the bullet and change layout */
- ac.ac_uid = current->uid;
- ac.ac_gid = current->gid;
-#if ACCT_VERSION==2
- ac.ac_ahz = AHZ;
-#endif
-#if ACCT_VERSION==1 || ACCT_VERSION==2
- /* backward-compatible 16 bit fields */
- ac.ac_uid16 = current->uid;
- ac.ac_gid16 = current->gid;
-#endif
-#if ACCT_VERSION==3
- ac.ac_pid = task_tgid_nr_ns(current, ns);
- rcu_read_lock();
- ac.ac_ppid = task_tgid_nr_ns(rcu_dereference(current->real_parent), ns);
- rcu_read_unlock();
-#endif
-
- spin_lock_irq(¤t->sighand->siglock);
- tty = current->signal->tty;
- ac.ac_tty = tty ? old_encode_dev(tty_devnum(tty)) : 0;
- ac.ac_utime = encode_comp_t(jiffies_to_AHZ(cputime_to_jiffies(pacct->ac_utime)));
- ac.ac_stime = encode_comp_t(jiffies_to_AHZ(cputime_to_jiffies(pacct->ac_stime)));
- ac.ac_flag = pacct->ac_flag;
- ac.ac_mem = encode_comp_t(pacct->ac_mem);
- ac.ac_minflt = encode_comp_t(pacct->ac_minflt);
- ac.ac_majflt = encode_comp_t(pacct->ac_majflt);
- ac.ac_exitcode = pacct->ac_exitcode;
- spin_unlock_irq(¤t->sighand->siglock);
- ac.ac_io = encode_comp_t(0 /* current->io_usage */); /* %% */
- ac.ac_rw = encode_comp_t(ac.ac_io / 1024);
- ac.ac_swaps = encode_comp_t(0);
-
- /*
- * Kernel segment override to datasegment and write it
- * to the accounting file.
- */
- fs = get_fs();
- set_fs(KERNEL_DS);
- /*
- * Accounting records are not subject to resource limits.
- */
- flim = current->signal->rlim[RLIMIT_FSIZE].rlim_cur;
- current->signal->rlim[RLIMIT_FSIZE].rlim_cur = RLIM_INFINITY;
- file->f_op->write(file, (char *)&ac,
- sizeof(acct_t), &file->f_pos);
- current->signal->rlim[RLIMIT_FSIZE].rlim_cur = flim;
- set_fs(fs);
-}
-
-/**
- * acct_init_pacct - initialize a new pacct_struct
- * @pacct: per-process accounting info struct to initialize
- */
-void acct_init_pacct(struct pacct_struct *pacct)
-{
- memset(pacct, 0, sizeof(struct pacct_struct));
- pacct->ac_utime = pacct->ac_stime = cputime_zero;
-}
-
-/**
- * acct_collect - collect accounting information into pacct_struct
- * @exitcode: task exit code
- * @group_dead: not 0, if this thread is the last one in the process.
- */
-void acct_collect(long exitcode, int group_dead)
-{
- struct pacct_struct *pacct = ¤t->signal->pacct;
- unsigned long vsize = 0;
-
- if (group_dead && current->mm) {
- struct vm_area_struct *vma;
- down_read(¤t->mm->mmap_sem);
- vma = current->mm->mmap;
- while (vma) {
- vsize += vma->vm_end - vma->vm_start;
- vma = vma->vm_next;
- }
- up_read(¤t->mm->mmap_sem);
- }
-
- spin_lock_irq(¤t->sighand->siglock);
- if (group_dead)
- pacct->ac_mem = vsize / 1024;
- if (thread_group_leader(current)) {
- pacct->ac_exitcode = exitcode;
- if (current->flags & PF_FORKNOEXEC)
- pacct->ac_flag |= AFORK;
- }
- if (current->flags & PF_SUPERPRIV)
- pacct->ac_flag |= ASU;
- if (current->flags & PF_DUMPCORE)
- pacct->ac_flag |= ACORE;
- if (current->flags & PF_SIGNALED)
- pacct->ac_flag |= AXSIG;
- pacct->ac_utime = cputime_add(pacct->ac_utime, current->utime);
- pacct->ac_stime = cputime_add(pacct->ac_stime, current->stime);
- pacct->ac_minflt += current->min_flt;
- pacct->ac_majflt += current->maj_flt;
- spin_unlock_irq(¤t->sighand->siglock);
-}
-
-static void acct_process_in_ns(struct pid_namespace *ns)
-{
- struct file *file = NULL;
- struct bsd_acct_struct *acct;
-
- acct = ns->bacct;
- /*
- * accelerate the common fastpath:
- */
- if (!acct || !acct->file)
- return;
-
- spin_lock(&acct_lock);
- file = acct->file;
- if (unlikely(!file)) {
- spin_unlock(&acct_lock);
- return;
- }
- get_file(file);
- spin_unlock(&acct_lock);
-
- do_acct_process(acct, ns, file);
- fput(file);
-}
-
-/**
- * acct_process - now just a wrapper around acct_process_in_ns,
- * which in turn is a wrapper around do_acct_process.
- *
- * handles process accounting for an exiting task
- */
-void acct_process(void)
-{
- struct pid_namespace *ns;
-
- /*
- * This loop is safe lockless, since current is still
- * alive and holds its namespace, which in turn holds
- * its parent.
- */
- for (ns = task_active_pid_ns(current); ns != NULL; ns = ns->parent)
- acct_process_in_ns(ns);
-}
-/* audit.c -- Auditing support
- * Gateway between the kernel (e.g., selinux) and the user-space audit daemon.
- * System-call specific features have moved to auditsc.c
- *
- * Copyright 2003-2007 Red Hat Inc., Durham, North Carolina.
- * All Rights Reserved.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * Written by Rickard E. (Rik) Faith
- *
- * Goals: 1) Integrate fully with Security Modules.
- * 2) Minimal run-time overhead:
- * a) Minimal when syscall auditing is disabled (audit_enable=0).
- * b) Small when syscall auditing is enabled and no audit record
- * is generated (defer as much work as possible to record
- * generation time):
- * i) context is allocated,
- * ii) names from getname are stored without a copy, and
- * iii) inode information stored from path_lookup.
- * 3) Ability to disable syscall auditing at boot time (audit=0).
- * 4) Usable by other parts of the kernel (if audit_log* is called,
- * then a syscall record will be generated automatically for the
- * current syscall).
- * 5) Netlink interface to user-space.
- * 6) Support low-overhead kernel-based filtering to minimize the
- * information that must be passed to user-space.
- *
- * Example user-space utilities: http://people.redhat.com/sgrubb/audit/
- */
-
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-
-#include
-
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-
-#include "audit.h"
-
-/* No auditing will take place until audit_initialized != 0.
- * (Initialization happens after skb_init is called.) */
-static int audit_initialized;
-
-#define AUDIT_OFF 0
-#define AUDIT_ON 1
-#define AUDIT_LOCKED 2
-int audit_enabled;
-int audit_ever_enabled;
-
-/* Default state when kernel boots without any parameters. */
-static int audit_default;
-
-/* If auditing cannot proceed, audit_failure selects what happens. */
-static int audit_failure = AUDIT_FAIL_PRINTK;
-
-/*
- * If audit records are to be written to the netlink socket, audit_pid
- * contains the pid of the auditd process and audit_nlk_pid contains
- * the pid to use to send netlink messages to that process.
- */
-int audit_pid;
-static int audit_nlk_pid;
-
-/* If audit_rate_limit is non-zero, limit the rate of sending audit records
- * to that number per second. This prevents DoS attacks, but results in
- * audit records being dropped. */
-static int audit_rate_limit;
-
-/* Number of outstanding audit_buffers allowed. */
-static int audit_backlog_limit = 64;
-static int audit_backlog_wait_time = 60 * HZ;
-static int audit_backlog_wait_overflow = 0;
-
-/* The identity of the user shutting down the audit system. */
-uid_t audit_sig_uid = -1;
-pid_t audit_sig_pid = -1;
-u32 audit_sig_sid = 0;
-
-/* Records can be lost in several ways:
- 0) [suppressed in audit_alloc]
- 1) out of memory in audit_log_start [kmalloc of struct audit_buffer]
- 2) out of memory in audit_log_move [alloc_skb]
- 3) suppressed due to audit_rate_limit
- 4) suppressed due to audit_backlog_limit
-*/
-static atomic_t audit_lost = ATOMIC_INIT(0);
-
-/* The netlink socket. */
-static struct sock *audit_sock;
-
-/* Inotify handle. */
-struct inotify_handle *audit_ih;
-
-/* Hash for inode-based rules */
-struct list_head audit_inode_hash[AUDIT_INODE_BUCKETS];
-
-/* The audit_freelist is a list of pre-allocated audit buffers (if more
- * than AUDIT_MAXFREE are in use, the audit buffer is freed instead of
- * being placed on the freelist). */
-static DEFINE_SPINLOCK(audit_freelist_lock);
-static int audit_freelist_count;
-static LIST_HEAD(audit_freelist);
-
-static struct sk_buff_head audit_skb_queue;
-/* queue of skbs to send to auditd when/if it comes back */
-static struct sk_buff_head audit_skb_hold_queue;
-static struct task_struct *kauditd_task;
-static DECLARE_WAIT_QUEUE_HEAD(kauditd_wait);
-static DECLARE_WAIT_QUEUE_HEAD(audit_backlog_wait);
-
-/* Serialize requests from userspace. */
-static DEFINE_MUTEX(audit_cmd_mutex);
-
-/* AUDIT_BUFSIZ is the size of the temporary buffer used for formatting
- * audit records. Since printk uses a 1024 byte buffer, this buffer
- * should be at least that large. */
-#define AUDIT_BUFSIZ 1024
-
-/* AUDIT_MAXFREE is the number of empty audit_buffers we keep on the
- * audit_freelist. Doing so eliminates many kmalloc/kfree calls. */
-#define AUDIT_MAXFREE (2*NR_CPUS)
-
-/* The audit_buffer is used when formatting an audit record. The caller
- * locks briefly to get the record off the freelist or to allocate the
- * buffer, and locks briefly to send the buffer to the netlink layer or
- * to place it on a transmit queue. Multiple audit_buffers can be in
- * use simultaneously. */
-struct audit_buffer {
- struct list_head list;
- struct sk_buff *skb; /* formatted skb ready to send */
- struct audit_context *ctx; /* NULL or associated context */
- gfp_t gfp_mask;
-};
-
-struct audit_reply {
- int pid;
- struct sk_buff *skb;
-};
-
-static void audit_set_pid(struct audit_buffer *ab, pid_t pid)
-{
- if (ab) {
- struct nlmsghdr *nlh = nlmsg_hdr(ab->skb);
- nlh->nlmsg_pid = pid;
- }
-}
-
-void audit_panic(const char *message)
-{
- switch (audit_failure)
- {
- case AUDIT_FAIL_SILENT:
- break;
- case AUDIT_FAIL_PRINTK:
- if (printk_ratelimit())
- printk(KERN_ERR "audit: %s\n", message);
- break;
- case AUDIT_FAIL_PANIC:
- /* test audit_pid since printk is always losey, why bother? */
- if (audit_pid)
- panic("audit: %s\n", message);
- break;
- }
-}
-
-static inline int audit_rate_check(void)
-{
- static unsigned long last_check = 0;
- static int messages = 0;
- static DEFINE_SPINLOCK(lock);
- unsigned long flags;
- unsigned long now;
- unsigned long elapsed;
- int retval = 0;
-
- if (!audit_rate_limit) return 1;
-
- spin_lock_irqsave(&lock, flags);
- if (++messages < audit_rate_limit) {
- retval = 1;
- } else {
- now = jiffies;
- elapsed = now - last_check;
- if (elapsed > HZ) {
- last_check = now;
- messages = 0;
- retval = 1;
- }
- }
- spin_unlock_irqrestore(&lock, flags);
-
- return retval;
-}
-
-/**
- * audit_log_lost - conditionally log lost audit message event
- * @message: the message stating reason for lost audit message
- *
- * Emit at least 1 message per second, even if audit_rate_check is
- * throttling.
- * Always increment the lost messages counter.
-*/
-void audit_log_lost(const char *message)
-{
- static unsigned long last_msg = 0;
- static DEFINE_SPINLOCK(lock);
- unsigned long flags;
- unsigned long now;
- int print;
-
- atomic_inc(&audit_lost);
-
- print = (audit_failure == AUDIT_FAIL_PANIC || !audit_rate_limit);
-
- if (!print) {
- spin_lock_irqsave(&lock, flags);
- now = jiffies;
- if (now - last_msg > HZ) {
- print = 1;
- last_msg = now;
- }
- spin_unlock_irqrestore(&lock, flags);
- }
-
- if (print) {
- if (printk_ratelimit())
- printk(KERN_WARNING
- "audit: audit_lost=%d audit_rate_limit=%d "
- "audit_backlog_limit=%d\n",
- atomic_read(&audit_lost),
- audit_rate_limit,
- audit_backlog_limit);
- audit_panic(message);
- }
-}
-
-static int audit_log_config_change(char *function_name, int new, int old,
- uid_t loginuid, u32 sessionid, u32 sid,
- int allow_changes)
-{
- struct audit_buffer *ab;
- int rc = 0;
-
- ab = audit_log_start(NULL, GFP_KERNEL, AUDIT_CONFIG_CHANGE);
- audit_log_format(ab, "%s=%d old=%d auid=%u ses=%u", function_name, new,
- old, loginuid, sessionid);
- if (sid) {
- char *ctx = NULL;
- u32 len;
-
- rc = security_secid_to_secctx(sid, &ctx, &len);
- if (rc) {
- audit_log_format(ab, " sid=%u", sid);
- allow_changes = 0; /* Something weird, deny request */
- } else {
- audit_log_format(ab, " subj=%s", ctx);
- security_release_secctx(ctx, len);
- }
- }
- audit_log_format(ab, " res=%d", allow_changes);
- audit_log_end(ab);
- return rc;
-}
-
-static int audit_do_config_change(char *function_name, int *to_change,
- int new, uid_t loginuid, u32 sessionid,
- u32 sid)
-{
- int allow_changes, rc = 0, old = *to_change;
-
- /* check if we are locked */
- if (audit_enabled == AUDIT_LOCKED)
- allow_changes = 0;
- else
- allow_changes = 1;
-
- if (audit_enabled != AUDIT_OFF) {
- rc = audit_log_config_change(function_name, new, old, loginuid,
- sessionid, sid, allow_changes);
- if (rc)
- allow_changes = 0;
- }
-
- /* If we are allowed, make the change */
- if (allow_changes == 1)
- *to_change = new;
- /* Not allowed, update reason */
- else if (rc == 0)
- rc = -EPERM;
- return rc;
-}
-
-static int audit_set_rate_limit(int limit, uid_t loginuid, u32 sessionid,
- u32 sid)
-{
- return audit_do_config_change("audit_rate_limit", &audit_rate_limit,
- limit, loginuid, sessionid, sid);
-}
-
-static int audit_set_backlog_limit(int limit, uid_t loginuid, u32 sessionid,
- u32 sid)
-{
- return audit_do_config_change("audit_backlog_limit", &audit_backlog_limit,
- limit, loginuid, sessionid, sid);
-}
-
-static int audit_set_enabled(int state, uid_t loginuid, u32 sessionid, u32 sid)
-{
- int rc;
- if (state < AUDIT_OFF || state > AUDIT_LOCKED)
- return -EINVAL;
-
- rc = audit_do_config_change("audit_enabled", &audit_enabled, state,
- loginuid, sessionid, sid);
-
- if (!rc)
- audit_ever_enabled |= !!state;
-
- return rc;
-}
-
-static int audit_set_failure(int state, uid_t loginuid, u32 sessionid, u32 sid)
-{
- if (state != AUDIT_FAIL_SILENT
- && state != AUDIT_FAIL_PRINTK
- && state != AUDIT_FAIL_PANIC)
- return -EINVAL;
-
- return audit_do_config_change("audit_failure", &audit_failure, state,
- loginuid, sessionid, sid);
-}
-
-/*
- * Queue skbs to be sent to auditd when/if it comes back. These skbs should
- * already have been sent via prink/syslog and so if these messages are dropped
- * it is not a huge concern since we already passed the audit_log_lost()
- * notification and stuff. This is just nice to get audit messages during
- * boot before auditd is running or messages generated while auditd is stopped.
- * This only holds messages is audit_default is set, aka booting with audit=1
- * or building your kernel that way.
- */
-static void audit_hold_skb(struct sk_buff *skb)
-{
- if (audit_default &&
- skb_queue_len(&audit_skb_hold_queue) < audit_backlog_limit)
- skb_queue_tail(&audit_skb_hold_queue, skb);
- else
- kfree_skb(skb);
-}
-
-static void kauditd_send_skb(struct sk_buff *skb)
-{
- int err;
- /* take a reference in case we can't send it and we want to hold it */
- skb_get(skb);
- err = netlink_unicast(audit_sock, skb, audit_nlk_pid, 0);
- if (err < 0) {
- BUG_ON(err != -ECONNREFUSED); /* Shoudn't happen */
- printk(KERN_ERR "audit: *NO* daemon at audit_pid=%d\n", audit_pid);
- audit_log_lost("auditd dissapeared\n");
- audit_pid = 0;
- /* we might get lucky and get this in the next auditd */
- audit_hold_skb(skb);
- } else
- /* drop the extra reference if sent ok */
- kfree_skb(skb);
-}
-
-static int kauditd_thread(void *dummy)
-{
- struct sk_buff *skb;
-
- set_freezable();
- while (!kthread_should_stop()) {
- /*
- * if auditd just started drain the queue of messages already
- * sent to syslog/printk. remember loss here is ok. we already
- * called audit_log_lost() if it didn't go out normally. so the
- * race between the skb_dequeue and the next check for audit_pid
- * doesn't matter.
- *
- * if you ever find kauditd to be too slow we can get a perf win
- * by doing our own locking and keeping better track if there
- * are messages in this queue. I don't see the need now, but
- * in 5 years when I want to play with this again I'll see this
- * note and still have no friggin idea what i'm thinking today.
- */
- if (audit_default && audit_pid) {
- skb = skb_dequeue(&audit_skb_hold_queue);
- if (unlikely(skb)) {
- while (skb && audit_pid) {
- kauditd_send_skb(skb);
- skb = skb_dequeue(&audit_skb_hold_queue);
- }
- }
- }
-
- skb = skb_dequeue(&audit_skb_queue);
- wake_up(&audit_backlog_wait);
- if (skb) {
- if (audit_pid)
- kauditd_send_skb(skb);
- else {
- if (printk_ratelimit())
- printk(KERN_NOTICE "%s\n", skb->data + NLMSG_SPACE(0));
- else
- audit_log_lost("printk limit exceeded\n");
-
- audit_hold_skb(skb);
- }
- } else {
- DECLARE_WAITQUEUE(wait, current);
- set_current_state(TASK_INTERRUPTIBLE);
- add_wait_queue(&kauditd_wait, &wait);
-
- if (!skb_queue_len(&audit_skb_queue)) {
- try_to_freeze();
- schedule();
- }
-
- __set_current_state(TASK_RUNNING);
- remove_wait_queue(&kauditd_wait, &wait);
- }
- }
- return 0;
-}
-
-static int audit_prepare_user_tty(pid_t pid, uid_t loginuid, u32 sessionid)
-{
- struct task_struct *tsk;
- int err;
-
- read_lock(&tasklist_lock);
- tsk = find_task_by_vpid(pid);
- err = -ESRCH;
- if (!tsk)
- goto out;
- err = 0;
-
- spin_lock_irq(&tsk->sighand->siglock);
- if (!tsk->signal->audit_tty)
- err = -EPERM;
- spin_unlock_irq(&tsk->sighand->siglock);
- if (err)
- goto out;
-
- tty_audit_push_task(tsk, loginuid, sessionid);
-out:
- read_unlock(&tasklist_lock);
- return err;
-}
-
-int audit_send_list(void *_dest)
-{
- struct audit_netlink_list *dest = _dest;
- int pid = dest->pid;
- struct sk_buff *skb;
-
- /* wait for parent to finish and send an ACK */
- mutex_lock(&audit_cmd_mutex);
- mutex_unlock(&audit_cmd_mutex);
-
- while ((skb = __skb_dequeue(&dest->q)) != NULL)
- netlink_unicast(audit_sock, skb, pid, 0);
-
- kfree(dest);
-
- return 0;
-}
-
-#ifdef CONFIG_AUDIT_TREE
-static int prune_tree_thread(void *unused)
-{
- mutex_lock(&audit_cmd_mutex);
- audit_prune_trees();
- mutex_unlock(&audit_cmd_mutex);
- return 0;
-}
-
-void audit_schedule_prune(void)
-{
- kthread_run(prune_tree_thread, NULL, "audit_prune_tree");
-}
-#endif
-
-struct sk_buff *audit_make_reply(int pid, int seq, int type, int done,
- int multi, void *payload, int size)
-{
- struct sk_buff *skb;
- struct nlmsghdr *nlh;
- int len = NLMSG_SPACE(size);
- void *data;
- int flags = multi ? NLM_F_MULTI : 0;
- int t = done ? NLMSG_DONE : type;
-
- skb = alloc_skb(len, GFP_KERNEL);
- if (!skb)
- return NULL;
-
- nlh = NLMSG_PUT(skb, pid, seq, t, size);
- nlh->nlmsg_flags = flags;
- data = NLMSG_DATA(nlh);
- memcpy(data, payload, size);
- return skb;
-
-nlmsg_failure: /* Used by NLMSG_PUT */
- if (skb)
- kfree_skb(skb);
- return NULL;
-}
-
-static int audit_send_reply_thread(void *arg)
-{
- struct audit_reply *reply = (struct audit_reply *)arg;
-
- mutex_lock(&audit_cmd_mutex);
- mutex_unlock(&audit_cmd_mutex);
-
- /* Ignore failure. It'll only happen if the sender goes away,
- because our timeout is set to infinite. */
- netlink_unicast(audit_sock, reply->skb, reply->pid, 0);
- kfree(reply);
- return 0;
-}
-/**
- * audit_send_reply - send an audit reply message via netlink
- * @pid: process id to send reply to
- * @seq: sequence number
- * @type: audit message type
- * @done: done (last) flag
- * @multi: multi-part message flag
- * @payload: payload data
- * @size: payload size
- *
- * Allocates an skb, builds the netlink message, and sends it to the pid.
- * No failure notifications.
- */
-void audit_send_reply(int pid, int seq, int type, int done, int multi,
- void *payload, int size)
-{
- struct sk_buff *skb;
- struct task_struct *tsk;
- struct audit_reply *reply = kmalloc(sizeof(struct audit_reply),
- GFP_KERNEL);
-
- if (!reply)
- return;
-
- skb = audit_make_reply(pid, seq, type, done, multi, payload, size);
- if (!skb)
- goto out;
-
- reply->pid = pid;
- reply->skb = skb;
-
- tsk = kthread_run(audit_send_reply_thread, reply, "audit_send_reply");
- if (!IS_ERR(tsk))
- return;
- kfree_skb(skb);
-out:
- kfree(reply);
-}
-
-/*
- * Check for appropriate CAP_AUDIT_ capabilities on incoming audit
- * control messages.
- */
-static int audit_netlink_ok(struct sk_buff *skb, u16 msg_type)
-{
- int err = 0;
-
- switch (msg_type) {
- case AUDIT_GET:
- case AUDIT_LIST:
- case AUDIT_LIST_RULES:
- case AUDIT_SET:
- case AUDIT_ADD:
- case AUDIT_ADD_RULE:
- case AUDIT_DEL:
- case AUDIT_DEL_RULE:
- case AUDIT_SIGNAL_INFO:
- case AUDIT_TTY_GET:
- case AUDIT_TTY_SET:
- case AUDIT_TRIM:
- case AUDIT_MAKE_EQUIV:
- if (security_netlink_recv(skb, CAP_AUDIT_CONTROL))
- err = -EPERM;
- break;
- case AUDIT_USER:
- case AUDIT_FIRST_USER_MSG ... AUDIT_LAST_USER_MSG:
- case AUDIT_FIRST_USER_MSG2 ... AUDIT_LAST_USER_MSG2:
- if (security_netlink_recv(skb, CAP_AUDIT_WRITE))
- err = -EPERM;
- break;
- default: /* bad msg */
- err = -EINVAL;
- }
-
- return err;
-}
-
-static int audit_log_common_recv_msg(struct audit_buffer **ab, u16 msg_type,
- u32 pid, u32 uid, uid_t auid, u32 ses,
- u32 sid)
-{
- int rc = 0;
- char *ctx = NULL;
- u32 len;
-
- if (!audit_enabled) {
- *ab = NULL;
- return rc;
- }
-
- *ab = audit_log_start(NULL, GFP_KERNEL, msg_type);
- audit_log_format(*ab, "user pid=%d uid=%u auid=%u ses=%u",
- pid, uid, auid, ses);
- if (sid) {
- rc = security_secid_to_secctx(sid, &ctx, &len);
- if (rc)
- audit_log_format(*ab, " ssid=%u", sid);
- else {
- audit_log_format(*ab, " subj=%s", ctx);
- security_release_secctx(ctx, len);
- }
- }
-
- return rc;
-}
-
-static int audit_receive_msg(struct sk_buff *skb, struct nlmsghdr *nlh)
-{
- u32 uid, pid, seq, sid;
- void *data;
- struct audit_status *status_get, status_set;
- int err;
- struct audit_buffer *ab;
- u16 msg_type = nlh->nlmsg_type;
- uid_t loginuid; /* loginuid of sender */
- u32 sessionid;
- struct audit_sig_info *sig_data;
- char *ctx = NULL;
- u32 len;
-
- err = audit_netlink_ok(skb, msg_type);
- if (err)
- return err;
-
- /* As soon as there's any sign of userspace auditd,
- * start kauditd to talk to it */
- if (!kauditd_task)
- kauditd_task = kthread_run(kauditd_thread, NULL, "kauditd");
- if (IS_ERR(kauditd_task)) {
- err = PTR_ERR(kauditd_task);
- kauditd_task = NULL;
- return err;
- }
-
- pid = NETLINK_CREDS(skb)->pid;
- uid = NETLINK_CREDS(skb)->uid;
- loginuid = NETLINK_CB(skb).loginuid;
- sessionid = NETLINK_CB(skb).sessionid;
- sid = NETLINK_CB(skb).sid;
- seq = nlh->nlmsg_seq;
- data = NLMSG_DATA(nlh);
-
- switch (msg_type) {
- case AUDIT_GET:
- status_set.enabled = audit_enabled;
- status_set.failure = audit_failure;
- status_set.pid = audit_pid;
- status_set.rate_limit = audit_rate_limit;
- status_set.backlog_limit = audit_backlog_limit;
- status_set.lost = atomic_read(&audit_lost);
- status_set.backlog = skb_queue_len(&audit_skb_queue);
- audit_send_reply(NETLINK_CB(skb).pid, seq, AUDIT_GET, 0, 0,
- &status_set, sizeof(status_set));
- break;
- case AUDIT_SET:
- if (nlh->nlmsg_len < sizeof(struct audit_status))
- return -EINVAL;
- status_get = (struct audit_status *)data;
- if (status_get->mask & AUDIT_STATUS_ENABLED) {
- err = audit_set_enabled(status_get->enabled,
- loginuid, sessionid, sid);
- if (err < 0)
- return err;
- }
- if (status_get->mask & AUDIT_STATUS_FAILURE) {
- err = audit_set_failure(status_get->failure,
- loginuid, sessionid, sid);
- if (err < 0)
- return err;
- }
- if (status_get->mask & AUDIT_STATUS_PID) {
- int new_pid = status_get->pid;
-
- if (audit_enabled != AUDIT_OFF)
- audit_log_config_change("audit_pid", new_pid,
- audit_pid, loginuid,
- sessionid, sid, 1);
-
- audit_pid = new_pid;
- audit_nlk_pid = NETLINK_CB(skb).pid;
- }
- if (status_get->mask & AUDIT_STATUS_RATE_LIMIT) {
- err = audit_set_rate_limit(status_get->rate_limit,
- loginuid, sessionid, sid);
- if (err < 0)
- return err;
- }
- if (status_get->mask & AUDIT_STATUS_BACKLOG_LIMIT)
- err = audit_set_backlog_limit(status_get->backlog_limit,
- loginuid, sessionid, sid);
- break;
- case AUDIT_USER:
- case AUDIT_FIRST_USER_MSG ... AUDIT_LAST_USER_MSG:
- case AUDIT_FIRST_USER_MSG2 ... AUDIT_LAST_USER_MSG2:
- if (!audit_enabled && msg_type != AUDIT_USER_AVC)
- return 0;
-
- err = audit_filter_user(&NETLINK_CB(skb));
- if (err == 1) {
- err = 0;
- if (msg_type == AUDIT_USER_TTY) {
- err = audit_prepare_user_tty(pid, loginuid,
- sessionid);
- if (err)
- break;
- }
- audit_log_common_recv_msg(&ab, msg_type, pid, uid,
- loginuid, sessionid, sid);
-
- if (msg_type != AUDIT_USER_TTY)
- audit_log_format(ab, " msg='%.1024s'",
- (char *)data);
- else {
- int size;
-
- audit_log_format(ab, " msg=");
- size = nlmsg_len(nlh);
- audit_log_n_untrustedstring(ab, data, size);
- }
- audit_set_pid(ab, pid);
- audit_log_end(ab);
- }
- break;
- case AUDIT_ADD:
- case AUDIT_DEL:
- if (nlmsg_len(nlh) < sizeof(struct audit_rule))
- return -EINVAL;
- if (audit_enabled == AUDIT_LOCKED) {
- audit_log_common_recv_msg(&ab, AUDIT_CONFIG_CHANGE, pid,
- uid, loginuid, sessionid, sid);
-
- audit_log_format(ab, " audit_enabled=%d res=0",
- audit_enabled);
- audit_log_end(ab);
- return -EPERM;
- }
- /* fallthrough */
- case AUDIT_LIST:
- err = audit_receive_filter(msg_type, NETLINK_CB(skb).pid,
- uid, seq, data, nlmsg_len(nlh),
- loginuid, sessionid, sid);
- break;
- case AUDIT_ADD_RULE:
- case AUDIT_DEL_RULE:
- if (nlmsg_len(nlh) < sizeof(struct audit_rule_data))
- return -EINVAL;
- if (audit_enabled == AUDIT_LOCKED) {
- audit_log_common_recv_msg(&ab, AUDIT_CONFIG_CHANGE, pid,
- uid, loginuid, sessionid, sid);
-
- audit_log_format(ab, " audit_enabled=%d res=0",
- audit_enabled);
- audit_log_end(ab);
- return -EPERM;
- }
- /* fallthrough */
- case AUDIT_LIST_RULES:
- err = audit_receive_filter(msg_type, NETLINK_CB(skb).pid,
- uid, seq, data, nlmsg_len(nlh),
- loginuid, sessionid, sid);
- break;
- case AUDIT_TRIM:
- audit_trim_trees();
-
- audit_log_common_recv_msg(&ab, AUDIT_CONFIG_CHANGE, pid,
- uid, loginuid, sessionid, sid);
-
- audit_log_format(ab, " op=trim res=1");
- audit_log_end(ab);
- break;
- case AUDIT_MAKE_EQUIV: {
- void *bufp = data;
- u32 sizes[2];
- size_t msglen = nlmsg_len(nlh);
- char *old, *new;
-
- err = -EINVAL;
- if (msglen < 2 * sizeof(u32))
- break;
- memcpy(sizes, bufp, 2 * sizeof(u32));
- bufp += 2 * sizeof(u32);
- msglen -= 2 * sizeof(u32);
- old = audit_unpack_string(&bufp, &msglen, sizes[0]);
- if (IS_ERR(old)) {
- err = PTR_ERR(old);
- break;
- }
- new = audit_unpack_string(&bufp, &msglen, sizes[1]);
- if (IS_ERR(new)) {
- err = PTR_ERR(new);
- kfree(old);
- break;
- }
- /* OK, here comes... */
- err = audit_tag_tree(old, new);
-
- audit_log_common_recv_msg(&ab, AUDIT_CONFIG_CHANGE, pid,
- uid, loginuid, sessionid, sid);
-
- audit_log_format(ab, " op=make_equiv old=");
- audit_log_untrustedstring(ab, old);
- audit_log_format(ab, " new=");
- audit_log_untrustedstring(ab, new);
- audit_log_format(ab, " res=%d", !err);
- audit_log_end(ab);
- kfree(old);
- kfree(new);
- break;
- }
- case AUDIT_SIGNAL_INFO:
- err = security_secid_to_secctx(audit_sig_sid, &ctx, &len);
- if (err)
- return err;
- sig_data = kmalloc(sizeof(*sig_data) + len, GFP_KERNEL);
- if (!sig_data) {
- security_release_secctx(ctx, len);
- return -ENOMEM;
- }
- sig_data->uid = audit_sig_uid;
- sig_data->pid = audit_sig_pid;
- memcpy(sig_data->ctx, ctx, len);
- security_release_secctx(ctx, len);
- audit_send_reply(NETLINK_CB(skb).pid, seq, AUDIT_SIGNAL_INFO,
- 0, 0, sig_data, sizeof(*sig_data) + len);
- kfree(sig_data);
- break;
- case AUDIT_TTY_GET: {
- struct audit_tty_status s;
- struct task_struct *tsk;
-
- read_lock(&tasklist_lock);
- tsk = find_task_by_vpid(pid);
- if (!tsk)
- err = -ESRCH;
- else {
- spin_lock_irq(&tsk->sighand->siglock);
- s.enabled = tsk->signal->audit_tty != 0;
- spin_unlock_irq(&tsk->sighand->siglock);
- }
- read_unlock(&tasklist_lock);
- audit_send_reply(NETLINK_CB(skb).pid, seq, AUDIT_TTY_GET, 0, 0,
- &s, sizeof(s));
- break;
- }
- case AUDIT_TTY_SET: {
- struct audit_tty_status *s;
- struct task_struct *tsk;
-
- if (nlh->nlmsg_len < sizeof(struct audit_tty_status))
- return -EINVAL;
- s = data;
- if (s->enabled != 0 && s->enabled != 1)
- return -EINVAL;
- read_lock(&tasklist_lock);
- tsk = find_task_by_vpid(pid);
- if (!tsk)
- err = -ESRCH;
- else {
- spin_lock_irq(&tsk->sighand->siglock);
- tsk->signal->audit_tty = s->enabled != 0;
- spin_unlock_irq(&tsk->sighand->siglock);
- }
- read_unlock(&tasklist_lock);
- break;
- }
- default:
- err = -EINVAL;
- break;
- }
-
- return err < 0 ? err : 0;
-}
-
-/*
- * Get message from skb (based on rtnetlink_rcv_skb). Each message is
- * processed by audit_receive_msg. Malformed skbs with wrong length are
- * discarded silently.
- */
-static void audit_receive_skb(struct sk_buff *skb)
-{
- int err;
- struct nlmsghdr *nlh;
- u32 rlen;
-
- while (skb->len >= NLMSG_SPACE(0)) {
- nlh = nlmsg_hdr(skb);
- if (nlh->nlmsg_len < sizeof(*nlh) || skb->len < nlh->nlmsg_len)
- return;
- rlen = NLMSG_ALIGN(nlh->nlmsg_len);
- if (rlen > skb->len)
- rlen = skb->len;
- if ((err = audit_receive_msg(skb, nlh))) {
- netlink_ack(skb, nlh, err);
- } else if (nlh->nlmsg_flags & NLM_F_ACK)
- netlink_ack(skb, nlh, 0);
- skb_pull(skb, rlen);
- }
-}
-
-/* Receive messages from netlink socket. */
-static void audit_receive(struct sk_buff *skb)
-{
- mutex_lock(&audit_cmd_mutex);
- audit_receive_skb(skb);
- mutex_unlock(&audit_cmd_mutex);
-}
-
-#ifdef CONFIG_AUDITSYSCALL
-static const struct inotify_operations audit_inotify_ops = {
- .handle_event = audit_handle_ievent,
- .destroy_watch = audit_free_parent,
-};
-#endif
-
-/* Initialize audit support at boot time. */
-static int __init audit_init(void)
-{
- int i;
-
- printk(KERN_INFO "audit: initializing netlink socket (%s)\n",
- audit_default ? "enabled" : "disabled");
- audit_sock = netlink_kernel_create(&init_net, NETLINK_AUDIT, 0,
- audit_receive, NULL, THIS_MODULE);
- if (!audit_sock)
- audit_panic("cannot initialize netlink socket");
- else
- audit_sock->sk_sndtimeo = MAX_SCHEDULE_TIMEOUT;
-
- skb_queue_head_init(&audit_skb_queue);
- skb_queue_head_init(&audit_skb_hold_queue);
- audit_initialized = 1;
- audit_enabled = audit_default;
- audit_ever_enabled |= !!audit_default;
-
- audit_log(NULL, GFP_KERNEL, AUDIT_KERNEL, "initialized");
-
-#ifdef CONFIG_AUDITSYSCALL
- audit_ih = inotify_init(&audit_inotify_ops);
- if (IS_ERR(audit_ih))
- audit_panic("cannot initialize inotify handle");
-#endif
-
- for (i = 0; i < AUDIT_INODE_BUCKETS; i++)
- INIT_LIST_HEAD(&audit_inode_hash[i]);
-
- return 0;
-}
-__initcall(audit_init);
-
-/* Process kernel command-line parameter at boot time. audit=0 or audit=1. */
-static int __init audit_enable(char *str)
-{
- audit_default = !!simple_strtol(str, NULL, 0);
- printk(KERN_INFO "audit: %s%s\n",
- audit_default ? "enabled" : "disabled",
- audit_initialized ? "" : " (after initialization)");
- if (audit_initialized) {
- audit_enabled = audit_default;
- audit_ever_enabled |= !!audit_default;
- }
- return 1;
-}
-
-__setup("audit=", audit_enable);
-
-static void audit_buffer_free(struct audit_buffer *ab)
-{
- unsigned long flags;
-
- if (!ab)
- return;
-
- if (ab->skb)
- kfree_skb(ab->skb);
-
- spin_lock_irqsave(&audit_freelist_lock, flags);
- if (audit_freelist_count > AUDIT_MAXFREE)
- kfree(ab);
- else {
- audit_freelist_count++;
- list_add(&ab->list, &audit_freelist);
- }
- spin_unlock_irqrestore(&audit_freelist_lock, flags);
-}
-
-static struct audit_buffer * audit_buffer_alloc(struct audit_context *ctx,
- gfp_t gfp_mask, int type)
-{
- unsigned long flags;
- struct audit_buffer *ab = NULL;
- struct nlmsghdr *nlh;
-
- spin_lock_irqsave(&audit_freelist_lock, flags);
- if (!list_empty(&audit_freelist)) {
- ab = list_entry(audit_freelist.next,
- struct audit_buffer, list);
- list_del(&ab->list);
- --audit_freelist_count;
- }
- spin_unlock_irqrestore(&audit_freelist_lock, flags);
-
- if (!ab) {
- ab = kmalloc(sizeof(*ab), gfp_mask);
- if (!ab)
- goto err;
- }
-
- ab->skb = alloc_skb(AUDIT_BUFSIZ, gfp_mask);
- if (!ab->skb)
- goto err;
-
- ab->ctx = ctx;
- ab->gfp_mask = gfp_mask;
- nlh = (struct nlmsghdr *)skb_put(ab->skb, NLMSG_SPACE(0));
- nlh->nlmsg_type = type;
- nlh->nlmsg_flags = 0;
- nlh->nlmsg_pid = 0;
- nlh->nlmsg_seq = 0;
- return ab;
-err:
- audit_buffer_free(ab);
- return NULL;
-}
-
-/**
- * audit_serial - compute a serial number for the audit record
- *
- * Compute a serial number for the audit record. Audit records are
- * written to user-space as soon as they are generated, so a complete
- * audit record may be written in several pieces. The timestamp of the
- * record and this serial number are used by the user-space tools to
- * determine which pieces belong to the same audit record. The
- * (timestamp,serial) tuple is unique for each syscall and is live from
- * syscall entry to syscall exit.
- *
- * NOTE: Another possibility is to store the formatted records off the
- * audit context (for those records that have a context), and emit them
- * all at syscall exit. However, this could delay the reporting of
- * significant errors until syscall exit (or never, if the system
- * halts).
- */
-unsigned int audit_serial(void)
-{
- static DEFINE_SPINLOCK(serial_lock);
- static unsigned int serial = 0;
-
- unsigned long flags;
- unsigned int ret;
-
- spin_lock_irqsave(&serial_lock, flags);
- do {
- ret = ++serial;
- } while (unlikely(!ret));
- spin_unlock_irqrestore(&serial_lock, flags);
-
- return ret;
-}
-
-static inline void audit_get_stamp(struct audit_context *ctx,
- struct timespec *t, unsigned int *serial)
-{
- if (ctx)
- auditsc_get_stamp(ctx, t, serial);
- else {
- *t = CURRENT_TIME;
- *serial = audit_serial();
- }
-}
-
-/* Obtain an audit buffer. This routine does locking to obtain the
- * audit buffer, but then no locking is required for calls to
- * audit_log_*format. If the tsk is a task that is currently in a
- * syscall, then the syscall is marked as auditable and an audit record
- * will be written at syscall exit. If there is no associated task, tsk
- * should be NULL. */
-
-/**
- * audit_log_start - obtain an audit buffer
- * @ctx: audit_context (may be NULL)
- * @gfp_mask: type of allocation
- * @type: audit message type
- *
- * Returns audit_buffer pointer on success or NULL on error.
- *
- * Obtain an audit buffer. This routine does locking to obtain the
- * audit buffer, but then no locking is required for calls to
- * audit_log_*format. If the task (ctx) is a task that is currently in a
- * syscall, then the syscall is marked as auditable and an audit record
- * will be written at syscall exit. If there is no associated task, then
- * task context (ctx) should be NULL.
- */
-struct audit_buffer *audit_log_start(struct audit_context *ctx, gfp_t gfp_mask,
- int type)
-{
- struct audit_buffer *ab = NULL;
- struct timespec t;
- unsigned int uninitialized_var(serial);
- int reserve;
- unsigned long timeout_start = jiffies;
-
- if (!audit_initialized)
- return NULL;
-
- if (unlikely(audit_filter_type(type)))
- return NULL;
-
- if (gfp_mask & __GFP_WAIT)
- reserve = 0;
- else
- reserve = 5; /* Allow atomic callers to go up to five
- entries over the normal backlog limit */
-
- while (audit_backlog_limit
- && skb_queue_len(&audit_skb_queue) > audit_backlog_limit + reserve) {
- if (gfp_mask & __GFP_WAIT && audit_backlog_wait_time
- && time_before(jiffies, timeout_start + audit_backlog_wait_time)) {
-
- /* Wait for auditd to drain the queue a little */
- DECLARE_WAITQUEUE(wait, current);
- set_current_state(TASK_INTERRUPTIBLE);
- add_wait_queue(&audit_backlog_wait, &wait);
-
- if (audit_backlog_limit &&
- skb_queue_len(&audit_skb_queue) > audit_backlog_limit)
- schedule_timeout(timeout_start + audit_backlog_wait_time - jiffies);
-
- __set_current_state(TASK_RUNNING);
- remove_wait_queue(&audit_backlog_wait, &wait);
- continue;
- }
- if (audit_rate_check() && printk_ratelimit())
- printk(KERN_WARNING
- "audit: audit_backlog=%d > "
- "audit_backlog_limit=%d\n",
- skb_queue_len(&audit_skb_queue),
- audit_backlog_limit);
- audit_log_lost("backlog limit exceeded");
- audit_backlog_wait_time = audit_backlog_wait_overflow;
- wake_up(&audit_backlog_wait);
- return NULL;
- }
-
- ab = audit_buffer_alloc(ctx, gfp_mask, type);
- if (!ab) {
- audit_log_lost("out of memory in audit_log_start");
- return NULL;
- }
-
- audit_get_stamp(ab->ctx, &t, &serial);
-
- audit_log_format(ab, "audit(%lu.%03lu:%u): ",
- t.tv_sec, t.tv_nsec/1000000, serial);
- return ab;
-}
-
-/**
- * audit_expand - expand skb in the audit buffer
- * @ab: audit_buffer
- * @extra: space to add at tail of the skb
- *
- * Returns 0 (no space) on failed expansion, or available space if
- * successful.
- */
-static inline int audit_expand(struct audit_buffer *ab, int extra)
-{
- struct sk_buff *skb = ab->skb;
- int oldtail = skb_tailroom(skb);
- int ret = pskb_expand_head(skb, 0, extra, ab->gfp_mask);
- int newtail = skb_tailroom(skb);
-
- if (ret < 0) {
- audit_log_lost("out of memory in audit_expand");
- return 0;
- }
-
- skb->truesize += newtail - oldtail;
- return newtail;
-}
-
-/*
- * Format an audit message into the audit buffer. If there isn't enough
- * room in the audit buffer, more room will be allocated and vsnprint
- * will be called a second time. Currently, we assume that a printk
- * can't format message larger than 1024 bytes, so we don't either.
- */
-static void audit_log_vformat(struct audit_buffer *ab, const char *fmt,
- va_list args)
-{
- int len, avail;
- struct sk_buff *skb;
- va_list args2;
-
- if (!ab)
- return;
-
- BUG_ON(!ab->skb);
- skb = ab->skb;
- avail = skb_tailroom(skb);
- if (avail == 0) {
- avail = audit_expand(ab, AUDIT_BUFSIZ);
- if (!avail)
- goto out;
- }
- va_copy(args2, args);
- len = vsnprintf(skb_tail_pointer(skb), avail, fmt, args);
- if (len >= avail) {
- /* The printk buffer is 1024 bytes long, so if we get
- * here and AUDIT_BUFSIZ is at least 1024, then we can
- * log everything that printk could have logged. */
- avail = audit_expand(ab,
- max_t(unsigned, AUDIT_BUFSIZ, 1+len-avail));
- if (!avail)
- goto out;
- len = vsnprintf(skb_tail_pointer(skb), avail, fmt, args2);
- }
- va_end(args2);
- if (len > 0)
- skb_put(skb, len);
-out:
- return;
-}
-
-/**
- * audit_log_format - format a message into the audit buffer.
- * @ab: audit_buffer
- * @fmt: format string
- * @...: optional parameters matching @fmt string
- *
- * All the work is done in audit_log_vformat.
- */
-void audit_log_format(struct audit_buffer *ab, const char *fmt, ...)
-{
- va_list args;
-
- if (!ab)
- return;
- va_start(args, fmt);
- audit_log_vformat(ab, fmt, args);
- va_end(args);
-}
-
-/**
- * audit_log_hex - convert a buffer to hex and append it to the audit skb
- * @ab: the audit_buffer
- * @buf: buffer to convert to hex
- * @len: length of @buf to be converted
- *
- * No return value; failure to expand is silently ignored.
- *
- * This function will take the passed buf and convert it into a string of
- * ascii hex digits. The new string is placed onto the skb.
- */
-void audit_log_n_hex(struct audit_buffer *ab, const unsigned char *buf,
- size_t len)
-{
- int i, avail, new_len;
- unsigned char *ptr;
- struct sk_buff *skb;
- static const unsigned char *hex = "0123456789ABCDEF";
-
- if (!ab)
- return;
-
- BUG_ON(!ab->skb);
- skb = ab->skb;
- avail = skb_tailroom(skb);
- new_len = len<<1;
- if (new_len >= avail) {
- /* Round the buffer request up to the next multiple */
- new_len = AUDIT_BUFSIZ*(((new_len-avail)/AUDIT_BUFSIZ) + 1);
- avail = audit_expand(ab, new_len);
- if (!avail)
- return;
- }
-
- ptr = skb_tail_pointer(skb);
- for (i=0; i>4]; /* Upper nibble */
- *ptr++ = hex[buf[i] & 0x0F]; /* Lower nibble */
- }
- *ptr = 0;
- skb_put(skb, len << 1); /* new string is twice the old string */
-}
-
-/*
- * Format a string of no more than slen characters into the audit buffer,
- * enclosed in quote marks.
- */
-void audit_log_n_string(struct audit_buffer *ab, const char *string,
- size_t slen)
-{
- int avail, new_len;
- unsigned char *ptr;
- struct sk_buff *skb;
-
- if (!ab)
- return;
-
- BUG_ON(!ab->skb);
- skb = ab->skb;
- avail = skb_tailroom(skb);
- new_len = slen + 3; /* enclosing quotes + null terminator */
- if (new_len > avail) {
- avail = audit_expand(ab, new_len);
- if (!avail)
- return;
- }
- ptr = skb_tail_pointer(skb);
- *ptr++ = '"';
- memcpy(ptr, string, slen);
- ptr += slen;
- *ptr++ = '"';
- *ptr = 0;
- skb_put(skb, slen + 2); /* don't include null terminator */
-}
-
-/**
- * audit_string_contains_control - does a string need to be logged in hex
- * @string: string to be checked
- * @len: max length of the string to check
- */
-int audit_string_contains_control(const char *string, size_t len)
-{
- const unsigned char *p;
- for (p = string; p < (const unsigned char *)string + len && *p; p++) {
- if (*p == '"' || *p < 0x21 || *p > 0x7e)
- return 1;
- }
- return 0;
-}
-
-/**
- * audit_log_n_untrustedstring - log a string that may contain random characters
- * @ab: audit_buffer
- * @len: length of string (not including trailing null)
- * @string: string to be logged
- *
- * This code will escape a string that is passed to it if the string
- * contains a control character, unprintable character, double quote mark,
- * or a space. Unescaped strings will start and end with a double quote mark.
- * Strings that are escaped are printed in hex (2 digits per char).
- *
- * The caller specifies the number of characters in the string to log, which may
- * or may not be the entire string.
- */
-void audit_log_n_untrustedstring(struct audit_buffer *ab, const char *string,
- size_t len)
-{
- if (audit_string_contains_control(string, len))
- audit_log_n_hex(ab, string, len);
- else
- audit_log_n_string(ab, string, len);
-}
-
-/**
- * audit_log_untrustedstring - log a string that may contain random characters
- * @ab: audit_buffer
- * @string: string to be logged
- *
- * Same as audit_log_n_untrustedstring(), except that strlen is used to
- * determine string length.
- */
-void audit_log_untrustedstring(struct audit_buffer *ab, const char *string)
-{
- audit_log_n_untrustedstring(ab, string, strlen(string));
-}
-
-/* This is a helper-function to print the escaped d_path */
-void audit_log_d_path(struct audit_buffer *ab, const char *prefix,
- struct path *path)
-{
- char *p, *pathname;
-
- if (prefix)
- audit_log_format(ab, " %s", prefix);
-
- /* We will allow 11 spaces for ' (deleted)' to be appended */
- pathname = kmalloc(PATH_MAX+11, ab->gfp_mask);
- if (!pathname) {
- audit_log_format(ab, "");
- return;
- }
- p = d_path(path, pathname, PATH_MAX+11);
- if (IS_ERR(p)) { /* Should never happen since we send PATH_MAX */
- /* FIXME: can we save some information here? */
- audit_log_format(ab, "");
- } else
- audit_log_untrustedstring(ab, p);
- kfree(pathname);
-}
-
-/**
- * audit_log_end - end one audit record
- * @ab: the audit_buffer
- *
- * The netlink_* functions cannot be called inside an irq context, so
- * the audit buffer is placed on a queue and a tasklet is scheduled to
- * remove them from the queue outside the irq context. May be called in
- * any context.
- */
-void audit_log_end(struct audit_buffer *ab)
-{
- if (!ab)
- return;
- if (!audit_rate_check()) {
- audit_log_lost("rate limit exceeded");
- } else {
- struct nlmsghdr *nlh = nlmsg_hdr(ab->skb);
- nlh->nlmsg_len = ab->skb->len - NLMSG_SPACE(0);
-
- if (audit_pid) {
- skb_queue_tail(&audit_skb_queue, ab->skb);
- wake_up_interruptible(&kauditd_wait);
- } else {
- if (nlh->nlmsg_type != AUDIT_EOE) {
- if (printk_ratelimit()) {
- printk(KERN_NOTICE "type=%d %s\n",
- nlh->nlmsg_type,
- ab->skb->data + NLMSG_SPACE(0));
- } else
- audit_log_lost("printk limit exceeded\n");
- }
- audit_hold_skb(ab->skb);
- }
- ab->skb = NULL;
- }
- audit_buffer_free(ab);
-}
-
-/**
- * audit_log - Log an audit record
- * @ctx: audit context
- * @gfp_mask: type of allocation
- * @type: audit message type
- * @fmt: format string to use
- * @...: variable parameters matching the format string
- *
- * This is a convenience function that calls audit_log_start,
- * audit_log_vformat, and audit_log_end. It may be called
- * in any context.
- */
-void audit_log(struct audit_context *ctx, gfp_t gfp_mask, int type,
- const char *fmt, ...)
-{
- struct audit_buffer *ab;
- va_list args;
-
- ab = audit_log_start(ctx, gfp_mask, type);
- if (ab) {
- va_start(args, fmt);
- audit_log_vformat(ab, fmt, args);
- va_end(args);
- audit_log_end(ab);
- }
-}
-
-EXPORT_SYMBOL(audit_log_start);
-EXPORT_SYMBOL(audit_log_end);
-EXPORT_SYMBOL(audit_log_format);
-EXPORT_SYMBOL(audit_log);
-#include "audit.h"
-#include
-#include
-#include
-
-struct audit_tree;
-struct audit_chunk;
-
-struct audit_tree {
- atomic_t count;
- int goner;
- struct audit_chunk *root;
- struct list_head chunks;
- struct list_head rules;
- struct list_head list;
- struct list_head same_root;
- struct rcu_head head;
- char pathname[];
-};
-
-struct audit_chunk {
- struct list_head hash;
- struct inotify_watch watch;
- struct list_head trees; /* with root here */
- int dead;
- int count;
- atomic_long_t refs;
- struct rcu_head head;
- struct node {
- struct list_head list;
- struct audit_tree *owner;
- unsigned index; /* index; upper bit indicates 'will prune' */
- } owners[];
-};
-
-static LIST_HEAD(tree_list);
-static LIST_HEAD(prune_list);
-
-/*
- * One struct chunk is attached to each inode of interest.
- * We replace struct chunk on tagging/untagging.
- * Rules have pointer to struct audit_tree.
- * Rules have struct list_head rlist forming a list of rules over
- * the same tree.
- * References to struct chunk are collected at audit_inode{,_child}()
- * time and used in AUDIT_TREE rule matching.
- * These references are dropped at the same time we are calling
- * audit_free_names(), etc.
- *
- * Cyclic lists galore:
- * tree.chunks anchors chunk.owners[].list hash_lock
- * tree.rules anchors rule.rlist audit_filter_mutex
- * chunk.trees anchors tree.same_root hash_lock
- * chunk.hash is a hash with middle bits of watch.inode as
- * a hash function. RCU, hash_lock
- *
- * tree is refcounted; one reference for "some rules on rules_list refer to
- * it", one for each chunk with pointer to it.
- *
- * chunk is refcounted by embedded inotify_watch + .refs (non-zero refcount
- * of watch contributes 1 to .refs).
- *
- * node.index allows to get from node.list to containing chunk.
- * MSB of that sucker is stolen to mark taggings that we might have to
- * revert - several operations have very unpleasant cleanup logics and
- * that makes a difference. Some.
- */
-
-static struct inotify_handle *rtree_ih;
-
-static struct audit_tree *alloc_tree(const char *s)
-{
- struct audit_tree *tree;
-
- tree = kmalloc(sizeof(struct audit_tree) + strlen(s) + 1, GFP_KERNEL);
- if (tree) {
- atomic_set(&tree->count, 1);
- tree->goner = 0;
- INIT_LIST_HEAD(&tree->chunks);
- INIT_LIST_HEAD(&tree->rules);
- INIT_LIST_HEAD(&tree->list);
- INIT_LIST_HEAD(&tree->same_root);
- tree->root = NULL;
- strcpy(tree->pathname, s);
- }
- return tree;
-}
-
-static inline void get_tree(struct audit_tree *tree)
-{
- atomic_inc(&tree->count);
-}
-
-static void __put_tree(struct rcu_head *rcu)
-{
- struct audit_tree *tree = container_of(rcu, struct audit_tree, head);
- kfree(tree);
-}
-
-static inline void put_tree(struct audit_tree *tree)
-{
- if (atomic_dec_and_test(&tree->count))
- call_rcu(&tree->head, __put_tree);
-}
-
-/* to avoid bringing the entire thing in audit.h */
-const char *audit_tree_path(struct audit_tree *tree)
-{
- return tree->pathname;
-}
-
-static struct audit_chunk *alloc_chunk(int count)
-{
- struct audit_chunk *chunk;
- size_t size;
- int i;
-
- size = offsetof(struct audit_chunk, owners) + count * sizeof(struct node);
- chunk = kzalloc(size, GFP_KERNEL);
- if (!chunk)
- return NULL;
-
- INIT_LIST_HEAD(&chunk->hash);
- INIT_LIST_HEAD(&chunk->trees);
- chunk->count = count;
- atomic_long_set(&chunk->refs, 1);
- for (i = 0; i < count; i++) {
- INIT_LIST_HEAD(&chunk->owners[i].list);
- chunk->owners[i].index = i;
- }
- inotify_init_watch(&chunk->watch);
- return chunk;
-}
-
-static void free_chunk(struct audit_chunk *chunk)
-{
- int i;
-
- for (i = 0; i < chunk->count; i++) {
- if (chunk->owners[i].owner)
- put_tree(chunk->owners[i].owner);
- }
- kfree(chunk);
-}
-
-void audit_put_chunk(struct audit_chunk *chunk)
-{
- if (atomic_long_dec_and_test(&chunk->refs))
- free_chunk(chunk);
-}
-
-static void __put_chunk(struct rcu_head *rcu)
-{
- struct audit_chunk *chunk = container_of(rcu, struct audit_chunk, head);
- audit_put_chunk(chunk);
-}
-
-enum {HASH_SIZE = 128};
-static struct list_head chunk_hash_heads[HASH_SIZE];
-static __cacheline_aligned_in_smp DEFINE_SPINLOCK(hash_lock);
-
-static inline struct list_head *chunk_hash(const struct inode *inode)
-{
- unsigned long n = (unsigned long)inode / L1_CACHE_BYTES;
- return chunk_hash_heads + n % HASH_SIZE;
-}
-
-/* hash_lock is held by caller */
-static void insert_hash(struct audit_chunk *chunk)
-{
- struct list_head *list = chunk_hash(chunk->watch.inode);
- list_add_rcu(&chunk->hash, list);
-}
-
-/* called under rcu_read_lock */
-struct audit_chunk *audit_tree_lookup(const struct inode *inode)
-{
- struct list_head *list = chunk_hash(inode);
- struct audit_chunk *p;
-
- list_for_each_entry_rcu(p, list, hash) {
- if (p->watch.inode == inode) {
- atomic_long_inc(&p->refs);
- return p;
- }
- }
- return NULL;
-}
-
-int audit_tree_match(struct audit_chunk *chunk, struct audit_tree *tree)
-{
- int n;
- for (n = 0; n < chunk->count; n++)
- if (chunk->owners[n].owner == tree)
- return 1;
- return 0;
-}
-
-/* tagging and untagging inodes with trees */
-
-static struct audit_chunk *find_chunk(struct node *p)
-{
- int index = p->index & ~(1U<<31);
- p -= index;
- return container_of(p, struct audit_chunk, owners[0]);
-}
-
-static void untag_chunk(struct node *p)
-{
- struct audit_chunk *chunk = find_chunk(p);
- struct audit_chunk *new;
- struct audit_tree *owner;
- int size = chunk->count - 1;
- int i, j;
-
- if (!pin_inotify_watch(&chunk->watch)) {
- /*
- * Filesystem is shutting down; all watches are getting
- * evicted, just take it off the node list for this
- * tree and let the eviction logics take care of the
- * rest.
- */
- owner = p->owner;
- if (owner->root == chunk) {
- list_del_init(&owner->same_root);
- owner->root = NULL;
- }
- list_del_init(&p->list);
- p->owner = NULL;
- put_tree(owner);
- return;
- }
-
- spin_unlock(&hash_lock);
-
- /*
- * pin_inotify_watch() succeeded, so the watch won't go away
- * from under us.
- */
- mutex_lock(&chunk->watch.inode->inotify_mutex);
- if (chunk->dead) {
- mutex_unlock(&chunk->watch.inode->inotify_mutex);
- goto out;
- }
-
- owner = p->owner;
-
- if (!size) {
- chunk->dead = 1;
- spin_lock(&hash_lock);
- list_del_init(&chunk->trees);
- if (owner->root == chunk)
- owner->root = NULL;
- list_del_init(&p->list);
- list_del_rcu(&chunk->hash);
- spin_unlock(&hash_lock);
- inotify_evict_watch(&chunk->watch);
- mutex_unlock(&chunk->watch.inode->inotify_mutex);
- put_inotify_watch(&chunk->watch);
- goto out;
- }
-
- new = alloc_chunk(size);
- if (!new)
- goto Fallback;
- if (inotify_clone_watch(&chunk->watch, &new->watch) < 0) {
- free_chunk(new);
- goto Fallback;
- }
-
- chunk->dead = 1;
- spin_lock(&hash_lock);
- list_replace_init(&chunk->trees, &new->trees);
- if (owner->root == chunk) {
- list_del_init(&owner->same_root);
- owner->root = NULL;
- }
-
- for (i = j = 0; j <= size; i++, j++) {
- struct audit_tree *s;
- if (&chunk->owners[j] == p) {
- list_del_init(&p->list);
- i--;
- continue;
- }
- s = chunk->owners[j].owner;
- new->owners[i].owner = s;
- new->owners[i].index = chunk->owners[j].index - j + i;
- if (!s) /* result of earlier fallback */
- continue;
- get_tree(s);
- list_replace_init(&chunk->owners[j].list, &new->owners[i].list);
- }
-
- list_replace_rcu(&chunk->hash, &new->hash);
- list_for_each_entry(owner, &new->trees, same_root)
- owner->root = new;
- spin_unlock(&hash_lock);
- inotify_evict_watch(&chunk->watch);
- mutex_unlock(&chunk->watch.inode->inotify_mutex);
- put_inotify_watch(&chunk->watch);
- goto out;
-
-Fallback:
- // do the best we can
- spin_lock(&hash_lock);
- if (owner->root == chunk) {
- list_del_init(&owner->same_root);
- owner->root = NULL;
- }
- list_del_init(&p->list);
- p->owner = NULL;
- put_tree(owner);
- spin_unlock(&hash_lock);
- mutex_unlock(&chunk->watch.inode->inotify_mutex);
-out:
- unpin_inotify_watch(&chunk->watch);
- spin_lock(&hash_lock);
-}
-
-static int create_chunk(struct inode *inode, struct audit_tree *tree)
-{
- struct audit_chunk *chunk = alloc_chunk(1);
- if (!chunk)
- return -ENOMEM;
-
- if (inotify_add_watch(rtree_ih, &chunk->watch, inode, IN_IGNORED | IN_DELETE_SELF) < 0) {
- free_chunk(chunk);
- return -ENOSPC;
- }
-
- mutex_lock(&inode->inotify_mutex);
- spin_lock(&hash_lock);
- if (tree->goner) {
- spin_unlock(&hash_lock);
- chunk->dead = 1;
- inotify_evict_watch(&chunk->watch);
- mutex_unlock(&inode->inotify_mutex);
- put_inotify_watch(&chunk->watch);
- return 0;
- }
- chunk->owners[0].index = (1U << 31);
- chunk->owners[0].owner = tree;
- get_tree(tree);
- list_add(&chunk->owners[0].list, &tree->chunks);
- if (!tree->root) {
- tree->root = chunk;
- list_add(&tree->same_root, &chunk->trees);
- }
- insert_hash(chunk);
- spin_unlock(&hash_lock);
- mutex_unlock(&inode->inotify_mutex);
- return 0;
-}
-
-/* the first tagged inode becomes root of tree */
-static int tag_chunk(struct inode *inode, struct audit_tree *tree)
-{
- struct inotify_watch *watch;
- struct audit_tree *owner;
- struct audit_chunk *chunk, *old;
- struct node *p;
- int n;
-
- if (inotify_find_watch(rtree_ih, inode, &watch) < 0)
- return create_chunk(inode, tree);
-
- old = container_of(watch, struct audit_chunk, watch);
-
- /* are we already there? */
- spin_lock(&hash_lock);
- for (n = 0; n < old->count; n++) {
- if (old->owners[n].owner == tree) {
- spin_unlock(&hash_lock);
- put_inotify_watch(&old->watch);
- return 0;
- }
- }
- spin_unlock(&hash_lock);
-
- chunk = alloc_chunk(old->count + 1);
- if (!chunk) {
- put_inotify_watch(&old->watch);
- return -ENOMEM;
- }
-
- mutex_lock(&inode->inotify_mutex);
- if (inotify_clone_watch(&old->watch, &chunk->watch) < 0) {
- mutex_unlock(&inode->inotify_mutex);
- free_chunk(chunk);
- return -ENOSPC;
- }
- spin_lock(&hash_lock);
- if (tree->goner) {
- spin_unlock(&hash_lock);
- chunk->dead = 1;
- inotify_evict_watch(&chunk->watch);
- mutex_unlock(&inode->inotify_mutex);
- put_inotify_watch(&chunk->watch);
- return 0;
- }
- list_replace_init(&old->trees, &chunk->trees);
- for (n = 0, p = chunk->owners; n < old->count; n++, p++) {
- struct audit_tree *s = old->owners[n].owner;
- p->owner = s;
- p->index = old->owners[n].index;
- if (!s) /* result of fallback in untag */
- continue;
- get_tree(s);
- list_replace_init(&old->owners[n].list, &p->list);
- }
- p->index = (chunk->count - 1) | (1U<<31);
- p->owner = tree;
- get_tree(tree);
- list_add(&p->list, &tree->chunks);
- list_replace_rcu(&old->hash, &chunk->hash);
- list_for_each_entry(owner, &chunk->trees, same_root)
- owner->root = chunk;
- old->dead = 1;
- if (!tree->root) {
- tree->root = chunk;
- list_add(&tree->same_root, &chunk->trees);
- }
- spin_unlock(&hash_lock);
- inotify_evict_watch(&old->watch);
- mutex_unlock(&inode->inotify_mutex);
- put_inotify_watch(&old->watch); /* pair to inotify_find_watch */
- put_inotify_watch(&old->watch); /* and kill it */
- return 0;
-}
-
-static void kill_rules(struct audit_tree *tree)
-{
- struct audit_krule *rule, *next;
- struct audit_entry *entry;
- struct audit_buffer *ab;
-
- list_for_each_entry_safe(rule, next, &tree->rules, rlist) {
- entry = container_of(rule, struct audit_entry, rule);
-
- list_del_init(&rule->rlist);
- if (rule->tree) {
- /* not a half-baked one */
- ab = audit_log_start(NULL, GFP_KERNEL, AUDIT_CONFIG_CHANGE);
- audit_log_format(ab, "op=remove rule dir=");
- audit_log_untrustedstring(ab, rule->tree->pathname);
- if (rule->filterkey) {
- audit_log_format(ab, " key=");
- audit_log_untrustedstring(ab, rule->filterkey);
- } else
- audit_log_format(ab, " key=(null)");
- audit_log_format(ab, " list=%d res=1", rule->listnr);
- audit_log_end(ab);
- rule->tree = NULL;
- list_del_rcu(&entry->list);
- call_rcu(&entry->rcu, audit_free_rule_rcu);
- }
- }
-}
-
-/*
- * finish killing struct audit_tree
- */
-static void prune_one(struct audit_tree *victim)
-{
- spin_lock(&hash_lock);
- while (!list_empty(&victim->chunks)) {
- struct node *p;
-
- p = list_entry(victim->chunks.next, struct node, list);
-
- untag_chunk(p);
- }
- spin_unlock(&hash_lock);
- put_tree(victim);
-}
-
-/* trim the uncommitted chunks from tree */
-
-static void trim_marked(struct audit_tree *tree)
-{
- struct list_head *p, *q;
- spin_lock(&hash_lock);
- if (tree->goner) {
- spin_unlock(&hash_lock);
- return;
- }
- /* reorder */
- for (p = tree->chunks.next; p != &tree->chunks; p = q) {
- struct node *node = list_entry(p, struct node, list);
- q = p->next;
- if (node->index & (1U<<31)) {
- list_del_init(p);
- list_add(p, &tree->chunks);
- }
- }
-
- while (!list_empty(&tree->chunks)) {
- struct node *node;
-
- node = list_entry(tree->chunks.next, struct node, list);
-
- /* have we run out of marked? */
- if (!(node->index & (1U<<31)))
- break;
-
- untag_chunk(node);
- }
- if (!tree->root && !tree->goner) {
- tree->goner = 1;
- spin_unlock(&hash_lock);
- mutex_lock(&audit_filter_mutex);
- kill_rules(tree);
- list_del_init(&tree->list);
- mutex_unlock(&audit_filter_mutex);
- prune_one(tree);
- } else {
- spin_unlock(&hash_lock);
- }
-}
-
-/* called with audit_filter_mutex */
-int audit_remove_tree_rule(struct audit_krule *rule)
-{
- struct audit_tree *tree;
- tree = rule->tree;
- if (tree) {
- spin_lock(&hash_lock);
- list_del_init(&rule->rlist);
- if (list_empty(&tree->rules) && !tree->goner) {
- tree->root = NULL;
- list_del_init(&tree->same_root);
- tree->goner = 1;
- list_move(&tree->list, &prune_list);
- rule->tree = NULL;
- spin_unlock(&hash_lock);
- audit_schedule_prune();
- return 1;
- }
- rule->tree = NULL;
- spin_unlock(&hash_lock);
- return 1;
- }
- return 0;
-}
-
-void audit_trim_trees(void)
-{
- struct list_head cursor;
-
- mutex_lock(&audit_filter_mutex);
- list_add(&cursor, &tree_list);
- while (cursor.next != &tree_list) {
- struct audit_tree *tree;
- struct nameidata nd;
- struct vfsmount *root_mnt;
- struct node *node;
- struct list_head list;
- int err;
-
- tree = container_of(cursor.next, struct audit_tree, list);
- get_tree(tree);
- list_del(&cursor);
- list_add(&cursor, &tree->list);
- mutex_unlock(&audit_filter_mutex);
-
- err = path_lookup(tree->pathname, 0, &nd);
- if (err)
- goto skip_it;
-
- root_mnt = collect_mounts(nd.path.mnt, nd.path.dentry);
- path_put(&nd.path);
- if (!root_mnt)
- goto skip_it;
-
- list_add_tail(&list, &root_mnt->mnt_list);
- spin_lock(&hash_lock);
- list_for_each_entry(node, &tree->chunks, list) {
- struct audit_chunk *chunk = find_chunk(node);
- struct inode *inode = chunk->watch.inode;
- struct vfsmount *mnt;
- node->index |= 1U<<31;
- list_for_each_entry(mnt, &list, mnt_list) {
- if (mnt->mnt_root->d_inode == inode) {
- node->index &= ~(1U<<31);
- break;
- }
- }
- }
- spin_unlock(&hash_lock);
- trim_marked(tree);
- put_tree(tree);
- list_del_init(&list);
- drop_collected_mounts(root_mnt);
-skip_it:
- mutex_lock(&audit_filter_mutex);
- }
- list_del(&cursor);
- mutex_unlock(&audit_filter_mutex);
-}
-
-static int is_under(struct vfsmount *mnt, struct dentry *dentry,
- struct nameidata *nd)
-{
- if (mnt != nd->path.mnt) {
- for (;;) {
- if (mnt->mnt_parent == mnt)
- return 0;
- if (mnt->mnt_parent == nd->path.mnt)
- break;
- mnt = mnt->mnt_parent;
- }
- dentry = mnt->mnt_mountpoint;
- }
- return is_subdir(dentry, nd->path.dentry);
-}
-
-int audit_make_tree(struct audit_krule *rule, char *pathname, u32 op)
-{
-
- if (pathname[0] != '/' ||
- rule->listnr != AUDIT_FILTER_EXIT ||
- op & ~AUDIT_EQUAL ||
- rule->inode_f || rule->watch || rule->tree)
- return -EINVAL;
- rule->tree = alloc_tree(pathname);
- if (!rule->tree)
- return -ENOMEM;
- return 0;
-}
-
-void audit_put_tree(struct audit_tree *tree)
-{
- put_tree(tree);
-}
-
-/* called with audit_filter_mutex */
-int audit_add_tree_rule(struct audit_krule *rule)
-{
- struct audit_tree *seed = rule->tree, *tree;
- struct nameidata nd;
- struct vfsmount *mnt, *p;
- struct list_head list;
- int err;
-
- list_for_each_entry(tree, &tree_list, list) {
- if (!strcmp(seed->pathname, tree->pathname)) {
- put_tree(seed);
- rule->tree = tree;
- list_add(&rule->rlist, &tree->rules);
- return 0;
- }
- }
- tree = seed;
- list_add(&tree->list, &tree_list);
- list_add(&rule->rlist, &tree->rules);
- /* do not set rule->tree yet */
- mutex_unlock(&audit_filter_mutex);
-
- err = path_lookup(tree->pathname, 0, &nd);
- if (err)
- goto Err;
- mnt = collect_mounts(nd.path.mnt, nd.path.dentry);
- path_put(&nd.path);
- if (!mnt) {
- err = -ENOMEM;
- goto Err;
- }
- list_add_tail(&list, &mnt->mnt_list);
-
- get_tree(tree);
- list_for_each_entry(p, &list, mnt_list) {
- err = tag_chunk(p->mnt_root->d_inode, tree);
- if (err)
- break;
- }
-
- list_del(&list);
- drop_collected_mounts(mnt);
-
- if (!err) {
- struct node *node;
- spin_lock(&hash_lock);
- list_for_each_entry(node, &tree->chunks, list)
- node->index &= ~(1U<<31);
- spin_unlock(&hash_lock);
- } else {
- trim_marked(tree);
- goto Err;
- }
-
- mutex_lock(&audit_filter_mutex);
- if (list_empty(&rule->rlist)) {
- put_tree(tree);
- return -ENOENT;
- }
- rule->tree = tree;
- put_tree(tree);
-
- return 0;
-Err:
- mutex_lock(&audit_filter_mutex);
- list_del_init(&tree->list);
- list_del_init(&tree->rules);
- put_tree(tree);
- return err;
-}
-
-int audit_tag_tree(char *old, char *new)
-{
- struct list_head cursor, barrier;
- int failed = 0;
- struct nameidata nd;
- struct vfsmount *tagged;
- struct list_head list;
- struct vfsmount *mnt;
- struct dentry *dentry;
- int err;
-
- err = path_lookup(new, 0, &nd);
- if (err)
- return err;
- tagged = collect_mounts(nd.path.mnt, nd.path.dentry);
- path_put(&nd.path);
- if (!tagged)
- return -ENOMEM;
-
- err = path_lookup(old, 0, &nd);
- if (err) {
- drop_collected_mounts(tagged);
- return err;
- }
- mnt = mntget(nd.path.mnt);
- dentry = dget(nd.path.dentry);
- path_put(&nd.path);
-
- if (dentry == tagged->mnt_root && dentry == mnt->mnt_root)
- follow_up(&mnt, &dentry);
-
- list_add_tail(&list, &tagged->mnt_list);
-
- mutex_lock(&audit_filter_mutex);
- list_add(&barrier, &tree_list);
- list_add(&cursor, &barrier);
-
- while (cursor.next != &tree_list) {
- struct audit_tree *tree;
- struct vfsmount *p;
-
- tree = container_of(cursor.next, struct audit_tree, list);
- get_tree(tree);
- list_del(&cursor);
- list_add(&cursor, &tree->list);
- mutex_unlock(&audit_filter_mutex);
-
- err = path_lookup(tree->pathname, 0, &nd);
- if (err) {
- put_tree(tree);
- mutex_lock(&audit_filter_mutex);
- continue;
- }
-
- spin_lock(&vfsmount_lock);
- if (!is_under(mnt, dentry, &nd)) {
- spin_unlock(&vfsmount_lock);
- path_put(&nd.path);
- put_tree(tree);
- mutex_lock(&audit_filter_mutex);
- continue;
- }
- spin_unlock(&vfsmount_lock);
- path_put(&nd.path);
-
- list_for_each_entry(p, &list, mnt_list) {
- failed = tag_chunk(p->mnt_root->d_inode, tree);
- if (failed)
- break;
- }
-
- if (failed) {
- put_tree(tree);
- mutex_lock(&audit_filter_mutex);
- break;
- }
-
- mutex_lock(&audit_filter_mutex);
- spin_lock(&hash_lock);
- if (!tree->goner) {
- list_del(&tree->list);
- list_add(&tree->list, &tree_list);
- }
- spin_unlock(&hash_lock);
- put_tree(tree);
- }
-
- while (barrier.prev != &tree_list) {
- struct audit_tree *tree;
-
- tree = container_of(barrier.prev, struct audit_tree, list);
- get_tree(tree);
- list_del(&tree->list);
- list_add(&tree->list, &barrier);
- mutex_unlock(&audit_filter_mutex);
-
- if (!failed) {
- struct node *node;
- spin_lock(&hash_lock);
- list_for_each_entry(node, &tree->chunks, list)
- node->index &= ~(1U<<31);
- spin_unlock(&hash_lock);
- } else {
- trim_marked(tree);
- }
-
- put_tree(tree);
- mutex_lock(&audit_filter_mutex);
- }
- list_del(&barrier);
- list_del(&cursor);
- list_del(&list);
- mutex_unlock(&audit_filter_mutex);
- dput(dentry);
- mntput(mnt);
- drop_collected_mounts(tagged);
- return failed;
-}
-
-/*
- * That gets run when evict_chunk() ends up needing to kill audit_tree.
- * Runs from a separate thread, with audit_cmd_mutex held.
- */
-void audit_prune_trees(void)
-{
- mutex_lock(&audit_filter_mutex);
-
- while (!list_empty(&prune_list)) {
- struct audit_tree *victim;
-
- victim = list_entry(prune_list.next, struct audit_tree, list);
- list_del_init(&victim->list);
-
- mutex_unlock(&audit_filter_mutex);
-
- prune_one(victim);
-
- mutex_lock(&audit_filter_mutex);
- }
-
- mutex_unlock(&audit_filter_mutex);
-}
-
-/*
- * Here comes the stuff asynchronous to auditctl operations
- */
-
-/* inode->inotify_mutex is locked */
-static void evict_chunk(struct audit_chunk *chunk)
-{
- struct audit_tree *owner;
- int n;
-
- if (chunk->dead)
- return;
-
- chunk->dead = 1;
- mutex_lock(&audit_filter_mutex);
- spin_lock(&hash_lock);
- while (!list_empty(&chunk->trees)) {
- owner = list_entry(chunk->trees.next,
- struct audit_tree, same_root);
- owner->goner = 1;
- owner->root = NULL;
- list_del_init(&owner->same_root);
- spin_unlock(&hash_lock);
- kill_rules(owner);
- list_move(&owner->list, &prune_list);
- audit_schedule_prune();
- spin_lock(&hash_lock);
- }
- list_del_rcu(&chunk->hash);
- for (n = 0; n < chunk->count; n++)
- list_del_init(&chunk->owners[n].list);
- spin_unlock(&hash_lock);
- mutex_unlock(&audit_filter_mutex);
-}
-
-static void handle_event(struct inotify_watch *watch, u32 wd, u32 mask,
- u32 cookie, const char *dname, struct inode *inode)
-{
- struct audit_chunk *chunk = container_of(watch, struct audit_chunk, watch);
-
- if (mask & IN_IGNORED) {
- evict_chunk(chunk);
- put_inotify_watch(watch);
- }
-}
-
-static void destroy_watch(struct inotify_watch *watch)
-{
- struct audit_chunk *chunk = container_of(watch, struct audit_chunk, watch);
- call_rcu(&chunk->head, __put_chunk);
-}
-
-static const struct inotify_operations rtree_inotify_ops = {
- .handle_event = handle_event,
- .destroy_watch = destroy_watch,
-};
-
-static int __init audit_tree_init(void)
-{
- int i;
-
- rtree_ih = inotify_init(&rtree_inotify_ops);
- if (IS_ERR(rtree_ih))
- audit_panic("cannot initialize inotify handle for rectree watches");
-
- for (i = 0; i < HASH_SIZE; i++)
- INIT_LIST_HEAD(&chunk_hash_heads[i]);
-
- return 0;
-}
-__initcall(audit_tree_init);
-/* auditfilter.c -- filtering of audit events
- *
- * Copyright 2003-2004 Red Hat, Inc.
- * Copyright 2005 Hewlett-Packard Development Company, L.P.
- * Copyright 2005 IBM Corporation
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- */
-
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include "audit.h"
-
-/*
- * Locking model:
- *
- * audit_filter_mutex:
- * Synchronizes writes and blocking reads of audit's filterlist
- * data. Rcu is used to traverse the filterlist and access
- * contents of structs audit_entry, audit_watch and opaque
- * LSM rules during filtering. If modified, these structures
- * must be copied and replace their counterparts in the filterlist.
- * An audit_parent struct is not accessed during filtering, so may
- * be written directly provided audit_filter_mutex is held.
- */
-
-/*
- * Reference counting:
- *
- * audit_parent: lifetime is from audit_init_parent() to receipt of an IN_IGNORED
- * event. Each audit_watch holds a reference to its associated parent.
- *
- * audit_watch: if added to lists, lifetime is from audit_init_watch() to
- * audit_remove_watch(). Additionally, an audit_watch may exist
- * temporarily to assist in searching existing filter data. Each
- * audit_krule holds a reference to its associated watch.
- */
-
-struct audit_parent {
- struct list_head ilist; /* entry in inotify registration list */
- struct list_head watches; /* associated watches */
- struct inotify_watch wdata; /* inotify watch data */
- unsigned flags; /* status flags */
-};
-
-/*
- * audit_parent status flags:
- *
- * AUDIT_PARENT_INVALID - set anytime rules/watches are auto-removed due to
- * a filesystem event to ensure we're adding audit watches to a valid parent.
- * Technically not needed for IN_DELETE_SELF or IN_UNMOUNT events, as we cannot
- * receive them while we have nameidata, but must be used for IN_MOVE_SELF which
- * we can receive while holding nameidata.
- */
-#define AUDIT_PARENT_INVALID 0x001
-
-/* Audit filter lists, defined in */
-struct list_head audit_filter_list[AUDIT_NR_FILTERS] = {
- LIST_HEAD_INIT(audit_filter_list[0]),
- LIST_HEAD_INIT(audit_filter_list[1]),
- LIST_HEAD_INIT(audit_filter_list[2]),
- LIST_HEAD_INIT(audit_filter_list[3]),
- LIST_HEAD_INIT(audit_filter_list[4]),
- LIST_HEAD_INIT(audit_filter_list[5]),
-#if AUDIT_NR_FILTERS != 6
-#error Fix audit_filter_list initialiser
-#endif
-};
-
-DEFINE_MUTEX(audit_filter_mutex);
-
-/* Inotify events we care about. */
-#define AUDIT_IN_WATCH IN_MOVE|IN_CREATE|IN_DELETE|IN_DELETE_SELF|IN_MOVE_SELF
-
-void audit_free_parent(struct inotify_watch *i_watch)
-{
- struct audit_parent *parent;
-
- parent = container_of(i_watch, struct audit_parent, wdata);
- WARN_ON(!list_empty(&parent->watches));
- kfree(parent);
-}
-
-static inline void audit_get_watch(struct audit_watch *watch)
-{
- atomic_inc(&watch->count);
-}
-
-static void audit_put_watch(struct audit_watch *watch)
-{
- if (atomic_dec_and_test(&watch->count)) {
- WARN_ON(watch->parent);
- WARN_ON(!list_empty(&watch->rules));
- kfree(watch->path);
- kfree(watch);
- }
-}
-
-static void audit_remove_watch(struct audit_watch *watch)
-{
- list_del(&watch->wlist);
- put_inotify_watch(&watch->parent->wdata);
- watch->parent = NULL;
- audit_put_watch(watch); /* match initial get */
-}
-
-static inline void audit_free_rule(struct audit_entry *e)
-{
- int i;
-
- /* some rules don't have associated watches */
- if (e->rule.watch)
- audit_put_watch(e->rule.watch);
- if (e->rule.fields)
- for (i = 0; i < e->rule.field_count; i++) {
- struct audit_field *f = &e->rule.fields[i];
- kfree(f->lsm_str);
- security_audit_rule_free(f->lsm_rule);
- }
- kfree(e->rule.fields);
- kfree(e->rule.filterkey);
- kfree(e);
-}
-
-void audit_free_rule_rcu(struct rcu_head *head)
-{
- struct audit_entry *e = container_of(head, struct audit_entry, rcu);
- audit_free_rule(e);
-}
-
-/* Initialize a parent watch entry. */
-static struct audit_parent *audit_init_parent(struct nameidata *ndp)
-{
- struct audit_parent *parent;
- s32 wd;
-
- parent = kzalloc(sizeof(*parent), GFP_KERNEL);
- if (unlikely(!parent))
- return ERR_PTR(-ENOMEM);
-
- INIT_LIST_HEAD(&parent->watches);
- parent->flags = 0;
-
- inotify_init_watch(&parent->wdata);
- /* grab a ref so inotify watch hangs around until we take audit_filter_mutex */
- get_inotify_watch(&parent->wdata);
- wd = inotify_add_watch(audit_ih, &parent->wdata,
- ndp->path.dentry->d_inode, AUDIT_IN_WATCH);
- if (wd < 0) {
- audit_free_parent(&parent->wdata);
- return ERR_PTR(wd);
- }
-
- return parent;
-}
-
-/* Initialize a watch entry. */
-static struct audit_watch *audit_init_watch(char *path)
-{
- struct audit_watch *watch;
-
- watch = kzalloc(sizeof(*watch), GFP_KERNEL);
- if (unlikely(!watch))
- return ERR_PTR(-ENOMEM);
-
- INIT_LIST_HEAD(&watch->rules);
- atomic_set(&watch->count, 1);
- watch->path = path;
- watch->dev = (dev_t)-1;
- watch->ino = (unsigned long)-1;
-
- return watch;
-}
-
-/* Initialize an audit filterlist entry. */
-static inline struct audit_entry *audit_init_entry(u32 field_count)
-{
- struct audit_entry *entry;
- struct audit_field *fields;
-
- entry = kzalloc(sizeof(*entry), GFP_KERNEL);
- if (unlikely(!entry))
- return NULL;
-
- fields = kzalloc(sizeof(*fields) * field_count, GFP_KERNEL);
- if (unlikely(!fields)) {
- kfree(entry);
- return NULL;
- }
- entry->rule.fields = fields;
-
- return entry;
-}
-
-/* Unpack a filter field's string representation from user-space
- * buffer. */
-char *audit_unpack_string(void **bufp, size_t *remain, size_t len)
-{
- char *str;
-
- if (!*bufp || (len == 0) || (len > *remain))
- return ERR_PTR(-EINVAL);
-
- /* Of the currently implemented string fields, PATH_MAX
- * defines the longest valid length.
- */
- if (len > PATH_MAX)
- return ERR_PTR(-ENAMETOOLONG);
-
- str = kmalloc(len + 1, GFP_KERNEL);
- if (unlikely(!str))
- return ERR_PTR(-ENOMEM);
-
- memcpy(str, *bufp, len);
- str[len] = 0;
- *bufp += len;
- *remain -= len;
-
- return str;
-}
-
-/* Translate an inode field to kernel respresentation. */
-static inline int audit_to_inode(struct audit_krule *krule,
- struct audit_field *f)
-{
- if (krule->listnr != AUDIT_FILTER_EXIT ||
- krule->watch || krule->inode_f || krule->tree)
- return -EINVAL;
-
- krule->inode_f = f;
- return 0;
-}
-
-/* Translate a watch string to kernel respresentation. */
-static int audit_to_watch(struct audit_krule *krule, char *path, int len,
- u32 op)
-{
- struct audit_watch *watch;
-
- if (!audit_ih)
- return -EOPNOTSUPP;
-
- if (path[0] != '/' || path[len-1] == '/' ||
- krule->listnr != AUDIT_FILTER_EXIT ||
- op & ~AUDIT_EQUAL ||
- krule->inode_f || krule->watch || krule->tree)
- return -EINVAL;
-
- watch = audit_init_watch(path);
- if (IS_ERR(watch))
- return PTR_ERR(watch);
-
- audit_get_watch(watch);
- krule->watch = watch;
-
- return 0;
-}
-
-static __u32 *classes[AUDIT_SYSCALL_CLASSES];
-
-int __init audit_register_class(int class, unsigned *list)
-{
- __u32 *p = kzalloc(AUDIT_BITMASK_SIZE * sizeof(__u32), GFP_KERNEL);
- if (!p)
- return -ENOMEM;
- while (*list != ~0U) {
- unsigned n = *list++;
- if (n >= AUDIT_BITMASK_SIZE * 32 - AUDIT_SYSCALL_CLASSES) {
- kfree(p);
- return -EINVAL;
- }
- p[AUDIT_WORD(n)] |= AUDIT_BIT(n);
- }
- if (class >= AUDIT_SYSCALL_CLASSES || classes[class]) {
- kfree(p);
- return -EINVAL;
- }
- classes[class] = p;
- return 0;
-}
-
-int audit_match_class(int class, unsigned syscall)
-{
- if (unlikely(syscall >= AUDIT_BITMASK_SIZE * 32))
- return 0;
- if (unlikely(class >= AUDIT_SYSCALL_CLASSES || !classes[class]))
- return 0;
- return classes[class][AUDIT_WORD(syscall)] & AUDIT_BIT(syscall);
-}
-
-#ifdef CONFIG_AUDITSYSCALL
-static inline int audit_match_class_bits(int class, u32 *mask)
-{
- int i;
-
- if (classes[class]) {
- for (i = 0; i < AUDIT_BITMASK_SIZE; i++)
- if (mask[i] & classes[class][i])
- return 0;
- }
- return 1;
-}
-
-static int audit_match_signal(struct audit_entry *entry)
-{
- struct audit_field *arch = entry->rule.arch_f;
-
- if (!arch) {
- /* When arch is unspecified, we must check both masks on biarch
- * as syscall number alone is ambiguous. */
- return (audit_match_class_bits(AUDIT_CLASS_SIGNAL,
- entry->rule.mask) &&
- audit_match_class_bits(AUDIT_CLASS_SIGNAL_32,
- entry->rule.mask));
- }
-
- switch(audit_classify_arch(arch->val)) {
- case 0: /* native */
- return (audit_match_class_bits(AUDIT_CLASS_SIGNAL,
- entry->rule.mask));
- case 1: /* 32bit on biarch */
- return (audit_match_class_bits(AUDIT_CLASS_SIGNAL_32,
- entry->rule.mask));
- default:
- return 1;
- }
-}
-#endif
-
-/* Common user-space to kernel rule translation. */
-static inline struct audit_entry *audit_to_entry_common(struct audit_rule *rule)
-{
- unsigned listnr;
- struct audit_entry *entry;
- int i, err;
-
- err = -EINVAL;
- listnr = rule->flags & ~AUDIT_FILTER_PREPEND;
- switch(listnr) {
- default:
- goto exit_err;
- case AUDIT_FILTER_USER:
- case AUDIT_FILTER_TYPE:
-#ifdef CONFIG_AUDITSYSCALL
- case AUDIT_FILTER_ENTRY:
- case AUDIT_FILTER_EXIT:
- case AUDIT_FILTER_TASK:
-#endif
- ;
- }
- if (unlikely(rule->action == AUDIT_POSSIBLE)) {
- printk(KERN_ERR "AUDIT_POSSIBLE is deprecated\n");
- goto exit_err;
- }
- if (rule->action != AUDIT_NEVER && rule->action != AUDIT_ALWAYS)
- goto exit_err;
- if (rule->field_count > AUDIT_MAX_FIELDS)
- goto exit_err;
-
- err = -ENOMEM;
- entry = audit_init_entry(rule->field_count);
- if (!entry)
- goto exit_err;
-
- entry->rule.flags = rule->flags & AUDIT_FILTER_PREPEND;
- entry->rule.listnr = listnr;
- entry->rule.action = rule->action;
- entry->rule.field_count = rule->field_count;
-
- for (i = 0; i < AUDIT_BITMASK_SIZE; i++)
- entry->rule.mask[i] = rule->mask[i];
-
- for (i = 0; i < AUDIT_SYSCALL_CLASSES; i++) {
- int bit = AUDIT_BITMASK_SIZE * 32 - i - 1;
- __u32 *p = &entry->rule.mask[AUDIT_WORD(bit)];
- __u32 *class;
-
- if (!(*p & AUDIT_BIT(bit)))
- continue;
- *p &= ~AUDIT_BIT(bit);
- class = classes[i];
- if (class) {
- int j;
- for (j = 0; j < AUDIT_BITMASK_SIZE; j++)
- entry->rule.mask[j] |= class[j];
- }
- }
-
- return entry;
-
-exit_err:
- return ERR_PTR(err);
-}
-
-/* Translate struct audit_rule to kernel's rule respresentation.
- * Exists for backward compatibility with userspace. */
-static struct audit_entry *audit_rule_to_entry(struct audit_rule *rule)
-{
- struct audit_entry *entry;
- struct audit_field *ino_f;
- int err = 0;
- int i;
-
- entry = audit_to_entry_common(rule);
- if (IS_ERR(entry))
- goto exit_nofree;
-
- for (i = 0; i < rule->field_count; i++) {
- struct audit_field *f = &entry->rule.fields[i];
-
- f->op = rule->fields[i] & (AUDIT_NEGATE|AUDIT_OPERATORS);
- f->type = rule->fields[i] & ~(AUDIT_NEGATE|AUDIT_OPERATORS);
- f->val = rule->values[i];
-
- err = -EINVAL;
- switch(f->type) {
- default:
- goto exit_free;
- case AUDIT_PID:
- case AUDIT_UID:
- case AUDIT_EUID:
- case AUDIT_SUID:
- case AUDIT_FSUID:
- case AUDIT_GID:
- case AUDIT_EGID:
- case AUDIT_SGID:
- case AUDIT_FSGID:
- case AUDIT_LOGINUID:
- case AUDIT_PERS:
- case AUDIT_MSGTYPE:
- case AUDIT_PPID:
- case AUDIT_DEVMAJOR:
- case AUDIT_DEVMINOR:
- case AUDIT_EXIT:
- case AUDIT_SUCCESS:
- /* bit ops are only useful on syscall args */
- if (f->op == AUDIT_BIT_MASK ||
- f->op == AUDIT_BIT_TEST) {
- err = -EINVAL;
- goto exit_free;
- }
- break;
- case AUDIT_ARG0:
- case AUDIT_ARG1:
- case AUDIT_ARG2:
- case AUDIT_ARG3:
- break;
- /* arch is only allowed to be = or != */
- case AUDIT_ARCH:
- if ((f->op != AUDIT_NOT_EQUAL) && (f->op != AUDIT_EQUAL)
- && (f->op != AUDIT_NEGATE) && (f->op)) {
- err = -EINVAL;
- goto exit_free;
- }
- entry->rule.arch_f = f;
- break;
- case AUDIT_PERM:
- if (f->val & ~15)
- goto exit_free;
- break;
- case AUDIT_FILETYPE:
- if ((f->val & ~S_IFMT) > S_IFMT)
- goto exit_free;
- break;
- case AUDIT_INODE:
- err = audit_to_inode(&entry->rule, f);
- if (err)
- goto exit_free;
- break;
- }
-
- entry->rule.vers_ops = (f->op & AUDIT_OPERATORS) ? 2 : 1;
-
- /* Support for legacy operators where
- * AUDIT_NEGATE bit signifies != and otherwise assumes == */
- if (f->op & AUDIT_NEGATE)
- f->op = AUDIT_NOT_EQUAL;
- else if (!f->op)
- f->op = AUDIT_EQUAL;
- else if (f->op == AUDIT_OPERATORS) {
- err = -EINVAL;
- goto exit_free;
- }
- }
-
- ino_f = entry->rule.inode_f;
- if (ino_f) {
- switch(ino_f->op) {
- case AUDIT_NOT_EQUAL:
- entry->rule.inode_f = NULL;
- case AUDIT_EQUAL:
- break;
- default:
- err = -EINVAL;
- goto exit_free;
- }
- }
-
-exit_nofree:
- return entry;
-
-exit_free:
- audit_free_rule(entry);
- return ERR_PTR(err);
-}
-
-/* Translate struct audit_rule_data to kernel's rule respresentation. */
-static struct audit_entry *audit_data_to_entry(struct audit_rule_data *data,
- size_t datasz)
-{
- int err = 0;
- struct audit_entry *entry;
- struct audit_field *ino_f;
- void *bufp;
- size_t remain = datasz - sizeof(struct audit_rule_data);
- int i;
- char *str;
-
- entry = audit_to_entry_common((struct audit_rule *)data);
- if (IS_ERR(entry))
- goto exit_nofree;
-
- bufp = data->buf;
- entry->rule.vers_ops = 2;
- for (i = 0; i < data->field_count; i++) {
- struct audit_field *f = &entry->rule.fields[i];
-
- err = -EINVAL;
- if (!(data->fieldflags[i] & AUDIT_OPERATORS) ||
- data->fieldflags[i] & ~AUDIT_OPERATORS)
- goto exit_free;
-
- f->op = data->fieldflags[i] & AUDIT_OPERATORS;
- f->type = data->fields[i];
- f->val = data->values[i];
- f->lsm_str = NULL;
- f->lsm_rule = NULL;
- switch(f->type) {
- case AUDIT_PID:
- case AUDIT_UID:
- case AUDIT_EUID:
- case AUDIT_SUID:
- case AUDIT_FSUID:
- case AUDIT_GID:
- case AUDIT_EGID:
- case AUDIT_SGID:
- case AUDIT_FSGID:
- case AUDIT_LOGINUID:
- case AUDIT_PERS:
- case AUDIT_MSGTYPE:
- case AUDIT_PPID:
- case AUDIT_DEVMAJOR:
- case AUDIT_DEVMINOR:
- case AUDIT_EXIT:
- case AUDIT_SUCCESS:
- case AUDIT_ARG0:
- case AUDIT_ARG1:
- case AUDIT_ARG2:
- case AUDIT_ARG3:
- break;
- case AUDIT_ARCH:
- entry->rule.arch_f = f;
- break;
- case AUDIT_SUBJ_USER:
- case AUDIT_SUBJ_ROLE:
- case AUDIT_SUBJ_TYPE:
- case AUDIT_SUBJ_SEN:
- case AUDIT_SUBJ_CLR:
- case AUDIT_OBJ_USER:
- case AUDIT_OBJ_ROLE:
- case AUDIT_OBJ_TYPE:
- case AUDIT_OBJ_LEV_LOW:
- case AUDIT_OBJ_LEV_HIGH:
- str = audit_unpack_string(&bufp, &remain, f->val);
- if (IS_ERR(str))
- goto exit_free;
- entry->rule.buflen += f->val;
-
- err = security_audit_rule_init(f->type, f->op, str,
- (void **)&f->lsm_rule);
- /* Keep currently invalid fields around in case they
- * become valid after a policy reload. */
- if (err == -EINVAL) {
- printk(KERN_WARNING "audit rule for LSM "
- "\'%s\' is invalid\n", str);
- err = 0;
- }
- if (err) {
- kfree(str);
- goto exit_free;
- } else
- f->lsm_str = str;
- break;
- case AUDIT_WATCH:
- str = audit_unpack_string(&bufp, &remain, f->val);
- if (IS_ERR(str))
- goto exit_free;
- entry->rule.buflen += f->val;
-
- err = audit_to_watch(&entry->rule, str, f->val, f->op);
- if (err) {
- kfree(str);
- goto exit_free;
- }
- break;
- case AUDIT_DIR:
- str = audit_unpack_string(&bufp, &remain, f->val);
- if (IS_ERR(str))
- goto exit_free;
- entry->rule.buflen += f->val;
-
- err = audit_make_tree(&entry->rule, str, f->op);
- kfree(str);
- if (err)
- goto exit_free;
- break;
- case AUDIT_INODE:
- err = audit_to_inode(&entry->rule, f);
- if (err)
- goto exit_free;
- break;
- case AUDIT_FILTERKEY:
- err = -EINVAL;
- if (entry->rule.filterkey || f->val > AUDIT_MAX_KEY_LEN)
- goto exit_free;
- str = audit_unpack_string(&bufp, &remain, f->val);
- if (IS_ERR(str))
- goto exit_free;
- entry->rule.buflen += f->val;
- entry->rule.filterkey = str;
- break;
- case AUDIT_PERM:
- if (f->val & ~15)
- goto exit_free;
- break;
- case AUDIT_FILETYPE:
- if ((f->val & ~S_IFMT) > S_IFMT)
- goto exit_free;
- break;
- default:
- goto exit_free;
- }
- }
-
- ino_f = entry->rule.inode_f;
- if (ino_f) {
- switch(ino_f->op) {
- case AUDIT_NOT_EQUAL:
- entry->rule.inode_f = NULL;
- case AUDIT_EQUAL:
- break;
- default:
- err = -EINVAL;
- goto exit_free;
- }
- }
-
-exit_nofree:
- return entry;
-
-exit_free:
- audit_free_rule(entry);
- return ERR_PTR(err);
-}
-
-/* Pack a filter field's string representation into data block. */
-static inline size_t audit_pack_string(void **bufp, const char *str)
-{
- size_t len = strlen(str);
-
- memcpy(*bufp, str, len);
- *bufp += len;
-
- return len;
-}
-
-/* Translate kernel rule respresentation to struct audit_rule.
- * Exists for backward compatibility with userspace. */
-static struct audit_rule *audit_krule_to_rule(struct audit_krule *krule)
-{
- struct audit_rule *rule;
- int i;
-
- rule = kzalloc(sizeof(*rule), GFP_KERNEL);
- if (unlikely(!rule))
- return NULL;
-
- rule->flags = krule->flags | krule->listnr;
- rule->action = krule->action;
- rule->field_count = krule->field_count;
- for (i = 0; i < rule->field_count; i++) {
- rule->values[i] = krule->fields[i].val;
- rule->fields[i] = krule->fields[i].type;
-
- if (krule->vers_ops == 1) {
- if (krule->fields[i].op & AUDIT_NOT_EQUAL)
- rule->fields[i] |= AUDIT_NEGATE;
- } else {
- rule->fields[i] |= krule->fields[i].op;
- }
- }
- for (i = 0; i < AUDIT_BITMASK_SIZE; i++) rule->mask[i] = krule->mask[i];
-
- return rule;
-}
-
-/* Translate kernel rule respresentation to struct audit_rule_data. */
-static struct audit_rule_data *audit_krule_to_data(struct audit_krule *krule)
-{
- struct audit_rule_data *data;
- void *bufp;
- int i;
-
- data = kmalloc(sizeof(*data) + krule->buflen, GFP_KERNEL);
- if (unlikely(!data))
- return NULL;
- memset(data, 0, sizeof(*data));
-
- data->flags = krule->flags | krule->listnr;
- data->action = krule->action;
- data->field_count = krule->field_count;
- bufp = data->buf;
- for (i = 0; i < data->field_count; i++) {
- struct audit_field *f = &krule->fields[i];
-
- data->fields[i] = f->type;
- data->fieldflags[i] = f->op;
- switch(f->type) {
- case AUDIT_SUBJ_USER:
- case AUDIT_SUBJ_ROLE:
- case AUDIT_SUBJ_TYPE:
- case AUDIT_SUBJ_SEN:
- case AUDIT_SUBJ_CLR:
- case AUDIT_OBJ_USER:
- case AUDIT_OBJ_ROLE:
- case AUDIT_OBJ_TYPE:
- case AUDIT_OBJ_LEV_LOW:
- case AUDIT_OBJ_LEV_HIGH:
- data->buflen += data->values[i] =
- audit_pack_string(&bufp, f->lsm_str);
- break;
- case AUDIT_WATCH:
- data->buflen += data->values[i] =
- audit_pack_string(&bufp, krule->watch->path);
- break;
- case AUDIT_DIR:
- data->buflen += data->values[i] =
- audit_pack_string(&bufp,
- audit_tree_path(krule->tree));
- break;
- case AUDIT_FILTERKEY:
- data->buflen += data->values[i] =
- audit_pack_string(&bufp, krule->filterkey);
- break;
- default:
- data->values[i] = f->val;
- }
- }
- for (i = 0; i < AUDIT_BITMASK_SIZE; i++) data->mask[i] = krule->mask[i];
-
- return data;
-}
-
-/* Compare two rules in kernel format. Considered success if rules
- * don't match. */
-static int audit_compare_rule(struct audit_krule *a, struct audit_krule *b)
-{
- int i;
-
- if (a->flags != b->flags ||
- a->listnr != b->listnr ||
- a->action != b->action ||
- a->field_count != b->field_count)
- return 1;
-
- for (i = 0; i < a->field_count; i++) {
- if (a->fields[i].type != b->fields[i].type ||
- a->fields[i].op != b->fields[i].op)
- return 1;
-
- switch(a->fields[i].type) {
- case AUDIT_SUBJ_USER:
- case AUDIT_SUBJ_ROLE:
- case AUDIT_SUBJ_TYPE:
- case AUDIT_SUBJ_SEN:
- case AUDIT_SUBJ_CLR:
- case AUDIT_OBJ_USER:
- case AUDIT_OBJ_ROLE:
- case AUDIT_OBJ_TYPE:
- case AUDIT_OBJ_LEV_LOW:
- case AUDIT_OBJ_LEV_HIGH:
- if (strcmp(a->fields[i].lsm_str, b->fields[i].lsm_str))
- return 1;
- break;
- case AUDIT_WATCH:
- if (strcmp(a->watch->path, b->watch->path))
- return 1;
- break;
- case AUDIT_DIR:
- if (strcmp(audit_tree_path(a->tree),
- audit_tree_path(b->tree)))
- return 1;
- break;
- case AUDIT_FILTERKEY:
- /* both filterkeys exist based on above type compare */
- if (strcmp(a->filterkey, b->filterkey))
- return 1;
- break;
- default:
- if (a->fields[i].val != b->fields[i].val)
- return 1;
- }
- }
-
- for (i = 0; i < AUDIT_BITMASK_SIZE; i++)
- if (a->mask[i] != b->mask[i])
- return 1;
-
- return 0;
-}
-
-/* Duplicate the given audit watch. The new watch's rules list is initialized
- * to an empty list and wlist is undefined. */
-static struct audit_watch *audit_dupe_watch(struct audit_watch *old)
-{
- char *path;
- struct audit_watch *new;
-
- path = kstrdup(old->path, GFP_KERNEL);
- if (unlikely(!path))
- return ERR_PTR(-ENOMEM);
-
- new = audit_init_watch(path);
- if (IS_ERR(new)) {
- kfree(path);
- goto out;
- }
-
- new->dev = old->dev;
- new->ino = old->ino;
- get_inotify_watch(&old->parent->wdata);
- new->parent = old->parent;
-
-out:
- return new;
-}
-
-/* Duplicate LSM field information. The lsm_rule is opaque, so must be
- * re-initialized. */
-static inline int audit_dupe_lsm_field(struct audit_field *df,
- struct audit_field *sf)
-{
- int ret = 0;
- char *lsm_str;
-
- /* our own copy of lsm_str */
- lsm_str = kstrdup(sf->lsm_str, GFP_KERNEL);
- if (unlikely(!lsm_str))
- return -ENOMEM;
- df->lsm_str = lsm_str;
-
- /* our own (refreshed) copy of lsm_rule */
- ret = security_audit_rule_init(df->type, df->op, df->lsm_str,
- (void **)&df->lsm_rule);
- /* Keep currently invalid fields around in case they
- * become valid after a policy reload. */
- if (ret == -EINVAL) {
- printk(KERN_WARNING "audit rule for LSM \'%s\' is "
- "invalid\n", df->lsm_str);
- ret = 0;
- }
-
- return ret;
-}
-
-/* Duplicate an audit rule. This will be a deep copy with the exception
- * of the watch - that pointer is carried over. The LSM specific fields
- * will be updated in the copy. The point is to be able to replace the old
- * rule with the new rule in the filterlist, then free the old rule.
- * The rlist element is undefined; list manipulations are handled apart from
- * the initial copy. */
-static struct audit_entry *audit_dupe_rule(struct audit_krule *old,
- struct audit_watch *watch)
-{
- u32 fcount = old->field_count;
- struct audit_entry *entry;
- struct audit_krule *new;
- char *fk;
- int i, err = 0;
-
- entry = audit_init_entry(fcount);
- if (unlikely(!entry))
- return ERR_PTR(-ENOMEM);
-
- new = &entry->rule;
- new->vers_ops = old->vers_ops;
- new->flags = old->flags;
- new->listnr = old->listnr;
- new->action = old->action;
- for (i = 0; i < AUDIT_BITMASK_SIZE; i++)
- new->mask[i] = old->mask[i];
- new->buflen = old->buflen;
- new->inode_f = old->inode_f;
- new->watch = NULL;
- new->field_count = old->field_count;
- /*
- * note that we are OK with not refcounting here; audit_match_tree()
- * never dereferences tree and we can't get false positives there
- * since we'd have to have rule gone from the list *and* removed
- * before the chunks found by lookup had been allocated, i.e. before
- * the beginning of list scan.
- */
- new->tree = old->tree;
- memcpy(new->fields, old->fields, sizeof(struct audit_field) * fcount);
-
- /* deep copy this information, updating the lsm_rule fields, because
- * the originals will all be freed when the old rule is freed. */
- for (i = 0; i < fcount; i++) {
- switch (new->fields[i].type) {
- case AUDIT_SUBJ_USER:
- case AUDIT_SUBJ_ROLE:
- case AUDIT_SUBJ_TYPE:
- case AUDIT_SUBJ_SEN:
- case AUDIT_SUBJ_CLR:
- case AUDIT_OBJ_USER:
- case AUDIT_OBJ_ROLE:
- case AUDIT_OBJ_TYPE:
- case AUDIT_OBJ_LEV_LOW:
- case AUDIT_OBJ_LEV_HIGH:
- err = audit_dupe_lsm_field(&new->fields[i],
- &old->fields[i]);
- break;
- case AUDIT_FILTERKEY:
- fk = kstrdup(old->filterkey, GFP_KERNEL);
- if (unlikely(!fk))
- err = -ENOMEM;
- else
- new->filterkey = fk;
- }
- if (err) {
- audit_free_rule(entry);
- return ERR_PTR(err);
- }
- }
-
- if (watch) {
- audit_get_watch(watch);
- new->watch = watch;
- }
-
- return entry;
-}
-
-/* Update inode info in audit rules based on filesystem event. */
-static void audit_update_watch(struct audit_parent *parent,
- const char *dname, dev_t dev,
- unsigned long ino, unsigned invalidating)
-{
- struct audit_watch *owatch, *nwatch, *nextw;
- struct audit_krule *r, *nextr;
- struct audit_entry *oentry, *nentry;
-
- mutex_lock(&audit_filter_mutex);
- list_for_each_entry_safe(owatch, nextw, &parent->watches, wlist) {
- if (audit_compare_dname_path(dname, owatch->path, NULL))
- continue;
-
- /* If the update involves invalidating rules, do the inode-based
- * filtering now, so we don't omit records. */
- if (invalidating && current->audit_context &&
- audit_filter_inodes(current, current->audit_context) == AUDIT_RECORD_CONTEXT)
- audit_set_auditable(current->audit_context);
-
- nwatch = audit_dupe_watch(owatch);
- if (IS_ERR(nwatch)) {
- mutex_unlock(&audit_filter_mutex);
- audit_panic("error updating watch, skipping");
- return;
- }
- nwatch->dev = dev;
- nwatch->ino = ino;
-
- list_for_each_entry_safe(r, nextr, &owatch->rules, rlist) {
-
- oentry = container_of(r, struct audit_entry, rule);
- list_del(&oentry->rule.rlist);
- list_del_rcu(&oentry->list);
-
- nentry = audit_dupe_rule(&oentry->rule, nwatch);
- if (IS_ERR(nentry))
- audit_panic("error updating watch, removing");
- else {
- int h = audit_hash_ino((u32)ino);
- list_add(&nentry->rule.rlist, &nwatch->rules);
- list_add_rcu(&nentry->list, &audit_inode_hash[h]);
- }
-
- call_rcu(&oentry->rcu, audit_free_rule_rcu);
- }
-
- if (audit_enabled) {
- struct audit_buffer *ab;
- ab = audit_log_start(NULL, GFP_KERNEL,
- AUDIT_CONFIG_CHANGE);
- audit_log_format(ab, "auid=%u ses=%u",
- audit_get_loginuid(current),
- audit_get_sessionid(current));
- audit_log_format(ab,
- " op=updated rules specifying path=");
- audit_log_untrustedstring(ab, owatch->path);
- audit_log_format(ab, " with dev=%u ino=%lu\n",
- dev, ino);
- audit_log_format(ab, " list=%d res=1", r->listnr);
- audit_log_end(ab);
- }
- audit_remove_watch(owatch);
- goto add_watch_to_parent; /* event applies to a single watch */
- }
- mutex_unlock(&audit_filter_mutex);
- return;
-
-add_watch_to_parent:
- list_add(&nwatch->wlist, &parent->watches);
- mutex_unlock(&audit_filter_mutex);
- return;
-}
-
-/* Remove all watches & rules associated with a parent that is going away. */
-static void audit_remove_parent_watches(struct audit_parent *parent)
-{
- struct audit_watch *w, *nextw;
- struct audit_krule *r, *nextr;
- struct audit_entry *e;
-
- mutex_lock(&audit_filter_mutex);
- parent->flags |= AUDIT_PARENT_INVALID;
- list_for_each_entry_safe(w, nextw, &parent->watches, wlist) {
- list_for_each_entry_safe(r, nextr, &w->rules, rlist) {
- e = container_of(r, struct audit_entry, rule);
- if (audit_enabled) {
- struct audit_buffer *ab;
- ab = audit_log_start(NULL, GFP_KERNEL,
- AUDIT_CONFIG_CHANGE);
- audit_log_format(ab, "auid=%u ses=%u",
- audit_get_loginuid(current),
- audit_get_sessionid(current));
- audit_log_format(ab, " op=remove rule path=");
- audit_log_untrustedstring(ab, w->path);
- if (r->filterkey) {
- audit_log_format(ab, " key=");
- audit_log_untrustedstring(ab,
- r->filterkey);
- } else
- audit_log_format(ab, " key=(null)");
- audit_log_format(ab, " list=%d res=1",
- r->listnr);
- audit_log_end(ab);
- }
- list_del(&r->rlist);
- list_del_rcu(&e->list);
- call_rcu(&e->rcu, audit_free_rule_rcu);
- }
- audit_remove_watch(w);
- }
- mutex_unlock(&audit_filter_mutex);
-}
-
-/* Unregister inotify watches for parents on in_list.
- * Generates an IN_IGNORED event. */
-static void audit_inotify_unregister(struct list_head *in_list)
-{
- struct audit_parent *p, *n;
-
- list_for_each_entry_safe(p, n, in_list, ilist) {
- list_del(&p->ilist);
- inotify_rm_watch(audit_ih, &p->wdata);
- /* the unpin matching the pin in audit_do_del_rule() */
- unpin_inotify_watch(&p->wdata);
- }
-}
-
-/* Find an existing audit rule.
- * Caller must hold audit_filter_mutex to prevent stale rule data. */
-static struct audit_entry *audit_find_rule(struct audit_entry *entry,
- struct list_head *list)
-{
- struct audit_entry *e, *found = NULL;
- int h;
-
- if (entry->rule.watch) {
- /* we don't know the inode number, so must walk entire hash */
- for (h = 0; h < AUDIT_INODE_BUCKETS; h++) {
- list = &audit_inode_hash[h];
- list_for_each_entry(e, list, list)
- if (!audit_compare_rule(&entry->rule, &e->rule)) {
- found = e;
- goto out;
- }
- }
- goto out;
- }
-
- list_for_each_entry(e, list, list)
- if (!audit_compare_rule(&entry->rule, &e->rule)) {
- found = e;
- goto out;
- }
-
-out:
- return found;
-}
-
-/* Get path information necessary for adding watches. */
-static int audit_get_nd(char *path, struct nameidata **ndp,
- struct nameidata **ndw)
-{
- struct nameidata *ndparent, *ndwatch;
- int err;
-
- ndparent = kmalloc(sizeof(*ndparent), GFP_KERNEL);
- if (unlikely(!ndparent))
- return -ENOMEM;
-
- ndwatch = kmalloc(sizeof(*ndwatch), GFP_KERNEL);
- if (unlikely(!ndwatch)) {
- kfree(ndparent);
- return -ENOMEM;
- }
-
- err = path_lookup(path, LOOKUP_PARENT, ndparent);
- if (err) {
- kfree(ndparent);
- kfree(ndwatch);
- return err;
- }
-
- err = path_lookup(path, 0, ndwatch);
- if (err) {
- kfree(ndwatch);
- ndwatch = NULL;
- }
-
- *ndp = ndparent;
- *ndw = ndwatch;
-
- return 0;
-}
-
-/* Release resources used for watch path information. */
-static void audit_put_nd(struct nameidata *ndp, struct nameidata *ndw)
-{
- if (ndp) {
- path_put(&ndp->path);
- kfree(ndp);
- }
- if (ndw) {
- path_put(&ndw->path);
- kfree(ndw);
- }
-}
-
-/* Associate the given rule with an existing parent inotify_watch.
- * Caller must hold audit_filter_mutex. */
-static void audit_add_to_parent(struct audit_krule *krule,
- struct audit_parent *parent)
-{
- struct audit_watch *w, *watch = krule->watch;
- int watch_found = 0;
-
- list_for_each_entry(w, &parent->watches, wlist) {
- if (strcmp(watch->path, w->path))
- continue;
-
- watch_found = 1;
-
- /* put krule's and initial refs to temporary watch */
- audit_put_watch(watch);
- audit_put_watch(watch);
-
- audit_get_watch(w);
- krule->watch = watch = w;
- break;
- }
-
- if (!watch_found) {
- get_inotify_watch(&parent->wdata);
- watch->parent = parent;
-
- list_add(&watch->wlist, &parent->watches);
- }
- list_add(&krule->rlist, &watch->rules);
-}
-
-/* Find a matching watch entry, or add this one.
- * Caller must hold audit_filter_mutex. */
-static int audit_add_watch(struct audit_krule *krule, struct nameidata *ndp,
- struct nameidata *ndw)
-{
- struct audit_watch *watch = krule->watch;
- struct inotify_watch *i_watch;
- struct audit_parent *parent;
- int ret = 0;
-
- /* update watch filter fields */
- if (ndw) {
- watch->dev = ndw->path.dentry->d_inode->i_sb->s_dev;
- watch->ino = ndw->path.dentry->d_inode->i_ino;
- }
-
- /* The audit_filter_mutex must not be held during inotify calls because
- * we hold it during inotify event callback processing. If an existing
- * inotify watch is found, inotify_find_watch() grabs a reference before
- * returning.
- */
- mutex_unlock(&audit_filter_mutex);
-
- if (inotify_find_watch(audit_ih, ndp->path.dentry->d_inode,
- &i_watch) < 0) {
- parent = audit_init_parent(ndp);
- if (IS_ERR(parent)) {
- /* caller expects mutex locked */
- mutex_lock(&audit_filter_mutex);
- return PTR_ERR(parent);
- }
- } else
- parent = container_of(i_watch, struct audit_parent, wdata);
-
- mutex_lock(&audit_filter_mutex);
-
- /* parent was moved before we took audit_filter_mutex */
- if (parent->flags & AUDIT_PARENT_INVALID)
- ret = -ENOENT;
- else
- audit_add_to_parent(krule, parent);
-
- /* match get in audit_init_parent or inotify_find_watch */
- put_inotify_watch(&parent->wdata);
- return ret;
-}
-
-/* Add rule to given filterlist if not a duplicate. */
-static inline int audit_add_rule(struct audit_entry *entry,
- struct list_head *list)
-{
- struct audit_entry *e;
- struct audit_field *inode_f = entry->rule.inode_f;
- struct audit_watch *watch = entry->rule.watch;
- struct audit_tree *tree = entry->rule.tree;
- struct nameidata *ndp = NULL, *ndw = NULL;
- int h, err;
-#ifdef CONFIG_AUDITSYSCALL
- int dont_count = 0;
-
- /* If either of these, don't count towards total */
- if (entry->rule.listnr == AUDIT_FILTER_USER ||
- entry->rule.listnr == AUDIT_FILTER_TYPE)
- dont_count = 1;
-#endif
-
- if (inode_f) {
- h = audit_hash_ino(inode_f->val);
- list = &audit_inode_hash[h];
- }
-
- mutex_lock(&audit_filter_mutex);
- e = audit_find_rule(entry, list);
- mutex_unlock(&audit_filter_mutex);
- if (e) {
- err = -EEXIST;
- /* normally audit_add_tree_rule() will free it on failure */
- if (tree)
- audit_put_tree(tree);
- goto error;
- }
-
- /* Avoid calling path_lookup under audit_filter_mutex. */
- if (watch) {
- err = audit_get_nd(watch->path, &ndp, &ndw);
- if (err)
- goto error;
- }
-
- mutex_lock(&audit_filter_mutex);
- if (watch) {
- /* audit_filter_mutex is dropped and re-taken during this call */
- err = audit_add_watch(&entry->rule, ndp, ndw);
- if (err) {
- mutex_unlock(&audit_filter_mutex);
- goto error;
- }
- h = audit_hash_ino((u32)watch->ino);
- list = &audit_inode_hash[h];
- }
- if (tree) {
- err = audit_add_tree_rule(&entry->rule);
- if (err) {
- mutex_unlock(&audit_filter_mutex);
- goto error;
- }
- }
-
- if (entry->rule.flags & AUDIT_FILTER_PREPEND) {
- list_add_rcu(&entry->list, list);
- entry->rule.flags &= ~AUDIT_FILTER_PREPEND;
- } else {
- list_add_tail_rcu(&entry->list, list);
- }
-#ifdef CONFIG_AUDITSYSCALL
- if (!dont_count)
- audit_n_rules++;
-
- if (!audit_match_signal(entry))
- audit_signals++;
-#endif
- mutex_unlock(&audit_filter_mutex);
-
- audit_put_nd(ndp, ndw); /* NULL args OK */
- return 0;
-
-error:
- audit_put_nd(ndp, ndw); /* NULL args OK */
- if (watch)
- audit_put_watch(watch); /* tmp watch, matches initial get */
- return err;
-}
-
-/* Remove an existing rule from filterlist. */
-static inline int audit_del_rule(struct audit_entry *entry,
- struct list_head *list)
-{
- struct audit_entry *e;
- struct audit_field *inode_f = entry->rule.inode_f;
- struct audit_watch *watch, *tmp_watch = entry->rule.watch;
- struct audit_tree *tree = entry->rule.tree;
- LIST_HEAD(inotify_list);
- int h, ret = 0;
-#ifdef CONFIG_AUDITSYSCALL
- int dont_count = 0;
-
- /* If either of these, don't count towards total */
- if (entry->rule.listnr == AUDIT_FILTER_USER ||
- entry->rule.listnr == AUDIT_FILTER_TYPE)
- dont_count = 1;
-#endif
-
- if (inode_f) {
- h = audit_hash_ino(inode_f->val);
- list = &audit_inode_hash[h];
- }
-
- mutex_lock(&audit_filter_mutex);
- e = audit_find_rule(entry, list);
- if (!e) {
- mutex_unlock(&audit_filter_mutex);
- ret = -ENOENT;
- goto out;
- }
-
- watch = e->rule.watch;
- if (watch) {
- struct audit_parent *parent = watch->parent;
-
- list_del(&e->rule.rlist);
-
- if (list_empty(&watch->rules)) {
- audit_remove_watch(watch);
-
- if (list_empty(&parent->watches)) {
- /* Put parent on the inotify un-registration
- * list. Grab a reference before releasing
- * audit_filter_mutex, to be released in
- * audit_inotify_unregister().
- * If filesystem is going away, just leave
- * the sucker alone, eviction will take
- * care of it.
- */
- if (pin_inotify_watch(&parent->wdata))
- list_add(&parent->ilist, &inotify_list);
- }
- }
- }
-
- if (e->rule.tree)
- audit_remove_tree_rule(&e->rule);
-
- list_del_rcu(&e->list);
- call_rcu(&e->rcu, audit_free_rule_rcu);
-
-#ifdef CONFIG_AUDITSYSCALL
- if (!dont_count)
- audit_n_rules--;
-
- if (!audit_match_signal(entry))
- audit_signals--;
-#endif
- mutex_unlock(&audit_filter_mutex);
-
- if (!list_empty(&inotify_list))
- audit_inotify_unregister(&inotify_list);
-
-out:
- if (tmp_watch)
- audit_put_watch(tmp_watch); /* match initial get */
- if (tree)
- audit_put_tree(tree); /* that's the temporary one */
-
- return ret;
-}
-
-/* List rules using struct audit_rule. Exists for backward
- * compatibility with userspace. */
-static void audit_list(int pid, int seq, struct sk_buff_head *q)
-{
- struct sk_buff *skb;
- struct audit_entry *entry;
- int i;
-
- /* This is a blocking read, so use audit_filter_mutex instead of rcu
- * iterator to sync with list writers. */
- for (i=0; irule);
- if (unlikely(!rule))
- break;
- skb = audit_make_reply(pid, seq, AUDIT_LIST, 0, 1,
- rule, sizeof(*rule));
- if (skb)
- skb_queue_tail(q, skb);
- kfree(rule);
- }
- }
- for (i = 0; i < AUDIT_INODE_BUCKETS; i++) {
- list_for_each_entry(entry, &audit_inode_hash[i], list) {
- struct audit_rule *rule;
-
- rule = audit_krule_to_rule(&entry->rule);
- if (unlikely(!rule))
- break;
- skb = audit_make_reply(pid, seq, AUDIT_LIST, 0, 1,
- rule, sizeof(*rule));
- if (skb)
- skb_queue_tail(q, skb);
- kfree(rule);
- }
- }
- skb = audit_make_reply(pid, seq, AUDIT_LIST, 1, 1, NULL, 0);
- if (skb)
- skb_queue_tail(q, skb);
-}
-
-/* List rules using struct audit_rule_data. */
-static void audit_list_rules(int pid, int seq, struct sk_buff_head *q)
-{
- struct sk_buff *skb;
- struct audit_entry *e;
- int i;
-
- /* This is a blocking read, so use audit_filter_mutex instead of rcu
- * iterator to sync with list writers. */
- for (i=0; irule);
- if (unlikely(!data))
- break;
- skb = audit_make_reply(pid, seq, AUDIT_LIST_RULES, 0, 1,
- data, sizeof(*data) + data->buflen);
- if (skb)
- skb_queue_tail(q, skb);
- kfree(data);
- }
- }
- for (i=0; i< AUDIT_INODE_BUCKETS; i++) {
- list_for_each_entry(e, &audit_inode_hash[i], list) {
- struct audit_rule_data *data;
-
- data = audit_krule_to_data(&e->rule);
- if (unlikely(!data))
- break;
- skb = audit_make_reply(pid, seq, AUDIT_LIST_RULES, 0, 1,
- data, sizeof(*data) + data->buflen);
- if (skb)
- skb_queue_tail(q, skb);
- kfree(data);
- }
- }
- skb = audit_make_reply(pid, seq, AUDIT_LIST_RULES, 1, 1, NULL, 0);
- if (skb)
- skb_queue_tail(q, skb);
-}
-
-/* Log rule additions and removals */
-static void audit_log_rule_change(uid_t loginuid, u32 sessionid, u32 sid,
- char *action, struct audit_krule *rule,
- int res)
-{
- struct audit_buffer *ab;
-
- if (!audit_enabled)
- return;
-
- ab = audit_log_start(NULL, GFP_KERNEL, AUDIT_CONFIG_CHANGE);
- if (!ab)
- return;
- audit_log_format(ab, "auid=%u ses=%u", loginuid, sessionid);
- if (sid) {
- char *ctx = NULL;
- u32 len;
- if (security_secid_to_secctx(sid, &ctx, &len))
- audit_log_format(ab, " ssid=%u", sid);
- else {
- audit_log_format(ab, " subj=%s", ctx);
- security_release_secctx(ctx, len);
- }
- }
- audit_log_format(ab, " op=%s rule key=", action);
- if (rule->filterkey)
- audit_log_untrustedstring(ab, rule->filterkey);
- else
- audit_log_format(ab, "(null)");
- audit_log_format(ab, " list=%d res=%d", rule->listnr, res);
- audit_log_end(ab);
-}
-
-/**
- * audit_receive_filter - apply all rules to the specified message type
- * @type: audit message type
- * @pid: target pid for netlink audit messages
- * @uid: target uid for netlink audit messages
- * @seq: netlink audit message sequence (serial) number
- * @data: payload data
- * @datasz: size of payload data
- * @loginuid: loginuid of sender
- * @sessionid: sessionid for netlink audit message
- * @sid: SE Linux Security ID of sender
- */
-int audit_receive_filter(int type, int pid, int uid, int seq, void *data,
- size_t datasz, uid_t loginuid, u32 sessionid, u32 sid)
-{
- struct task_struct *tsk;
- struct audit_netlink_list *dest;
- int err = 0;
- struct audit_entry *entry;
-
- switch (type) {
- case AUDIT_LIST:
- case AUDIT_LIST_RULES:
- /* We can't just spew out the rules here because we might fill
- * the available socket buffer space and deadlock waiting for
- * auditctl to read from it... which isn't ever going to
- * happen if we're actually running in the context of auditctl
- * trying to _send_ the stuff */
-
- dest = kmalloc(sizeof(struct audit_netlink_list), GFP_KERNEL);
- if (!dest)
- return -ENOMEM;
- dest->pid = pid;
- skb_queue_head_init(&dest->q);
-
- mutex_lock(&audit_filter_mutex);
- if (type == AUDIT_LIST)
- audit_list(pid, seq, &dest->q);
- else
- audit_list_rules(pid, seq, &dest->q);
- mutex_unlock(&audit_filter_mutex);
-
- tsk = kthread_run(audit_send_list, dest, "audit_send_list");
- if (IS_ERR(tsk)) {
- skb_queue_purge(&dest->q);
- kfree(dest);
- err = PTR_ERR(tsk);
- }
- break;
- case AUDIT_ADD:
- case AUDIT_ADD_RULE:
- if (type == AUDIT_ADD)
- entry = audit_rule_to_entry(data);
- else
- entry = audit_data_to_entry(data, datasz);
- if (IS_ERR(entry))
- return PTR_ERR(entry);
-
- err = audit_add_rule(entry,
- &audit_filter_list[entry->rule.listnr]);
- audit_log_rule_change(loginuid, sessionid, sid, "add",
- &entry->rule, !err);
-
- if (err)
- audit_free_rule(entry);
- break;
- case AUDIT_DEL:
- case AUDIT_DEL_RULE:
- if (type == AUDIT_DEL)
- entry = audit_rule_to_entry(data);
- else
- entry = audit_data_to_entry(data, datasz);
- if (IS_ERR(entry))
- return PTR_ERR(entry);
-
- err = audit_del_rule(entry,
- &audit_filter_list[entry->rule.listnr]);
- audit_log_rule_change(loginuid, sessionid, sid, "remove",
- &entry->rule, !err);
-
- audit_free_rule(entry);
- break;
- default:
- return -EINVAL;
- }
-
- return err;
-}
-
-int audit_comparator(const u32 left, const u32 op, const u32 right)
-{
- switch (op) {
- case AUDIT_EQUAL:
- return (left == right);
- case AUDIT_NOT_EQUAL:
- return (left != right);
- case AUDIT_LESS_THAN:
- return (left < right);
- case AUDIT_LESS_THAN_OR_EQUAL:
- return (left <= right);
- case AUDIT_GREATER_THAN:
- return (left > right);
- case AUDIT_GREATER_THAN_OR_EQUAL:
- return (left >= right);
- case AUDIT_BIT_MASK:
- return (left & right);
- case AUDIT_BIT_TEST:
- return ((left & right) == right);
- }
- BUG();
- return 0;
-}
-
-/* Compare given dentry name with last component in given path,
- * return of 0 indicates a match. */
-int audit_compare_dname_path(const char *dname, const char *path,
- int *dirlen)
-{
- int dlen, plen;
- const char *p;
-
- if (!dname || !path)
- return 1;
-
- dlen = strlen(dname);
- plen = strlen(path);
- if (plen < dlen)
- return 1;
-
- /* disregard trailing slashes */
- p = path + plen - 1;
- while ((*p == '/') && (p > path))
- p--;
-
- /* find last path component */
- p = p - dlen + 1;
- if (p < path)
- return 1;
- else if (p > path) {
- if (*--p != '/')
- return 1;
- else
- p++;
- }
-
- /* return length of path's directory component */
- if (dirlen)
- *dirlen = p - path;
- return strncmp(p, dname, dlen);
-}
-
-static int audit_filter_user_rules(struct netlink_skb_parms *cb,
- struct audit_krule *rule,
- enum audit_state *state)
-{
- int i;
-
- for (i = 0; i < rule->field_count; i++) {
- struct audit_field *f = &rule->fields[i];
- int result = 0;
-
- switch (f->type) {
- case AUDIT_PID:
- result = audit_comparator(cb->creds.pid, f->op, f->val);
- break;
- case AUDIT_UID:
- result = audit_comparator(cb->creds.uid, f->op, f->val);
- break;
- case AUDIT_GID:
- result = audit_comparator(cb->creds.gid, f->op, f->val);
- break;
- case AUDIT_LOGINUID:
- result = audit_comparator(cb->loginuid, f->op, f->val);
- break;
- }
-
- if (!result)
- return 0;
- }
- switch (rule->action) {
- case AUDIT_NEVER: *state = AUDIT_DISABLED; break;
- case AUDIT_ALWAYS: *state = AUDIT_RECORD_CONTEXT; break;
- }
- return 1;
-}
-
-int audit_filter_user(struct netlink_skb_parms *cb)
-{
- enum audit_state state = AUDIT_DISABLED;
- struct audit_entry *e;
- int ret = 1;
-
- rcu_read_lock();
- list_for_each_entry_rcu(e, &audit_filter_list[AUDIT_FILTER_USER], list) {
- if (audit_filter_user_rules(cb, &e->rule, &state)) {
- if (state == AUDIT_DISABLED)
- ret = 0;
- break;
- }
- }
- rcu_read_unlock();
-
- return ret; /* Audit by default */
-}
-
-int audit_filter_type(int type)
-{
- struct audit_entry *e;
- int result = 0;
-
- rcu_read_lock();
- if (list_empty(&audit_filter_list[AUDIT_FILTER_TYPE]))
- goto unlock_and_return;
-
- list_for_each_entry_rcu(e, &audit_filter_list[AUDIT_FILTER_TYPE],
- list) {
- int i;
- for (i = 0; i < e->rule.field_count; i++) {
- struct audit_field *f = &e->rule.fields[i];
- if (f->type == AUDIT_MSGTYPE) {
- result = audit_comparator(type, f->op, f->val);
- if (!result)
- break;
- }
- }
- if (result)
- goto unlock_and_return;
- }
-unlock_and_return:
- rcu_read_unlock();
- return result;
-}
-
-/* This function will re-initialize the lsm_rule field of all applicable rules.
- * It will traverse the filter lists serarching for rules that contain LSM
- * specific filter fields. When such a rule is found, it is copied, the
- * LSM field is re-initialized, and the old rule is replaced with the
- * updated rule. */
-int audit_update_lsm_rules(void)
-{
- struct audit_entry *entry, *n, *nentry;
- struct audit_watch *watch;
- struct audit_tree *tree;
- int i, err = 0;
-
- /* audit_filter_mutex synchronizes the writers */
- mutex_lock(&audit_filter_mutex);
-
- for (i = 0; i < AUDIT_NR_FILTERS; i++) {
- list_for_each_entry_safe(entry, n, &audit_filter_list[i], list) {
- if (!security_audit_rule_known(&entry->rule))
- continue;
-
- watch = entry->rule.watch;
- tree = entry->rule.tree;
- nentry = audit_dupe_rule(&entry->rule, watch);
- if (IS_ERR(nentry)) {
- /* save the first error encountered for the
- * return value */
- if (!err)
- err = PTR_ERR(nentry);
- audit_panic("error updating LSM filters");
- if (watch)
- list_del(&entry->rule.rlist);
- list_del_rcu(&entry->list);
- } else {
- if (watch) {
- list_add(&nentry->rule.rlist,
- &watch->rules);
- list_del(&entry->rule.rlist);
- } else if (tree)
- list_replace_init(&entry->rule.rlist,
- &nentry->rule.rlist);
- list_replace_rcu(&entry->list, &nentry->list);
- }
- call_rcu(&entry->rcu, audit_free_rule_rcu);
- }
- }
-
- mutex_unlock(&audit_filter_mutex);
-
- return err;
-}
-
-/* Update watch data in audit rules based on inotify events. */
-void audit_handle_ievent(struct inotify_watch *i_watch, u32 wd, u32 mask,
- u32 cookie, const char *dname, struct inode *inode)
-{
- struct audit_parent *parent;
-
- parent = container_of(i_watch, struct audit_parent, wdata);
-
- if (mask & (IN_CREATE|IN_MOVED_TO) && inode)
- audit_update_watch(parent, dname, inode->i_sb->s_dev,
- inode->i_ino, 0);
- else if (mask & (IN_DELETE|IN_MOVED_FROM))
- audit_update_watch(parent, dname, (dev_t)-1, (unsigned long)-1, 1);
- /* inotify automatically removes the watch and sends IN_IGNORED */
- else if (mask & (IN_DELETE_SELF|IN_UNMOUNT))
- audit_remove_parent_watches(parent);
- /* inotify does not remove the watch, so remove it manually */
- else if(mask & IN_MOVE_SELF) {
- audit_remove_parent_watches(parent);
- inotify_remove_watch_locked(audit_ih, i_watch);
- } else if (mask & IN_IGNORED)
- put_inotify_watch(i_watch);
-}
-/* auditsc.c -- System-call auditing support
- * Handles all system-call specific auditing features.
- *
- * Copyright 2003-2004 Red Hat Inc., Durham, North Carolina.
- * Copyright 2005 Hewlett-Packard Development Company, L.P.
- * Copyright (C) 2005, 2006 IBM Corporation
- * All Rights Reserved.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * Written by Rickard E. (Rik) Faith
- *
- * Many of the ideas implemented here are from Stephen C. Tweedie,
- * especially the idea of avoiding a copy by using getname.
- *
- * The method for actual interception of syscall entry and exit (not in
- * this file -- see entry.S) is based on a GPL'd patch written by
- * okir@suse.de and Copyright 2003 SuSE Linux AG.
- *
- * POSIX message queue support added by George Wilson ,
- * 2006.
- *
- * The support of additional filter rules compares (>, <, >=, <=) was
- * added by Dustin Kirkland , 2005.
- *
- * Modified by Amy Griffis to collect additional
- * filesystem information.
- *
- * Subject and object context labeling support added by
- * and for LSPP certification compliance.
- */
-
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-
-#include "audit.h"
-
-/* AUDIT_NAMES is the number of slots we reserve in the audit_context
- * for saving names from getname(). */
-#define AUDIT_NAMES 20
-
-/* Indicates that audit should log the full pathname. */
-#define AUDIT_NAME_FULL -1
-
-/* no execve audit message should be longer than this (userspace limits) */
-#define MAX_EXECVE_AUDIT_LEN 7500
-
-/* number of audit rules */
-int audit_n_rules;
-
-/* determines whether we collect data for signals sent */
-int audit_signals;
-
-/* When fs/namei.c:getname() is called, we store the pointer in name and
- * we don't let putname() free it (instead we free all of the saved
- * pointers at syscall exit time).
- *
- * Further, in fs/namei.c:path_lookup() we store the inode and device. */
-struct audit_names {
- const char *name;
- int name_len; /* number of name's characters to log */
- unsigned name_put; /* call __putname() for this name */
- unsigned long ino;
- dev_t dev;
- umode_t mode;
- uid_t uid;
- gid_t gid;
- dev_t rdev;
- u32 osid;
-};
-
-struct audit_aux_data {
- struct audit_aux_data *next;
- int type;
-};
-
-#define AUDIT_AUX_IPCPERM 0
-
-/* Number of target pids per aux struct. */
-#define AUDIT_AUX_PIDS 16
-
-struct audit_aux_data_mq_open {
- struct audit_aux_data d;
- int oflag;
- mode_t mode;
- struct mq_attr attr;
-};
-
-struct audit_aux_data_mq_sendrecv {
- struct audit_aux_data d;
- mqd_t mqdes;
- size_t msg_len;
- unsigned int msg_prio;
- struct timespec abs_timeout;
-};
-
-struct audit_aux_data_mq_notify {
- struct audit_aux_data d;
- mqd_t mqdes;
- struct sigevent notification;
-};
-
-struct audit_aux_data_mq_getsetattr {
- struct audit_aux_data d;
- mqd_t mqdes;
- struct mq_attr mqstat;
-};
-
-struct audit_aux_data_ipcctl {
- struct audit_aux_data d;
- struct ipc_perm p;
- unsigned long qbytes;
- uid_t uid;
- gid_t gid;
- mode_t mode;
- u32 osid;
-};
-
-struct audit_aux_data_execve {
- struct audit_aux_data d;
- int argc;
- int envc;
- struct mm_struct *mm;
-};
-
-struct audit_aux_data_socketcall {
- struct audit_aux_data d;
- int nargs;
- unsigned long args[0];
-};
-
-struct audit_aux_data_sockaddr {
- struct audit_aux_data d;
- int len;
- char a[0];
-};
-
-struct audit_aux_data_fd_pair {
- struct audit_aux_data d;
- int fd[2];
-};
-
-struct audit_aux_data_pids {
- struct audit_aux_data d;
- pid_t target_pid[AUDIT_AUX_PIDS];
- uid_t target_auid[AUDIT_AUX_PIDS];
- uid_t target_uid[AUDIT_AUX_PIDS];
- unsigned int target_sessionid[AUDIT_AUX_PIDS];
- u32 target_sid[AUDIT_AUX_PIDS];
- char target_comm[AUDIT_AUX_PIDS][TASK_COMM_LEN];
- int pid_count;
-};
-
-struct audit_tree_refs {
- struct audit_tree_refs *next;
- struct audit_chunk *c[31];
-};
-
-/* The per-task audit context. */
-struct audit_context {
- int dummy; /* must be the first element */
- int in_syscall; /* 1 if task is in a syscall */
- enum audit_state state;
- unsigned int serial; /* serial number for record */
- struct timespec ctime; /* time of syscall entry */
- int major; /* syscall number */
- unsigned long argv[4]; /* syscall arguments */
- int return_valid; /* return code is valid */
- long return_code;/* syscall return code */
- int auditable; /* 1 if record should be written */
- int name_count;
- struct audit_names names[AUDIT_NAMES];
- char * filterkey; /* key for rule that triggered record */
- struct path pwd;
- struct audit_context *previous; /* For nested syscalls */
- struct audit_aux_data *aux;
- struct audit_aux_data *aux_pids;
-
- /* Save things to print about task_struct */
- pid_t pid, ppid;
- uid_t uid, euid, suid, fsuid;
- gid_t gid, egid, sgid, fsgid;
- unsigned long personality;
- int arch;
-
- pid_t target_pid;
- uid_t target_auid;
- uid_t target_uid;
- unsigned int target_sessionid;
- u32 target_sid;
- char target_comm[TASK_COMM_LEN];
-
- struct audit_tree_refs *trees, *first_trees;
- int tree_count;
-
-#if AUDIT_DEBUG
- int put_count;
- int ino_count;
-#endif
-};
-
-#define ACC_MODE(x) ("\004\002\006\006"[(x)&O_ACCMODE])
-static inline int open_arg(int flags, int mask)
-{
- int n = ACC_MODE(flags);
- if (flags & (O_TRUNC | O_CREAT))
- n |= AUDIT_PERM_WRITE;
- return n & mask;
-}
-
-static int audit_match_perm(struct audit_context *ctx, int mask)
-{
- unsigned n;
- if (unlikely(!ctx))
- return 0;
-
- n = ctx->major;
- switch (audit_classify_syscall(ctx->arch, n)) {
- case 0: /* native */
- if ((mask & AUDIT_PERM_WRITE) &&
- audit_match_class(AUDIT_CLASS_WRITE, n))
- return 1;
- if ((mask & AUDIT_PERM_READ) &&
- audit_match_class(AUDIT_CLASS_READ, n))
- return 1;
- if ((mask & AUDIT_PERM_ATTR) &&
- audit_match_class(AUDIT_CLASS_CHATTR, n))
- return 1;
- return 0;
- case 1: /* 32bit on biarch */
- if ((mask & AUDIT_PERM_WRITE) &&
- audit_match_class(AUDIT_CLASS_WRITE_32, n))
- return 1;
- if ((mask & AUDIT_PERM_READ) &&
- audit_match_class(AUDIT_CLASS_READ_32, n))
- return 1;
- if ((mask & AUDIT_PERM_ATTR) &&
- audit_match_class(AUDIT_CLASS_CHATTR_32, n))
- return 1;
- return 0;
- case 2: /* open */
- return mask & ACC_MODE(ctx->argv[1]);
- case 3: /* openat */
- return mask & ACC_MODE(ctx->argv[2]);
- case 4: /* socketcall */
- return ((mask & AUDIT_PERM_WRITE) && ctx->argv[0] == SYS_BIND);
- case 5: /* execve */
- return mask & AUDIT_PERM_EXEC;
- default:
- return 0;
- }
-}
-
-static int audit_match_filetype(struct audit_context *ctx, int which)
-{
- unsigned index = which & ~S_IFMT;
- mode_t mode = which & S_IFMT;
-
- if (unlikely(!ctx))
- return 0;
-
- if (index >= ctx->name_count)
- return 0;
- if (ctx->names[index].ino == -1)
- return 0;
- if ((ctx->names[index].mode ^ mode) & S_IFMT)
- return 0;
- return 1;
-}
-
-/*
- * We keep a linked list of fixed-sized (31 pointer) arrays of audit_chunk *;
- * ->first_trees points to its beginning, ->trees - to the current end of data.
- * ->tree_count is the number of free entries in array pointed to by ->trees.
- * Original condition is (NULL, NULL, 0); as soon as it grows we never revert to NULL,
- * "empty" becomes (p, p, 31) afterwards. We don't shrink the list (and seriously,
- * it's going to remain 1-element for almost any setup) until we free context itself.
- * References in it _are_ dropped - at the same time we free/drop aux stuff.
- */
-
-#ifdef CONFIG_AUDIT_TREE
-static int put_tree_ref(struct audit_context *ctx, struct audit_chunk *chunk)
-{
- struct audit_tree_refs *p = ctx->trees;
- int left = ctx->tree_count;
- if (likely(left)) {
- p->c[--left] = chunk;
- ctx->tree_count = left;
- return 1;
- }
- if (!p)
- return 0;
- p = p->next;
- if (p) {
- p->c[30] = chunk;
- ctx->trees = p;
- ctx->tree_count = 30;
- return 1;
- }
- return 0;
-}
-
-static int grow_tree_refs(struct audit_context *ctx)
-{
- struct audit_tree_refs *p = ctx->trees;
- ctx->trees = kzalloc(sizeof(struct audit_tree_refs), GFP_KERNEL);
- if (!ctx->trees) {
- ctx->trees = p;
- return 0;
- }
- if (p)
- p->next = ctx->trees;
- else
- ctx->first_trees = ctx->trees;
- ctx->tree_count = 31;
- return 1;
-}
-#endif
-
-static void unroll_tree_refs(struct audit_context *ctx,
- struct audit_tree_refs *p, int count)
-{
-#ifdef CONFIG_AUDIT_TREE
- struct audit_tree_refs *q;
- int n;
- if (!p) {
- /* we started with empty chain */
- p = ctx->first_trees;
- count = 31;
- /* if the very first allocation has failed, nothing to do */
- if (!p)
- return;
- }
- n = count;
- for (q = p; q != ctx->trees; q = q->next, n = 31) {
- while (n--) {
- audit_put_chunk(q->c[n]);
- q->c[n] = NULL;
- }
- }
- while (n-- > ctx->tree_count) {
- audit_put_chunk(q->c[n]);
- q->c[n] = NULL;
- }
- ctx->trees = p;
- ctx->tree_count = count;
-#endif
-}
-
-static void free_tree_refs(struct audit_context *ctx)
-{
- struct audit_tree_refs *p, *q;
- for (p = ctx->first_trees; p; p = q) {
- q = p->next;
- kfree(p);
- }
-}
-
-static int match_tree_refs(struct audit_context *ctx, struct audit_tree *tree)
-{
-#ifdef CONFIG_AUDIT_TREE
- struct audit_tree_refs *p;
- int n;
- if (!tree)
- return 0;
- /* full ones */
- for (p = ctx->first_trees; p != ctx->trees; p = p->next) {
- for (n = 0; n < 31; n++)
- if (audit_tree_match(p->c[n], tree))
- return 1;
- }
- /* partial */
- if (p) {
- for (n = ctx->tree_count; n < 31; n++)
- if (audit_tree_match(p->c[n], tree))
- return 1;
- }
-#endif
- return 0;
-}
-
-/* Determine if any context name data matches a rule's watch data */
-/* Compare a task_struct with an audit_rule. Return 1 on match, 0
- * otherwise. */
-static int audit_filter_rules(struct task_struct *tsk,
- struct audit_krule *rule,
- struct audit_context *ctx,
- struct audit_names *name,
- enum audit_state *state)
-{
- int i, j, need_sid = 1;
- u32 sid;
-
- for (i = 0; i < rule->field_count; i++) {
- struct audit_field *f = &rule->fields[i];
- int result = 0;
-
- switch (f->type) {
- case AUDIT_PID:
- result = audit_comparator(tsk->pid, f->op, f->val);
- break;
- case AUDIT_PPID:
- if (ctx) {
- if (!ctx->ppid)
- ctx->ppid = sys_getppid();
- result = audit_comparator(ctx->ppid, f->op, f->val);
- }
- break;
- case AUDIT_UID:
- result = audit_comparator(tsk->uid, f->op, f->val);
- break;
- case AUDIT_EUID:
- result = audit_comparator(tsk->euid, f->op, f->val);
- break;
- case AUDIT_SUID:
- result = audit_comparator(tsk->suid, f->op, f->val);
- break;
- case AUDIT_FSUID:
- result = audit_comparator(tsk->fsuid, f->op, f->val);
- break;
- case AUDIT_GID:
- result = audit_comparator(tsk->gid, f->op, f->val);
- break;
- case AUDIT_EGID:
- result = audit_comparator(tsk->egid, f->op, f->val);
- break;
- case AUDIT_SGID:
- result = audit_comparator(tsk->sgid, f->op, f->val);
- break;
- case AUDIT_FSGID:
- result = audit_comparator(tsk->fsgid, f->op, f->val);
- break;
- case AUDIT_PERS:
- result = audit_comparator(tsk->personality, f->op, f->val);
- break;
- case AUDIT_ARCH:
- if (ctx)
- result = audit_comparator(ctx->arch, f->op, f->val);
- break;
-
- case AUDIT_EXIT:
- if (ctx && ctx->return_valid)
- result = audit_comparator(ctx->return_code, f->op, f->val);
- break;
- case AUDIT_SUCCESS:
- if (ctx && ctx->return_valid) {
- if (f->val)
- result = audit_comparator(ctx->return_valid, f->op, AUDITSC_SUCCESS);
- else
- result = audit_comparator(ctx->return_valid, f->op, AUDITSC_FAILURE);
- }
- break;
- case AUDIT_DEVMAJOR:
- if (name)
- result = audit_comparator(MAJOR(name->dev),
- f->op, f->val);
- else if (ctx) {
- for (j = 0; j < ctx->name_count; j++) {
- if (audit_comparator(MAJOR(ctx->names[j].dev), f->op, f->val)) {
- ++result;
- break;
- }
- }
- }
- break;
- case AUDIT_DEVMINOR:
- if (name)
- result = audit_comparator(MINOR(name->dev),
- f->op, f->val);
- else if (ctx) {
- for (j = 0; j < ctx->name_count; j++) {
- if (audit_comparator(MINOR(ctx->names[j].dev), f->op, f->val)) {
- ++result;
- break;
- }
- }
- }
- break;
- case AUDIT_INODE:
- if (name)
- result = (name->ino == f->val);
- else if (ctx) {
- for (j = 0; j < ctx->name_count; j++) {
- if (audit_comparator(ctx->names[j].ino, f->op, f->val)) {
- ++result;
- break;
- }
- }
- }
- break;
- case AUDIT_WATCH:
- if (name && rule->watch->ino != (unsigned long)-1)
- result = (name->dev == rule->watch->dev &&
- name->ino == rule->watch->ino);
- break;
- case AUDIT_DIR:
- if (ctx)
- result = match_tree_refs(ctx, rule->tree);
- break;
- case AUDIT_LOGINUID:
- result = 0;
- if (ctx)
- result = audit_comparator(tsk->loginuid, f->op, f->val);
- break;
- case AUDIT_SUBJ_USER:
- case AUDIT_SUBJ_ROLE:
- case AUDIT_SUBJ_TYPE:
- case AUDIT_SUBJ_SEN:
- case AUDIT_SUBJ_CLR:
- /* NOTE: this may return negative values indicating
- a temporary error. We simply treat this as a
- match for now to avoid losing information that
- may be wanted. An error message will also be
- logged upon error */
- if (f->lsm_rule) {
- if (need_sid) {
- security_task_getsecid(tsk, &sid);
- need_sid = 0;
- }
- result = security_audit_rule_match(sid, f->type,
- f->op,
- f->lsm_rule,
- ctx);
- }
- break;
- case AUDIT_OBJ_USER:
- case AUDIT_OBJ_ROLE:
- case AUDIT_OBJ_TYPE:
- case AUDIT_OBJ_LEV_LOW:
- case AUDIT_OBJ_LEV_HIGH:
- /* The above note for AUDIT_SUBJ_USER...AUDIT_SUBJ_CLR
- also applies here */
- if (f->lsm_rule) {
- /* Find files that match */
- if (name) {
- result = security_audit_rule_match(
- name->osid, f->type, f->op,
- f->lsm_rule, ctx);
- } else if (ctx) {
- for (j = 0; j < ctx->name_count; j++) {
- if (security_audit_rule_match(
- ctx->names[j].osid,
- f->type, f->op,
- f->lsm_rule, ctx)) {
- ++result;
- break;
- }
- }
- }
- /* Find ipc objects that match */
- if (ctx) {
- struct audit_aux_data *aux;
- for (aux = ctx->aux; aux;
- aux = aux->next) {
- if (aux->type == AUDIT_IPC) {
- struct audit_aux_data_ipcctl *axi = (void *)aux;
- if (security_audit_rule_match(axi->osid, f->type, f->op, f->lsm_rule, ctx)) {
- ++result;
- break;
- }
- }
- }
- }
- }
- break;
- case AUDIT_ARG0:
- case AUDIT_ARG1:
- case AUDIT_ARG2:
- case AUDIT_ARG3:
- if (ctx)
- result = audit_comparator(ctx->argv[f->type-AUDIT_ARG0], f->op, f->val);
- break;
- case AUDIT_FILTERKEY:
- /* ignore this field for filtering */
- result = 1;
- break;
- case AUDIT_PERM:
- result = audit_match_perm(ctx, f->val);
- break;
- case AUDIT_FILETYPE:
- result = audit_match_filetype(ctx, f->val);
- break;
- }
-
- if (!result)
- return 0;
- }
- if (rule->filterkey && ctx)
- ctx->filterkey = kstrdup(rule->filterkey, GFP_ATOMIC);
- switch (rule->action) {
- case AUDIT_NEVER: *state = AUDIT_DISABLED; break;
- case AUDIT_ALWAYS: *state = AUDIT_RECORD_CONTEXT; break;
- }
- return 1;
-}
-
-/* At process creation time, we can determine if system-call auditing is
- * completely disabled for this task. Since we only have the task
- * structure at this point, we can only check uid and gid.
- */
-static enum audit_state audit_filter_task(struct task_struct *tsk)
-{
- struct audit_entry *e;
- enum audit_state state;
-
- rcu_read_lock();
- list_for_each_entry_rcu(e, &audit_filter_list[AUDIT_FILTER_TASK], list) {
- if (audit_filter_rules(tsk, &e->rule, NULL, NULL, &state)) {
- rcu_read_unlock();
- return state;
- }
- }
- rcu_read_unlock();
- return AUDIT_BUILD_CONTEXT;
-}
-
-/* At syscall entry and exit time, this filter is called if the
- * audit_state is not low enough that auditing cannot take place, but is
- * also not high enough that we already know we have to write an audit
- * record (i.e., the state is AUDIT_SETUP_CONTEXT or AUDIT_BUILD_CONTEXT).
- */
-static enum audit_state audit_filter_syscall(struct task_struct *tsk,
- struct audit_context *ctx,
- struct list_head *list)
-{
- struct audit_entry *e;
- enum audit_state state;
-
- if (audit_pid && tsk->tgid == audit_pid)
- return AUDIT_DISABLED;
-
- rcu_read_lock();
- if (!list_empty(list)) {
- int word = AUDIT_WORD(ctx->major);
- int bit = AUDIT_BIT(ctx->major);
-
- list_for_each_entry_rcu(e, list, list) {
- if ((e->rule.mask[word] & bit) == bit &&
- audit_filter_rules(tsk, &e->rule, ctx, NULL,
- &state)) {
- rcu_read_unlock();
- return state;
- }
- }
- }
- rcu_read_unlock();
- return AUDIT_BUILD_CONTEXT;
-}
-
-/* At syscall exit time, this filter is called if any audit_names[] have been
- * collected during syscall processing. We only check rules in sublists at hash
- * buckets applicable to the inode numbers in audit_names[].
- * Regarding audit_state, same rules apply as for audit_filter_syscall().
- */
-enum audit_state audit_filter_inodes(struct task_struct *tsk,
- struct audit_context *ctx)
-{
- int i;
- struct audit_entry *e;
- enum audit_state state;
-
- if (audit_pid && tsk->tgid == audit_pid)
- return AUDIT_DISABLED;
-
- rcu_read_lock();
- for (i = 0; i < ctx->name_count; i++) {
- int word = AUDIT_WORD(ctx->major);
- int bit = AUDIT_BIT(ctx->major);
- struct audit_names *n = &ctx->names[i];
- int h = audit_hash_ino((u32)n->ino);
- struct list_head *list = &audit_inode_hash[h];
-
- if (list_empty(list))
- continue;
-
- list_for_each_entry_rcu(e, list, list) {
- if ((e->rule.mask[word] & bit) == bit &&
- audit_filter_rules(tsk, &e->rule, ctx, n, &state)) {
- rcu_read_unlock();
- return state;
- }
- }
- }
- rcu_read_unlock();
- return AUDIT_BUILD_CONTEXT;
-}
-
-void audit_set_auditable(struct audit_context *ctx)
-{
- ctx->auditable = 1;
-}
-
-static inline struct audit_context *audit_get_context(struct task_struct *tsk,
- int return_valid,
- int return_code)
-{
- struct audit_context *context = tsk->audit_context;
-
- if (likely(!context))
- return NULL;
- context->return_valid = return_valid;
-
- /*
- * we need to fix up the return code in the audit logs if the actual
- * return codes are later going to be fixed up by the arch specific
- * signal handlers
- *
- * This is actually a test for:
- * (rc == ERESTARTSYS ) || (rc == ERESTARTNOINTR) ||
- * (rc == ERESTARTNOHAND) || (rc == ERESTART_RESTARTBLOCK)
- *
- * but is faster than a bunch of ||
- */
- if (unlikely(return_code <= -ERESTARTSYS) &&
- (return_code >= -ERESTART_RESTARTBLOCK) &&
- (return_code != -ENOIOCTLCMD))
- context->return_code = -EINTR;
- else
- context->return_code = return_code;
-
- if (context->in_syscall && !context->dummy && !context->auditable) {
- enum audit_state state;
-
- state = audit_filter_syscall(tsk, context, &audit_filter_list[AUDIT_FILTER_EXIT]);
- if (state == AUDIT_RECORD_CONTEXT) {
- context->auditable = 1;
- goto get_context;
- }
-
- state = audit_filter_inodes(tsk, context);
- if (state == AUDIT_RECORD_CONTEXT)
- context->auditable = 1;
-
- }
-
-get_context:
-
- tsk->audit_context = NULL;
- return context;
-}
-
-static inline void audit_free_names(struct audit_context *context)
-{
- int i;
-
-#if AUDIT_DEBUG == 2
- if (context->auditable
- ||context->put_count + context->ino_count != context->name_count) {
- printk(KERN_ERR "%s:%d(:%d): major=%d in_syscall=%d"
- " name_count=%d put_count=%d"
- " ino_count=%d [NOT freeing]\n",
- __FILE__, __LINE__,
- context->serial, context->major, context->in_syscall,
- context->name_count, context->put_count,
- context->ino_count);
- for (i = 0; i < context->name_count; i++) {
- printk(KERN_ERR "names[%d] = %p = %s\n", i,
- context->names[i].name,
- context->names[i].name ?: "(null)");
- }
- dump_stack();
- return;
- }
-#endif
-#if AUDIT_DEBUG
- context->put_count = 0;
- context->ino_count = 0;
-#endif
-
- for (i = 0; i < context->name_count; i++) {
- if (context->names[i].name && context->names[i].name_put)
- __putname(context->names[i].name);
- }
- context->name_count = 0;
- path_put(&context->pwd);
- context->pwd.dentry = NULL;
- context->pwd.mnt = NULL;
-}
-
-static inline void audit_free_aux(struct audit_context *context)
-{
- struct audit_aux_data *aux;
-
- while ((aux = context->aux)) {
- context->aux = aux->next;
- kfree(aux);
- }
- while ((aux = context->aux_pids)) {
- context->aux_pids = aux->next;
- kfree(aux);
- }
-}
-
-static inline void audit_zero_context(struct audit_context *context,
- enum audit_state state)
-{
- memset(context, 0, sizeof(*context));
- context->state = state;
-}
-
-static inline struct audit_context *audit_alloc_context(enum audit_state state)
-{
- struct audit_context *context;
-
- if (!(context = kmalloc(sizeof(*context), GFP_KERNEL)))
- return NULL;
- audit_zero_context(context, state);
- return context;
-}
-
-/**
- * audit_alloc - allocate an audit context block for a task
- * @tsk: task
- *
- * Filter on the task information and allocate a per-task audit context
- * if necessary. Doing so turns on system call auditing for the
- * specified task. This is called from copy_process, so no lock is
- * needed.
- */
-int audit_alloc(struct task_struct *tsk)
-{
- struct audit_context *context;
- enum audit_state state;
-
- if (likely(!audit_ever_enabled))
- return 0; /* Return if not auditing. */
-
- state = audit_filter_task(tsk);
- if (likely(state == AUDIT_DISABLED))
- return 0;
-
- if (!(context = audit_alloc_context(state))) {
- audit_log_lost("out of memory in audit_alloc");
- return -ENOMEM;
- }
-
- tsk->audit_context = context;
- set_tsk_thread_flag(tsk, TIF_SYSCALL_AUDIT);
- return 0;
-}
-
-static inline void audit_free_context(struct audit_context *context)
-{
- struct audit_context *previous;
- int count = 0;
-
- do {
- previous = context->previous;
- if (previous || (count && count < 10)) {
- ++count;
- printk(KERN_ERR "audit(:%d): major=%d name_count=%d:"
- " freeing multiple contexts (%d)\n",
- context->serial, context->major,
- context->name_count, count);
- }
- audit_free_names(context);
- unroll_tree_refs(context, NULL, 0);
- free_tree_refs(context);
- audit_free_aux(context);
- kfree(context->filterkey);
- kfree(context);
- context = previous;
- } while (context);
- if (count >= 10)
- printk(KERN_ERR "audit: freed %d contexts\n", count);
-}
-
-void audit_log_task_context(struct audit_buffer *ab)
-{
- char *ctx = NULL;
- unsigned len;
- int error;
- u32 sid;
-
- security_task_getsecid(current, &sid);
- if (!sid)
- return;
-
- error = security_secid_to_secctx(sid, &ctx, &len);
- if (error) {
- if (error != -EINVAL)
- goto error_path;
- return;
- }
-
- audit_log_format(ab, " subj=%s", ctx);
- security_release_secctx(ctx, len);
- return;
-
-error_path:
- audit_panic("error in audit_log_task_context");
- return;
-}
-
-EXPORT_SYMBOL(audit_log_task_context);
-
-static void audit_log_task_info(struct audit_buffer *ab, struct task_struct *tsk)
-{
- char name[sizeof(tsk->comm)];
- struct mm_struct *mm = tsk->mm;
- struct vm_area_struct *vma;
-
- /* tsk == current */
-
- get_task_comm(name, tsk);
- audit_log_format(ab, " comm=");
- audit_log_untrustedstring(ab, name);
-
- if (mm) {
- down_read(&mm->mmap_sem);
- vma = mm->mmap;
- while (vma) {
- if ((vma->vm_flags & VM_EXECUTABLE) &&
- vma->vm_file) {
- audit_log_d_path(ab, "exe=",
- &vma->vm_file->f_path);
- break;
- }
- vma = vma->vm_next;
- }
- up_read(&mm->mmap_sem);
- }
- audit_log_task_context(ab);
-}
-
-static int audit_log_pid_context(struct audit_context *context, pid_t pid,
- uid_t auid, uid_t uid, unsigned int sessionid,
- u32 sid, char *comm)
-{
- struct audit_buffer *ab;
- char *ctx = NULL;
- u32 len;
- int rc = 0;
-
- ab = audit_log_start(context, GFP_KERNEL, AUDIT_OBJ_PID);
- if (!ab)
- return rc;
-
- audit_log_format(ab, "opid=%d oauid=%d ouid=%d oses=%d", pid, auid,
- uid, sessionid);
- if (security_secid_to_secctx(sid, &ctx, &len)) {
- audit_log_format(ab, " obj=(none)");
- rc = 1;
- } else {
- audit_log_format(ab, " obj=%s", ctx);
- security_release_secctx(ctx, len);
- }
- audit_log_format(ab, " ocomm=");
- audit_log_untrustedstring(ab, comm);
- audit_log_end(ab);
-
- return rc;
-}
-
-/*
- * to_send and len_sent accounting are very loose estimates. We aren't
- * really worried about a hard cap to MAX_EXECVE_AUDIT_LEN so much as being
- * within about 500 bytes (next page boundry)
- *
- * why snprintf? an int is up to 12 digits long. if we just assumed when
- * logging that a[%d]= was going to be 16 characters long we would be wasting
- * space in every audit message. In one 7500 byte message we can log up to
- * about 1000 min size arguments. That comes down to about 50% waste of space
- * if we didn't do the snprintf to find out how long arg_num_len was.
- */
-static int audit_log_single_execve_arg(struct audit_context *context,
- struct audit_buffer **ab,
- int arg_num,
- size_t *len_sent,
- const char __user *p,
- char *buf)
-{
- char arg_num_len_buf[12];
- const char __user *tmp_p = p;
- /* how many digits are in arg_num? 3 is the length of a=\n */
- size_t arg_num_len = snprintf(arg_num_len_buf, 12, "%d", arg_num) + 3;
- size_t len, len_left, to_send;
- size_t max_execve_audit_len = MAX_EXECVE_AUDIT_LEN;
- unsigned int i, has_cntl = 0, too_long = 0;
- int ret;
-
- /* strnlen_user includes the null we don't want to send */
- len_left = len = strnlen_user(p, MAX_ARG_STRLEN) - 1;
-
- /*
- * We just created this mm, if we can't find the strings
- * we just copied into it something is _very_ wrong. Similar
- * for strings that are too long, we should not have created
- * any.
- */
- if (unlikely((len == -1) || len > MAX_ARG_STRLEN - 1)) {
- WARN_ON(1);
- send_sig(SIGKILL, current, 0);
- return -1;
- }
-
- /* walk the whole argument looking for non-ascii chars */
- do {
- if (len_left > MAX_EXECVE_AUDIT_LEN)
- to_send = MAX_EXECVE_AUDIT_LEN;
- else
- to_send = len_left;
- ret = copy_from_user(buf, tmp_p, to_send);
- /*
- * There is no reason for this copy to be short. We just
- * copied them here, and the mm hasn't been exposed to user-
- * space yet.
- */
- if (ret) {
- WARN_ON(1);
- send_sig(SIGKILL, current, 0);
- return -1;
- }
- buf[to_send] = '\0';
- has_cntl = audit_string_contains_control(buf, to_send);
- if (has_cntl) {
- /*
- * hex messages get logged as 2 bytes, so we can only
- * send half as much in each message
- */
- max_execve_audit_len = MAX_EXECVE_AUDIT_LEN / 2;
- break;
- }
- len_left -= to_send;
- tmp_p += to_send;
- } while (len_left > 0);
-
- len_left = len;
-
- if (len > max_execve_audit_len)
- too_long = 1;
-
- /* rewalk the argument actually logging the message */
- for (i = 0; len_left > 0; i++) {
- int room_left;
-
- if (len_left > max_execve_audit_len)
- to_send = max_execve_audit_len;
- else
- to_send = len_left;
-
- /* do we have space left to send this argument in this ab? */
- room_left = MAX_EXECVE_AUDIT_LEN - arg_num_len - *len_sent;
- if (has_cntl)
- room_left -= (to_send * 2);
- else
- room_left -= to_send;
- if (room_left < 0) {
- *len_sent = 0;
- audit_log_end(*ab);
- *ab = audit_log_start(context, GFP_KERNEL, AUDIT_EXECVE);
- if (!*ab)
- return 0;
- }
-
- /*
- * first record needs to say how long the original string was
- * so we can be sure nothing was lost.
- */
- if ((i == 0) && (too_long))
- audit_log_format(*ab, "a%d_len=%zu ", arg_num,
- has_cntl ? 2*len : len);
-
- /*
- * normally arguments are small enough to fit and we already
- * filled buf above when we checked for control characters
- * so don't bother with another copy_from_user
- */
- if (len >= max_execve_audit_len)
- ret = copy_from_user(buf, p, to_send);
- else
- ret = 0;
- if (ret) {
- WARN_ON(1);
- send_sig(SIGKILL, current, 0);
- return -1;
- }
- buf[to_send] = '\0';
-
- /* actually log it */
- audit_log_format(*ab, "a%d", arg_num);
- if (too_long)
- audit_log_format(*ab, "[%d]", i);
- audit_log_format(*ab, "=");
- if (has_cntl)
- audit_log_n_hex(*ab, buf, to_send);
- else
- audit_log_format(*ab, "\"%s\"", buf);
- audit_log_format(*ab, "\n");
-
- p += to_send;
- len_left -= to_send;
- *len_sent += arg_num_len;
- if (has_cntl)
- *len_sent += to_send * 2;
- else
- *len_sent += to_send;
- }
- /* include the null we didn't log */
- return len + 1;
-}
-
-static void audit_log_execve_info(struct audit_context *context,
- struct audit_buffer **ab,
- struct audit_aux_data_execve *axi)
-{
- int i;
- size_t len, len_sent = 0;
- const char __user *p;
- char *buf;
-
- if (axi->mm != current->mm)
- return; /* execve failed, no additional info */
-
- p = (const char __user *)axi->mm->arg_start;
-
- audit_log_format(*ab, "argc=%d ", axi->argc);
-
- /*
- * we need some kernel buffer to hold the userspace args. Just
- * allocate one big one rather than allocating one of the right size
- * for every single argument inside audit_log_single_execve_arg()
- * should be <8k allocation so should be pretty safe.
- */
- buf = kmalloc(MAX_EXECVE_AUDIT_LEN + 1, GFP_KERNEL);
- if (!buf) {
- audit_panic("out of memory for argv string\n");
- return;
- }
-
- for (i = 0; i < axi->argc; i++) {
- len = audit_log_single_execve_arg(context, ab, i,
- &len_sent, p, buf);
- if (len <= 0)
- break;
- p += len;
- }
- kfree(buf);
-}
-
-static void audit_log_exit(struct audit_context *context, struct task_struct *tsk)
-{
- int i, call_panic = 0;
- struct audit_buffer *ab;
- struct audit_aux_data *aux;
- const char *tty;
-
- /* tsk == current */
- context->pid = tsk->pid;
- if (!context->ppid)
- context->ppid = sys_getppid();
- context->uid = tsk->uid;
- context->gid = tsk->gid;
- context->euid = tsk->euid;
- context->suid = tsk->suid;
- context->fsuid = tsk->fsuid;
- context->egid = tsk->egid;
- context->sgid = tsk->sgid;
- context->fsgid = tsk->fsgid;
- context->personality = tsk->personality;
-
- ab = audit_log_start(context, GFP_KERNEL, AUDIT_SYSCALL);
- if (!ab)
- return; /* audit_panic has been called */
- audit_log_format(ab, "arch=%x syscall=%d",
- context->arch, context->major);
- if (context->personality != PER_LINUX)
- audit_log_format(ab, " per=%lx", context->personality);
- if (context->return_valid)
- audit_log_format(ab, " success=%s exit=%ld",
- (context->return_valid==AUDITSC_SUCCESS)?"yes":"no",
- context->return_code);
-
- mutex_lock(&tty_mutex);
- read_lock(&tasklist_lock);
- if (tsk->signal && tsk->signal->tty && tsk->signal->tty->name)
- tty = tsk->signal->tty->name;
- else
- tty = "(none)";
- read_unlock(&tasklist_lock);
- audit_log_format(ab,
- " a0=%lx a1=%lx a2=%lx a3=%lx items=%d"
- " ppid=%d pid=%d auid=%u uid=%u gid=%u"
- " euid=%u suid=%u fsuid=%u"
- " egid=%u sgid=%u fsgid=%u tty=%s ses=%u",
- context->argv[0],
- context->argv[1],
- context->argv[2],
- context->argv[3],
- context->name_count,
- context->ppid,
- context->pid,
- tsk->loginuid,
- context->uid,
- context->gid,
- context->euid, context->suid, context->fsuid,
- context->egid, context->sgid, context->fsgid, tty,
- tsk->sessionid);
-
- mutex_unlock(&tty_mutex);
-
- audit_log_task_info(ab, tsk);
- if (context->filterkey) {
- audit_log_format(ab, " key=");
- audit_log_untrustedstring(ab, context->filterkey);
- } else
- audit_log_format(ab, " key=(null)");
- audit_log_end(ab);
-
- for (aux = context->aux; aux; aux = aux->next) {
-
- ab = audit_log_start(context, GFP_KERNEL, aux->type);
- if (!ab)
- continue; /* audit_panic has been called */
-
- switch (aux->type) {
- case AUDIT_MQ_OPEN: {
- struct audit_aux_data_mq_open *axi = (void *)aux;
- audit_log_format(ab,
- "oflag=0x%x mode=%#o mq_flags=0x%lx mq_maxmsg=%ld "
- "mq_msgsize=%ld mq_curmsgs=%ld",
- axi->oflag, axi->mode, axi->attr.mq_flags,
- axi->attr.mq_maxmsg, axi->attr.mq_msgsize,
- axi->attr.mq_curmsgs);
- break; }
-
- case AUDIT_MQ_SENDRECV: {
- struct audit_aux_data_mq_sendrecv *axi = (void *)aux;
- audit_log_format(ab,
- "mqdes=%d msg_len=%zd msg_prio=%u "
- "abs_timeout_sec=%ld abs_timeout_nsec=%ld",
- axi->mqdes, axi->msg_len, axi->msg_prio,
- axi->abs_timeout.tv_sec, axi->abs_timeout.tv_nsec);
- break; }
-
- case AUDIT_MQ_NOTIFY: {
- struct audit_aux_data_mq_notify *axi = (void *)aux;
- audit_log_format(ab,
- "mqdes=%d sigev_signo=%d",
- axi->mqdes,
- axi->notification.sigev_signo);
- break; }
-
- case AUDIT_MQ_GETSETATTR: {
- struct audit_aux_data_mq_getsetattr *axi = (void *)aux;
- audit_log_format(ab,
- "mqdes=%d mq_flags=0x%lx mq_maxmsg=%ld mq_msgsize=%ld "
- "mq_curmsgs=%ld ",
- axi->mqdes,
- axi->mqstat.mq_flags, axi->mqstat.mq_maxmsg,
- axi->mqstat.mq_msgsize, axi->mqstat.mq_curmsgs);
- break; }
-
- case AUDIT_IPC: {
- struct audit_aux_data_ipcctl *axi = (void *)aux;
- audit_log_format(ab,
- "ouid=%u ogid=%u mode=%#o",
- axi->uid, axi->gid, axi->mode);
- if (axi->osid != 0) {
- char *ctx = NULL;
- u32 len;
- if (security_secid_to_secctx(
- axi->osid, &ctx, &len)) {
- audit_log_format(ab, " osid=%u",
- axi->osid);
- call_panic = 1;
- } else {
- audit_log_format(ab, " obj=%s", ctx);
- security_release_secctx(ctx, len);
- }
- }
- break; }
-
- case AUDIT_IPC_SET_PERM: {
- struct audit_aux_data_ipcctl *axi = (void *)aux;
- audit_log_format(ab,
- "qbytes=%lx ouid=%u ogid=%u mode=%#o",
- axi->qbytes, axi->uid, axi->gid, axi->mode);
- break; }
-
- case AUDIT_EXECVE: {
- struct audit_aux_data_execve *axi = (void *)aux;
- audit_log_execve_info(context, &ab, axi);
- break; }
-
- case AUDIT_SOCKETCALL: {
- struct audit_aux_data_socketcall *axs = (void *)aux;
- audit_log_format(ab, "nargs=%d", axs->nargs);
- for (i=0; inargs; i++)
- audit_log_format(ab, " a%d=%lx", i, axs->args[i]);
- break; }
-
- case AUDIT_SOCKADDR: {
- struct audit_aux_data_sockaddr *axs = (void *)aux;
-
- audit_log_format(ab, "saddr=");
- audit_log_n_hex(ab, axs->a, axs->len);
- break; }
-
- case AUDIT_FD_PAIR: {
- struct audit_aux_data_fd_pair *axs = (void *)aux;
- audit_log_format(ab, "fd0=%d fd1=%d", axs->fd[0], axs->fd[1]);
- break; }
-
- }
- audit_log_end(ab);
- }
-
- for (aux = context->aux_pids; aux; aux = aux->next) {
- struct audit_aux_data_pids *axs = (void *)aux;
-
- for (i = 0; i < axs->pid_count; i++)
- if (audit_log_pid_context(context, axs->target_pid[i],
- axs->target_auid[i],
- axs->target_uid[i],
- axs->target_sessionid[i],
- axs->target_sid[i],
- axs->target_comm[i]))
- call_panic = 1;
- }
-
- if (context->target_pid &&
- audit_log_pid_context(context, context->target_pid,
- context->target_auid, context->target_uid,
- context->target_sessionid,
- context->target_sid, context->target_comm))
- call_panic = 1;
-
- if (context->pwd.dentry && context->pwd.mnt) {
- ab = audit_log_start(context, GFP_KERNEL, AUDIT_CWD);
- if (ab) {
- audit_log_d_path(ab, "cwd=", &context->pwd);
- audit_log_end(ab);
- }
- }
- for (i = 0; i < context->name_count; i++) {
- struct audit_names *n = &context->names[i];
-
- ab = audit_log_start(context, GFP_KERNEL, AUDIT_PATH);
- if (!ab)
- continue; /* audit_panic has been called */
-
- audit_log_format(ab, "item=%d", i);
-
- if (n->name) {
- switch(n->name_len) {
- case AUDIT_NAME_FULL:
- /* log the full path */
- audit_log_format(ab, " name=");
- audit_log_untrustedstring(ab, n->name);
- break;
- case 0:
- /* name was specified as a relative path and the
- * directory component is the cwd */
- audit_log_d_path(ab, " name=", &context->pwd);
- break;
- default:
- /* log the name's directory component */
- audit_log_format(ab, " name=");
- audit_log_n_untrustedstring(ab, n->name,
- n->name_len);
- }
- } else
- audit_log_format(ab, " name=(null)");
-
- if (n->ino != (unsigned long)-1) {
- audit_log_format(ab, " inode=%lu"
- " dev=%02x:%02x mode=%#o"
- " ouid=%u ogid=%u rdev=%02x:%02x",
- n->ino,
- MAJOR(n->dev),
- MINOR(n->dev),
- n->mode,
- n->uid,
- n->gid,
- MAJOR(n->rdev),
- MINOR(n->rdev));
- }
- if (n->osid != 0) {
- char *ctx = NULL;
- u32 len;
- if (security_secid_to_secctx(
- n->osid, &ctx, &len)) {
- audit_log_format(ab, " osid=%u", n->osid);
- call_panic = 2;
- } else {
- audit_log_format(ab, " obj=%s", ctx);
- security_release_secctx(ctx, len);
- }
- }
-
- audit_log_end(ab);
- }
-
- /* Send end of event record to help user space know we are finished */
- ab = audit_log_start(context, GFP_KERNEL, AUDIT_EOE);
- if (ab)
- audit_log_end(ab);
- if (call_panic)
- audit_panic("error converting sid to string");
-}
-
-/**
- * audit_free - free a per-task audit context
- * @tsk: task whose audit context block to free
- *
- * Called from copy_process and do_exit
- */
-void audit_free(struct task_struct *tsk)
-{
- struct audit_context *context;
-
- context = audit_get_context(tsk, 0, 0);
- if (likely(!context))
- return;
-
- /* Check for system calls that do not go through the exit
- * function (e.g., exit_group), then free context block.
- * We use GFP_ATOMIC here because we might be doing this
- * in the context of the idle thread */
- /* that can happen only if we are called from do_exit() */
- if (context->in_syscall && context->auditable)
- audit_log_exit(context, tsk);
-
- audit_free_context(context);
-}
-
-/**
- * audit_syscall_entry - fill in an audit record at syscall entry
- * @tsk: task being audited
- * @arch: architecture type
- * @major: major syscall type (function)
- * @a1: additional syscall register 1
- * @a2: additional syscall register 2
- * @a3: additional syscall register 3
- * @a4: additional syscall register 4
- *
- * Fill in audit context at syscall entry. This only happens if the
- * audit context was created when the task was created and the state or
- * filters demand the audit context be built. If the state from the
- * per-task filter or from the per-syscall filter is AUDIT_RECORD_CONTEXT,
- * then the record will be written at syscall exit time (otherwise, it
- * will only be written if another part of the kernel requests that it
- * be written).
- */
-void audit_syscall_entry(int arch, int major,
- unsigned long a1, unsigned long a2,
- unsigned long a3, unsigned long a4)
-{
- struct task_struct *tsk = current;
- struct audit_context *context = tsk->audit_context;
- enum audit_state state;
-
- if (unlikely(!context))
- return;
-
- /*
- * This happens only on certain architectures that make system
- * calls in kernel_thread via the entry.S interface, instead of
- * with direct calls. (If you are porting to a new
- * architecture, hitting this condition can indicate that you
- * got the _exit/_leave calls backward in entry.S.)
- *
- * i386 no
- * x86_64 no
- * ppc64 yes (see arch/powerpc/platforms/iseries/misc.S)
- *
- * This also happens with vm86 emulation in a non-nested manner
- * (entries without exits), so this case must be caught.
- */
- if (context->in_syscall) {
- struct audit_context *newctx;
-
-#if AUDIT_DEBUG
- printk(KERN_ERR
- "audit(:%d) pid=%d in syscall=%d;"
- " entering syscall=%d\n",
- context->serial, tsk->pid, context->major, major);
-#endif
- newctx = audit_alloc_context(context->state);
- if (newctx) {
- newctx->previous = context;
- context = newctx;
- tsk->audit_context = newctx;
- } else {
- /* If we can't alloc a new context, the best we
- * can do is to leak memory (any pending putname
- * will be lost). The only other alternative is
- * to abandon auditing. */
- audit_zero_context(context, context->state);
- }
- }
- BUG_ON(context->in_syscall || context->name_count);
-
- if (!audit_enabled)
- return;
-
- context->arch = arch;
- context->major = major;
- context->argv[0] = a1;
- context->argv[1] = a2;
- context->argv[2] = a3;
- context->argv[3] = a4;
-
- state = context->state;
- context->dummy = !audit_n_rules;
- if (!context->dummy && (state == AUDIT_SETUP_CONTEXT || state == AUDIT_BUILD_CONTEXT))
- state = audit_filter_syscall(tsk, context, &audit_filter_list[AUDIT_FILTER_ENTRY]);
- if (likely(state == AUDIT_DISABLED))
- return;
-
- context->serial = 0;
- context->ctime = CURRENT_TIME;
- context->in_syscall = 1;
- context->auditable = !!(state == AUDIT_RECORD_CONTEXT);
- context->ppid = 0;
-}
-
-/**
- * audit_syscall_exit - deallocate audit context after a system call
- * @tsk: task being audited
- * @valid: success/failure flag
- * @return_code: syscall return value
- *
- * Tear down after system call. If the audit context has been marked as
- * auditable (either because of the AUDIT_RECORD_CONTEXT state from
- * filtering, or because some other part of the kernel write an audit
- * message), then write out the syscall information. In call cases,
- * free the names stored from getname().
- */
-void audit_syscall_exit(int valid, long return_code)
-{
- struct task_struct *tsk = current;
- struct audit_context *context;
-
- context = audit_get_context(tsk, valid, return_code);
-
- if (likely(!context))
- return;
-
- if (context->in_syscall && context->auditable)
- audit_log_exit(context, tsk);
-
- context->in_syscall = 0;
- context->auditable = 0;
-
- if (context->previous) {
- struct audit_context *new_context = context->previous;
- context->previous = NULL;
- audit_free_context(context);
- tsk->audit_context = new_context;
- } else {
- audit_free_names(context);
- unroll_tree_refs(context, NULL, 0);
- audit_free_aux(context);
- context->aux = NULL;
- context->aux_pids = NULL;
- context->target_pid = 0;
- context->target_sid = 0;
- kfree(context->filterkey);
- context->filterkey = NULL;
- tsk->audit_context = context;
- }
-}
-
-static inline void handle_one(const struct inode *inode)
-{
-#ifdef CONFIG_AUDIT_TREE
- struct audit_context *context;
- struct audit_tree_refs *p;
- struct audit_chunk *chunk;
- int count;
- if (likely(list_empty(&inode->inotify_watches)))
- return;
- context = current->audit_context;
- p = context->trees;
- count = context->tree_count;
- rcu_read_lock();
- chunk = audit_tree_lookup(inode);
- rcu_read_unlock();
- if (!chunk)
- return;
- if (likely(put_tree_ref(context, chunk)))
- return;
- if (unlikely(!grow_tree_refs(context))) {
- printk(KERN_WARNING "out of memory, audit has lost a tree reference\n");
- audit_set_auditable(context);
- audit_put_chunk(chunk);
- unroll_tree_refs(context, p, count);
- return;
- }
- put_tree_ref(context, chunk);
-#endif
-}
-
-static void handle_path(const struct dentry *dentry)
-{
-#ifdef CONFIG_AUDIT_TREE
- struct audit_context *context;
- struct audit_tree_refs *p;
- const struct dentry *d, *parent;
- struct audit_chunk *drop;
- unsigned long seq;
- int count;
-
- context = current->audit_context;
- p = context->trees;
- count = context->tree_count;
-retry:
- drop = NULL;
- d = dentry;
- rcu_read_lock();
- seq = read_seqbegin(&rename_lock);
- for(;;) {
- struct inode *inode = d->d_inode;
- if (inode && unlikely(!list_empty(&inode->inotify_watches))) {
- struct audit_chunk *chunk;
- chunk = audit_tree_lookup(inode);
- if (chunk) {
- if (unlikely(!put_tree_ref(context, chunk))) {
- drop = chunk;
- break;
- }
- }
- }
- parent = d->d_parent;
- if (parent == d)
- break;
- d = parent;
- }
- if (unlikely(read_seqretry(&rename_lock, seq) || drop)) { /* in this order */
- rcu_read_unlock();
- if (!drop) {
- /* just a race with rename */
- unroll_tree_refs(context, p, count);
- goto retry;
- }
- audit_put_chunk(drop);
- if (grow_tree_refs(context)) {
- /* OK, got more space */
- unroll_tree_refs(context, p, count);
- goto retry;
- }
- /* too bad */
- printk(KERN_WARNING
- "out of memory, audit has lost a tree reference\n");
- unroll_tree_refs(context, p, count);
- audit_set_auditable(context);
- return;
- }
- rcu_read_unlock();
-#endif
-}
-
-/**
- * audit_getname - add a name to the list
- * @name: name to add
- *
- * Add a name to the list of audit names for this context.
- * Called from fs/namei.c:getname().
- */
-void __audit_getname(const char *name)
-{
- struct audit_context *context = current->audit_context;
-
- if (IS_ERR(name) || !name)
- return;
-
- if (!context->in_syscall) {
-#if AUDIT_DEBUG == 2
- printk(KERN_ERR "%s:%d(:%d): ignoring getname(%p)\n",
- __FILE__, __LINE__, context->serial, name);
- dump_stack();
-#endif
- return;
- }
- BUG_ON(context->name_count >= AUDIT_NAMES);
- context->names[context->name_count].name = name;
- context->names[context->name_count].name_len = AUDIT_NAME_FULL;
- context->names[context->name_count].name_put = 1;
- context->names[context->name_count].ino = (unsigned long)-1;
- context->names[context->name_count].osid = 0;
- ++context->name_count;
- if (!context->pwd.dentry) {
- read_lock(¤t->fs->lock);
- context->pwd = current->fs->pwd;
- path_get(¤t->fs->pwd);
- read_unlock(¤t->fs->lock);
- }
-
-}
-
-/* audit_putname - intercept a putname request
- * @name: name to intercept and delay for putname
- *
- * If we have stored the name from getname in the audit context,
- * then we delay the putname until syscall exit.
- * Called from include/linux/fs.h:putname().
- */
-void audit_putname(const char *name)
-{
- struct audit_context *context = current->audit_context;
-
- BUG_ON(!context);
- if (!context->in_syscall) {
-#if AUDIT_DEBUG == 2
- printk(KERN_ERR "%s:%d(:%d): __putname(%p)\n",
- __FILE__, __LINE__, context->serial, name);
- if (context->name_count) {
- int i;
- for (i = 0; i < context->name_count; i++)
- printk(KERN_ERR "name[%d] = %p = %s\n", i,
- context->names[i].name,
- context->names[i].name ?: "(null)");
- }
-#endif
- __putname(name);
- }
-#if AUDIT_DEBUG
- else {
- ++context->put_count;
- if (context->put_count > context->name_count) {
- printk(KERN_ERR "%s:%d(:%d): major=%d"
- " in_syscall=%d putname(%p) name_count=%d"
- " put_count=%d\n",
- __FILE__, __LINE__,
- context->serial, context->major,
- context->in_syscall, name, context->name_count,
- context->put_count);
- dump_stack();
- }
- }
-#endif
-}
-
-static int audit_inc_name_count(struct audit_context *context,
- const struct inode *inode)
-{
- if (context->name_count >= AUDIT_NAMES) {
- if (inode)
- printk(KERN_DEBUG "name_count maxed, losing inode data: "
- "dev=%02x:%02x, inode=%lu\n",
- MAJOR(inode->i_sb->s_dev),
- MINOR(inode->i_sb->s_dev),
- inode->i_ino);
-
- else
- printk(KERN_DEBUG "name_count maxed, losing inode data\n");
- return 1;
- }
- context->name_count++;
-#if AUDIT_DEBUG
- context->ino_count++;
-#endif
- return 0;
-}
-
-/* Copy inode data into an audit_names. */
-static void audit_copy_inode(struct audit_names *name, const struct inode *inode)
-{
- name->ino = inode->i_ino;
- name->dev = inode->i_sb->s_dev;
- name->mode = inode->i_mode;
- name->uid = inode->i_uid;
- name->gid = inode->i_gid;
- name->rdev = inode->i_rdev;
- security_inode_getsecid(inode, &name->osid);
-}
-
-/**
- * audit_inode - store the inode and device from a lookup
- * @name: name being audited
- * @dentry: dentry being audited
- *
- * Called from fs/namei.c:path_lookup().
- */
-void __audit_inode(const char *name, const struct dentry *dentry)
-{
- int idx;
- struct audit_context *context = current->audit_context;
- const struct inode *inode = dentry->d_inode;
-
- if (!context->in_syscall)
- return;
- if (context->name_count
- && context->names[context->name_count-1].name
- && context->names[context->name_count-1].name == name)
- idx = context->name_count - 1;
- else if (context->name_count > 1
- && context->names[context->name_count-2].name
- && context->names[context->name_count-2].name == name)
- idx = context->name_count - 2;
- else {
- /* FIXME: how much do we care about inodes that have no
- * associated name? */
- if (audit_inc_name_count(context, inode))
- return;
- idx = context->name_count - 1;
- context->names[idx].name = NULL;
- }
- handle_path(dentry);
- audit_copy_inode(&context->names[idx], inode);
-}
-
-/**
- * audit_inode_child - collect inode info for created/removed objects
- * @dname: inode's dentry name
- * @dentry: dentry being audited
- * @parent: inode of dentry parent
- *
- * For syscalls that create or remove filesystem objects, audit_inode
- * can only collect information for the filesystem object's parent.
- * This call updates the audit context with the child's information.
- * Syscalls that create a new filesystem object must be hooked after
- * the object is created. Syscalls that remove a filesystem object
- * must be hooked prior, in order to capture the target inode during
- * unsuccessful attempts.
- */
-void __audit_inode_child(const char *dname, const struct dentry *dentry,
- const struct inode *parent)
-{
- int idx;
- struct audit_context *context = current->audit_context;
- const char *found_parent = NULL, *found_child = NULL;
- const struct inode *inode = dentry->d_inode;
- int dirlen = 0;
-
- if (!context->in_syscall)
- return;
-
- if (inode)
- handle_one(inode);
- /* determine matching parent */
- if (!dname)
- goto add_names;
-
- /* parent is more likely, look for it first */
- for (idx = 0; idx < context->name_count; idx++) {
- struct audit_names *n = &context->names[idx];
-
- if (!n->name)
- continue;
-
- if (n->ino == parent->i_ino &&
- !audit_compare_dname_path(dname, n->name, &dirlen)) {
- n->name_len = dirlen; /* update parent data in place */
- found_parent = n->name;
- goto add_names;
- }
- }
-
- /* no matching parent, look for matching child */
- for (idx = 0; idx < context->name_count; idx++) {
- struct audit_names *n = &context->names[idx];
-
- if (!n->name)
- continue;
-
- /* strcmp() is the more likely scenario */
- if (!strcmp(dname, n->name) ||
- !audit_compare_dname_path(dname, n->name, &dirlen)) {
- if (inode)
- audit_copy_inode(n, inode);
- else
- n->ino = (unsigned long)-1;
- found_child = n->name;
- goto add_names;
- }
- }
-
-add_names:
- if (!found_parent) {
- if (audit_inc_name_count(context, parent))
- return;
- idx = context->name_count - 1;
- context->names[idx].name = NULL;
- audit_copy_inode(&context->names[idx], parent);
- }
-
- if (!found_child) {
- if (audit_inc_name_count(context, inode))
- return;
- idx = context->name_count - 1;
-
- /* Re-use the name belonging to the slot for a matching parent
- * directory. All names for this context are relinquished in
- * audit_free_names() */
- if (found_parent) {
- context->names[idx].name = found_parent;
- context->names[idx].name_len = AUDIT_NAME_FULL;
- /* don't call __putname() */
- context->names[idx].name_put = 0;
- } else {
- context->names[idx].name = NULL;
- }
-
- if (inode)
- audit_copy_inode(&context->names[idx], inode);
- else
- context->names[idx].ino = (unsigned long)-1;
- }
-}
-EXPORT_SYMBOL_GPL(__audit_inode_child);
-
-/**
- * auditsc_get_stamp - get local copies of audit_context values
- * @ctx: audit_context for the task
- * @t: timespec to store time recorded in the audit_context
- * @serial: serial value that is recorded in the audit_context
- *
- * Also sets the context as auditable.
- */
-void auditsc_get_stamp(struct audit_context *ctx,
- struct timespec *t, unsigned int *serial)
-{
- if (!ctx->serial)
- ctx->serial = audit_serial();
- t->tv_sec = ctx->ctime.tv_sec;
- t->tv_nsec = ctx->ctime.tv_nsec;
- *serial = ctx->serial;
- ctx->auditable = 1;
-}
-
-/* global counter which is incremented every time something logs in */
-static atomic_t session_id = ATOMIC_INIT(0);
-
-/**
- * audit_set_loginuid - set a task's audit_context loginuid
- * @task: task whose audit context is being modified
- * @loginuid: loginuid value
- *
- * Returns 0.
- *
- * Called (set) from fs/proc/base.c::proc_loginuid_write().
- */
-int audit_set_loginuid(struct task_struct *task, uid_t loginuid)
-{
- unsigned int sessionid = atomic_inc_return(&session_id);
- struct audit_context *context = task->audit_context;
-
- if (context && context->in_syscall) {
- struct audit_buffer *ab;
-
- ab = audit_log_start(NULL, GFP_KERNEL, AUDIT_LOGIN);
- if (ab) {
- audit_log_format(ab, "login pid=%d uid=%u "
- "old auid=%u new auid=%u"
- " old ses=%u new ses=%u",
- task->pid, task->uid,
- task->loginuid, loginuid,
- task->sessionid, sessionid);
- audit_log_end(ab);
- }
- }
- task->sessionid = sessionid;
- task->loginuid = loginuid;
- return 0;
-}
-
-/**
- * __audit_mq_open - record audit data for a POSIX MQ open
- * @oflag: open flag
- * @mode: mode bits
- * @u_attr: queue attributes
- *
- * Returns 0 for success or NULL context or < 0 on error.
- */
-int __audit_mq_open(int oflag, mode_t mode, struct mq_attr __user *u_attr)
-{
- struct audit_aux_data_mq_open *ax;
- struct audit_context *context = current->audit_context;
-
- if (!audit_enabled)
- return 0;
-
- if (likely(!context))
- return 0;
-
- ax = kmalloc(sizeof(*ax), GFP_ATOMIC);
- if (!ax)
- return -ENOMEM;
-
- if (u_attr != NULL) {
- if (copy_from_user(&ax->attr, u_attr, sizeof(ax->attr))) {
- kfree(ax);
- return -EFAULT;
- }
- } else
- memset(&ax->attr, 0, sizeof(ax->attr));
-
- ax->oflag = oflag;
- ax->mode = mode;
-
- ax->d.type = AUDIT_MQ_OPEN;
- ax->d.next = context->aux;
- context->aux = (void *)ax;
- return 0;
-}
-
-/**
- * __audit_mq_timedsend - record audit data for a POSIX MQ timed send
- * @mqdes: MQ descriptor
- * @msg_len: Message length
- * @msg_prio: Message priority
- * @u_abs_timeout: Message timeout in absolute time
- *
- * Returns 0 for success or NULL context or < 0 on error.
- */
-int __audit_mq_timedsend(mqd_t mqdes, size_t msg_len, unsigned int msg_prio,
- const struct timespec __user *u_abs_timeout)
-{
- struct audit_aux_data_mq_sendrecv *ax;
- struct audit_context *context = current->audit_context;
-
- if (!audit_enabled)
- return 0;
-
- if (likely(!context))
- return 0;
-
- ax = kmalloc(sizeof(*ax), GFP_ATOMIC);
- if (!ax)
- return -ENOMEM;
-
- if (u_abs_timeout != NULL) {
- if (copy_from_user(&ax->abs_timeout, u_abs_timeout, sizeof(ax->abs_timeout))) {
- kfree(ax);
- return -EFAULT;
- }
- } else
- memset(&ax->abs_timeout, 0, sizeof(ax->abs_timeout));
-
- ax->mqdes = mqdes;
- ax->msg_len = msg_len;
- ax->msg_prio = msg_prio;
-
- ax->d.type = AUDIT_MQ_SENDRECV;
- ax->d.next = context->aux;
- context->aux = (void *)ax;
- return 0;
-}
-
-/**
- * __audit_mq_timedreceive - record audit data for a POSIX MQ timed receive
- * @mqdes: MQ descriptor
- * @msg_len: Message length
- * @u_msg_prio: Message priority
- * @u_abs_timeout: Message timeout in absolute time
- *
- * Returns 0 for success or NULL context or < 0 on error.
- */
-int __audit_mq_timedreceive(mqd_t mqdes, size_t msg_len,
- unsigned int __user *u_msg_prio,
- const struct timespec __user *u_abs_timeout)
-{
- struct audit_aux_data_mq_sendrecv *ax;
- struct audit_context *context = current->audit_context;
-
- if (!audit_enabled)
- return 0;
-
- if (likely(!context))
- return 0;
-
- ax = kmalloc(sizeof(*ax), GFP_ATOMIC);
- if (!ax)
- return -ENOMEM;
-
- if (u_msg_prio != NULL) {
- if (get_user(ax->msg_prio, u_msg_prio)) {
- kfree(ax);
- return -EFAULT;
- }
- } else
- ax->msg_prio = 0;
-
- if (u_abs_timeout != NULL) {
- if (copy_from_user(&ax->abs_timeout, u_abs_timeout, sizeof(ax->abs_timeout))) {
- kfree(ax);
- return -EFAULT;
- }
- } else
- memset(&ax->abs_timeout, 0, sizeof(ax->abs_timeout));
-
- ax->mqdes = mqdes;
- ax->msg_len = msg_len;
-
- ax->d.type = AUDIT_MQ_SENDRECV;
- ax->d.next = context->aux;
- context->aux = (void *)ax;
- return 0;
-}
-
-/**
- * __audit_mq_notify - record audit data for a POSIX MQ notify
- * @mqdes: MQ descriptor
- * @u_notification: Notification event
- *
- * Returns 0 for success or NULL context or < 0 on error.
- */
-
-int __audit_mq_notify(mqd_t mqdes, const struct sigevent __user *u_notification)
-{
- struct audit_aux_data_mq_notify *ax;
- struct audit_context *context = current->audit_context;
-
- if (!audit_enabled)
- return 0;
-
- if (likely(!context))
- return 0;
-
- ax = kmalloc(sizeof(*ax), GFP_ATOMIC);
- if (!ax)
- return -ENOMEM;
-
- if (u_notification != NULL) {
- if (copy_from_user(&ax->notification, u_notification, sizeof(ax->notification))) {
- kfree(ax);
- return -EFAULT;
- }
- } else
- memset(&ax->notification, 0, sizeof(ax->notification));
-
- ax->mqdes = mqdes;
-
- ax->d.type = AUDIT_MQ_NOTIFY;
- ax->d.next = context->aux;
- context->aux = (void *)ax;
- return 0;
-}
-
-/**
- * __audit_mq_getsetattr - record audit data for a POSIX MQ get/set attribute
- * @mqdes: MQ descriptor
- * @mqstat: MQ flags
- *
- * Returns 0 for success or NULL context or < 0 on error.
- */
-int __audit_mq_getsetattr(mqd_t mqdes, struct mq_attr *mqstat)
-{
- struct audit_aux_data_mq_getsetattr *ax;
- struct audit_context *context = current->audit_context;
-
- if (!audit_enabled)
- return 0;
-
- if (likely(!context))
- return 0;
-
- ax = kmalloc(sizeof(*ax), GFP_ATOMIC);
- if (!ax)
- return -ENOMEM;
-
- ax->mqdes = mqdes;
- ax->mqstat = *mqstat;
-
- ax->d.type = AUDIT_MQ_GETSETATTR;
- ax->d.next = context->aux;
- context->aux = (void *)ax;
- return 0;
-}
-
-/**
- * audit_ipc_obj - record audit data for ipc object
- * @ipcp: ipc permissions
- *
- * Returns 0 for success or NULL context or < 0 on error.
- */
-int __audit_ipc_obj(struct kern_ipc_perm *ipcp)
-{
- struct audit_aux_data_ipcctl *ax;
- struct audit_context *context = current->audit_context;
-
- ax = kmalloc(sizeof(*ax), GFP_ATOMIC);
- if (!ax)
- return -ENOMEM;
-
- ax->uid = ipcp->uid;
- ax->gid = ipcp->gid;
- ax->mode = ipcp->mode;
- security_ipc_getsecid(ipcp, &ax->osid);
- ax->d.type = AUDIT_IPC;
- ax->d.next = context->aux;
- context->aux = (void *)ax;
- return 0;
-}
-
-/**
- * audit_ipc_set_perm - record audit data for new ipc permissions
- * @qbytes: msgq bytes
- * @uid: msgq user id
- * @gid: msgq group id
- * @mode: msgq mode (permissions)
- *
- * Returns 0 for success or NULL context or < 0 on error.
- */
-int __audit_ipc_set_perm(unsigned long qbytes, uid_t uid, gid_t gid, mode_t mode)
-{
- struct audit_aux_data_ipcctl *ax;
- struct audit_context *context = current->audit_context;
-
- ax = kmalloc(sizeof(*ax), GFP_ATOMIC);
- if (!ax)
- return -ENOMEM;
-
- ax->qbytes = qbytes;
- ax->uid = uid;
- ax->gid = gid;
- ax->mode = mode;
-
- ax->d.type = AUDIT_IPC_SET_PERM;
- ax->d.next = context->aux;
- context->aux = (void *)ax;
- return 0;
-}
-
-int audit_bprm(struct linux_binprm *bprm)
-{
- struct audit_aux_data_execve *ax;
- struct audit_context *context = current->audit_context;
-
- if (likely(!audit_enabled || !context || context->dummy))
- return 0;
-
- ax = kmalloc(sizeof(*ax), GFP_KERNEL);
- if (!ax)
- return -ENOMEM;
-
- ax->argc = bprm->argc;
- ax->envc = bprm->envc;
- ax->mm = bprm->mm;
- ax->d.type = AUDIT_EXECVE;
- ax->d.next = context->aux;
- context->aux = (void *)ax;
- return 0;
-}
-
-
-/**
- * audit_socketcall - record audit data for sys_socketcall
- * @nargs: number of args
- * @args: args array
- *
- * Returns 0 for success or NULL context or < 0 on error.
- */
-int audit_socketcall(int nargs, unsigned long *args)
-{
- struct audit_aux_data_socketcall *ax;
- struct audit_context *context = current->audit_context;
-
- if (likely(!context || context->dummy))
- return 0;
-
- ax = kmalloc(sizeof(*ax) + nargs * sizeof(unsigned long), GFP_KERNEL);
- if (!ax)
- return -ENOMEM;
-
- ax->nargs = nargs;
- memcpy(ax->args, args, nargs * sizeof(unsigned long));
-
- ax->d.type = AUDIT_SOCKETCALL;
- ax->d.next = context->aux;
- context->aux = (void *)ax;
- return 0;
-}
-
-/**
- * __audit_fd_pair - record audit data for pipe and socketpair
- * @fd1: the first file descriptor
- * @fd2: the second file descriptor
- *
- * Returns 0 for success or NULL context or < 0 on error.
- */
-int __audit_fd_pair(int fd1, int fd2)
-{
- struct audit_context *context = current->audit_context;
- struct audit_aux_data_fd_pair *ax;
-
- if (likely(!context)) {
- return 0;
- }
-
- ax = kmalloc(sizeof(*ax), GFP_KERNEL);
- if (!ax) {
- return -ENOMEM;
- }
-
- ax->fd[0] = fd1;
- ax->fd[1] = fd2;
-
- ax->d.type = AUDIT_FD_PAIR;
- ax->d.next = context->aux;
- context->aux = (void *)ax;
- return 0;
-}
-
-/**
- * audit_sockaddr - record audit data for sys_bind, sys_connect, sys_sendto
- * @len: data length in user space
- * @a: data address in kernel space
- *
- * Returns 0 for success or NULL context or < 0 on error.
- */
-int audit_sockaddr(int len, void *a)
-{
- struct audit_aux_data_sockaddr *ax;
- struct audit_context *context = current->audit_context;
-
- if (likely(!context || context->dummy))
- return 0;
-
- ax = kmalloc(sizeof(*ax) + len, GFP_KERNEL);
- if (!ax)
- return -ENOMEM;
-
- ax->len = len;
- memcpy(ax->a, a, len);
-
- ax->d.type = AUDIT_SOCKADDR;
- ax->d.next = context->aux;
- context->aux = (void *)ax;
- return 0;
-}
-
-void __audit_ptrace(struct task_struct *t)
-{
- struct audit_context *context = current->audit_context;
-
- context->target_pid = t->pid;
- context->target_auid = audit_get_loginuid(t);
- context->target_uid = t->uid;
- context->target_sessionid = audit_get_sessionid(t);
- security_task_getsecid(t, &context->target_sid);
- memcpy(context->target_comm, t->comm, TASK_COMM_LEN);
-}
-
-/**
- * audit_signal_info - record signal info for shutting down audit subsystem
- * @sig: signal value
- * @t: task being signaled
- *
- * If the audit subsystem is being terminated, record the task (pid)
- * and uid that is doing that.
- */
-int __audit_signal_info(int sig, struct task_struct *t)
-{
- struct audit_aux_data_pids *axp;
- struct task_struct *tsk = current;
- struct audit_context *ctx = tsk->audit_context;
-
- if (audit_pid && t->tgid == audit_pid) {
- if (sig == SIGTERM || sig == SIGHUP || sig == SIGUSR1 || sig == SIGUSR2) {
- audit_sig_pid = tsk->pid;
- if (tsk->loginuid != -1)
- audit_sig_uid = tsk->loginuid;
- else
- audit_sig_uid = tsk->uid;
- security_task_getsecid(tsk, &audit_sig_sid);
- }
- if (!audit_signals || audit_dummy_context())
- return 0;
- }
-
- /* optimize the common case by putting first signal recipient directly
- * in audit_context */
- if (!ctx->target_pid) {
- ctx->target_pid = t->tgid;
- ctx->target_auid = audit_get_loginuid(t);
- ctx->target_uid = t->uid;
- ctx->target_sessionid = audit_get_sessionid(t);
- security_task_getsecid(t, &ctx->target_sid);
- memcpy(ctx->target_comm, t->comm, TASK_COMM_LEN);
- return 0;
- }
-
- axp = (void *)ctx->aux_pids;
- if (!axp || axp->pid_count == AUDIT_AUX_PIDS) {
- axp = kzalloc(sizeof(*axp), GFP_ATOMIC);
- if (!axp)
- return -ENOMEM;
-
- axp->d.type = AUDIT_OBJ_PID;
- axp->d.next = ctx->aux_pids;
- ctx->aux_pids = (void *)axp;
- }
- BUG_ON(axp->pid_count >= AUDIT_AUX_PIDS);
-
- axp->target_pid[axp->pid_count] = t->tgid;
- axp->target_auid[axp->pid_count] = audit_get_loginuid(t);
- axp->target_uid[axp->pid_count] = t->uid;
- axp->target_sessionid[axp->pid_count] = audit_get_sessionid(t);
- security_task_getsecid(t, &axp->target_sid[axp->pid_count]);
- memcpy(axp->target_comm[axp->pid_count], t->comm, TASK_COMM_LEN);
- axp->pid_count++;
-
- return 0;
-}
-
-/**
- * audit_core_dumps - record information about processes that end abnormally
- * @signr: signal value
- *
- * If a process ends with a core dump, something fishy is going on and we
- * should record the event for investigation.
- */
-void audit_core_dumps(long signr)
-{
- struct audit_buffer *ab;
- u32 sid;
- uid_t auid = audit_get_loginuid(current);
- unsigned int sessionid = audit_get_sessionid(current);
-
- if (!audit_enabled)
- return;
-
- if (signr == SIGQUIT) /* don't care for those */
- return;
-
- ab = audit_log_start(NULL, GFP_KERNEL, AUDIT_ANOM_ABEND);
- audit_log_format(ab, "auid=%u uid=%u gid=%u ses=%u",
- auid, current->uid, current->gid, sessionid);
- security_task_getsecid(current, &sid);
- if (sid) {
- char *ctx = NULL;
- u32 len;
-
- if (security_secid_to_secctx(sid, &ctx, &len))
- audit_log_format(ab, " ssid=%u", sid);
- else {
- audit_log_format(ab, " subj=%s", ctx);
- security_release_secctx(ctx, len);
- }
- }
- audit_log_format(ab, " pid=%d comm=", current->pid);
- audit_log_untrustedstring(ab, current->comm);
- audit_log_format(ab, " sig=%ld", signr);
- audit_log_end(ab);
-}
-/*
- * Simple stack backtrace regression test module
- *
- * (C) Copyright 2008 Intel Corporation
- * Author: Arjan van de Ven
- *
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; version 2
- * of the License.
- */
-
-#include
-#include
-#include
-#include
-#include
-#include
-
-static void backtrace_test_normal(void)
-{
- printk("Testing a backtrace from process context.\n");
- printk("The following trace is a kernel self test and not a bug!\n");
-
- dump_stack();
-}
-
-static DECLARE_COMPLETION(backtrace_work);
-
-static void backtrace_test_irq_callback(unsigned long data)
-{
- dump_stack();
- complete(&backtrace_work);
-}
-
-static DECLARE_TASKLET(backtrace_tasklet, &backtrace_test_irq_callback, 0);
-
-static void backtrace_test_irq(void)
-{
- printk("Testing a backtrace from irq context.\n");
- printk("The following trace is a kernel self test and not a bug!\n");
-
- init_completion(&backtrace_work);
- tasklet_schedule(&backtrace_tasklet);
- wait_for_completion(&backtrace_work);
-}
-
-#ifdef CONFIG_STACKTRACE
-static void backtrace_test_saved(void)
-{
- struct stack_trace trace;
- unsigned long entries[8];
-
- printk("Testing a saved backtrace.\n");
- printk("The following trace is a kernel self test and not a bug!\n");
-
- trace.nr_entries = 0;
- trace.max_entries = ARRAY_SIZE(entries);
- trace.entries = entries;
- trace.skip = 0;
-
- save_stack_trace(&trace);
- print_stack_trace(&trace, 0);
-}
-#else
-static void backtrace_test_saved(void)
-{
- printk("Saved backtrace test skipped.\n");
-}
-#endif
-
-static int backtrace_regression_test(void)
-{
- printk("====[ backtrace testing ]===========\n");
-
- backtrace_test_normal();
- backtrace_test_irq();
- backtrace_test_saved();
-
- printk("====[ end of backtrace testing ]====\n");
- return 0;
-}
-
-static void exitf(void)
-{
-}
-
-module_init(backtrace_regression_test);
-module_exit(exitf);
-MODULE_LICENSE("GPL");
-MODULE_AUTHOR("Arjan van de Ven ");
-/*
- * Generate definitions needed by the preprocessor.
- * This code generates raw asm output which is post-processed
- * to extract and format the required data.
- */
-
-#define __GENERATING_BOUNDS_H
-/* Include headers that define the enum constants of interest */
-#include
-#include
-#include
-
-void foo(void)
-{
- /* The enum constants to put into include/linux/bounds.h */
- DEFINE(NR_PAGEFLAGS, __NR_PAGEFLAGS);
- DEFINE(MAX_NR_ZONES, __MAX_NR_ZONES);
- /* End of constants */
-}
-/*
- * linux/kernel/capability.c
- *
- * Copyright (C) 1997 Andrew Main
- *
- * Integrated into 2.1.97+, Andrew G. Morgan
- * 30 May 2002: Cleanup, Robert M. Love
- */
-
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-
-/*
- * This lock protects task->cap_* for all tasks including current.
- * Locking rule: acquire this prior to tasklist_lock.
- */
-static DEFINE_SPINLOCK(task_capability_lock);
-
-/*
- * Leveraged for setting/resetting capabilities
- */
-
-const kernel_cap_t __cap_empty_set = CAP_EMPTY_SET;
-const kernel_cap_t __cap_full_set = CAP_FULL_SET;
-const kernel_cap_t __cap_init_eff_set = CAP_INIT_EFF_SET;
-
-EXPORT_SYMBOL(__cap_empty_set);
-EXPORT_SYMBOL(__cap_full_set);
-EXPORT_SYMBOL(__cap_init_eff_set);
-
-/*
- * More recent versions of libcap are available from:
- *
- * http://www.kernel.org/pub/linux/libs/security/linux-privs/
- */
-
-static void warn_legacy_capability_use(void)
-{
- static int warned;
- if (!warned) {
- char name[sizeof(current->comm)];
-
- printk(KERN_INFO "warning: `%s' uses 32-bit capabilities"
- " (legacy support in use)\n",
- get_task_comm(name, current));
- warned = 1;
- }
-}
-
-/*
- * Version 2 capabilities worked fine, but the linux/capability.h file
- * that accompanied their introduction encouraged their use without
- * the necessary user-space source code changes. As such, we have
- * created a version 3 with equivalent functionality to version 2, but
- * with a header change to protect legacy source code from using
- * version 2 when it wanted to use version 1. If your system has code
- * that trips the following warning, it is using version 2 specific
- * capabilities and may be doing so insecurely.
- *
- * The remedy is to either upgrade your version of libcap (to 2.10+,
- * if the application is linked against it), or recompile your
- * application with modern kernel headers and this warning will go
- * away.
- */
-
-static void warn_deprecated_v2(void)
-{
- static int warned;
-
- if (!warned) {
- char name[sizeof(current->comm)];
-
- printk(KERN_INFO "warning: `%s' uses deprecated v2"
- " capabilities in a way that may be insecure.\n",
- get_task_comm(name, current));
- warned = 1;
- }
-}
-
-/*
- * Version check. Return the number of u32s in each capability flag
- * array, or a negative value on error.
- */
-static int cap_validate_magic(cap_user_header_t header, unsigned *tocopy)
-{
- __u32 version;
-
- if (get_user(version, &header->version))
- return -EFAULT;
-
- switch (version) {
- case _LINUX_CAPABILITY_VERSION_1:
- warn_legacy_capability_use();
- *tocopy = _LINUX_CAPABILITY_U32S_1;
- break;
- case _LINUX_CAPABILITY_VERSION_2:
- warn_deprecated_v2();
- /*
- * fall through - v3 is otherwise equivalent to v2.
- */
- case _LINUX_CAPABILITY_VERSION_3:
- *tocopy = _LINUX_CAPABILITY_U32S_3;
- break;
- default:
- if (put_user((u32)_KERNEL_CAPABILITY_VERSION, &header->version))
- return -EFAULT;
- return -EINVAL;
- }
-
- return 0;
-}
-
-#ifndef CONFIG_SECURITY_FILE_CAPABILITIES
-
-/*
- * Without filesystem capability support, we nominally support one process
- * setting the capabilities of another
- */
-static inline int cap_get_target_pid(pid_t pid, kernel_cap_t *pEp,
- kernel_cap_t *pIp, kernel_cap_t *pPp)
-{
- struct task_struct *target;
- int ret;
-
- spin_lock(&task_capability_lock);
- read_lock(&tasklist_lock);
-
- if (pid && pid != task_pid_vnr(current)) {
- target = find_task_by_vpid(pid);
- if (!target) {
- ret = -ESRCH;
- goto out;
- }
- } else
- target = current;
-
- ret = security_capget(target, pEp, pIp, pPp);
-
-out:
- read_unlock(&tasklist_lock);
- spin_unlock(&task_capability_lock);
-
- return ret;
-}
-
-/*
- * cap_set_pg - set capabilities for all processes in a given process
- * group. We call this holding task_capability_lock and tasklist_lock.
- */
-static inline int cap_set_pg(int pgrp_nr, kernel_cap_t *effective,
- kernel_cap_t *inheritable,
- kernel_cap_t *permitted)
-{
- struct task_struct *g, *target;
- int ret = -EPERM;
- int found = 0;
- struct pid *pgrp;
-
- spin_lock(&task_capability_lock);
- read_lock(&tasklist_lock);
-
- pgrp = find_vpid(pgrp_nr);
- do_each_pid_task(pgrp, PIDTYPE_PGID, g) {
- target = g;
- while_each_thread(g, target) {
- if (!security_capset_check(target, effective,
- inheritable, permitted)) {
- security_capset_set(target, effective,
- inheritable, permitted);
- ret = 0;
- }
- found = 1;
- }
- } while_each_pid_task(pgrp, PIDTYPE_PGID, g);
-
- read_unlock(&tasklist_lock);
- spin_unlock(&task_capability_lock);
-
- if (!found)
- ret = 0;
- return ret;
-}
-
-/*
- * cap_set_all - set capabilities for all processes other than init
- * and self. We call this holding task_capability_lock and tasklist_lock.
- */
-static inline int cap_set_all(kernel_cap_t *effective,
- kernel_cap_t *inheritable,
- kernel_cap_t *permitted)
-{
- struct task_struct *g, *target;
- int ret = -EPERM;
- int found = 0;
-
- spin_lock(&task_capability_lock);
- read_lock(&tasklist_lock);
-
- do_each_thread(g, target) {
- if (target == current
- || is_container_init(target->group_leader))
- continue;
- found = 1;
- if (security_capset_check(target, effective, inheritable,
- permitted))
- continue;
- ret = 0;
- security_capset_set(target, effective, inheritable, permitted);
- } while_each_thread(g, target);
-
- read_unlock(&tasklist_lock);
- spin_unlock(&task_capability_lock);
-
- if (!found)
- ret = 0;
-
- return ret;
-}
-
-/*
- * Given the target pid does not refer to the current process we
- * need more elaborate support... (This support is not present when
- * filesystem capabilities are configured.)
- */
-static inline int do_sys_capset_other_tasks(pid_t pid, kernel_cap_t *effective,
- kernel_cap_t *inheritable,
- kernel_cap_t *permitted)
-{
- struct task_struct *target;
- int ret;
-
- if (!capable(CAP_SETPCAP))
- return -EPERM;
-
- if (pid == -1) /* all procs other than current and init */
- return cap_set_all(effective, inheritable, permitted);
-
- else if (pid < 0) /* all procs in process group */
- return cap_set_pg(-pid, effective, inheritable, permitted);
-
- /* target != current */
- spin_lock(&task_capability_lock);
- read_lock(&tasklist_lock);
-
- target = find_task_by_vpid(pid);
- if (!target)
- ret = -ESRCH;
- else {
- ret = security_capset_check(target, effective, inheritable,
- permitted);
-
- /* having verified that the proposed changes are legal,
- we now put them into effect. */
- if (!ret)
- security_capset_set(target, effective, inheritable,
- permitted);
- }
-
- read_unlock(&tasklist_lock);
- spin_unlock(&task_capability_lock);
-
- return ret;
-}
-
-#else /* ie., def CONFIG_SECURITY_FILE_CAPABILITIES */
-
-/*
- * If we have configured with filesystem capability support, then the
- * only thing that can change the capabilities of the current process
- * is the current process. As such, we can't be in this code at the
- * same time as we are in the process of setting capabilities in this
- * process. The net result is that we can limit our use of locks to
- * when we are reading the caps of another process.
- */
-static inline int cap_get_target_pid(pid_t pid, kernel_cap_t *pEp,
- kernel_cap_t *pIp, kernel_cap_t *pPp)
-{
- int ret;
-
- if (pid && (pid != task_pid_vnr(current))) {
- struct task_struct *target;
-
- spin_lock(&task_capability_lock);
- read_lock(&tasklist_lock);
-
- target = find_task_by_vpid(pid);
- if (!target)
- ret = -ESRCH;
- else
- ret = security_capget(target, pEp, pIp, pPp);
-
- read_unlock(&tasklist_lock);
- spin_unlock(&task_capability_lock);
- } else
- ret = security_capget(current, pEp, pIp, pPp);
-
- return ret;
-}
-
-/*
- * With filesystem capability support configured, the kernel does not
- * permit the changing of capabilities in one process by another
- * process. (CAP_SETPCAP has much less broad semantics when configured
- * this way.)
- */
-static inline int do_sys_capset_other_tasks(pid_t pid,
- kernel_cap_t *effective,
- kernel_cap_t *inheritable,
- kernel_cap_t *permitted)
-{
- return -EPERM;
-}
-
-#endif /* ie., ndef CONFIG_SECURITY_FILE_CAPABILITIES */
-
-/*
- * Atomically modify the effective capabilities returning the original
- * value. No permission check is performed here - it is assumed that the
- * caller is permitted to set the desired effective capabilities.
- */
-kernel_cap_t cap_set_effective(const kernel_cap_t pE_new)
-{
- kernel_cap_t pE_old;
-
- spin_lock(&task_capability_lock);
-
- pE_old = current->cap_effective;
- current->cap_effective = pE_new;
-
- spin_unlock(&task_capability_lock);
-
- return pE_old;
-}
-
-EXPORT_SYMBOL(cap_set_effective);
-
-/**
- * sys_capget - get the capabilities of a given process.
- * @header: pointer to struct that contains capability version and
- * target pid data
- * @dataptr: pointer to struct that contains the effective, permitted,
- * and inheritable capabilities that are returned
- *
- * Returns 0 on success and < 0 on error.
- */
-SYSCALL_DEFINE2(capget, cap_user_header_t, header, cap_user_data_t, dataptr)
-{
- int ret = 0;
- pid_t pid;
- unsigned tocopy;
- kernel_cap_t pE, pI, pP;
-
- ret = cap_validate_magic(header, &tocopy);
- if (ret != 0)
- return ret;
-
- if (get_user(pid, &header->pid))
- return -EFAULT;
-
- if (pid < 0)
- return -EINVAL;
-
- ret = cap_get_target_pid(pid, &pE, &pI, &pP);
-
- if (!ret) {
- struct __user_cap_data_struct kdata[_KERNEL_CAPABILITY_U32S];
- unsigned i;
-
- for (i = 0; i < tocopy; i++) {
- kdata[i].effective = pE.cap[i];
- kdata[i].permitted = pP.cap[i];
- kdata[i].inheritable = pI.cap[i];
- }
-
- /*
- * Note, in the case, tocopy < _KERNEL_CAPABILITY_U32S,
- * we silently drop the upper capabilities here. This
- * has the effect of making older libcap
- * implementations implicitly drop upper capability
- * bits when they perform a: capget/modify/capset
- * sequence.
- *
- * This behavior is considered fail-safe
- * behavior. Upgrading the application to a newer
- * version of libcap will enable access to the newer
- * capabilities.
- *
- * An alternative would be to return an error here
- * (-ERANGE), but that causes legacy applications to
- * unexpectidly fail; the capget/modify/capset aborts
- * before modification is attempted and the application
- * fails.
- */
- if (copy_to_user(dataptr, kdata, tocopy
- * sizeof(struct __user_cap_data_struct))) {
- return -EFAULT;
- }
- }
-
- return ret;
-}
-
-/**
- * sys_capset - set capabilities for a process or (*) a group of processes
- * @header: pointer to struct that contains capability version and
- * target pid data
- * @data: pointer to struct that contains the effective, permitted,
- * and inheritable capabilities
- *
- * Set capabilities for a given process, all processes, or all
- * processes in a given process group.
- *
- * The restrictions on setting capabilities are specified as:
- *
- * [pid is for the 'target' task. 'current' is the calling task.]
- *
- * I: any raised capabilities must be a subset of the (old current) permitted
- * P: any raised capabilities must be a subset of the (old current) permitted
- * E: must be set to a subset of (new target) permitted
- *
- * Returns 0 on success and < 0 on error.
- */
-SYSCALL_DEFINE2(capset, cap_user_header_t, header, const cap_user_data_t, data)
-{
- struct __user_cap_data_struct kdata[_KERNEL_CAPABILITY_U32S];
- unsigned i, tocopy;
- kernel_cap_t inheritable, permitted, effective;
- int ret;
- pid_t pid;
-
- ret = cap_validate_magic(header, &tocopy);
- if (ret != 0)
- return ret;
-
- if (get_user(pid, &header->pid))
- return -EFAULT;
-
- if (copy_from_user(&kdata, data, tocopy
- * sizeof(struct __user_cap_data_struct))) {
- return -EFAULT;
- }
-
- for (i = 0; i < tocopy; i++) {
- effective.cap[i] = kdata[i].effective;
- permitted.cap[i] = kdata[i].permitted;
- inheritable.cap[i] = kdata[i].inheritable;
- }
- while (i < _KERNEL_CAPABILITY_U32S) {
- effective.cap[i] = 0;
- permitted.cap[i] = 0;
- inheritable.cap[i] = 0;
- i++;
- }
-
- if (pid && (pid != task_pid_vnr(current)))
- ret = do_sys_capset_other_tasks(pid, &effective, &inheritable,
- &permitted);
- else {
- /*
- * This lock is required even when filesystem
- * capability support is configured - it protects the
- * sys_capget() call from returning incorrect data in
- * the case that the targeted process is not the
- * current one.
- */
- spin_lock(&task_capability_lock);
-
- ret = security_capset_check(current, &effective, &inheritable,
- &permitted);
- /*
- * Having verified that the proposed changes are
- * legal, we now put them into effect.
- */
- if (!ret)
- security_capset_set(current, &effective, &inheritable,
- &permitted);
- spin_unlock(&task_capability_lock);
- }
-
-
- return ret;
-}
-
-/**
- * capable - Determine if the current task has a superior capability in effect
- * @cap: The capability to be tested for
- *
- * Return true if the current task has the given superior capability currently
- * available for use, false if not.
- *
- * This sets PF_SUPERPRIV on the task if the capability is available on the
- * assumption that it's about to be used.
- */
-int capable(int cap)
-{
- if (has_capability(current, cap)) {
- current->flags |= PF_SUPERPRIV;
- return 1;
- }
- return 0;
-}
-EXPORT_SYMBOL(capable);
-/*
- * Generic process-grouping system.
- *
- * Based originally on the cpuset system, extracted by Paul Menage
- * Copyright (C) 2006 Google, Inc
- *
- * Copyright notices from the original cpuset code:
- * --------------------------------------------------
- * Copyright (C) 2003 BULL SA.
- * Copyright (C) 2004-2006 Silicon Graphics, Inc.
- *
- * Portions derived from Patrick Mochel's sysfs code.
- * sysfs is Copyright (c) 2001-3 Patrick Mochel
- *
- * 2003-10-10 Written by Simon Derr.
- * 2003-10-22 Updates by Stephen Hemminger.
- * 2004 May-July Rework by Paul Jackson.
- * ---------------------------------------------------
- *
- * This file is subject to the terms and conditions of the GNU General Public
- * License. See the file COPYING in the main directory of the Linux
- * distribution for more details.
- */
-
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-
-#include
-
-static DEFINE_MUTEX(cgroup_mutex);
-
-/* Generate an array of cgroup subsystem pointers */
-#define SUBSYS(_x) &_x ## _subsys,
-
-static struct cgroup_subsys *subsys[] = {
-#include
-};
-
-/*
- * A cgroupfs_root represents the root of a cgroup hierarchy,
- * and may be associated with a superblock to form an active
- * hierarchy
- */
-struct cgroupfs_root {
- struct super_block *sb;
-
- /*
- * The bitmask of subsystems intended to be attached to this
- * hierarchy
- */
- unsigned long subsys_bits;
-
- /* The bitmask of subsystems currently attached to this hierarchy */
- unsigned long actual_subsys_bits;
-
- /* A list running through the attached subsystems */
- struct list_head subsys_list;
-
- /* The root cgroup for this hierarchy */
- struct cgroup top_cgroup;
-
- /* Tracks how many cgroups are currently defined in hierarchy.*/
- int number_of_cgroups;
-
- /* A list running through the mounted hierarchies */
- struct list_head root_list;
-
- /* Hierarchy-specific flags */
- unsigned long flags;
-
- /* The path to use for release notifications. */
- char release_agent_path[PATH_MAX];
-};
-
-
-/*
- * The "rootnode" hierarchy is the "dummy hierarchy", reserved for the
- * subsystems that are otherwise unattached - it never has more than a
- * single cgroup, and all tasks are part of that cgroup.
- */
-static struct cgroupfs_root rootnode;
-
-/* The list of hierarchy roots */
-
-static LIST_HEAD(roots);
-static int root_count;
-
-/* dummytop is a shorthand for the dummy hierarchy's top cgroup */
-#define dummytop (&rootnode.top_cgroup)
-
-/* This flag indicates whether tasks in the fork and exit paths should
- * check for fork/exit handlers to call. This avoids us having to do
- * extra work in the fork/exit path if none of the subsystems need to
- * be called.
- */
-static int need_forkexit_callback __read_mostly;
-static int need_mm_owner_callback __read_mostly;
-
-/* convenient tests for these bits */
-inline int cgroup_is_removed(const struct cgroup *cgrp)
-{
- return test_bit(CGRP_REMOVED, &cgrp->flags);
-}
-
-/* bits in struct cgroupfs_root flags field */
-enum {
- ROOT_NOPREFIX, /* mounted subsystems have no named prefix */
-};
-
-static int cgroup_is_releasable(const struct cgroup *cgrp)
-{
- const int bits =
- (1 << CGRP_RELEASABLE) |
- (1 << CGRP_NOTIFY_ON_RELEASE);
- return (cgrp->flags & bits) == bits;
-}
-
-static int notify_on_release(const struct cgroup *cgrp)
-{
- return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
-}
-
-/*
- * for_each_subsys() allows you to iterate on each subsystem attached to
- * an active hierarchy
- */
-#define for_each_subsys(_root, _ss) \
-list_for_each_entry(_ss, &_root->subsys_list, sibling)
-
-/* for_each_root() allows you to iterate across the active hierarchies */
-#define for_each_root(_root) \
-list_for_each_entry(_root, &roots, root_list)
-
-/* the list of cgroups eligible for automatic release. Protected by
- * release_list_lock */
-static LIST_HEAD(release_list);
-static DEFINE_SPINLOCK(release_list_lock);
-static void cgroup_release_agent(struct work_struct *work);
-static DECLARE_WORK(release_agent_work, cgroup_release_agent);
-static void check_for_release(struct cgroup *cgrp);
-
-/* Link structure for associating css_set objects with cgroups */
-struct cg_cgroup_link {
- /*
- * List running through cg_cgroup_links associated with a
- * cgroup, anchored on cgroup->css_sets
- */
- struct list_head cgrp_link_list;
- /*
- * List running through cg_cgroup_links pointing at a
- * single css_set object, anchored on css_set->cg_links
- */
- struct list_head cg_link_list;
- struct css_set *cg;
-};
-
-/* The default css_set - used by init and its children prior to any
- * hierarchies being mounted. It contains a pointer to the root state
- * for each subsystem. Also used to anchor the list of css_sets. Not
- * reference-counted, to improve performance when child cgroups
- * haven't been created.
- */
-
-static struct css_set init_css_set;
-static struct cg_cgroup_link init_css_set_link;
-
-/* css_set_lock protects the list of css_set objects, and the
- * chain of tasks off each css_set. Nests outside task->alloc_lock
- * due to cgroup_iter_start() */
-static DEFINE_RWLOCK(css_set_lock);
-static int css_set_count;
-
-/* hash table for cgroup groups. This improves the performance to
- * find an existing css_set */
-#define CSS_SET_HASH_BITS 7
-#define CSS_SET_TABLE_SIZE (1 << CSS_SET_HASH_BITS)
-static struct hlist_head css_set_table[CSS_SET_TABLE_SIZE];
-
-static struct hlist_head *css_set_hash(struct cgroup_subsys_state *css[])
-{
- int i;
- int index;
- unsigned long tmp = 0UL;
-
- for (i = 0; i < CGROUP_SUBSYS_COUNT; i++)
- tmp += (unsigned long)css[i];
- tmp = (tmp >> 16) ^ tmp;
-
- index = hash_long(tmp, CSS_SET_HASH_BITS);
-
- return &css_set_table[index];
-}
-
-/* We don't maintain the lists running through each css_set to its
- * task until after the first call to cgroup_iter_start(). This
- * reduces the fork()/exit() overhead for people who have cgroups
- * compiled into their kernel but not actually in use */
-static int use_task_css_set_links __read_mostly;
-
-/* When we create or destroy a css_set, the operation simply
- * takes/releases a reference count on all the cgroups referenced
- * by subsystems in this css_set. This can end up multiple-counting
- * some cgroups, but that's OK - the ref-count is just a
- * busy/not-busy indicator; ensuring that we only count each cgroup
- * once would require taking a global lock to ensure that no
- * subsystems moved between hierarchies while we were doing so.
- *
- * Possible TODO: decide at boot time based on the number of
- * registered subsystems and the number of CPUs or NUMA nodes whether
- * it's better for performance to ref-count every subsystem, or to
- * take a global lock and only add one ref count to each hierarchy.
- */
-
-/*
- * unlink a css_set from the list and free it
- */
-static void unlink_css_set(struct css_set *cg)
-{
- struct cg_cgroup_link *link;
- struct cg_cgroup_link *saved_link;
-
- write_lock(&css_set_lock);
- hlist_del(&cg->hlist);
- css_set_count--;
-
- list_for_each_entry_safe(link, saved_link, &cg->cg_links,
- cg_link_list) {
- list_del(&link->cg_link_list);
- list_del(&link->cgrp_link_list);
- kfree(link);
- }
-
- write_unlock(&css_set_lock);
-}
-
-static void __release_css_set(struct kref *k, int taskexit)
-{
- int i;
- struct css_set *cg = container_of(k, struct css_set, ref);
-
- unlink_css_set(cg);
-
- rcu_read_lock();
- for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
- struct cgroup *cgrp = cg->subsys[i]->cgroup;
- if (atomic_dec_and_test(&cgrp->count) &&
- notify_on_release(cgrp)) {
- if (taskexit)
- set_bit(CGRP_RELEASABLE, &cgrp->flags);
- check_for_release(cgrp);
- }
- }
- rcu_read_unlock();
- kfree(cg);
-}
-
-static void release_css_set(struct kref *k)
-{
- __release_css_set(k, 0);
-}
-
-static void release_css_set_taskexit(struct kref *k)
-{
- __release_css_set(k, 1);
-}
-
-/*
- * refcounted get/put for css_set objects
- */
-static inline void get_css_set(struct css_set *cg)
-{
- kref_get(&cg->ref);
-}
-
-static inline void put_css_set(struct css_set *cg)
-{
- kref_put(&cg->ref, release_css_set);
-}
-
-static inline void put_css_set_taskexit(struct css_set *cg)
-{
- kref_put(&cg->ref, release_css_set_taskexit);
-}
-
-/*
- * find_existing_css_set() is a helper for
- * find_css_set(), and checks to see whether an existing
- * css_set is suitable.
- *
- * oldcg: the cgroup group that we're using before the cgroup
- * transition
- *
- * cgrp: the cgroup that we're moving into
- *
- * template: location in which to build the desired set of subsystem
- * state objects for the new cgroup group
- */
-static struct css_set *find_existing_css_set(
- struct css_set *oldcg,
- struct cgroup *cgrp,
- struct cgroup_subsys_state *template[])
-{
- int i;
- struct cgroupfs_root *root = cgrp->root;
- struct hlist_head *hhead;
- struct hlist_node *node;
- struct css_set *cg;
-
- /* Built the set of subsystem state objects that we want to
- * see in the new css_set */
- for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
- if (root->subsys_bits & (1UL << i)) {
- /* Subsystem is in this hierarchy. So we want
- * the subsystem state from the new
- * cgroup */
- template[i] = cgrp->subsys[i];
- } else {
- /* Subsystem is not in this hierarchy, so we
- * don't want to change the subsystem state */
- template[i] = oldcg->subsys[i];
- }
- }
-
- hhead = css_set_hash(template);
- hlist_for_each_entry(cg, node, hhead, hlist) {
- if (!memcmp(template, cg->subsys, sizeof(cg->subsys))) {
- /* All subsystems matched */
- return cg;
- }
- }
-
- /* No existing cgroup group matched */
- return NULL;
-}
-
-static void free_cg_links(struct list_head *tmp)
-{
- struct cg_cgroup_link *link;
- struct cg_cgroup_link *saved_link;
-
- list_for_each_entry_safe(link, saved_link, tmp, cgrp_link_list) {
- list_del(&link->cgrp_link_list);
- kfree(link);
- }
-}
-
-/*
- * allocate_cg_links() allocates "count" cg_cgroup_link structures
- * and chains them on tmp through their cgrp_link_list fields. Returns 0 on
- * success or a negative error
- */
-static int allocate_cg_links(int count, struct list_head *tmp)
-{
- struct cg_cgroup_link *link;
- int i;
- INIT_LIST_HEAD(tmp);
- for (i = 0; i < count; i++) {
- link = kmalloc(sizeof(*link), GFP_KERNEL);
- if (!link) {
- free_cg_links(tmp);
- return -ENOMEM;
- }
- list_add(&link->cgrp_link_list, tmp);
- }
- return 0;
-}
-
-/*
- * find_css_set() takes an existing cgroup group and a
- * cgroup object, and returns a css_set object that's
- * equivalent to the old group, but with the given cgroup
- * substituted into the appropriate hierarchy. Must be called with
- * cgroup_mutex held
- */
-static struct css_set *find_css_set(
- struct css_set *oldcg, struct cgroup *cgrp)
-{
- struct css_set *res;
- struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT];
- int i;
-
- struct list_head tmp_cg_links;
- struct cg_cgroup_link *link;
-
- struct hlist_head *hhead;
-
- /* First see if we already have a cgroup group that matches
- * the desired set */
- read_lock(&css_set_lock);
- res = find_existing_css_set(oldcg, cgrp, template);
- if (res)
- get_css_set(res);
- read_unlock(&css_set_lock);
-
- if (res)
- return res;
-
- res = kmalloc(sizeof(*res), GFP_KERNEL);
- if (!res)
- return NULL;
-
- /* Allocate all the cg_cgroup_link objects that we'll need */
- if (allocate_cg_links(root_count, &tmp_cg_links) < 0) {
- kfree(res);
- return NULL;
- }
-
- kref_init(&res->ref);
- INIT_LIST_HEAD(&res->cg_links);
- INIT_LIST_HEAD(&res->tasks);
- INIT_HLIST_NODE(&res->hlist);
-
- /* Copy the set of subsystem state objects generated in
- * find_existing_css_set() */
- memcpy(res->subsys, template, sizeof(res->subsys));
-
- write_lock(&css_set_lock);
- /* Add reference counts and links from the new css_set. */
- for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
- struct cgroup *cgrp = res->subsys[i]->cgroup;
- struct cgroup_subsys *ss = subsys[i];
- atomic_inc(&cgrp->count);
- /*
- * We want to add a link once per cgroup, so we
- * only do it for the first subsystem in each
- * hierarchy
- */
- if (ss->root->subsys_list.next == &ss->sibling) {
- BUG_ON(list_empty(&tmp_cg_links));
- link = list_entry(tmp_cg_links.next,
- struct cg_cgroup_link,
- cgrp_link_list);
- list_del(&link->cgrp_link_list);
- list_add(&link->cgrp_link_list, &cgrp->css_sets);
- link->cg = res;
- list_add(&link->cg_link_list, &res->cg_links);
- }
- }
- if (list_empty(&rootnode.subsys_list)) {
- link = list_entry(tmp_cg_links.next,
- struct cg_cgroup_link,
- cgrp_link_list);
- list_del(&link->cgrp_link_list);
- list_add(&link->cgrp_link_list, &dummytop->css_sets);
- link->cg = res;
- list_add(&link->cg_link_list, &res->cg_links);
- }
-
- BUG_ON(!list_empty(&tmp_cg_links));
-
- css_set_count++;
-
- /* Add this cgroup group to the hash table */
- hhead = css_set_hash(res->subsys);
- hlist_add_head(&res->hlist, hhead);
-
- write_unlock(&css_set_lock);
-
- return res;
-}
-
-/*
- * There is one global cgroup mutex. We also require taking
- * task_lock() when dereferencing a task's cgroup subsys pointers.
- * See "The task_lock() exception", at the end of this comment.
- *
- * A task must hold cgroup_mutex to modify cgroups.
- *
- * Any task can increment and decrement the count field without lock.
- * So in general, code holding cgroup_mutex can't rely on the count
- * field not changing. However, if the count goes to zero, then only
- * cgroup_attach_task() can increment it again. Because a count of zero
- * means that no tasks are currently attached, therefore there is no
- * way a task attached to that cgroup can fork (the other way to
- * increment the count). So code holding cgroup_mutex can safely
- * assume that if the count is zero, it will stay zero. Similarly, if
- * a task holds cgroup_mutex on a cgroup with zero count, it
- * knows that the cgroup won't be removed, as cgroup_rmdir()
- * needs that mutex.
- *
- * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
- * (usually) take cgroup_mutex. These are the two most performance
- * critical pieces of code here. The exception occurs on cgroup_exit(),
- * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
- * is taken, and if the cgroup count is zero, a usermode call made
- * to the release agent with the name of the cgroup (path relative to
- * the root of cgroup file system) as the argument.
- *
- * A cgroup can only be deleted if both its 'count' of using tasks
- * is zero, and its list of 'children' cgroups is empty. Since all
- * tasks in the system use _some_ cgroup, and since there is always at
- * least one task in the system (init, pid == 1), therefore, top_cgroup
- * always has either children cgroups and/or using tasks. So we don't
- * need a special hack to ensure that top_cgroup cannot be deleted.
- *
- * The task_lock() exception
- *
- * The need for this exception arises from the action of
- * cgroup_attach_task(), which overwrites one tasks cgroup pointer with
- * another. It does so using cgroup_mutex, however there are
- * several performance critical places that need to reference
- * task->cgroup without the expense of grabbing a system global
- * mutex. Therefore except as noted below, when dereferencing or, as
- * in cgroup_attach_task(), modifying a task'ss cgroup pointer we use
- * task_lock(), which acts on a spinlock (task->alloc_lock) already in
- * the task_struct routinely used for such matters.
- *
- * P.S. One more locking exception. RCU is used to guard the
- * update of a tasks cgroup pointer by cgroup_attach_task()
- */
-
-/**
- * cgroup_lock - lock out any changes to cgroup structures
- *
- */
-void cgroup_lock(void)
-{
- mutex_lock(&cgroup_mutex);
-}
-
-/**
- * cgroup_unlock - release lock on cgroup changes
- *
- * Undo the lock taken in a previous cgroup_lock() call.
- */
-void cgroup_unlock(void)
-{
- mutex_unlock(&cgroup_mutex);
-}
-
-/*
- * A couple of forward declarations required, due to cyclic reference loop:
- * cgroup_mkdir -> cgroup_create -> cgroup_populate_dir ->
- * cgroup_add_file -> cgroup_create_file -> cgroup_dir_inode_operations
- * -> cgroup_mkdir.
- */
-
-static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, int mode);
-static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry);
-static int cgroup_populate_dir(struct cgroup *cgrp);
-static struct inode_operations cgroup_dir_inode_operations;
-static struct file_operations proc_cgroupstats_operations;
-
-static struct backing_dev_info cgroup_backing_dev_info = {
- .capabilities = BDI_CAP_NO_ACCT_AND_WRITEBACK,
-};
-
-static struct inode *cgroup_new_inode(mode_t mode, struct super_block *sb)
-{
- struct inode *inode = new_inode(sb);
-
- if (inode) {
- inode->i_mode = mode;
- inode->i_uid = current->fsuid;
- inode->i_gid = current->fsgid;
- inode->i_blocks = 0;
- inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
- inode->i_mapping->backing_dev_info = &cgroup_backing_dev_info;
- }
- return inode;
-}
-
-/*
- * Call subsys's pre_destroy handler.
- * This is called before css refcnt check.
- */
-static void cgroup_call_pre_destroy(struct cgroup *cgrp)
-{
- struct cgroup_subsys *ss;
- for_each_subsys(cgrp->root, ss)
- if (ss->pre_destroy && cgrp->subsys[ss->subsys_id])
- ss->pre_destroy(ss, cgrp);
- return;
-}
-
-static void cgroup_diput(struct dentry *dentry, struct inode *inode)
-{
- /* is dentry a directory ? if so, kfree() associated cgroup */
- if (S_ISDIR(inode->i_mode)) {
- struct cgroup *cgrp = dentry->d_fsdata;
- struct cgroup_subsys *ss;
- BUG_ON(!(cgroup_is_removed(cgrp)));
- /* It's possible for external users to be holding css
- * reference counts on a cgroup; css_put() needs to
- * be able to access the cgroup after decrementing
- * the reference count in order to know if it needs to
- * queue the cgroup to be handled by the release
- * agent */
- synchronize_rcu();
-
- mutex_lock(&cgroup_mutex);
- /*
- * Release the subsystem state objects.
- */
- for_each_subsys(cgrp->root, ss) {
- if (cgrp->subsys[ss->subsys_id])
- ss->destroy(ss, cgrp);
- }
-
- cgrp->root->number_of_cgroups--;
- mutex_unlock(&cgroup_mutex);
-
- /* Drop the active superblock reference that we took when we
- * created the cgroup */
- deactivate_super(cgrp->root->sb);
-
- kfree(cgrp);
- }
- iput(inode);
-}
-
-static void remove_dir(struct dentry *d)
-{
- struct dentry *parent = dget(d->d_parent);
-
- d_delete(d);
- simple_rmdir(parent->d_inode, d);
- dput(parent);
-}
-
-static void cgroup_clear_directory(struct dentry *dentry)
-{
- struct list_head *node;
-
- BUG_ON(!mutex_is_locked(&dentry->d_inode->i_mutex));
- spin_lock(&dcache_lock);
- node = dentry->d_subdirs.next;
- while (node != &dentry->d_subdirs) {
- struct dentry *d = list_entry(node, struct dentry, d_u.d_child);
- list_del_init(node);
- if (d->d_inode) {
- /* This should never be called on a cgroup
- * directory with child cgroups */
- BUG_ON(d->d_inode->i_mode & S_IFDIR);
- d = dget_locked(d);
- spin_unlock(&dcache_lock);
- d_delete(d);
- simple_unlink(dentry->d_inode, d);
- dput(d);
- spin_lock(&dcache_lock);
- }
- node = dentry->d_subdirs.next;
- }
- spin_unlock(&dcache_lock);
-}
-
-/*
- * NOTE : the dentry must have been dget()'ed
- */
-static void cgroup_d_remove_dir(struct dentry *dentry)
-{
- cgroup_clear_directory(dentry);
-
- spin_lock(&dcache_lock);
- list_del_init(&dentry->d_u.d_child);
- spin_unlock(&dcache_lock);
- remove_dir(dentry);
-}
-
-static int rebind_subsystems(struct cgroupfs_root *root,
- unsigned long final_bits)
-{
- unsigned long added_bits, removed_bits;
- struct cgroup *cgrp = &root->top_cgroup;
- int i;
-
- removed_bits = root->actual_subsys_bits & ~final_bits;
- added_bits = final_bits & ~root->actual_subsys_bits;
- /* Check that any added subsystems are currently free */
- for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
- unsigned long bit = 1UL << i;
- struct cgroup_subsys *ss = subsys[i];
- if (!(bit & added_bits))
- continue;
- if (ss->root != &rootnode) {
- /* Subsystem isn't free */
- return -EBUSY;
- }
- }
-
- /* Currently we don't handle adding/removing subsystems when
- * any child cgroups exist. This is theoretically supportable
- * but involves complex error handling, so it's being left until
- * later */
- if (!list_empty(&cgrp->children))
- return -EBUSY;
-
- /* Process each subsystem */
- for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
- struct cgroup_subsys *ss = subsys[i];
- unsigned long bit = 1UL << i;
- if (bit & added_bits) {
- /* We're binding this subsystem to this hierarchy */
- BUG_ON(cgrp->subsys[i]);
- BUG_ON(!dummytop->subsys[i]);
- BUG_ON(dummytop->subsys[i]->cgroup != dummytop);
- cgrp->subsys[i] = dummytop->subsys[i];
- cgrp->subsys[i]->cgroup = cgrp;
- list_add(&ss->sibling, &root->subsys_list);
- rcu_assign_pointer(ss->root, root);
- if (ss->bind)
- ss->bind(ss, cgrp);
-
- } else if (bit & removed_bits) {
- /* We're removing this subsystem */
- BUG_ON(cgrp->subsys[i] != dummytop->subsys[i]);
- BUG_ON(cgrp->subsys[i]->cgroup != cgrp);
- if (ss->bind)
- ss->bind(ss, dummytop);
- dummytop->subsys[i]->cgroup = dummytop;
- cgrp->subsys[i] = NULL;
- rcu_assign_pointer(subsys[i]->root, &rootnode);
- list_del(&ss->sibling);
- } else if (bit & final_bits) {
- /* Subsystem state should already exist */
- BUG_ON(!cgrp->subsys[i]);
- } else {
- /* Subsystem state shouldn't exist */
- BUG_ON(cgrp->subsys[i]);
- }
- }
- root->subsys_bits = root->actual_subsys_bits = final_bits;
- synchronize_rcu();
-
- return 0;
-}
-
-static int cgroup_show_options(struct seq_file *seq, struct vfsmount *vfs)
-{
- struct cgroupfs_root *root = vfs->mnt_sb->s_fs_info;
- struct cgroup_subsys *ss;
-
- mutex_lock(&cgroup_mutex);
- for_each_subsys(root, ss)
- seq_printf(seq, ",%s", ss->name);
- if (test_bit(ROOT_NOPREFIX, &root->flags))
- seq_puts(seq, ",noprefix");
- if (strlen(root->release_agent_path))
- seq_printf(seq, ",release_agent=%s", root->release_agent_path);
- mutex_unlock(&cgroup_mutex);
- return 0;
-}
-
-struct cgroup_sb_opts {
- unsigned long subsys_bits;
- unsigned long flags;
- char *release_agent;
-};
-
-/* Convert a hierarchy specifier into a bitmask of subsystems and
- * flags. */
-static int parse_cgroupfs_options(char *data,
- struct cgroup_sb_opts *opts)
-{
- char *token, *o = data ?: "all";
-
- opts->subsys_bits = 0;
- opts->flags = 0;
- opts->release_agent = NULL;
-
- while ((token = strsep(&o, ",")) != NULL) {
- if (!*token)
- return -EINVAL;
- if (!strcmp(token, "all")) {
- /* Add all non-disabled subsystems */
- int i;
- opts->subsys_bits = 0;
- for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
- struct cgroup_subsys *ss = subsys[i];
- if (!ss->disabled)
- opts->subsys_bits |= 1ul << i;
- }
- } else if (!strcmp(token, "noprefix")) {
- set_bit(ROOT_NOPREFIX, &opts->flags);
- } else if (!strncmp(token, "release_agent=", 14)) {
- /* Specifying two release agents is forbidden */
- if (opts->release_agent)
- return -EINVAL;
- opts->release_agent = kzalloc(PATH_MAX, GFP_KERNEL);
- if (!opts->release_agent)
- return -ENOMEM;
- strncpy(opts->release_agent, token + 14, PATH_MAX - 1);
- opts->release_agent[PATH_MAX - 1] = 0;
- } else {
- struct cgroup_subsys *ss;
- int i;
- for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
- ss = subsys[i];
- if (!strcmp(token, ss->name)) {
- if (!ss->disabled)
- set_bit(i, &opts->subsys_bits);
- break;
- }
- }
- if (i == CGROUP_SUBSYS_COUNT)
- return -ENOENT;
- }
- }
-
- /* We can't have an empty hierarchy */
- if (!opts->subsys_bits)
- return -EINVAL;
-
- return 0;
-}
-
-static int cgroup_remount(struct super_block *sb, int *flags, char *data)
-{
- int ret = 0;
- struct cgroupfs_root *root = sb->s_fs_info;
- struct cgroup *cgrp = &root->top_cgroup;
- struct cgroup_sb_opts opts;
-
- mutex_lock(&cgrp->dentry->d_inode->i_mutex);
- mutex_lock(&cgroup_mutex);
-
- /* See what subsystems are wanted */
- ret = parse_cgroupfs_options(data, &opts);
- if (ret)
- goto out_unlock;
-
- /* Don't allow flags to change at remount */
- if (opts.flags != root->flags) {
- ret = -EINVAL;
- goto out_unlock;
- }
-
- ret = rebind_subsystems(root, opts.subsys_bits);
-
- /* (re)populate subsystem files */
- if (!ret)
- cgroup_populate_dir(cgrp);
-
- if (opts.release_agent)
- strcpy(root->release_agent_path, opts.release_agent);
- out_unlock:
- if (opts.release_agent)
- kfree(opts.release_agent);
- mutex_unlock(&cgroup_mutex);
- mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
- return ret;
-}
-
-static struct super_operations cgroup_ops = {
- .statfs = simple_statfs,
- .drop_inode = generic_delete_inode,
- .show_options = cgroup_show_options,
- .remount_fs = cgroup_remount,
-};
-
-static void init_cgroup_root(struct cgroupfs_root *root)
-{
- struct cgroup *cgrp = &root->top_cgroup;
- INIT_LIST_HEAD(&root->subsys_list);
- INIT_LIST_HEAD(&root->root_list);
- root->number_of_cgroups = 1;
- cgrp->root = root;
- cgrp->top_cgroup = cgrp;
- INIT_LIST_HEAD(&cgrp->sibling);
- INIT_LIST_HEAD(&cgrp->children);
- INIT_LIST_HEAD(&cgrp->css_sets);
- INIT_LIST_HEAD(&cgrp->release_list);
-}
-
-static int cgroup_test_super(struct super_block *sb, void *data)
-{
- struct cgroupfs_root *new = data;
- struct cgroupfs_root *root = sb->s_fs_info;
-
- /* First check subsystems */
- if (new->subsys_bits != root->subsys_bits)
- return 0;
-
- /* Next check flags */
- if (new->flags != root->flags)
- return 0;
-
- return 1;
-}
-
-static int cgroup_set_super(struct super_block *sb, void *data)
-{
- int ret;
- struct cgroupfs_root *root = data;
-
- ret = set_anon_super(sb, NULL);
- if (ret)
- return ret;
-
- sb->s_fs_info = root;
- root->sb = sb;
-
- sb->s_blocksize = PAGE_CACHE_SIZE;
- sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
- sb->s_magic = CGROUP_SUPER_MAGIC;
- sb->s_op = &cgroup_ops;
-
- return 0;
-}
-
-static int cgroup_get_rootdir(struct super_block *sb)
-{
- struct inode *inode =
- cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
- struct dentry *dentry;
-
- if (!inode)
- return -ENOMEM;
-
- inode->i_fop = &simple_dir_operations;
- inode->i_op = &cgroup_dir_inode_operations;
- /* directories start off with i_nlink == 2 (for "." entry) */
- inc_nlink(inode);
- dentry = d_alloc_root(inode);
- if (!dentry) {
- iput(inode);
- return -ENOMEM;
- }
- sb->s_root = dentry;
- return 0;
-}
-
-static int cgroup_get_sb(struct file_system_type *fs_type,
- int flags, const char *unused_dev_name,
- void *data, struct vfsmount *mnt)
-{
- struct cgroup_sb_opts opts;
- int ret = 0;
- struct super_block *sb;
- struct cgroupfs_root *root;
- struct list_head tmp_cg_links;
-
- /* First find the desired set of subsystems */
- ret = parse_cgroupfs_options(data, &opts);
- if (ret) {
- if (opts.release_agent)
- kfree(opts.release_agent);
- return ret;
- }
-
- root = kzalloc(sizeof(*root), GFP_KERNEL);
- if (!root) {
- if (opts.release_agent)
- kfree(opts.release_agent);
- return -ENOMEM;
- }
-
- init_cgroup_root(root);
- root->subsys_bits = opts.subsys_bits;
- root->flags = opts.flags;
- if (opts.release_agent) {
- strcpy(root->release_agent_path, opts.release_agent);
- kfree(opts.release_agent);
- }
-
- sb = sget(fs_type, cgroup_test_super, cgroup_set_super, root);
-
- if (IS_ERR(sb)) {
- kfree(root);
- return PTR_ERR(sb);
- }
-
- if (sb->s_fs_info != root) {
- /* Reusing an existing superblock */
- BUG_ON(sb->s_root == NULL);
- kfree(root);
- root = NULL;
- } else {
- /* New superblock */
- struct cgroup *cgrp = &root->top_cgroup;
- struct inode *inode;
- int i;
-
- BUG_ON(sb->s_root != NULL);
-
- ret = cgroup_get_rootdir(sb);
- if (ret)
- goto drop_new_super;
- inode = sb->s_root->d_inode;
-
- mutex_lock(&inode->i_mutex);
- mutex_lock(&cgroup_mutex);
-
- /*
- * We're accessing css_set_count without locking
- * css_set_lock here, but that's OK - it can only be
- * increased by someone holding cgroup_lock, and
- * that's us. The worst that can happen is that we
- * have some link structures left over
- */
- ret = allocate_cg_links(css_set_count, &tmp_cg_links);
- if (ret) {
- mutex_unlock(&cgroup_mutex);
- mutex_unlock(&inode->i_mutex);
- goto drop_new_super;
- }
-
- ret = rebind_subsystems(root, root->subsys_bits);
- if (ret == -EBUSY) {
- mutex_unlock(&cgroup_mutex);
- mutex_unlock(&inode->i_mutex);
- goto drop_new_super;
- }
-
- /* EBUSY should be the only error here */
- BUG_ON(ret);
-
- list_add(&root->root_list, &roots);
- root_count++;
-
- sb->s_root->d_fsdata = &root->top_cgroup;
- root->top_cgroup.dentry = sb->s_root;
-
- /* Link the top cgroup in this hierarchy into all
- * the css_set objects */
- write_lock(&css_set_lock);
- for (i = 0; i < CSS_SET_TABLE_SIZE; i++) {
- struct hlist_head *hhead = &css_set_table[i];
- struct hlist_node *node;
- struct css_set *cg;
-
- hlist_for_each_entry(cg, node, hhead, hlist) {
- struct cg_cgroup_link *link;
-
- BUG_ON(list_empty(&tmp_cg_links));
- link = list_entry(tmp_cg_links.next,
- struct cg_cgroup_link,
- cgrp_link_list);
- list_del(&link->cgrp_link_list);
- link->cg = cg;
- list_add(&link->cgrp_link_list,
- &root->top_cgroup.css_sets);
- list_add(&link->cg_link_list, &cg->cg_links);
- }
- }
- write_unlock(&css_set_lock);
-
- free_cg_links(&tmp_cg_links);
-
- BUG_ON(!list_empty(&cgrp->sibling));
- BUG_ON(!list_empty(&cgrp->children));
- BUG_ON(root->number_of_cgroups != 1);
-
- cgroup_populate_dir(cgrp);
- mutex_unlock(&inode->i_mutex);
- mutex_unlock(&cgroup_mutex);
- }
-
- return simple_set_mnt(mnt, sb);
-
- drop_new_super:
- up_write(&sb->s_umount);
- deactivate_super(sb);
- free_cg_links(&tmp_cg_links);
- return ret;
-}
-
-static void cgroup_kill_sb(struct super_block *sb) {
- struct cgroupfs_root *root = sb->s_fs_info;
- struct cgroup *cgrp = &root->top_cgroup;
- int ret;
- struct cg_cgroup_link *link;
- struct cg_cgroup_link *saved_link;
-
- BUG_ON(!root);
-
- BUG_ON(root->number_of_cgroups != 1);
- BUG_ON(!list_empty(&cgrp->children));
- BUG_ON(!list_empty(&cgrp->sibling));
-
- mutex_lock(&cgroup_mutex);
-
- /* Rebind all subsystems back to the default hierarchy */
- ret = rebind_subsystems(root, 0);
- /* Shouldn't be able to fail ... */
- BUG_ON(ret);
-
- /*
- * Release all the links from css_sets to this hierarchy's
- * root cgroup
- */
- write_lock(&css_set_lock);
-
- list_for_each_entry_safe(link, saved_link, &cgrp->css_sets,
- cgrp_link_list) {
- list_del(&link->cg_link_list);
- list_del(&link->cgrp_link_list);
- kfree(link);
- }
- write_unlock(&css_set_lock);
-
- if (!list_empty(&root->root_list)) {
- list_del(&root->root_list);
- root_count--;
- }
- mutex_unlock(&cgroup_mutex);
-
- kfree(root);
- kill_litter_super(sb);
-}
-
-static struct file_system_type cgroup_fs_type = {
- .name = "cgroup",
- .get_sb = cgroup_get_sb,
- .kill_sb = cgroup_kill_sb,
-};
-
-static inline struct cgroup *__d_cgrp(struct dentry *dentry)
-{
- return dentry->d_fsdata;
-}
-
-static inline struct cftype *__d_cft(struct dentry *dentry)
-{
- return dentry->d_fsdata;
-}
-
-/**
- * cgroup_path - generate the path of a cgroup
- * @cgrp: the cgroup in question
- * @buf: the buffer to write the path into
- * @buflen: the length of the buffer
- *
- * Called with cgroup_mutex held. Writes path of cgroup into buf.
- * Returns 0 on success, -errno on error.
- */
-int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
-{
- char *start;
-
- if (cgrp == dummytop) {
- /*
- * Inactive subsystems have no dentry for their root
- * cgroup
- */
- strcpy(buf, "/");
- return 0;
- }
-
- start = buf + buflen;
-
- *--start = '\0';
- for (;;) {
- int len = cgrp->dentry->d_name.len;
- if ((start -= len) < buf)
- return -ENAMETOOLONG;
- memcpy(start, cgrp->dentry->d_name.name, len);
- cgrp = cgrp->parent;
- if (!cgrp)
- break;
- if (!cgrp->parent)
- continue;
- if (--start < buf)
- return -ENAMETOOLONG;
- *start = '/';
- }
- memmove(buf, start, buf + buflen - start);
- return 0;
-}
-
-/*
- * Return the first subsystem attached to a cgroup's hierarchy, and
- * its subsystem id.
- */
-
-static void get_first_subsys(const struct cgroup *cgrp,
- struct cgroup_subsys_state **css, int *subsys_id)
-{
- const struct cgroupfs_root *root = cgrp->root;
- const struct cgroup_subsys *test_ss;
- BUG_ON(list_empty(&root->subsys_list));
- test_ss = list_entry(root->subsys_list.next,
- struct cgroup_subsys, sibling);
- if (css) {
- *css = cgrp->subsys[test_ss->subsys_id];
- BUG_ON(!*css);
- }
- if (subsys_id)
- *subsys_id = test_ss->subsys_id;
-}
-
-/**
- * cgroup_attach_task - attach task 'tsk' to cgroup 'cgrp'
- * @cgrp: the cgroup the task is attaching to
- * @tsk: the task to be attached
- *
- * Call holding cgroup_mutex. May take task_lock of
- * the task 'tsk' during call.
- */
-int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk)
-{
- int retval = 0;
- struct cgroup_subsys *ss;
- struct cgroup *oldcgrp;
- struct css_set *cg = tsk->cgroups;
- struct css_set *newcg;
- struct cgroupfs_root *root = cgrp->root;
- int subsys_id;
-
- get_first_subsys(cgrp, NULL, &subsys_id);
-
- /* Nothing to do if the task is already in that cgroup */
- oldcgrp = task_cgroup(tsk, subsys_id);
- if (cgrp == oldcgrp)
- return 0;
-
- for_each_subsys(root, ss) {
- if (ss->can_attach) {
- retval = ss->can_attach(ss, cgrp, tsk);
- if (retval)
- return retval;
- }
- }
-
- /*
- * Locate or allocate a new css_set for this task,
- * based on its final set of cgroups
- */
- newcg = find_css_set(cg, cgrp);
- if (!newcg)
- return -ENOMEM;
-
- task_lock(tsk);
- if (tsk->flags & PF_EXITING) {
- task_unlock(tsk);
- put_css_set(newcg);
- return -ESRCH;
- }
- rcu_assign_pointer(tsk->cgroups, newcg);
- task_unlock(tsk);
-
- /* Update the css_set linked lists if we're using them */
- write_lock(&css_set_lock);
- if (!list_empty(&tsk->cg_list)) {
- list_del(&tsk->cg_list);
- list_add(&tsk->cg_list, &newcg->tasks);
- }
- write_unlock(&css_set_lock);
-
- for_each_subsys(root, ss) {
- if (ss->attach)
- ss->attach(ss, cgrp, oldcgrp, tsk);
- }
- set_bit(CGRP_RELEASABLE, &oldcgrp->flags);
- synchronize_rcu();
- put_css_set(cg);
- return 0;
-}
-
-/*
- * Attach task with pid 'pid' to cgroup 'cgrp'. Call with cgroup_mutex
- * held. May take task_lock of task
- */
-static int attach_task_by_pid(struct cgroup *cgrp, u64 pid)
-{
- struct task_struct *tsk;
- int ret;
-
- if (pid) {
- rcu_read_lock();
- tsk = find_task_by_vpid(pid);
- if (!tsk || tsk->flags & PF_EXITING) {
- rcu_read_unlock();
- return -ESRCH;
- }
- get_task_struct(tsk);
- rcu_read_unlock();
-
- if ((current->euid) && (current->euid != tsk->uid)
- && (current->euid != tsk->suid)) {
- put_task_struct(tsk);
- return -EACCES;
- }
- } else {
- tsk = current;
- get_task_struct(tsk);
- }
-
- ret = cgroup_attach_task(cgrp, tsk);
- put_task_struct(tsk);
- return ret;
-}
-
-static int cgroup_tasks_write(struct cgroup *cgrp, struct cftype *cft, u64 pid)
-{
- int ret;
- if (!cgroup_lock_live_group(cgrp))
- return -ENODEV;
- ret = attach_task_by_pid(cgrp, pid);
- cgroup_unlock();
- return ret;
-}
-
-/* The various types of files and directories in a cgroup file system */
-enum cgroup_filetype {
- FILE_ROOT,
- FILE_DIR,
- FILE_TASKLIST,
- FILE_NOTIFY_ON_RELEASE,
- FILE_RELEASE_AGENT,
-};
-
-/**
- * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
- * @cgrp: the cgroup to be checked for liveness
- *
- * On success, returns true; the lock should be later released with
- * cgroup_unlock(). On failure returns false with no lock held.
- */
-bool cgroup_lock_live_group(struct cgroup *cgrp)
-{
- mutex_lock(&cgroup_mutex);
- if (cgroup_is_removed(cgrp)) {
- mutex_unlock(&cgroup_mutex);
- return false;
- }
- return true;
-}
-
-static int cgroup_release_agent_write(struct cgroup *cgrp, struct cftype *cft,
- const char *buffer)
-{
- BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
- if (!cgroup_lock_live_group(cgrp))
- return -ENODEV;
- strcpy(cgrp->root->release_agent_path, buffer);
- cgroup_unlock();
- return 0;
-}
-
-static int cgroup_release_agent_show(struct cgroup *cgrp, struct cftype *cft,
- struct seq_file *seq)
-{
- if (!cgroup_lock_live_group(cgrp))
- return -ENODEV;
- seq_puts(seq, cgrp->root->release_agent_path);
- seq_putc(seq, '\n');
- cgroup_unlock();
- return 0;
-}
-
-/* A buffer size big enough for numbers or short strings */
-#define CGROUP_LOCAL_BUFFER_SIZE 64
-
-static ssize_t cgroup_write_X64(struct cgroup *cgrp, struct cftype *cft,
- struct file *file,
- const char __user *userbuf,
- size_t nbytes, loff_t *unused_ppos)
-{
- char buffer[CGROUP_LOCAL_BUFFER_SIZE];
- int retval = 0;
- char *end;
-
- if (!nbytes)
- return -EINVAL;
- if (nbytes >= sizeof(buffer))
- return -E2BIG;
- if (copy_from_user(buffer, userbuf, nbytes))
- return -EFAULT;
-
- buffer[nbytes] = 0; /* nul-terminate */
- strstrip(buffer);
- if (cft->write_u64) {
- u64 val = simple_strtoull(buffer, &end, 0);
- if (*end)
- return -EINVAL;
- retval = cft->write_u64(cgrp, cft, val);
- } else {
- s64 val = simple_strtoll(buffer, &end, 0);
- if (*end)
- return -EINVAL;
- retval = cft->write_s64(cgrp, cft, val);
- }
- if (!retval)
- retval = nbytes;
- return retval;
-}
-
-static ssize_t cgroup_write_string(struct cgroup *cgrp, struct cftype *cft,
- struct file *file,
- const char __user *userbuf,
- size_t nbytes, loff_t *unused_ppos)
-{
- char local_buffer[CGROUP_LOCAL_BUFFER_SIZE];
- int retval = 0;
- size_t max_bytes = cft->max_write_len;
- char *buffer = local_buffer;
-
- if (!max_bytes)
- max_bytes = sizeof(local_buffer) - 1;
- if (nbytes >= max_bytes)
- return -E2BIG;
- /* Allocate a dynamic buffer if we need one */
- if (nbytes >= sizeof(local_buffer)) {
- buffer = kmalloc(nbytes + 1, GFP_KERNEL);
- if (buffer == NULL)
- return -ENOMEM;
- }
- if (nbytes && copy_from_user(buffer, userbuf, nbytes)) {
- retval = -EFAULT;
- goto out;
- }
-
- buffer[nbytes] = 0; /* nul-terminate */
- strstrip(buffer);
- retval = cft->write_string(cgrp, cft, buffer);
- if (!retval)
- retval = nbytes;
-out:
- if (buffer != local_buffer)
- kfree(buffer);
- return retval;
-}
-
-static ssize_t cgroup_file_write(struct file *file, const char __user *buf,
- size_t nbytes, loff_t *ppos)
-{
- struct cftype *cft = __d_cft(file->f_dentry);
- struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
-
- if (!cft || cgroup_is_removed(cgrp))
- return -ENODEV;
- if (cft->write)
- return cft->write(cgrp, cft, file, buf, nbytes, ppos);
- if (cft->write_u64 || cft->write_s64)
- return cgroup_write_X64(cgrp, cft, file, buf, nbytes, ppos);
- if (cft->write_string)
- return cgroup_write_string(cgrp, cft, file, buf, nbytes, ppos);
- if (cft->trigger) {
- int ret = cft->trigger(cgrp, (unsigned int)cft->private);
- return ret ? ret : nbytes;
- }
- return -EINVAL;
-}
-
-static ssize_t cgroup_read_u64(struct cgroup *cgrp, struct cftype *cft,
- struct file *file,
- char __user *buf, size_t nbytes,
- loff_t *ppos)
-{
- char tmp[CGROUP_LOCAL_BUFFER_SIZE];
- u64 val = cft->read_u64(cgrp, cft);
- int len = sprintf(tmp, "%llu\n", (unsigned long long) val);
-
- return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
-}
-
-static ssize_t cgroup_read_s64(struct cgroup *cgrp, struct cftype *cft,
- struct file *file,
- char __user *buf, size_t nbytes,
- loff_t *ppos)
-{
- char tmp[CGROUP_LOCAL_BUFFER_SIZE];
- s64 val = cft->read_s64(cgrp, cft);
- int len = sprintf(tmp, "%lld\n", (long long) val);
-
- return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
-}
-
-static ssize_t cgroup_file_read(struct file *file, char __user *buf,
- size_t nbytes, loff_t *ppos)
-{
- struct cftype *cft = __d_cft(file->f_dentry);
- struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
-
- if (!cft || cgroup_is_removed(cgrp))
- return -ENODEV;
-
- if (cft->read)
- return cft->read(cgrp, cft, file, buf, nbytes, ppos);
- if (cft->read_u64)
- return cgroup_read_u64(cgrp, cft, file, buf, nbytes, ppos);
- if (cft->read_s64)
- return cgroup_read_s64(cgrp, cft, file, buf, nbytes, ppos);
- return -EINVAL;
-}
-
-/*
- * seqfile ops/methods for returning structured data. Currently just
- * supports string->u64 maps, but can be extended in future.
- */
-
-struct cgroup_seqfile_state {
- struct cftype *cft;
- struct cgroup *cgroup;
-};
-
-static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value)
-{
- struct seq_file *sf = cb->state;
- return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value);
-}
-
-static int cgroup_seqfile_show(struct seq_file *m, void *arg)
-{
- struct cgroup_seqfile_state *state = m->private;
- struct cftype *cft = state->cft;
- if (cft->read_map) {
- struct cgroup_map_cb cb = {
- .fill = cgroup_map_add,
- .state = m,
- };
- return cft->read_map(state->cgroup, cft, &cb);
- }
- return cft->read_seq_string(state->cgroup, cft, m);
-}
-
-static int cgroup_seqfile_release(struct inode *inode, struct file *file)
-{
- struct seq_file *seq = file->private_data;
- kfree(seq->private);
- return single_release(inode, file);
-}
-
-static struct file_operations cgroup_seqfile_operations = {
- .read = seq_read,
- .write = cgroup_file_write,
- .llseek = seq_lseek,
- .release = cgroup_seqfile_release,
-};
-
-static int cgroup_file_open(struct inode *inode, struct file *file)
-{
- int err;
- struct cftype *cft;
-
- err = generic_file_open(inode, file);
- if (err)
- return err;
-
- cft = __d_cft(file->f_dentry);
- if (!cft)
- return -ENODEV;
- if (cft->read_map || cft->read_seq_string) {
- struct cgroup_seqfile_state *state =
- kzalloc(sizeof(*state), GFP_USER);
- if (!state)
- return -ENOMEM;
- state->cft = cft;
- state->cgroup = __d_cgrp(file->f_dentry->d_parent);
- file->f_op = &cgroup_seqfile_operations;
- err = single_open(file, cgroup_seqfile_show, state);
- if (err < 0)
- kfree(state);
- } else if (cft->open)
- err = cft->open(inode, file);
- else
- err = 0;
-
- return err;
-}
-
-static int cgroup_file_release(struct inode *inode, struct file *file)
-{
- struct cftype *cft = __d_cft(file->f_dentry);
- if (cft->release)
- return cft->release(inode, file);
- return 0;
-}
-
-/*
- * cgroup_rename - Only allow simple rename of directories in place.
- */
-static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
- struct inode *new_dir, struct dentry *new_dentry)
-{
- if (!S_ISDIR(old_dentry->d_inode->i_mode))
- return -ENOTDIR;
- if (new_dentry->d_inode)
- return -EEXIST;
- if (old_dir != new_dir)
- return -EIO;
- return simple_rename(old_dir, old_dentry, new_dir, new_dentry);
-}
-
-static struct file_operations cgroup_file_operations = {
- .read = cgroup_file_read,
- .write = cgroup_file_write,
- .llseek = generic_file_llseek,
- .open = cgroup_file_open,
- .release = cgroup_file_release,
-};
-
-static struct inode_operations cgroup_dir_inode_operations = {
- .lookup = simple_lookup,
- .mkdir = cgroup_mkdir,
- .rmdir = cgroup_rmdir,
- .rename = cgroup_rename,
-};
-
-static int cgroup_create_file(struct dentry *dentry, int mode,
- struct super_block *sb)
-{
- static struct dentry_operations cgroup_dops = {
- .d_iput = cgroup_diput,
- };
-
- struct inode *inode;
-
- if (!dentry)
- return -ENOENT;
- if (dentry->d_inode)
- return -EEXIST;
-
- inode = cgroup_new_inode(mode, sb);
- if (!inode)
- return -ENOMEM;
-
- if (S_ISDIR(mode)) {
- inode->i_op = &cgroup_dir_inode_operations;
- inode->i_fop = &simple_dir_operations;
-
- /* start off with i_nlink == 2 (for "." entry) */
- inc_nlink(inode);
-
- /* start with the directory inode held, so that we can
- * populate it without racing with another mkdir */
- mutex_lock_nested(&inode->i_mutex, I_MUTEX_CHILD);
- } else if (S_ISREG(mode)) {
- inode->i_size = 0;
- inode->i_fop = &cgroup_file_operations;
- }
- dentry->d_op = &cgroup_dops;
- d_instantiate(dentry, inode);
- dget(dentry); /* Extra count - pin the dentry in core */
- return 0;
-}
-
-/*
- * cgroup_create_dir - create a directory for an object.
- * @cgrp: the cgroup we create the directory for. It must have a valid
- * ->parent field. And we are going to fill its ->dentry field.
- * @dentry: dentry of the new cgroup
- * @mode: mode to set on new directory.
- */
-static int cgroup_create_dir(struct cgroup *cgrp, struct dentry *dentry,
- int mode)
-{
- struct dentry *parent;
- int error = 0;
-
- parent = cgrp->parent->dentry;
- error = cgroup_create_file(dentry, S_IFDIR | mode, cgrp->root->sb);
- if (!error) {
- dentry->d_fsdata = cgrp;
- inc_nlink(parent->d_inode);
- cgrp->dentry = dentry;
- dget(dentry);
- }
- dput(dentry);
-
- return error;
-}
-
-int cgroup_add_file(struct cgroup *cgrp,
- struct cgroup_subsys *subsys,
- const struct cftype *cft)
-{
- struct dentry *dir = cgrp->dentry;
- struct dentry *dentry;
- int error;
-
- char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
- if (subsys && !test_bit(ROOT_NOPREFIX, &cgrp->root->flags)) {
- strcpy(name, subsys->name);
- strcat(name, ".");
- }
- strcat(name, cft->name);
- BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
- dentry = lookup_one_len(name, dir, strlen(name));
- if (!IS_ERR(dentry)) {
- error = cgroup_create_file(dentry, 0644 | S_IFREG,
- cgrp->root->sb);
- if (!error)
- dentry->d_fsdata = (void *)cft;
- dput(dentry);
- } else
- error = PTR_ERR(dentry);
- return error;
-}
-
-int cgroup_add_files(struct cgroup *cgrp,
- struct cgroup_subsys *subsys,
- const struct cftype cft[],
- int count)
-{
- int i, err;
- for (i = 0; i < count; i++) {
- err = cgroup_add_file(cgrp, subsys, &cft[i]);
- if (err)
- return err;
- }
- return 0;
-}
-
-/**
- * cgroup_task_count - count the number of tasks in a cgroup.
- * @cgrp: the cgroup in question
- *
- * Return the number of tasks in the cgroup.
- */
-int cgroup_task_count(const struct cgroup *cgrp)
-{
- int count = 0;
- struct cg_cgroup_link *link;
-
- read_lock(&css_set_lock);
- list_for_each_entry(link, &cgrp->css_sets, cgrp_link_list) {
- count += atomic_read(&link->cg->ref.refcount);
- }
- read_unlock(&css_set_lock);
- return count;
-}
-
-/*
- * Advance a list_head iterator. The iterator should be positioned at
- * the start of a css_set
- */
-static void cgroup_advance_iter(struct cgroup *cgrp,
- struct cgroup_iter *it)
-{
- struct list_head *l = it->cg_link;
- struct cg_cgroup_link *link;
- struct css_set *cg;
-
- /* Advance to the next non-empty css_set */
- do {
- l = l->next;
- if (l == &cgrp->css_sets) {
- it->cg_link = NULL;
- return;
- }
- link = list_entry(l, struct cg_cgroup_link, cgrp_link_list);
- cg = link->cg;
- } while (list_empty(&cg->tasks));
- it->cg_link = l;
- it->task = cg->tasks.next;
-}
-
-/*
- * To reduce the fork() overhead for systems that are not actually
- * using their cgroups capability, we don't maintain the lists running
- * through each css_set to its tasks until we see the list actually
- * used - in other words after the first call to cgroup_iter_start().
- *
- * The tasklist_lock is not held here, as do_each_thread() and
- * while_each_thread() are protected by RCU.
- */
-static void cgroup_enable_task_cg_lists(void)
-{
- struct task_struct *p, *g;
- write_lock(&css_set_lock);
- use_task_css_set_links = 1;
- do_each_thread(g, p) {
- task_lock(p);
- /*
- * We should check if the process is exiting, otherwise
- * it will race with cgroup_exit() in that the list
- * entry won't be deleted though the process has exited.
- */
- if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
- list_add(&p->cg_list, &p->cgroups->tasks);
- task_unlock(p);
- } while_each_thread(g, p);
- write_unlock(&css_set_lock);
-}
-
-void cgroup_iter_start(struct cgroup *cgrp, struct cgroup_iter *it)
-{
- /*
- * The first time anyone tries to iterate across a cgroup,
- * we need to enable the list linking each css_set to its
- * tasks, and fix up all existing tasks.
- */
- if (!use_task_css_set_links)
- cgroup_enable_task_cg_lists();
-
- read_lock(&css_set_lock);
- it->cg_link = &cgrp->css_sets;
- cgroup_advance_iter(cgrp, it);
-}
-
-struct task_struct *cgroup_iter_next(struct cgroup *cgrp,
- struct cgroup_iter *it)
-{
- struct task_struct *res;
- struct list_head *l = it->task;
-
- /* If the iterator cg is NULL, we have no tasks */
- if (!it->cg_link)
- return NULL;
- res = list_entry(l, struct task_struct, cg_list);
- /* Advance iterator to find next entry */
- l = l->next;
- if (l == &res->cgroups->tasks) {
- /* We reached the end of this task list - move on to
- * the next cg_cgroup_link */
- cgroup_advance_iter(cgrp, it);
- } else {
- it->task = l;
- }
- return res;
-}
-
-void cgroup_iter_end(struct cgroup *cgrp, struct cgroup_iter *it)
-{
- read_unlock(&css_set_lock);
-}
-
-static inline int started_after_time(struct task_struct *t1,
- struct timespec *time,
- struct task_struct *t2)
-{
- int start_diff = timespec_compare(&t1->start_time, time);
- if (start_diff > 0) {
- return 1;
- } else if (start_diff < 0) {
- return 0;
- } else {
- /*
- * Arbitrarily, if two processes started at the same
- * time, we'll say that the lower pointer value
- * started first. Note that t2 may have exited by now
- * so this may not be a valid pointer any longer, but
- * that's fine - it still serves to distinguish
- * between two tasks started (effectively) simultaneously.
- */
- return t1 > t2;
- }
-}
-
-/*
- * This function is a callback from heap_insert() and is used to order
- * the heap.
- * In this case we order the heap in descending task start time.
- */
-static inline int started_after(void *p1, void *p2)
-{
- struct task_struct *t1 = p1;
- struct task_struct *t2 = p2;
- return started_after_time(t1, &t2->start_time, t2);
-}
-
-/**
- * cgroup_scan_tasks - iterate though all the tasks in a cgroup
- * @scan: struct cgroup_scanner containing arguments for the scan
- *
- * Arguments include pointers to callback functions test_task() and
- * process_task().
- * Iterate through all the tasks in a cgroup, calling test_task() for each,
- * and if it returns true, call process_task() for it also.
- * The test_task pointer may be NULL, meaning always true (select all tasks).
- * Effectively duplicates cgroup_iter_{start,next,end}()
- * but does not lock css_set_lock for the call to process_task().
- * The struct cgroup_scanner may be embedded in any structure of the caller's
- * creation.
- * It is guaranteed that process_task() will act on every task that
- * is a member of the cgroup for the duration of this call. This
- * function may or may not call process_task() for tasks that exit
- * or move to a different cgroup during the call, or are forked or
- * move into the cgroup during the call.
- *
- * Note that test_task() may be called with locks held, and may in some
- * situations be called multiple times for the same task, so it should
- * be cheap.
- * If the heap pointer in the struct cgroup_scanner is non-NULL, a heap has been
- * pre-allocated and will be used for heap operations (and its "gt" member will
- * be overwritten), else a temporary heap will be used (allocation of which
- * may cause this function to fail).
- */
-int cgroup_scan_tasks(struct cgroup_scanner *scan)
-{
- int retval, i;
- struct cgroup_iter it;
- struct task_struct *p, *dropped;
- /* Never dereference latest_task, since it's not refcounted */
- struct task_struct *latest_task = NULL;
- struct ptr_heap tmp_heap;
- struct ptr_heap *heap;
- struct timespec latest_time = { 0, 0 };
-
- if (scan->heap) {
- /* The caller supplied our heap and pre-allocated its memory */
- heap = scan->heap;
- heap->gt = &started_after;
- } else {
- /* We need to allocate our own heap memory */
- heap = &tmp_heap;
- retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
- if (retval)
- /* cannot allocate the heap */
- return retval;
- }
-
- again:
- /*
- * Scan tasks in the cgroup, using the scanner's "test_task" callback
- * to determine which are of interest, and using the scanner's
- * "process_task" callback to process any of them that need an update.
- * Since we don't want to hold any locks during the task updates,
- * gather tasks to be processed in a heap structure.
- * The heap is sorted by descending task start time.
- * If the statically-sized heap fills up, we overflow tasks that
- * started later, and in future iterations only consider tasks that
- * started after the latest task in the previous pass. This
- * guarantees forward progress and that we don't miss any tasks.
- */
- heap->size = 0;
- cgroup_iter_start(scan->cg, &it);
- while ((p = cgroup_iter_next(scan->cg, &it))) {
- /*
- * Only affect tasks that qualify per the caller's callback,
- * if he provided one
- */
- if (scan->test_task && !scan->test_task(p, scan))
- continue;
- /*
- * Only process tasks that started after the last task
- * we processed
- */
- if (!started_after_time(p, &latest_time, latest_task))
- continue;
- dropped = heap_insert(heap, p);
- if (dropped == NULL) {
- /*
- * The new task was inserted; the heap wasn't
- * previously full
- */
- get_task_struct(p);
- } else if (dropped != p) {
- /*
- * The new task was inserted, and pushed out a
- * different task
- */
- get_task_struct(p);
- put_task_struct(dropped);
- }
- /*
- * Else the new task was newer than anything already in
- * the heap and wasn't inserted
- */
- }
- cgroup_iter_end(scan->cg, &it);
-
- if (heap->size) {
- for (i = 0; i < heap->size; i++) {
- struct task_struct *q = heap->ptrs[i];
- if (i == 0) {
- latest_time = q->start_time;
- latest_task = q;
- }
- /* Process the task per the caller's callback */
- scan->process_task(q, scan);
- put_task_struct(q);
- }
- /*
- * If we had to process any tasks at all, scan again
- * in case some of them were in the middle of forking
- * children that didn't get processed.
- * Not the most efficient way to do it, but it avoids
- * having to take callback_mutex in the fork path
- */
- goto again;
- }
- if (heap == &tmp_heap)
- heap_free(&tmp_heap);
- return 0;
-}
-
-/*
- * Stuff for reading the 'tasks' file.
- *
- * Reading this file can return large amounts of data if a cgroup has
- * *lots* of attached tasks. So it may need several calls to read(),
- * but we cannot guarantee that the information we produce is correct
- * unless we produce it entirely atomically.
- *
- * Upon tasks file open(), a struct ctr_struct is allocated, that
- * will have a pointer to an array (also allocated here). The struct
- * ctr_struct * is stored in file->private_data. Its resources will
- * be freed by release() when the file is closed. The array is used
- * to sprintf the PIDs and then used by read().
- */
-struct ctr_struct {
- char *buf;
- int bufsz;
-};
-
-/*
- * Load into 'pidarray' up to 'npids' of the tasks using cgroup
- * 'cgrp'. Return actual number of pids loaded. No need to
- * task_lock(p) when reading out p->cgroup, since we're in an RCU
- * read section, so the css_set can't go away, and is
- * immutable after creation.
- */
-static int pid_array_load(pid_t *pidarray, int npids, struct cgroup *cgrp)
-{
- int n = 0;
- struct cgroup_iter it;
- struct task_struct *tsk;
- cgroup_iter_start(cgrp, &it);
- while ((tsk = cgroup_iter_next(cgrp, &it))) {
- if (unlikely(n == npids))
- break;
- pidarray[n++] = task_pid_vnr(tsk);
- }
- cgroup_iter_end(cgrp, &it);
- return n;
-}
-
-/**
- * cgroupstats_build - build and fill cgroupstats
- * @stats: cgroupstats to fill information into
- * @dentry: A dentry entry belonging to the cgroup for which stats have
- * been requested.
- *
- * Build and fill cgroupstats so that taskstats can export it to user
- * space.
- */
-int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
-{
- int ret = -EINVAL;
- struct cgroup *cgrp;
- struct cgroup_iter it;
- struct task_struct *tsk;
-
- /*
- * Validate dentry by checking the superblock operations,
- * and make sure it's a directory.
- */
- if (dentry->d_sb->s_op != &cgroup_ops ||
- !S_ISDIR(dentry->d_inode->i_mode))
- goto err;
-
- ret = 0;
- cgrp = dentry->d_fsdata;
- rcu_read_lock();
-
- cgroup_iter_start(cgrp, &it);
- while ((tsk = cgroup_iter_next(cgrp, &it))) {
- switch (tsk->state) {
- case TASK_RUNNING:
- stats->nr_running++;
- break;
- case TASK_INTERRUPTIBLE:
- stats->nr_sleeping++;
- break;
- case TASK_UNINTERRUPTIBLE:
- stats->nr_uninterruptible++;
- break;
- case TASK_STOPPED:
- stats->nr_stopped++;
- break;
- default:
- if (delayacct_is_task_waiting_on_io(tsk))
- stats->nr_io_wait++;
- break;
- }
- }
- cgroup_iter_end(cgrp, &it);
-
- rcu_read_unlock();
-err:
- return ret;
-}
-
-static int cmppid(const void *a, const void *b)
-{
- return *(pid_t *)a - *(pid_t *)b;
-}
-
-/*
- * Convert array 'a' of 'npids' pid_t's to a string of newline separated
- * decimal pids in 'buf'. Don't write more than 'sz' chars, but return
- * count 'cnt' of how many chars would be written if buf were large enough.
- */
-static int pid_array_to_buf(char *buf, int sz, pid_t *a, int npids)
-{
- int cnt = 0;
- int i;
-
- for (i = 0; i < npids; i++)
- cnt += snprintf(buf + cnt, max(sz - cnt, 0), "%d\n", a[i]);
- return cnt;
-}
-
-/*
- * Handle an open on 'tasks' file. Prepare a buffer listing the
- * process id's of tasks currently attached to the cgroup being opened.
- *
- * Does not require any specific cgroup mutexes, and does not take any.
- */
-static int cgroup_tasks_open(struct inode *unused, struct file *file)
-{
- struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
- struct ctr_struct *ctr;
- pid_t *pidarray;
- int npids;
- char c;
-
- if (!(file->f_mode & FMODE_READ))
- return 0;
-
- ctr = kmalloc(sizeof(*ctr), GFP_KERNEL);
- if (!ctr)
- goto err0;
-
- /*
- * If cgroup gets more users after we read count, we won't have
- * enough space - tough. This race is indistinguishable to the
- * caller from the case that the additional cgroup users didn't
- * show up until sometime later on.
- */
- npids = cgroup_task_count(cgrp);
- if (npids) {
- pidarray = kmalloc(npids * sizeof(pid_t), GFP_KERNEL);
- if (!pidarray)
- goto err1;
-
- npids = pid_array_load(pidarray, npids, cgrp);
- sort(pidarray, npids, sizeof(pid_t), cmppid, NULL);
-
- /* Call pid_array_to_buf() twice, first just to get bufsz */
- ctr->bufsz = pid_array_to_buf(&c, sizeof(c), pidarray, npids) + 1;
- ctr->buf = kmalloc(ctr->bufsz, GFP_KERNEL);
- if (!ctr->buf)
- goto err2;
- ctr->bufsz = pid_array_to_buf(ctr->buf, ctr->bufsz, pidarray, npids);
-
- kfree(pidarray);
- } else {
- ctr->buf = NULL;
- ctr->bufsz = 0;
- }
- file->private_data = ctr;
- return 0;
-
-err2:
- kfree(pidarray);
-err1:
- kfree(ctr);
-err0:
- return -ENOMEM;
-}
-
-static ssize_t cgroup_tasks_read(struct cgroup *cgrp,
- struct cftype *cft,
- struct file *file, char __user *buf,
- size_t nbytes, loff_t *ppos)
-{
- struct ctr_struct *ctr = file->private_data;
-
- return simple_read_from_buffer(buf, nbytes, ppos, ctr->buf, ctr->bufsz);
-}
-
-static int cgroup_tasks_release(struct inode *unused_inode,
- struct file *file)
-{
- struct ctr_struct *ctr;
-
- if (file->f_mode & FMODE_READ) {
- ctr = file->private_data;
- kfree(ctr->buf);
- kfree(ctr);
- }
- return 0;
-}
-
-static u64 cgroup_read_notify_on_release(struct cgroup *cgrp,
- struct cftype *cft)
-{
- return notify_on_release(cgrp);
-}
-
-static int cgroup_write_notify_on_release(struct cgroup *cgrp,
- struct cftype *cft,
- u64 val)
-{
- clear_bit(CGRP_RELEASABLE, &cgrp->flags);
- if (val)
- set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
- else
- clear_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
- return 0;
-}
-
-/*
- * for the common functions, 'private' gives the type of file
- */
-static struct cftype files[] = {
- {
- .name = "tasks",
- .open = cgroup_tasks_open,
- .read = cgroup_tasks_read,
- .write_u64 = cgroup_tasks_write,
- .release = cgroup_tasks_release,
- .private = FILE_TASKLIST,
- },
-
- {
- .name = "notify_on_release",
- .read_u64 = cgroup_read_notify_on_release,
- .write_u64 = cgroup_write_notify_on_release,
- .private = FILE_NOTIFY_ON_RELEASE,
- },
-};
-
-static struct cftype cft_release_agent = {
- .name = "release_agent",
- .read_seq_string = cgroup_release_agent_show,
- .write_string = cgroup_release_agent_write,
- .max_write_len = PATH_MAX,
- .private = FILE_RELEASE_AGENT,
-};
-
-static int cgroup_populate_dir(struct cgroup *cgrp)
-{
- int err;
- struct cgroup_subsys *ss;
-
- /* First clear out any existing files */
- cgroup_clear_directory(cgrp->dentry);
-
- err = cgroup_add_files(cgrp, NULL, files, ARRAY_SIZE(files));
- if (err < 0)
- return err;
-
- if (cgrp == cgrp->top_cgroup) {
- if ((err = cgroup_add_file(cgrp, NULL, &cft_release_agent)) < 0)
- return err;
- }
-
- for_each_subsys(cgrp->root, ss) {
- if (ss->populate && (err = ss->populate(ss, cgrp)) < 0)
- return err;
- }
-
- return 0;
-}
-
-static void init_cgroup_css(struct cgroup_subsys_state *css,
- struct cgroup_subsys *ss,
- struct cgroup *cgrp)
-{
- css->cgroup = cgrp;
- atomic_set(&css->refcnt, 0);
- css->flags = 0;
- if (cgrp == dummytop)
- set_bit(CSS_ROOT, &css->flags);
- BUG_ON(cgrp->subsys[ss->subsys_id]);
- cgrp->subsys[ss->subsys_id] = css;
-}
-
-/*
- * cgroup_create - create a cgroup
- * @parent: cgroup that will be parent of the new cgroup
- * @dentry: dentry of the new cgroup
- * @mode: mode to set on new inode
- *
- * Must be called with the mutex on the parent inode held
- */
-static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
- int mode)
-{
- struct cgroup *cgrp;
- struct cgroupfs_root *root = parent->root;
- int err = 0;
- struct cgroup_subsys *ss;
- struct super_block *sb = root->sb;
-
- cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
- if (!cgrp)
- return -ENOMEM;
-
- /* Grab a reference on the superblock so the hierarchy doesn't
- * get deleted on unmount if there are child cgroups. This
- * can be done outside cgroup_mutex, since the sb can't
- * disappear while someone has an open control file on the
- * fs */
- atomic_inc(&sb->s_active);
-
- mutex_lock(&cgroup_mutex);
-
- INIT_LIST_HEAD(&cgrp->sibling);
- INIT_LIST_HEAD(&cgrp->children);
- INIT_LIST_HEAD(&cgrp->css_sets);
- INIT_LIST_HEAD(&cgrp->release_list);
-
- cgrp->parent = parent;
- cgrp->root = parent->root;
- cgrp->top_cgroup = parent->top_cgroup;
-
- if (notify_on_release(parent))
- set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
-
- for_each_subsys(root, ss) {
- struct cgroup_subsys_state *css = ss->create(ss, cgrp);
- if (IS_ERR(css)) {
- err = PTR_ERR(css);
- goto err_destroy;
- }
- init_cgroup_css(css, ss, cgrp);
- }
-
- list_add(&cgrp->sibling, &cgrp->parent->children);
- root->number_of_cgroups++;
-
- err = cgroup_create_dir(cgrp, dentry, mode);
- if (err < 0)
- goto err_remove;
-
- /* The cgroup directory was pre-locked for us */
- BUG_ON(!mutex_is_locked(&cgrp->dentry->d_inode->i_mutex));
-
- err = cgroup_populate_dir(cgrp);
- /* If err < 0, we have a half-filled directory - oh well ;) */
-
- mutex_unlock(&cgroup_mutex);
- mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
-
- return 0;
-
- err_remove:
-
- list_del(&cgrp->sibling);
- root->number_of_cgroups--;
-
- err_destroy:
-
- for_each_subsys(root, ss) {
- if (cgrp->subsys[ss->subsys_id])
- ss->destroy(ss, cgrp);
- }
-
- mutex_unlock(&cgroup_mutex);
-
- /* Release the reference count that we took on the superblock */
- deactivate_super(sb);
-
- kfree(cgrp);
- return err;
-}
-
-static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, int mode)
-{
- struct cgroup *c_parent = dentry->d_parent->d_fsdata;
-
- /* the vfs holds inode->i_mutex already */
- return cgroup_create(c_parent, dentry, mode | S_IFDIR);
-}
-
-static int cgroup_has_css_refs(struct cgroup *cgrp)
-{
- /* Check the reference count on each subsystem. Since we
- * already established that there are no tasks in the
- * cgroup, if the css refcount is also 0, then there should
- * be no outstanding references, so the subsystem is safe to
- * destroy. We scan across all subsystems rather than using
- * the per-hierarchy linked list of mounted subsystems since
- * we can be called via check_for_release() with no
- * synchronization other than RCU, and the subsystem linked
- * list isn't RCU-safe */
- int i;
- for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
- struct cgroup_subsys *ss = subsys[i];
- struct cgroup_subsys_state *css;
- /* Skip subsystems not in this hierarchy */
- if (ss->root != cgrp->root)
- continue;
- css = cgrp->subsys[ss->subsys_id];
- /* When called from check_for_release() it's possible
- * that by this point the cgroup has been removed
- * and the css deleted. But a false-positive doesn't
- * matter, since it can only happen if the cgroup
- * has been deleted and hence no longer needs the
- * release agent to be called anyway. */
- if (css && atomic_read(&css->refcnt))
- return 1;
- }
- return 0;
-}
-
-static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
-{
- struct cgroup *cgrp = dentry->d_fsdata;
- struct dentry *d;
- struct cgroup *parent;
- struct super_block *sb;
- struct cgroupfs_root *root;
-
- /* the vfs holds both inode->i_mutex already */
-
- mutex_lock(&cgroup_mutex);
- if (atomic_read(&cgrp->count) != 0) {
- mutex_unlock(&cgroup_mutex);
- return -EBUSY;
- }
- if (!list_empty(&cgrp->children)) {
- mutex_unlock(&cgroup_mutex);
- return -EBUSY;
- }
-
- parent = cgrp->parent;
- root = cgrp->root;
- sb = root->sb;
-
- /*
- * Call pre_destroy handlers of subsys. Notify subsystems
- * that rmdir() request comes.
- */
- cgroup_call_pre_destroy(cgrp);
-
- if (cgroup_has_css_refs(cgrp)) {
- mutex_unlock(&cgroup_mutex);
- return -EBUSY;
- }
-
- spin_lock(&release_list_lock);
- set_bit(CGRP_REMOVED, &cgrp->flags);
- if (!list_empty(&cgrp->release_list))
- list_del(&cgrp->release_list);
- spin_unlock(&release_list_lock);
- /* delete my sibling from parent->children */
- list_del(&cgrp->sibling);
- spin_lock(&cgrp->dentry->d_lock);
- d = dget(cgrp->dentry);
- spin_unlock(&d->d_lock);
-
- cgroup_d_remove_dir(d);
- dput(d);
-
- set_bit(CGRP_RELEASABLE, &parent->flags);
- check_for_release(parent);
-
- mutex_unlock(&cgroup_mutex);
- return 0;
-}
-
-static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
-{
- struct cgroup_subsys_state *css;
-
- printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
-
- /* Create the top cgroup state for this subsystem */
- ss->root = &rootnode;
- css = ss->create(ss, dummytop);
- /* We don't handle early failures gracefully */
- BUG_ON(IS_ERR(css));
- init_cgroup_css(css, ss, dummytop);
-
- /* Update the init_css_set to contain a subsys
- * pointer to this state - since the subsystem is
- * newly registered, all tasks and hence the
- * init_css_set is in the subsystem's top cgroup. */
- init_css_set.subsys[ss->subsys_id] = dummytop->subsys[ss->subsys_id];
-
- need_forkexit_callback |= ss->fork || ss->exit;
- need_mm_owner_callback |= !!ss->mm_owner_changed;
-
- /* At system boot, before all subsystems have been
- * registered, no tasks have been forked, so we don't
- * need to invoke fork callbacks here. */
- BUG_ON(!list_empty(&init_task.tasks));
-
- ss->active = 1;
-}
-
-/**
- * cgroup_init_early - cgroup initialization at system boot
- *
- * Initialize cgroups at system boot, and initialize any
- * subsystems that request early init.
- */
-int __init cgroup_init_early(void)
-{
- int i;
- kref_init(&init_css_set.ref);
- kref_get(&init_css_set.ref);
- INIT_LIST_HEAD(&init_css_set.cg_links);
- INIT_LIST_HEAD(&init_css_set.tasks);
- INIT_HLIST_NODE(&init_css_set.hlist);
- css_set_count = 1;
- init_cgroup_root(&rootnode);
- list_add(&rootnode.root_list, &roots);
- root_count = 1;
- init_task.cgroups = &init_css_set;
-
- init_css_set_link.cg = &init_css_set;
- list_add(&init_css_set_link.cgrp_link_list,
- &rootnode.top_cgroup.css_sets);
- list_add(&init_css_set_link.cg_link_list,
- &init_css_set.cg_links);
-
- for (i = 0; i < CSS_SET_TABLE_SIZE; i++)
- INIT_HLIST_HEAD(&css_set_table[i]);
-
- for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
- struct cgroup_subsys *ss = subsys[i];
-
- BUG_ON(!ss->name);
- BUG_ON(strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN);
- BUG_ON(!ss->create);
- BUG_ON(!ss->destroy);
- if (ss->subsys_id != i) {
- printk(KERN_ERR "cgroup: Subsys %s id == %d\n",
- ss->name, ss->subsys_id);
- BUG();
- }
-
- if (ss->early_init)
- cgroup_init_subsys(ss);
- }
- return 0;
-}
-
-/**
- * cgroup_init - cgroup initialization
- *
- * Register cgroup filesystem and /proc file, and initialize
- * any subsystems that didn't request early init.
- */
-int __init cgroup_init(void)
-{
- int err;
- int i;
- struct hlist_head *hhead;
-
- err = bdi_init(&cgroup_backing_dev_info);
- if (err)
- return err;
-
- for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
- struct cgroup_subsys *ss = subsys[i];
- if (!ss->early_init)
- cgroup_init_subsys(ss);
- }
-
- /* Add init_css_set to the hash table */
- hhead = css_set_hash(init_css_set.subsys);
- hlist_add_head(&init_css_set.hlist, hhead);
-
- err = register_filesystem(&cgroup_fs_type);
- if (err < 0)
- goto out;
-
- proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
-
-out:
- if (err)
- bdi_destroy(&cgroup_backing_dev_info);
-
- return err;
-}
-
-/*
- * proc_cgroup_show()
- * - Print task's cgroup paths into seq_file, one line for each hierarchy
- * - Used for /proc//cgroup.
- * - No need to task_lock(tsk) on this tsk->cgroup reference, as it
- * doesn't really matter if tsk->cgroup changes after we read it,
- * and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
- * anyway. No need to check that tsk->cgroup != NULL, thanks to
- * the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
- * cgroup to top_cgroup.
- */
-
-/* TODO: Use a proper seq_file iterator */
-static int proc_cgroup_show(struct seq_file *m, void *v)
-{
- struct pid *pid;
- struct task_struct *tsk;
- char *buf;
- int retval;
- struct cgroupfs_root *root;
-
- retval = -ENOMEM;
- buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
- if (!buf)
- goto out;
-
- retval = -ESRCH;
- pid = m->private;
- tsk = get_pid_task(pid, PIDTYPE_PID);
- if (!tsk)
- goto out_free;
-
- retval = 0;
-
- mutex_lock(&cgroup_mutex);
-
- for_each_root(root) {
- struct cgroup_subsys *ss;
- struct cgroup *cgrp;
- int subsys_id;
- int count = 0;
-
- /* Skip this hierarchy if it has no active subsystems */
- if (!root->actual_subsys_bits)
- continue;
- seq_printf(m, "%lu:", root->subsys_bits);
- for_each_subsys(root, ss)
- seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
- seq_putc(m, ':');
- get_first_subsys(&root->top_cgroup, NULL, &subsys_id);
- cgrp = task_cgroup(tsk, subsys_id);
- retval = cgroup_path(cgrp, buf, PAGE_SIZE);
- if (retval < 0)
- goto out_unlock;
- seq_puts(m, buf);
- seq_putc(m, '\n');
- }
-
-out_unlock:
- mutex_unlock(&cgroup_mutex);
- put_task_struct(tsk);
-out_free:
- kfree(buf);
-out:
- return retval;
-}
-
-static int cgroup_open(struct inode *inode, struct file *file)
-{
- struct pid *pid = PROC_I(inode)->pid;
- return single_open(file, proc_cgroup_show, pid);
-}
-
-struct file_operations proc_cgroup_operations = {
- .open = cgroup_open,
- .read = seq_read,
- .llseek = seq_lseek,
- .release = single_release,
-};
-
-/* Display information about each subsystem and each hierarchy */
-static int proc_cgroupstats_show(struct seq_file *m, void *v)
-{
- int i;
-
- seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
- mutex_lock(&cgroup_mutex);
- for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
- struct cgroup_subsys *ss = subsys[i];
- seq_printf(m, "%s\t%lu\t%d\t%d\n",
- ss->name, ss->root->subsys_bits,
- ss->root->number_of_cgroups, !ss->disabled);
- }
- mutex_unlock(&cgroup_mutex);
- return 0;
-}
-
-static int cgroupstats_open(struct inode *inode, struct file *file)
-{
- return single_open(file, proc_cgroupstats_show, NULL);
-}
-
-static struct file_operations proc_cgroupstats_operations = {
- .open = cgroupstats_open,
- .read = seq_read,
- .llseek = seq_lseek,
- .release = single_release,
-};
-
-/**
- * cgroup_fork - attach newly forked task to its parents cgroup.
- * @child: pointer to task_struct of forking parent process.
- *
- * Description: A task inherits its parent's cgroup at fork().
- *
- * A pointer to the shared css_set was automatically copied in
- * fork.c by dup_task_struct(). However, we ignore that copy, since
- * it was not made under the protection of RCU or cgroup_mutex, so
- * might no longer be a valid cgroup pointer. cgroup_attach_task() might
- * have already changed current->cgroups, allowing the previously
- * referenced cgroup group to be removed and freed.
- *
- * At the point that cgroup_fork() is called, 'current' is the parent
- * task, and the passed argument 'child' points to the child task.
- */
-void cgroup_fork(struct task_struct *child)
-{
- task_lock(current);
- child->cgroups = current->cgroups;
- get_css_set(child->cgroups);
- task_unlock(current);
- INIT_LIST_HEAD(&child->cg_list);
-}
-
-/**
- * cgroup_fork_callbacks - run fork callbacks
- * @child: the new task
- *
- * Called on a new task very soon before adding it to the
- * tasklist. No need to take any locks since no-one can
- * be operating on this task.
- */
-void cgroup_fork_callbacks(struct task_struct *child)
-{
- if (need_forkexit_callback) {
- int i;
- for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
- struct cgroup_subsys *ss = subsys[i];
- if (ss->fork)
- ss->fork(ss, child);
- }
- }
-}
-
-#ifdef CONFIG_MM_OWNER
-/**
- * cgroup_mm_owner_callbacks - run callbacks when the mm->owner changes
- * @p: the new owner
- *
- * Called on every change to mm->owner. mm_init_owner() does not
- * invoke this routine, since it assigns the mm->owner the first time
- * and does not change it.
- */
-void cgroup_mm_owner_callbacks(struct task_struct *old, struct task_struct *new)
-{
- struct cgroup *oldcgrp, *newcgrp = NULL;
-
- if (need_mm_owner_callback) {
- int i;
- for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
- struct cgroup_subsys *ss = subsys[i];
- oldcgrp = task_cgroup(old, ss->subsys_id);
- if (new)
- newcgrp = task_cgroup(new, ss->subsys_id);
- if (oldcgrp == newcgrp)
- continue;
- if (ss->mm_owner_changed)
- ss->mm_owner_changed(ss, oldcgrp, newcgrp);
- }
- }
-}
-#endif /* CONFIG_MM_OWNER */
-
-/**
- * cgroup_post_fork - called on a new task after adding it to the task list
- * @child: the task in question
- *
- * Adds the task to the list running through its css_set if necessary.
- * Has to be after the task is visible on the task list in case we race
- * with the first call to cgroup_iter_start() - to guarantee that the
- * new task ends up on its list.
- */
-void cgroup_post_fork(struct task_struct *child)
-{
- if (use_task_css_set_links) {
- write_lock(&css_set_lock);
- if (list_empty(&child->cg_list))
- list_add(&child->cg_list, &child->cgroups->tasks);
- write_unlock(&css_set_lock);
- }
-}
-/**
- * cgroup_exit - detach cgroup from exiting task
- * @tsk: pointer to task_struct of exiting process
- * @run_callback: run exit callbacks?
- *
- * Description: Detach cgroup from @tsk and release it.
- *
- * Note that cgroups marked notify_on_release force every task in
- * them to take the global cgroup_mutex mutex when exiting.
- * This could impact scaling on very large systems. Be reluctant to
- * use notify_on_release cgroups where very high task exit scaling
- * is required on large systems.
- *
- * the_top_cgroup_hack:
- *
- * Set the exiting tasks cgroup to the root cgroup (top_cgroup).
- *
- * We call cgroup_exit() while the task is still competent to
- * handle notify_on_release(), then leave the task attached to the
- * root cgroup in each hierarchy for the remainder of its exit.
- *
- * To do this properly, we would increment the reference count on
- * top_cgroup, and near the very end of the kernel/exit.c do_exit()
- * code we would add a second cgroup function call, to drop that
- * reference. This would just create an unnecessary hot spot on
- * the top_cgroup reference count, to no avail.
- *
- * Normally, holding a reference to a cgroup without bumping its
- * count is unsafe. The cgroup could go away, or someone could
- * attach us to a different cgroup, decrementing the count on
- * the first cgroup that we never incremented. But in this case,
- * top_cgroup isn't going away, and either task has PF_EXITING set,
- * which wards off any cgroup_attach_task() attempts, or task is a failed
- * fork, never visible to cgroup_attach_task.
- */
-void cgroup_exit(struct task_struct *tsk, int run_callbacks)
-{
- int i;
- struct css_set *cg;
-
- if (run_callbacks && need_forkexit_callback) {
- for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
- struct cgroup_subsys *ss = subsys[i];
- if (ss->exit)
- ss->exit(ss, tsk);
- }
- }
-
- /*
- * Unlink from the css_set task list if necessary.
- * Optimistically check cg_list before taking
- * css_set_lock
- */
- if (!list_empty(&tsk->cg_list)) {
- write_lock(&css_set_lock);
- if (!list_empty(&tsk->cg_list))
- list_del(&tsk->cg_list);
- write_unlock(&css_set_lock);
- }
-
- /* Reassign the task to the init_css_set. */
- task_lock(tsk);
- cg = tsk->cgroups;
- tsk->cgroups = &init_css_set;
- task_unlock(tsk);
- if (cg)
- put_css_set_taskexit(cg);
-}
-
-/**
- * cgroup_clone - clone the cgroup the given subsystem is attached to
- * @tsk: the task to be moved
- * @subsys: the given subsystem
- * @nodename: the name for the new cgroup
- *
- * Duplicate the current cgroup in the hierarchy that the given
- * subsystem is attached to, and move this task into the new
- * child.
- */
-int cgroup_clone(struct task_struct *tsk, struct cgroup_subsys *subsys,
- char *nodename)
-{
- struct dentry *dentry;
- int ret = 0;
- struct cgroup *parent, *child;
- struct inode *inode;
- struct css_set *cg;
- struct cgroupfs_root *root;
- struct cgroup_subsys *ss;
-
- /* We shouldn't be called by an unregistered subsystem */
- BUG_ON(!subsys->active);
-
- /* First figure out what hierarchy and cgroup we're dealing
- * with, and pin them so we can drop cgroup_mutex */
- mutex_lock(&cgroup_mutex);
- again:
- root = subsys->root;
- if (root == &rootnode) {
- printk(KERN_INFO
- "Not cloning cgroup for unused subsystem %s\n",
- subsys->name);
- mutex_unlock(&cgroup_mutex);
- return 0;
- }
- cg = tsk->cgroups;
- parent = task_cgroup(tsk, subsys->subsys_id);
-
- /* Pin the hierarchy */
- if (!atomic_inc_not_zero(&parent->root->sb->s_active)) {
- /* We race with the final deactivate_super() */
- mutex_unlock(&cgroup_mutex);
- return 0;
- }
-
- /* Keep the cgroup alive */
- get_css_set(cg);
- mutex_unlock(&cgroup_mutex);
-
- /* Now do the VFS work to create a cgroup */
- inode = parent->dentry->d_inode;
-
- /* Hold the parent directory mutex across this operation to
- * stop anyone else deleting the new cgroup */
- mutex_lock(&inode->i_mutex);
- dentry = lookup_one_len(nodename, parent->dentry, strlen(nodename));
- if (IS_ERR(dentry)) {
- printk(KERN_INFO
- "cgroup: Couldn't allocate dentry for %s: %ld\n", nodename,
- PTR_ERR(dentry));
- ret = PTR_ERR(dentry);
- goto out_release;
- }
-
- /* Create the cgroup directory, which also creates the cgroup */
- ret = vfs_mkdir(inode, dentry, S_IFDIR | 0755);
- child = __d_cgrp(dentry);
- dput(dentry);
- if (ret) {
- printk(KERN_INFO
- "Failed to create cgroup %s: %d\n", nodename,
- ret);
- goto out_release;
- }
-
- if (!child) {
- printk(KERN_INFO
- "Couldn't find new cgroup %s\n", nodename);
- ret = -ENOMEM;
- goto out_release;
- }
-
- /* The cgroup now exists. Retake cgroup_mutex and check
- * that we're still in the same state that we thought we
- * were. */
- mutex_lock(&cgroup_mutex);
- if ((root != subsys->root) ||
- (parent != task_cgroup(tsk, subsys->subsys_id))) {
- /* Aargh, we raced ... */
- mutex_unlock(&inode->i_mutex);
- put_css_set(cg);
-
- deactivate_super(parent->root->sb);
- /* The cgroup is still accessible in the VFS, but
- * we're not going to try to rmdir() it at this
- * point. */
- printk(KERN_INFO
- "Race in cgroup_clone() - leaking cgroup %s\n",
- nodename);
- goto again;
- }
-
- /* do any required auto-setup */
- for_each_subsys(root, ss) {
- if (ss->post_clone)
- ss->post_clone(ss, child);
- }
-
- /* All seems fine. Finish by moving the task into the new cgroup */
- ret = cgroup_attach_task(child, tsk);
- mutex_unlock(&cgroup_mutex);
-
- out_release:
- mutex_unlock(&inode->i_mutex);
-
- mutex_lock(&cgroup_mutex);
- put_css_set(cg);
- mutex_unlock(&cgroup_mutex);
- deactivate_super(parent->root->sb);
- return ret;
-}
-
-/**
- * cgroup_is_descendant - see if @cgrp is a descendant of current task's cgrp
- * @cgrp: the cgroup in question
- *
- * See if @cgrp is a descendant of the current task's cgroup in
- * the appropriate hierarchy.
- *
- * If we are sending in dummytop, then presumably we are creating
- * the top cgroup in the subsystem.
- *
- * Called only by the ns (nsproxy) cgroup.
- */
-int cgroup_is_descendant(const struct cgroup *cgrp)
-{
- int ret;
- struct cgroup *target;
- int subsys_id;
-
- if (cgrp == dummytop)
- return 1;
-
- get_first_subsys(cgrp, NULL, &subsys_id);
- target = task_cgroup(current, subsys_id);
- while (cgrp != target && cgrp!= cgrp->top_cgroup)
- cgrp = cgrp->parent;
- ret = (cgrp == target);
- return ret;
-}
-
-static void check_for_release(struct cgroup *cgrp)
-{
- /* All of these checks rely on RCU to keep the cgroup
- * structure alive */
- if (cgroup_is_releasable(cgrp) && !atomic_read(&cgrp->count)
- && list_empty(&cgrp->children) && !cgroup_has_css_refs(cgrp)) {
- /* Control Group is currently removeable. If it's not
- * already queued for a userspace notification, queue
- * it now */
- int need_schedule_work = 0;
- spin_lock(&release_list_lock);
- if (!cgroup_is_removed(cgrp) &&
- list_empty(&cgrp->release_list)) {
- list_add(&cgrp->release_list, &release_list);
- need_schedule_work = 1;
- }
- spin_unlock(&release_list_lock);
- if (need_schedule_work)
- schedule_work(&release_agent_work);
- }
-}
-
-void __css_put(struct cgroup_subsys_state *css)
-{
- struct cgroup *cgrp = css->cgroup;
- rcu_read_lock();
- if (atomic_dec_and_test(&css->refcnt) && notify_on_release(cgrp)) {
- set_bit(CGRP_RELEASABLE, &cgrp->flags);
- check_for_release(cgrp);
- }
- rcu_read_unlock();
-}
-
-/*
- * Notify userspace when a cgroup is released, by running the
- * configured release agent with the name of the cgroup (path
- * relative to the root of cgroup file system) as the argument.
- *
- * Most likely, this user command will try to rmdir this cgroup.
- *
- * This races with the possibility that some other task will be
- * attached to this cgroup before it is removed, or that some other
- * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
- * The presumed 'rmdir' will fail quietly if this cgroup is no longer
- * unused, and this cgroup will be reprieved from its death sentence,
- * to continue to serve a useful existence. Next time it's released,
- * we will get notified again, if it still has 'notify_on_release' set.
- *
- * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
- * means only wait until the task is successfully execve()'d. The
- * separate release agent task is forked by call_usermodehelper(),
- * then control in this thread returns here, without waiting for the
- * release agent task. We don't bother to wait because the caller of
- * this routine has no use for the exit status of the release agent
- * task, so no sense holding our caller up for that.
- */
-static void cgroup_release_agent(struct work_struct *work)
-{
- BUG_ON(work != &release_agent_work);
- mutex_lock(&cgroup_mutex);
- spin_lock(&release_list_lock);
- while (!list_empty(&release_list)) {
- char *argv[3], *envp[3];
- int i;
- char *pathbuf = NULL, *agentbuf = NULL;
- struct cgroup *cgrp = list_entry(release_list.next,
- struct cgroup,
- release_list);
- list_del_init(&cgrp->release_list);
- spin_unlock(&release_list_lock);
- pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
- if (!pathbuf)
- goto continue_free;
- if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
- goto continue_free;
- agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
- if (!agentbuf)
- goto continue_free;
-
- i = 0;
- argv[i++] = agentbuf;
- argv[i++] = pathbuf;
- argv[i] = NULL;
-
- i = 0;
- /* minimal command environment */
- envp[i++] = "HOME=/";
- envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
- envp[i] = NULL;
-
- /* Drop the lock while we invoke the usermode helper,
- * since the exec could involve hitting disk and hence
- * be a slow process */
- mutex_unlock(&cgroup_mutex);
- call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
- mutex_lock(&cgroup_mutex);
- continue_free:
- kfree(pathbuf);
- kfree(agentbuf);
- spin_lock(&release_list_lock);
- }
- spin_unlock(&release_list_lock);
- mutex_unlock(&cgroup_mutex);
-}
-
-static int __init cgroup_disable(char *str)
-{
- int i;
- char *token;
-
- while ((token = strsep(&str, ",")) != NULL) {
- if (!*token)
- continue;
-
- for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
- struct cgroup_subsys *ss = subsys[i];
-
- if (!strcmp(token, ss->name)) {
- ss->disabled = 1;
- printk(KERN_INFO "Disabling %s control group"
- " subsystem\n", ss->name);
- break;
- }
- }
- }
- return 1;
-}
-__setup("cgroup_disable=", cgroup_disable);
-/*
- * kernel/cgroup_debug.c - Example cgroup subsystem that
- * exposes debug info
- *
- * Copyright (C) Google Inc, 2007
- *
- * Developed by Paul Menage (menage@google.com)
- *
- */
-
-#include
-#include
-#include
-#include
-
-#include
-
-static struct cgroup_subsys_state *debug_create(struct cgroup_subsys *ss,
- struct cgroup *cont)
-{
- struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
-
- if (!css)
- return ERR_PTR(-ENOMEM);
-
- return css;
-}
-
-static void debug_destroy(struct cgroup_subsys *ss, struct cgroup *cont)
-{
- kfree(cont->subsys[debug_subsys_id]);
-}
-
-static u64 cgroup_refcount_read(struct cgroup *cont, struct cftype *cft)
-{
- return atomic_read(&cont->count);
-}
-
-static u64 taskcount_read(struct cgroup *cont, struct cftype *cft)
-{
- u64 count;
-
- cgroup_lock();
- count = cgroup_task_count(cont);
- cgroup_unlock();
- return count;
-}
-
-static u64 current_css_set_read(struct cgroup *cont, struct cftype *cft)
-{
- return (u64)(long)current->cgroups;
-}
-
-static u64 current_css_set_refcount_read(struct cgroup *cont,
- struct cftype *cft)
-{
- u64 count;
-
- rcu_read_lock();
- count = atomic_read(¤t->cgroups->ref.refcount);
- rcu_read_unlock();
- return count;
-}
-
-static u64 releasable_read(struct cgroup *cgrp, struct cftype *cft)
-{
- return test_bit(CGRP_RELEASABLE, &cgrp->flags);
-}
-
-static struct cftype files[] = {
- {
- .name = "cgroup_refcount",
- .read_u64 = cgroup_refcount_read,
- },
- {
- .name = "taskcount",
- .read_u64 = taskcount_read,
- },
-
- {
- .name = "current_css_set",
- .read_u64 = current_css_set_read,
- },
-
- {
- .name = "current_css_set_refcount",
- .read_u64 = current_css_set_refcount_read,
- },
-
- {
- .name = "releasable",
- .read_u64 = releasable_read,
- }
-};
-
-static int debug_populate(struct cgroup_subsys *ss, struct cgroup *cont)
-{
- return cgroup_add_files(cont, ss, files, ARRAY_SIZE(files));
-}
-
-struct cgroup_subsys debug_subsys = {
- .name = "debug",
- .create = debug_create,
- .destroy = debug_destroy,
- .populate = debug_populate,
- .subsys_id = debug_subsys_id,
-};
-/*
- * linux/kernel/compat.c
- *
- * Kernel compatibililty routines for e.g. 32 bit syscall support
- * on 64 bit kernels.
- *
- * Copyright (C) 2002-2003 Stephen Rothwell, IBM Corporation
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License version 2 as
- * published by the Free Software Foundation.
- */
-
-#include
-#include
-#include
-#include
-#include
-#include /* for MAX_SCHEDULE_TIMEOUT */
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-
-#include
-
-int get_compat_timespec(struct timespec *ts, const struct compat_timespec __user *cts)
-{
- return (!access_ok(VERIFY_READ, cts, sizeof(*cts)) ||
- __get_user(ts->tv_sec, &cts->tv_sec) ||
- __get_user(ts->tv_nsec, &cts->tv_nsec)) ? -EFAULT : 0;
-}
-
-int put_compat_timespec(const struct timespec *ts, struct compat_timespec __user *cts)
-{
- return (!access_ok(VERIFY_WRITE, cts, sizeof(*cts)) ||
- __put_user(ts->tv_sec, &cts->tv_sec) ||
- __put_user(ts->tv_nsec, &cts->tv_nsec)) ? -EFAULT : 0;
-}
-
-static long compat_nanosleep_restart(struct restart_block *restart)
-{
- struct compat_timespec __user *rmtp;
- struct timespec rmt;
- mm_segment_t oldfs;
- long ret;
-
- restart->nanosleep.rmtp = (struct timespec __user *) &rmt;
- oldfs = get_fs();
- set_fs(KERNEL_DS);
- ret = hrtimer_nanosleep_restart(restart);
- set_fs(oldfs);
-
- if (ret) {
- rmtp = restart->nanosleep.compat_rmtp;
-
- if (rmtp && put_compat_timespec(&rmt, rmtp))
- return -EFAULT;
- }
-
- return ret;
-}
-
-asmlinkage long compat_sys_nanosleep(struct compat_timespec __user *rqtp,
- struct compat_timespec __user *rmtp)
-{
- struct timespec tu, rmt;
- mm_segment_t oldfs;
- long ret;
-
- if (get_compat_timespec(&tu, rqtp))
- return -EFAULT;
-
- if (!timespec_valid(&tu))
- return -EINVAL;
-
- oldfs = get_fs();
- set_fs(KERNEL_DS);
- ret = hrtimer_nanosleep(&tu,
- rmtp ? (struct timespec __user *)&rmt : NULL,
- HRTIMER_MODE_REL, CLOCK_MONOTONIC);
- set_fs(oldfs);
-
- if (ret) {
- struct restart_block *restart
- = ¤t_thread_info()->restart_block;
-
- restart->fn = compat_nanosleep_restart;
- restart->nanosleep.compat_rmtp = rmtp;
-
- if (rmtp && put_compat_timespec(&rmt, rmtp))
- return -EFAULT;
- }
-
- return ret;
-}
-
-static inline long get_compat_itimerval(struct itimerval *o,
- struct compat_itimerval __user *i)
-{
- return (!access_ok(VERIFY_READ, i, sizeof(*i)) ||
- (__get_user(o->it_interval.tv_sec, &i->it_interval.tv_sec) |
- __get_user(o->it_interval.tv_usec, &i->it_interval.tv_usec) |
- __get_user(o->it_value.tv_sec, &i->it_value.tv_sec) |
- __get_user(o->it_value.tv_usec, &i->it_value.tv_usec)));
-}
-
-static inline long put_compat_itimerval(struct compat_itimerval __user *o,
- struct itimerval *i)
-{
- return (!access_ok(VERIFY_WRITE, o, sizeof(*o)) ||
- (__put_user(i->it_interval.tv_sec, &o->it_interval.tv_sec) |
- __put_user(i->it_interval.tv_usec, &o->it_interval.tv_usec) |
- __put_user(i->it_value.tv_sec, &o->it_value.tv_sec) |
- __put_user(i->it_value.tv_usec, &o->it_value.tv_usec)));
-}
-
-asmlinkage long compat_sys_getitimer(int which,
- struct compat_itimerval __user *it)
-{
- struct itimerval kit;
- int error;
-
- error = do_getitimer(which, &kit);
- if (!error && put_compat_itimerval(it, &kit))
- error = -EFAULT;
- return error;
-}
-
-asmlinkage long compat_sys_setitimer(int which,
- struct compat_itimerval __user *in,
- struct compat_itimerval __user *out)
-{
- struct itimerval kin, kout;
- int error;
-
- if (in) {
- if (get_compat_itimerval(&kin, in))
- return -EFAULT;
- } else
- memset(&kin, 0, sizeof(kin));
-
- error = do_setitimer(which, &kin, out ? &kout : NULL);
- if (error || !out)
- return error;
- if (put_compat_itimerval(out, &kout))
- return -EFAULT;
- return 0;
-}
-
-asmlinkage long compat_sys_times(struct compat_tms __user *tbuf)
-{
- /*
- * In the SMP world we might just be unlucky and have one of
- * the times increment as we use it. Since the value is an
- * atomically safe type this is just fine. Conceptually its
- * as if the syscall took an instant longer to occur.
- */
- if (tbuf) {
- struct compat_tms tmp;
- struct task_struct *tsk = current;
- struct task_struct *t;
- cputime_t utime, stime, cutime, cstime;
-
- read_lock(&tasklist_lock);
- utime = tsk->signal->utime;
- stime = tsk->signal->stime;
- t = tsk;
- do {
- utime = cputime_add(utime, t->utime);
- stime = cputime_add(stime, t->stime);
- t = next_thread(t);
- } while (t != tsk);
-
- /*
- * While we have tasklist_lock read-locked, no dying thread
- * can be updating current->signal->[us]time. Instead,
- * we got their counts included in the live thread loop.
- * However, another thread can come in right now and
- * do a wait call that updates current->signal->c[us]time.
- * To make sure we always see that pair updated atomically,
- * we take the siglock around fetching them.
- */
- spin_lock_irq(&tsk->sighand->siglock);
- cutime = tsk->signal->cutime;
- cstime = tsk->signal->cstime;
- spin_unlock_irq(&tsk->sighand->siglock);
- read_unlock(&tasklist_lock);
-
- tmp.tms_utime = compat_jiffies_to_clock_t(cputime_to_jiffies(utime));
- tmp.tms_stime = compat_jiffies_to_clock_t(cputime_to_jiffies(stime));
- tmp.tms_cutime = compat_jiffies_to_clock_t(cputime_to_jiffies(cutime));
- tmp.tms_cstime = compat_jiffies_to_clock_t(cputime_to_jiffies(cstime));
- if (copy_to_user(tbuf, &tmp, sizeof(tmp)))
- return -EFAULT;
- }
- return compat_jiffies_to_clock_t(jiffies);
-}
-
-/*
- * Assumption: old_sigset_t and compat_old_sigset_t are both
- * types that can be passed to put_user()/get_user().
- */
-
-asmlinkage long compat_sys_sigpending(compat_old_sigset_t __user *set)
-{
- old_sigset_t s;
- long ret;
- mm_segment_t old_fs = get_fs();
-
- set_fs(KERNEL_DS);
- ret = sys_sigpending((old_sigset_t __user *) &s);
- set_fs(old_fs);
- if (ret == 0)
- ret = put_user(s, set);
- return ret;
-}
-
-asmlinkage long compat_sys_sigprocmask(int how, compat_old_sigset_t __user *set,
- compat_old_sigset_t __user *oset)
-{
- old_sigset_t s;
- long ret;
- mm_segment_t old_fs;
-
- if (set && get_user(s, set))
- return -EFAULT;
- old_fs = get_fs();
- set_fs(KERNEL_DS);
- ret = sys_sigprocmask(how,
- set ? (old_sigset_t __user *) &s : NULL,
- oset ? (old_sigset_t __user *) &s : NULL);
- set_fs(old_fs);
- if (ret == 0)
- if (oset)
- ret = put_user(s, oset);
- return ret;
-}
-
-asmlinkage long compat_sys_setrlimit(unsigned int resource,
- struct compat_rlimit __user *rlim)
-{
- struct rlimit r;
- int ret;
- mm_segment_t old_fs = get_fs ();
-
- if (resource >= RLIM_NLIMITS)
- return -EINVAL;
-
- if (!access_ok(VERIFY_READ, rlim, sizeof(*rlim)) ||
- __get_user(r.rlim_cur, &rlim->rlim_cur) ||
- __get_user(r.rlim_max, &rlim->rlim_max))
- return -EFAULT;
-
- if (r.rlim_cur == COMPAT_RLIM_INFINITY)
- r.rlim_cur = RLIM_INFINITY;
- if (r.rlim_max == COMPAT_RLIM_INFINITY)
- r.rlim_max = RLIM_INFINITY;
- set_fs(KERNEL_DS);
- ret = sys_setrlimit(resource, (struct rlimit __user *) &r);
- set_fs(old_fs);
- return ret;
-}
-
-#ifdef COMPAT_RLIM_OLD_INFINITY
-
-asmlinkage long compat_sys_old_getrlimit(unsigned int resource,
- struct compat_rlimit __user *rlim)
-{
- struct rlimit r;
- int ret;
- mm_segment_t old_fs = get_fs();
-
- set_fs(KERNEL_DS);
- ret = sys_old_getrlimit(resource, &r);
- set_fs(old_fs);
-
- if (!ret) {
- if (r.rlim_cur > COMPAT_RLIM_OLD_INFINITY)
- r.rlim_cur = COMPAT_RLIM_INFINITY;
- if (r.rlim_max > COMPAT_RLIM_OLD_INFINITY)
- r.rlim_max = COMPAT_RLIM_INFINITY;
-
- if (!access_ok(VERIFY_WRITE, rlim, sizeof(*rlim)) ||
- __put_user(r.rlim_cur, &rlim->rlim_cur) ||
- __put_user(r.rlim_max, &rlim->rlim_max))
- return -EFAULT;
- }
- return ret;
-}
-
-#endif
-
-asmlinkage long compat_sys_getrlimit (unsigned int resource,
- struct compat_rlimit __user *rlim)
-{
- struct rlimit r;
- int ret;
- mm_segment_t old_fs = get_fs();
-
- set_fs(KERNEL_DS);
- ret = sys_getrlimit(resource, (struct rlimit __user *) &r);
- set_fs(old_fs);
- if (!ret) {
- if (r.rlim_cur > COMPAT_RLIM_INFINITY)
- r.rlim_cur = COMPAT_RLIM_INFINITY;
- if (r.rlim_max > COMPAT_RLIM_INFINITY)
- r.rlim_max = COMPAT_RLIM_INFINITY;
-
- if (!access_ok(VERIFY_WRITE, rlim, sizeof(*rlim)) ||
- __put_user(r.rlim_cur, &rlim->rlim_cur) ||
- __put_user(r.rlim_max, &rlim->rlim_max))
- return -EFAULT;
- }
- return ret;
-}
-
-int put_compat_rusage(const struct rusage *r, struct compat_rusage __user *ru)
-{
- if (!access_ok(VERIFY_WRITE, ru, sizeof(*ru)) ||
- __put_user(r->ru_utime.tv_sec, &ru->ru_utime.tv_sec) ||
- __put_user(r->ru_utime.tv_usec, &ru->ru_utime.tv_usec) ||
- __put_user(r->ru_stime.tv_sec, &ru->ru_stime.tv_sec) ||
- __put_user(r->ru_stime.tv_usec, &ru->ru_stime.tv_usec) ||
- __put_user(r->ru_maxrss, &ru->ru_maxrss) ||
- __put_user(r->ru_ixrss, &ru->ru_ixrss) ||
- __put_user(r->ru_idrss, &ru->ru_idrss) ||
- __put_user(r->ru_isrss, &ru->ru_isrss) ||
- __put_user(r->ru_minflt, &ru->ru_minflt) ||
- __put_user(r->ru_majflt, &ru->ru_majflt) ||
- __put_user(r->ru_nswap, &ru->ru_nswap) ||
- __put_user(r->ru_inblock, &ru->ru_inblock) ||
- __put_user(r->ru_oublock, &ru->ru_oublock) ||
- __put_user(r->ru_msgsnd, &ru->ru_msgsnd) ||
- __put_user(r->ru_msgrcv, &ru->ru_msgrcv) ||
- __put_user(r->ru_nsignals, &ru->ru_nsignals) ||
- __put_user(r->ru_nvcsw, &ru->ru_nvcsw) ||
- __put_user(r->ru_nivcsw, &ru->ru_nivcsw))
- return -EFAULT;
- return 0;
-}
-
-asmlinkage long compat_sys_getrusage(int who, struct compat_rusage __user *ru)
-{
- struct rusage r;
- int ret;
- mm_segment_t old_fs = get_fs();
-
- set_fs(KERNEL_DS);
- ret = sys_getrusage(who, (struct rusage __user *) &r);
- set_fs(old_fs);
-
- if (ret)
- return ret;
-
- if (put_compat_rusage(&r, ru))
- return -EFAULT;
-
- return 0;
-}
-
-asmlinkage long
-compat_sys_wait4(compat_pid_t pid, compat_uint_t __user *stat_addr, int options,
- struct compat_rusage __user *ru)
-{
- if (!ru) {
- return sys_wait4(pid, stat_addr, options, NULL);
- } else {
- struct rusage r;
- int ret;
- unsigned int status;
- mm_segment_t old_fs = get_fs();
-
- set_fs (KERNEL_DS);
- ret = sys_wait4(pid,
- (stat_addr ?
- (unsigned int __user *) &status : NULL),
- options, (struct rusage __user *) &r);
- set_fs (old_fs);
-
- if (ret > 0) {
- if (put_compat_rusage(&r, ru))
- return -EFAULT;
- if (stat_addr && put_user(status, stat_addr))
- return -EFAULT;
- }
- return ret;
- }
-}
-
-asmlinkage long compat_sys_waitid(int which, compat_pid_t pid,
- struct compat_siginfo __user *uinfo, int options,
- struct compat_rusage __user *uru)
-{
- siginfo_t info;
- struct rusage ru;
- long ret;
- mm_segment_t old_fs = get_fs();
-
- memset(&info, 0, sizeof(info));
-
- set_fs(KERNEL_DS);
- ret = sys_waitid(which, pid, (siginfo_t __user *)&info, options,
- uru ? (struct rusage __user *)&ru : NULL);
- set_fs(old_fs);
-
- if ((ret < 0) || (info.si_signo == 0))
- return ret;
-
- if (uru) {
- ret = put_compat_rusage(&ru, uru);
- if (ret)
- return ret;
- }
-
- BUG_ON(info.si_code & __SI_MASK);
- info.si_code |= __SI_CHLD;
- return copy_siginfo_to_user32(uinfo, &info);
-}
-
-static int compat_get_user_cpu_mask(compat_ulong_t __user *user_mask_ptr,
- unsigned len, cpumask_t *new_mask)
-{
- unsigned long *k;
-
- if (len < sizeof(cpumask_t))
- memset(new_mask, 0, sizeof(cpumask_t));
- else if (len > sizeof(cpumask_t))
- len = sizeof(cpumask_t);
-
- k = cpus_addr(*new_mask);
- return compat_get_bitmap(k, user_mask_ptr, len * 8);
-}
-
-asmlinkage long compat_sys_sched_setaffinity(compat_pid_t pid,
- unsigned int len,
- compat_ulong_t __user *user_mask_ptr)
-{
- cpumask_t new_mask;
- int retval;
-
- retval = compat_get_user_cpu_mask(user_mask_ptr, len, &new_mask);
- if (retval)
- return retval;
-
- return sched_setaffinity(pid, &new_mask);
-}
-
-asmlinkage long compat_sys_sched_getaffinity(compat_pid_t pid, unsigned int len,
- compat_ulong_t __user *user_mask_ptr)
-{
- int ret;
- cpumask_t mask;
- unsigned long *k;
- unsigned int min_length = sizeof(cpumask_t);
-
- if (NR_CPUS <= BITS_PER_COMPAT_LONG)
- min_length = sizeof(compat_ulong_t);
-
- if (len < min_length)
- return -EINVAL;
-
- ret = sched_getaffinity(pid, &mask);
- if (ret < 0)
- return ret;
-
- k = cpus_addr(mask);
- ret = compat_put_bitmap(user_mask_ptr, k, min_length * 8);
- if (ret)
- return ret;
-
- return min_length;
-}
-
-int get_compat_itimerspec(struct itimerspec *dst,
- const struct compat_itimerspec __user *src)
-{
- if (get_compat_timespec(&dst->it_interval, &src->it_interval) ||
- get_compat_timespec(&dst->it_value, &src->it_value))
- return -EFAULT;
- return 0;
-}
-
-int put_compat_itimerspec(struct compat_itimerspec __user *dst,
- const struct itimerspec *src)
-{
- if (put_compat_timespec(&src->it_interval, &dst->it_interval) ||
- put_compat_timespec(&src->it_value, &dst->it_value))
- return -EFAULT;
- return 0;
-}
-
-long compat_sys_timer_create(clockid_t which_clock,
- struct compat_sigevent __user *timer_event_spec,
- timer_t __user *created_timer_id)
-{
- struct sigevent __user *event = NULL;
-
- if (timer_event_spec) {
- struct sigevent kevent;
-
- event = compat_alloc_user_space(sizeof(*event));
- if (get_compat_sigevent(&kevent, timer_event_spec) ||
- copy_to_user(event, &kevent, sizeof(*event)))
- return -EFAULT;
- }
-
- return sys_timer_create(which_clock, event, created_timer_id);
-}
-
-long compat_sys_timer_settime(timer_t timer_id, int flags,
- struct compat_itimerspec __user *new,
- struct compat_itimerspec __user *old)
-{
- long err;
- mm_segment_t oldfs;
- struct itimerspec newts, oldts;
-
- if (!new)
- return -EINVAL;
- if (get_compat_itimerspec(&newts, new))
- return -EFAULT;
- oldfs = get_fs();
- set_fs(KERNEL_DS);
- err = sys_timer_settime(timer_id, flags,
- (struct itimerspec __user *) &newts,
- (struct itimerspec __user *) &oldts);
- set_fs(oldfs);
- if (!err && old && put_compat_itimerspec(old, &oldts))
- return -EFAULT;
- return err;
-}
-
-long compat_sys_timer_gettime(timer_t timer_id,
- struct compat_itimerspec __user *setting)
-{
- long err;
- mm_segment_t oldfs;
- struct itimerspec ts;
-
- oldfs = get_fs();
- set_fs(KERNEL_DS);
- err = sys_timer_gettime(timer_id,
- (struct itimerspec __user *) &ts);
- set_fs(oldfs);
- if (!err && put_compat_itimerspec(setting, &ts))
- return -EFAULT;
- return err;
-}
-
-long compat_sys_clock_settime(clockid_t which_clock,
- struct compat_timespec __user *tp)
-{
- long err;
- mm_segment_t oldfs;
- struct timespec ts;
-
- if (get_compat_timespec(&ts, tp))
- return -EFAULT;
- oldfs = get_fs();
- set_fs(KERNEL_DS);
- err = sys_clock_settime(which_clock,
- (struct timespec __user *) &ts);
- set_fs(oldfs);
- return err;
-}
-
-long compat_sys_clock_gettime(clockid_t which_clock,
- struct compat_timespec __user *tp)
-{
- long err;
- mm_segment_t oldfs;
- struct timespec ts;
-
- oldfs = get_fs();
- set_fs(KERNEL_DS);
- err = sys_clock_gettime(which_clock,
- (struct timespec __user *) &ts);
- set_fs(oldfs);
- if (!err && put_compat_timespec(&ts, tp))
- return -EFAULT;
- return err;
-}
-
-long compat_sys_clock_getres(clockid_t which_clock,
- struct compat_timespec __user *tp)
-{
- long err;
- mm_segment_t oldfs;
- struct timespec ts;
-
- oldfs = get_fs();
- set_fs(KERNEL_DS);
- err = sys_clock_getres(which_clock,
- (struct timespec __user *) &ts);
- set_fs(oldfs);
- if (!err && tp && put_compat_timespec(&ts, tp))
- return -EFAULT;
- return err;
-}
-
-static long compat_clock_nanosleep_restart(struct restart_block *restart)
-{
- long err;
- mm_segment_t oldfs;
- struct timespec tu;
- struct compat_timespec *rmtp = restart->nanosleep.compat_rmtp;
-
- restart->nanosleep.rmtp = (struct timespec __user *) &tu;
- oldfs = get_fs();
- set_fs(KERNEL_DS);
- err = clock_nanosleep_restart(restart);
- set_fs(oldfs);
-
- if ((err == -ERESTART_RESTARTBLOCK) && rmtp &&
- put_compat_timespec(&tu, rmtp))
- return -EFAULT;
-
- if (err == -ERESTART_RESTARTBLOCK) {
- restart->fn = compat_clock_nanosleep_restart;
- restart->nanosleep.compat_rmtp = rmtp;
- }
- return err;
-}
-
-long compat_sys_clock_nanosleep(clockid_t which_clock, int flags,
- struct compat_timespec __user *rqtp,
- struct compat_timespec __user *rmtp)
-{
- long err;
- mm_segment_t oldfs;
- struct timespec in, out;
- struct restart_block *restart;
-
- if (get_compat_timespec(&in, rqtp))
- return -EFAULT;
-
- oldfs = get_fs();
- set_fs(KERNEL_DS);
- err = sys_clock_nanosleep(which_clock, flags,
- (struct timespec __user *) &in,
- (struct timespec __user *) &out);
- set_fs(oldfs);
-
- if ((err == -ERESTART_RESTARTBLOCK) && rmtp &&
- put_compat_timespec(&out, rmtp))
- return -EFAULT;
-
- if (err == -ERESTART_RESTARTBLOCK) {
- restart = ¤t_thread_info()->restart_block;
- restart->fn = compat_clock_nanosleep_restart;
- restart->nanosleep.compat_rmtp = rmtp;
- }
- return err;
-}
-
-/*
- * We currently only need the following fields from the sigevent
- * structure: sigev_value, sigev_signo, sig_notify and (sometimes
- * sigev_notify_thread_id). The others are handled in user mode.
- * We also assume that copying sigev_value.sival_int is sufficient
- * to keep all the bits of sigev_value.sival_ptr intact.
- */
-int get_compat_sigevent(struct sigevent *event,
- const struct compat_sigevent __user *u_event)
-{
- memset(event, 0, sizeof(*event));
- return (!access_ok(VERIFY_READ, u_event, sizeof(*u_event)) ||
- __get_user(event->sigev_value.sival_int,
- &u_event->sigev_value.sival_int) ||
- __get_user(event->sigev_signo, &u_event->sigev_signo) ||
- __get_user(event->sigev_notify, &u_event->sigev_notify) ||
- __get_user(event->sigev_notify_thread_id,
- &u_event->sigev_notify_thread_id))
- ? -EFAULT : 0;
-}
-
-long compat_get_bitmap(unsigned long *mask, const compat_ulong_t __user *umask,
- unsigned long bitmap_size)
-{
- int i, j;
- unsigned long m;
- compat_ulong_t um;
- unsigned long nr_compat_longs;
-
- /* align bitmap up to nearest compat_long_t boundary */
- bitmap_size = ALIGN(bitmap_size, BITS_PER_COMPAT_LONG);
-
- if (!access_ok(VERIFY_READ, umask, bitmap_size / 8))
- return -EFAULT;
-
- nr_compat_longs = BITS_TO_COMPAT_LONGS(bitmap_size);
-
- for (i = 0; i < BITS_TO_LONGS(bitmap_size); i++) {
- m = 0;
-
- for (j = 0; j < sizeof(m)/sizeof(um); j++) {
- /*
- * We dont want to read past the end of the userspace
- * bitmap. We must however ensure the end of the
- * kernel bitmap is zeroed.
- */
- if (nr_compat_longs-- > 0) {
- if (__get_user(um, umask))
- return -EFAULT;
- } else {
- um = 0;
- }
-
- umask++;
- m |= (long)um << (j * BITS_PER_COMPAT_LONG);
- }
- *mask++ = m;
- }
-
- return 0;
-}
-
-long compat_put_bitmap(compat_ulong_t __user *umask, unsigned long *mask,
- unsigned long bitmap_size)
-{
- int i, j;
- unsigned long m;
- compat_ulong_t um;
- unsigned long nr_compat_longs;
-
- /* align bitmap up to nearest compat_long_t boundary */
- bitmap_size = ALIGN(bitmap_size, BITS_PER_COMPAT_LONG);
-
- if (!access_ok(VERIFY_WRITE, umask, bitmap_size / 8))
- return -EFAULT;
-
- nr_compat_longs = BITS_TO_COMPAT_LONGS(bitmap_size);
-
- for (i = 0; i < BITS_TO_LONGS(bitmap_size); i++) {
- m = *mask++;
-
- for (j = 0; j < sizeof(m)/sizeof(um); j++) {
- um = m;
-
- /*
- * We dont want to write past the end of the userspace
- * bitmap.
- */
- if (nr_compat_longs-- > 0) {
- if (__put_user(um, umask))
- return -EFAULT;
- }
-
- umask++;
- m >>= 4*sizeof(um);
- m >>= 4*sizeof(um);
- }
- }
-
- return 0;
-}
-
-void
-sigset_from_compat (sigset_t *set, compat_sigset_t *compat)
-{
- switch (_NSIG_WORDS) {
- case 4: set->sig[3] = compat->sig[6] | (((long)compat->sig[7]) << 32 );
- case 3: set->sig[2] = compat->sig[4] | (((long)compat->sig[5]) << 32 );
- case 2: set->sig[1] = compat->sig[2] | (((long)compat->sig[3]) << 32 );
- case 1: set->sig[0] = compat->sig[0] | (((long)compat->sig[1]) << 32 );
- }
-}
-
-asmlinkage long
-compat_sys_rt_sigtimedwait (compat_sigset_t __user *uthese,
- struct compat_siginfo __user *uinfo,
- struct compat_timespec __user *uts, compat_size_t sigsetsize)
-{
- compat_sigset_t s32;
- sigset_t s;
- int sig;
- struct timespec t;
- siginfo_t info;
- long ret, timeout = 0;
-
- if (sigsetsize != sizeof(sigset_t))
- return -EINVAL;
-
- if (copy_from_user(&s32, uthese, sizeof(compat_sigset_t)))
- return -EFAULT;
- sigset_from_compat(&s, &s32);
- sigdelsetmask(&s,sigmask(SIGKILL)|sigmask(SIGSTOP));
- signotset(&s);
-
- if (uts) {
- if (get_compat_timespec (&t, uts))
- return -EFAULT;
- if (t.tv_nsec >= 1000000000L || t.tv_nsec < 0
- || t.tv_sec < 0)
- return -EINVAL;
- }
-
- spin_lock_irq(¤t->sighand->siglock);
- sig = dequeue_signal(current, &s, &info);
- if (!sig) {
- timeout = MAX_SCHEDULE_TIMEOUT;
- if (uts)
- timeout = timespec_to_jiffies(&t)
- +(t.tv_sec || t.tv_nsec);
- if (timeout) {
- current->real_blocked = current->blocked;
- sigandsets(¤t->blocked, ¤t->blocked, &s);
-
- recalc_sigpending();
- spin_unlock_irq(¤t->sighand->siglock);
-
- timeout = schedule_timeout_interruptible(timeout);
-
- spin_lock_irq(¤t->sighand->siglock);
- sig = dequeue_signal(current, &s, &info);
- current->blocked = current->real_blocked;
- siginitset(¤t->real_blocked, 0);
- recalc_sigpending();
- }
- }
- spin_unlock_irq(¤t->sighand->siglock);
-
- if (sig) {
- ret = sig;
- if (uinfo) {
- if (copy_siginfo_to_user32(uinfo, &info))
- ret = -EFAULT;
- }
- }else {
- ret = timeout?-EINTR:-EAGAIN;
- }
- return ret;
-
-}
-
-#ifdef __ARCH_WANT_COMPAT_SYS_TIME
-
-/* compat_time_t is a 32 bit "long" and needs to get converted. */
-
-asmlinkage long compat_sys_time(compat_time_t __user * tloc)
-{
- compat_time_t i;
- struct timeval tv;
-
- do_gettimeofday(&tv);
- i = tv.tv_sec;
-
- if (tloc) {
- if (put_user(i,tloc))
- i = -EFAULT;
- }
- return i;
-}
-
-asmlinkage long compat_sys_stime(compat_time_t __user *tptr)
-{
- struct timespec tv;
- int err;
-
- if (get_user(tv.tv_sec, tptr))
- return -EFAULT;
-
- tv.tv_nsec = 0;
-
- err = security_settime(&tv, NULL);
- if (err)
- return err;
-
- do_settimeofday(&tv);
- return 0;
-}
-
-#endif /* __ARCH_WANT_COMPAT_SYS_TIME */
-
-#ifdef __ARCH_WANT_COMPAT_SYS_RT_SIGSUSPEND
-asmlinkage long compat_sys_rt_sigsuspend(compat_sigset_t __user *unewset, compat_size_t sigsetsize)
-{
- sigset_t newset;
- compat_sigset_t newset32;
-
- /* XXX: Don't preclude handling different sized sigset_t's. */
- if (sigsetsize != sizeof(sigset_t))
- return -EINVAL;
-
- if (copy_from_user(&newset32, unewset, sizeof(compat_sigset_t)))
- return -EFAULT;
- sigset_from_compat(&newset, &newset32);
- sigdelsetmask(&newset, sigmask(SIGKILL)|sigmask(SIGSTOP));
-
- spin_lock_irq(¤t->sighand->siglock);
- current->saved_sigmask = current->blocked;
- current->blocked = newset;
- recalc_sigpending();
- spin_unlock_irq(¤t->sighand->siglock);
-
- current->state = TASK_INTERRUPTIBLE;
- schedule();
- set_restore_sigmask();
- return -ERESTARTNOHAND;
-}
-#endif /* __ARCH_WANT_COMPAT_SYS_RT_SIGSUSPEND */
-
-asmlinkage long compat_sys_adjtimex(struct compat_timex __user *utp)
-{
- struct timex txc;
- int ret;
-
- memset(&txc, 0, sizeof(struct timex));
-
- if (!access_ok(VERIFY_READ, utp, sizeof(struct compat_timex)) ||
- __get_user(txc.modes, &utp->modes) ||
- __get_user(txc.offset, &utp->offset) ||
- __get_user(txc.freq, &utp->freq) ||
- __get_user(txc.maxerror, &utp->maxerror) ||
- __get_user(txc.esterror, &utp->esterror) ||
- __get_user(txc.status, &utp->status) ||
- __get_user(txc.constant, &utp->constant) ||
- __get_user(txc.precision, &utp->precision) ||
- __get_user(txc.tolerance, &utp->tolerance) ||
- __get_user(txc.time.tv_sec, &utp->time.tv_sec) ||
- __get_user(txc.time.tv_usec, &utp->time.tv_usec) ||
- __get_user(txc.tick, &utp->tick) ||
- __get_user(txc.ppsfreq, &utp->ppsfreq) ||
- __get_user(txc.jitter, &utp->jitter) ||
- __get_user(txc.shift, &utp->shift) ||
- __get_user(txc.stabil, &utp->stabil) ||
- __get_user(txc.jitcnt, &utp->jitcnt) ||
- __get_user(txc.calcnt, &utp->calcnt) ||
- __get_user(txc.errcnt, &utp->errcnt) ||
- __get_user(txc.stbcnt, &utp->stbcnt))
- return -EFAULT;
-
- ret = do_adjtimex(&txc);
-
- if (!access_ok(VERIFY_WRITE, utp, sizeof(struct compat_timex)) ||
- __put_user(txc.modes, &utp->modes) ||
- __put_user(txc.offset, &utp->offset) ||
- __put_user(txc.freq, &utp->freq) ||
- __put_user(txc.maxerror, &utp->maxerror) ||
- __put_user(txc.esterror, &utp->esterror) ||
- __put_user(txc.status, &utp->status) ||
- __put_user(txc.constant, &utp->constant) ||
- __put_user(txc.precision, &utp->precision) ||
- __put_user(txc.tolerance, &utp->tolerance) ||
- __put_user(txc.time.tv_sec, &utp->time.tv_sec) ||
- __put_user(txc.time.tv_usec, &utp->time.tv_usec) ||
- __put_user(txc.tick, &utp->tick) ||
- __put_user(txc.ppsfreq, &utp->ppsfreq) ||
- __put_user(txc.jitter, &utp->jitter) ||
- __put_user(txc.shift, &utp->shift) ||
- __put_user(txc.stabil, &utp->stabil) ||
- __put_user(txc.jitcnt, &utp->jitcnt) ||
- __put_user(txc.calcnt, &utp->calcnt) ||
- __put_user(txc.errcnt, &utp->errcnt) ||
- __put_user(txc.stbcnt, &utp->stbcnt) ||
- __put_user(txc.tai, &utp->tai))
- ret = -EFAULT;
-
- return ret;
-}
-
-#ifdef CONFIG_NUMA
-asmlinkage long compat_sys_move_pages(pid_t pid, unsigned long nr_pages,
- compat_uptr_t __user *pages32,
- const int __user *nodes,
- int __user *status,
- int flags)
-{
- const void __user * __user *pages;
- int i;
-
- pages = compat_alloc_user_space(nr_pages * sizeof(void *));
- for (i = 0; i < nr_pages; i++) {
- compat_uptr_t p;
-
- if (get_user(p, pages32 + i) ||
- put_user(compat_ptr(p), pages + i))
- return -EFAULT;
- }
- return sys_move_pages(pid, nr_pages, pages, nodes, status, flags);
-}
-
-asmlinkage long compat_sys_migrate_pages(compat_pid_t pid,
- compat_ulong_t maxnode,
- const compat_ulong_t __user *old_nodes,
- const compat_ulong_t __user *new_nodes)
-{
- unsigned long __user *old = NULL;
- unsigned long __user *new = NULL;
- nodemask_t tmp_mask;
- unsigned long nr_bits;
- unsigned long size;
-
- nr_bits = min_t(unsigned long, maxnode - 1, MAX_NUMNODES);
- size = ALIGN(nr_bits, BITS_PER_LONG) / 8;
- if (old_nodes) {
- if (compat_get_bitmap(nodes_addr(tmp_mask), old_nodes, nr_bits))
- return -EFAULT;
- old = compat_alloc_user_space(new_nodes ? size * 2 : size);
- if (new_nodes)
- new = old + size / sizeof(unsigned long);
- if (copy_to_user(old, nodes_addr(tmp_mask), size))
- return -EFAULT;
- }
- if (new_nodes) {
- if (compat_get_bitmap(nodes_addr(tmp_mask), new_nodes, nr_bits))
- return -EFAULT;
- if (new == NULL)
- new = compat_alloc_user_space(size);
- if (copy_to_user(new, nodes_addr(tmp_mask), size))
- return -EFAULT;
- }
- return sys_migrate_pages(pid, nr_bits + 1, old, new);
-}
-#endif
-
-struct compat_sysinfo {
- s32 uptime;
- u32 loads[3];
- u32 totalram;
- u32 freeram;
- u32 sharedram;
- u32 bufferram;
- u32 totalswap;
- u32 freeswap;
- u16 procs;
- u16 pad;
- u32 totalhigh;
- u32 freehigh;
- u32 mem_unit;
- char _f[20-2*sizeof(u32)-sizeof(int)];
-};
-
-asmlinkage long
-compat_sys_sysinfo(struct compat_sysinfo __user *info)
-{
- struct sysinfo s;
-
- do_sysinfo(&s);
-
- /* Check to see if any memory value is too large for 32-bit and scale
- * down if needed
- */
- if ((s.totalram >> 32) || (s.totalswap >> 32)) {
- int bitcount = 0;
-
- while (s.mem_unit < PAGE_SIZE) {
- s.mem_unit <<= 1;
- bitcount++;
- }
-
- s.totalram >>= bitcount;
- s.freeram >>= bitcount;
- s.sharedram >>= bitcount;
- s.bufferram >>= bitcount;
- s.totalswap >>= bitcount;
- s.freeswap >>= bitcount;
- s.totalhigh >>= bitcount;
- s.freehigh >>= bitcount;
- }
-
- if (!access_ok(VERIFY_WRITE, info, sizeof(struct compat_sysinfo)) ||
- __put_user (s.uptime, &info->uptime) ||
- __put_user (s.loads[0], &info->loads[0]) ||
- __put_user (s.loads[1], &info->loads[1]) ||
- __put_user (s.loads[2], &info->loads[2]) ||
- __put_user (s.totalram, &info->totalram) ||
- __put_user (s.freeram, &info->freeram) ||
- __put_user (s.sharedram, &info->sharedram) ||
- __put_user (s.bufferram, &info->bufferram) ||
- __put_user (s.totalswap, &info->totalswap) ||
- __put_user (s.freeswap, &info->freeswap) ||
- __put_user (s.procs, &info->procs) ||
- __put_user (s.totalhigh, &info->totalhigh) ||
- __put_user (s.freehigh, &info->freehigh) ||
- __put_user (s.mem_unit, &info->mem_unit))
- return -EFAULT;
-
- return 0;
-}
-
-/*
- * Allocate user-space memory for the duration of a single system call,
- * in order to marshall parameters inside a compat thunk.
- */
-void __user *compat_alloc_user_space(unsigned long len)
-{
- void __user *ptr;
-
- /* If len would occupy more than half of the entire compat space... */
- if (unlikely(len > (((compat_uptr_t)~0) >> 1)))
- return NULL;
-
- ptr = arch_compat_alloc_user_space(len);
-
- if (unlikely(!access_ok(VERIFY_WRITE, ptr, len)))
- return NULL;
-
- return ptr;
-}
-EXPORT_SYMBOL_GPL(compat_alloc_user_space);
-/*
- * kernel/configs.c
- * Echo the kernel .config file used to build the kernel
- *
- * Copyright (C) 2002 Khalid Aziz
- * Copyright (C) 2002 Randy Dunlap
- * Copyright (C) 2002 Al Stone
- * Copyright (C) 2002 Hewlett-Packard Company
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or (at
- * your option) any later version.
- *
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or
- * NON INFRINGEMENT. See the GNU General Public License for more
- * details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
- */
-
-#include
-#include