mirror of
https://github.com/bashrc/LKMPG.git
synced 2018-06-11 03:06:54 +02:00
5423 lines
336 KiB
HTML
5423 lines
336 KiB
HTML
<?xml version="1.0" encoding="utf-8"?>
|
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
|
|
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
|
|
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
|
|
<head>
|
|
<!-- 2017-08-03 Thu 13:03 -->
|
|
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
|
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
<title>The Linux Kernel Module Programming Guide</title>
|
|
<meta name="generator" content="Org mode" />
|
|
<meta name="author" content="Peter Jay Salzman, Michael Burian, Ori Pomerantz, Bob Mottram" />
|
|
<meta name="description" content="How to make kernel modules for Linux"
|
|
/>
|
|
<meta name="keywords" content="linux, kernel, kernel module, kernel programming" />
|
|
<style type="text/css">
|
|
<!--/*--><![CDATA[/*><!--*/
|
|
.title { text-align: center;
|
|
margin-bottom: .2em; }
|
|
.subtitle { text-align: center;
|
|
font-size: medium;
|
|
font-weight: bold;
|
|
margin-top:0; }
|
|
.todo { font-family: monospace; color: red; }
|
|
.done { font-family: monospace; color: green; }
|
|
.priority { font-family: monospace; color: orange; }
|
|
.tag { background-color: #eee; font-family: monospace;
|
|
padding: 2px; font-size: 80%; font-weight: normal; }
|
|
.timestamp { color: #bebebe; }
|
|
.timestamp-kwd { color: #5f9ea0; }
|
|
.org-right { margin-left: auto; margin-right: 0px; text-align: right; }
|
|
.org-left { margin-left: 0px; margin-right: auto; text-align: left; }
|
|
.org-center { margin-left: auto; margin-right: auto; text-align: center; }
|
|
.underline { text-decoration: underline; }
|
|
#postamble p, #preamble p { font-size: 90%; margin: .2em; }
|
|
p.verse { margin-left: 3%; }
|
|
pre {
|
|
border: 1px solid #ccc;
|
|
box-shadow: 3px 3px 3px #eee;
|
|
padding: 8pt;
|
|
font-family: monospace;
|
|
overflow: auto;
|
|
margin: 1.2em;
|
|
}
|
|
pre.src {
|
|
position: relative;
|
|
overflow: visible;
|
|
padding-top: 1.2em;
|
|
}
|
|
pre.src:before {
|
|
display: none;
|
|
position: absolute;
|
|
background-color: white;
|
|
top: -10px;
|
|
right: 10px;
|
|
padding: 3px;
|
|
border: 1px solid black;
|
|
}
|
|
pre.src:hover:before { display: inline;}
|
|
/* Languages per Org manual */
|
|
pre.src-asymptote:before { content: 'Asymptote'; }
|
|
pre.src-awk:before { content: 'Awk'; }
|
|
pre.src-C:before { content: 'C'; }
|
|
/* pre.src-C++ doesn't work in CSS */
|
|
pre.src-clojure:before { content: 'Clojure'; }
|
|
pre.src-css:before { content: 'CSS'; }
|
|
pre.src-D:before { content: 'D'; }
|
|
pre.src-ditaa:before { content: 'ditaa'; }
|
|
pre.src-dot:before { content: 'Graphviz'; }
|
|
pre.src-calc:before { content: 'Emacs Calc'; }
|
|
pre.src-emacs-lisp:before { content: 'Emacs Lisp'; }
|
|
pre.src-fortran:before { content: 'Fortran'; }
|
|
pre.src-gnuplot:before { content: 'gnuplot'; }
|
|
pre.src-haskell:before { content: 'Haskell'; }
|
|
pre.src-hledger:before { content: 'hledger'; }
|
|
pre.src-java:before { content: 'Java'; }
|
|
pre.src-js:before { content: 'Javascript'; }
|
|
pre.src-latex:before { content: 'LaTeX'; }
|
|
pre.src-ledger:before { content: 'Ledger'; }
|
|
pre.src-lisp:before { content: 'Lisp'; }
|
|
pre.src-lilypond:before { content: 'Lilypond'; }
|
|
pre.src-lua:before { content: 'Lua'; }
|
|
pre.src-matlab:before { content: 'MATLAB'; }
|
|
pre.src-mscgen:before { content: 'Mscgen'; }
|
|
pre.src-ocaml:before { content: 'Objective Caml'; }
|
|
pre.src-octave:before { content: 'Octave'; }
|
|
pre.src-org:before { content: 'Org mode'; }
|
|
pre.src-oz:before { content: 'OZ'; }
|
|
pre.src-plantuml:before { content: 'Plantuml'; }
|
|
pre.src-processing:before { content: 'Processing.js'; }
|
|
pre.src-python:before { content: 'Python'; }
|
|
pre.src-R:before { content: 'R'; }
|
|
pre.src-ruby:before { content: 'Ruby'; }
|
|
pre.src-sass:before { content: 'Sass'; }
|
|
pre.src-scheme:before { content: 'Scheme'; }
|
|
pre.src-screen:before { content: 'Gnu Screen'; }
|
|
pre.src-sed:before { content: 'Sed'; }
|
|
pre.src-sh:before { content: 'shell'; }
|
|
pre.src-sql:before { content: 'SQL'; }
|
|
pre.src-sqlite:before { content: 'SQLite'; }
|
|
/* additional languages in org.el's org-babel-load-languages alist */
|
|
pre.src-forth:before { content: 'Forth'; }
|
|
pre.src-io:before { content: 'IO'; }
|
|
pre.src-J:before { content: 'J'; }
|
|
pre.src-makefile:before { content: 'Makefile'; }
|
|
pre.src-maxima:before { content: 'Maxima'; }
|
|
pre.src-perl:before { content: 'Perl'; }
|
|
pre.src-picolisp:before { content: 'Pico Lisp'; }
|
|
pre.src-scala:before { content: 'Scala'; }
|
|
pre.src-shell:before { content: 'Shell Script'; }
|
|
pre.src-ebnf2ps:before { content: 'ebfn2ps'; }
|
|
/* additional language identifiers per "defun org-babel-execute"
|
|
in ob-*.el */
|
|
pre.src-cpp:before { content: 'C++'; }
|
|
pre.src-abc:before { content: 'ABC'; }
|
|
pre.src-coq:before { content: 'Coq'; }
|
|
pre.src-groovy:before { content: 'Groovy'; }
|
|
/* additional language identifiers from org-babel-shell-names in
|
|
ob-shell.el: ob-shell is the only babel language using a lambda to put
|
|
the execution function name together. */
|
|
pre.src-bash:before { content: 'bash'; }
|
|
pre.src-csh:before { content: 'csh'; }
|
|
pre.src-ash:before { content: 'ash'; }
|
|
pre.src-dash:before { content: 'dash'; }
|
|
pre.src-ksh:before { content: 'ksh'; }
|
|
pre.src-mksh:before { content: 'mksh'; }
|
|
pre.src-posh:before { content: 'posh'; }
|
|
/* Additional Emacs modes also supported by the LaTeX listings package */
|
|
pre.src-ada:before { content: 'Ada'; }
|
|
pre.src-asm:before { content: 'Assembler'; }
|
|
pre.src-caml:before { content: 'Caml'; }
|
|
pre.src-delphi:before { content: 'Delphi'; }
|
|
pre.src-html:before { content: 'HTML'; }
|
|
pre.src-idl:before { content: 'IDL'; }
|
|
pre.src-mercury:before { content: 'Mercury'; }
|
|
pre.src-metapost:before { content: 'MetaPost'; }
|
|
pre.src-modula-2:before { content: 'Modula-2'; }
|
|
pre.src-pascal:before { content: 'Pascal'; }
|
|
pre.src-ps:before { content: 'PostScript'; }
|
|
pre.src-prolog:before { content: 'Prolog'; }
|
|
pre.src-simula:before { content: 'Simula'; }
|
|
pre.src-tcl:before { content: 'tcl'; }
|
|
pre.src-tex:before { content: 'TeX'; }
|
|
pre.src-plain-tex:before { content: 'Plain TeX'; }
|
|
pre.src-verilog:before { content: 'Verilog'; }
|
|
pre.src-vhdl:before { content: 'VHDL'; }
|
|
pre.src-xml:before { content: 'XML'; }
|
|
pre.src-nxml:before { content: 'XML'; }
|
|
/* add a generic configuration mode; LaTeX export needs an additional
|
|
(add-to-list 'org-latex-listings-langs '(conf " ")) in .emacs */
|
|
pre.src-conf:before { content: 'Configuration File'; }
|
|
|
|
table { border-collapse:collapse; }
|
|
caption.t-above { caption-side: top; }
|
|
caption.t-bottom { caption-side: bottom; }
|
|
td, th { vertical-align:top; }
|
|
th.org-right { text-align: center; }
|
|
th.org-left { text-align: center; }
|
|
th.org-center { text-align: center; }
|
|
td.org-right { text-align: right; }
|
|
td.org-left { text-align: left; }
|
|
td.org-center { text-align: center; }
|
|
dt { font-weight: bold; }
|
|
.footpara { display: inline; }
|
|
.footdef { margin-bottom: 1em; }
|
|
.figure { padding: 1em; }
|
|
.figure p { text-align: center; }
|
|
.inlinetask {
|
|
padding: 10px;
|
|
border: 2px solid gray;
|
|
margin: 10px;
|
|
background: #ffffcc;
|
|
}
|
|
#org-div-home-and-up
|
|
{ text-align: right; font-size: 70%; white-space: nowrap; }
|
|
textarea { overflow-x: auto; }
|
|
.linenr { font-size: smaller }
|
|
.code-highlighted { background-color: #ffff00; }
|
|
.org-info-js_info-navigation { border-style: none; }
|
|
#org-info-js_console-label
|
|
{ font-size: 10px; font-weight: bold; white-space: nowrap; }
|
|
.org-info-js_search-highlight
|
|
{ background-color: #ffff00; color: #000000; font-weight: bold; }
|
|
.org-svg { width: 90%; }
|
|
/*]]>*/-->
|
|
</style>
|
|
<link rel="stylesheet" type="text/css" href="https://freedombone.net/css/foundation.min.css"></link>
|
|
<link rel="stylesheet" type="text/css" href="https://freedombone.net/css/org-export.css"></link>
|
|
<link rel="stylesheet" type="text/css" href="https://freedombone.net/css/style.css"></link>
|
|
<script type="text/javascript">
|
|
/*
|
|
@licstart The following is the entire license notice for the
|
|
JavaScript code in this tag.
|
|
|
|
Copyright (C) 2012-2017 Free Software Foundation, Inc.
|
|
|
|
The JavaScript code in this tag is free software: you can
|
|
redistribute it and/or modify it under the terms of the GNU
|
|
General Public License (GNU GPL) as published by the Free Software
|
|
Foundation, either version 3 of the License, or (at your option)
|
|
any later version. The code is distributed WITHOUT ANY WARRANTY;
|
|
without even the implied warranty of MERCHANTABILITY or FITNESS
|
|
FOR A PARTICULAR PURPOSE. See the GNU GPL for more details.
|
|
|
|
As additional permission under GNU GPL version 3 section 7, you
|
|
may distribute non-source (e.g., minimized or compacted) forms of
|
|
that code without the copy of the GNU GPL normally required by
|
|
section 4, provided you include this license notice and a URL
|
|
through which recipients can access the Corresponding Source.
|
|
|
|
|
|
@licend The above is the entire license notice
|
|
for the JavaScript code in this tag.
|
|
*/
|
|
<!--/*--><![CDATA[/*><!--*/
|
|
function CodeHighlightOn(elem, id)
|
|
{
|
|
var target = document.getElementById(id);
|
|
if(null != target) {
|
|
elem.cacheClassElem = elem.className;
|
|
elem.cacheClassTarget = target.className;
|
|
target.className = "code-highlighted";
|
|
elem.className = "code-highlighted";
|
|
}
|
|
}
|
|
function CodeHighlightOff(elem, id)
|
|
{
|
|
var target = document.getElementById(id);
|
|
if(elem.cacheClassElem)
|
|
elem.className = elem.cacheClassElem;
|
|
if(elem.cacheClassTarget)
|
|
target.className = elem.cacheClassTarget;
|
|
}
|
|
/*]]>*///-->
|
|
</script>
|
|
<script type="text/x-mathjax-config">
|
|
MathJax.Hub.Config({
|
|
displayAlign: "center",
|
|
displayIndent: "0em",
|
|
|
|
"HTML-CSS": { scale: 100,
|
|
linebreaks: { automatic: "false" },
|
|
webFont: "TeX"
|
|
},
|
|
SVG: {scale: 100,
|
|
linebreaks: { automatic: "false" },
|
|
font: "TeX"},
|
|
NativeMML: {scale: 100},
|
|
TeX: { equationNumbers: {autoNumber: "AMS"},
|
|
MultLineWidth: "85%",
|
|
TagSide: "right",
|
|
TagIndent: ".8em"
|
|
}
|
|
});
|
|
</script>
|
|
<script type="text/javascript"
|
|
src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-AMS_HTML"></script>
|
|
</head>
|
|
<body>
|
|
<div id="preamble" class="status">
|
|
<a name="top" id="top"></a>
|
|
</div>
|
|
<div id="content">
|
|
<h1 class="title">The Linux Kernel Module Programming Guide</h1>
|
|
<div id="table-of-contents">
|
|
<h2>Table of Contents</h2>
|
|
<div id="text-table-of-contents">
|
|
<ul>
|
|
<li><a href="#org610de5f">Introduction</a>
|
|
<ul>
|
|
<li><a href="#org252dbd0">Authorship</a></li>
|
|
<li><a href="#org7293619">Versioning and Notes</a></li>
|
|
<li><a href="#org922de34">Acknowledgements</a></li>
|
|
<li><a href="#orgbc46e96">What Is A Kernel Module?</a></li>
|
|
<li><a href="#org560454d">Kernel module package</a></li>
|
|
<li><a href="#org559f5f0">What Modules are in my Kernel?</a></li>
|
|
<li><a href="#orgc2f4544">Do I need to download and compile the kernel?</a></li>
|
|
<li><a href="#org9ccd372">Before We Begin</a></li>
|
|
</ul>
|
|
</li>
|
|
<li><a href="#org1e43e79">Headers</a></li>
|
|
<li><a href="#org7db670c">Examples</a></li>
|
|
<li><a href="#orgdac48b1">Hello World</a>
|
|
<ul>
|
|
<li><a href="#orgf7ef000">The Simplest Module</a></li>
|
|
<li><a href="#orgb73885a">Hello and Goodbye</a></li>
|
|
<li><a href="#org2bc20f2">The __init and __exit Macros</a></li>
|
|
<li><a href="#org26186d4">Licensing and Module Documentation</a></li>
|
|
<li><a href="#orgea77d95">Passing Command Line Arguments to a Module</a></li>
|
|
<li><a href="#org50373a3">Modules Spanning Multiple Files</a></li>
|
|
<li><a href="#org87541b0">Building modules for a precompiled kernel</a></li>
|
|
</ul>
|
|
</li>
|
|
<li><a href="#org2e995ae">Preliminaries</a>
|
|
<ul>
|
|
<li><a href="#org2c984aa">How modules begin and end</a></li>
|
|
<li><a href="#org27d800d">Functions available to modules</a></li>
|
|
<li><a href="#org2af6d40">User Space vs Kernel Space</a></li>
|
|
<li><a href="#org7de38e9">Name Space</a></li>
|
|
<li><a href="#org0a073e1">Code space</a></li>
|
|
<li><a href="#orgad8ccf5">Device Drivers</a></li>
|
|
</ul>
|
|
</li>
|
|
<li><a href="#org15e4afe">Character Device drivers</a>
|
|
<ul>
|
|
<li><a href="#orgf3946e3">The file_operations Structure</a></li>
|
|
<li><a href="#org4f5ee68">The file structure</a></li>
|
|
<li><a href="#org582dd8b">Registering A Device</a></li>
|
|
<li><a href="#orga4ee863">Unregistering A Device</a></li>
|
|
<li><a href="#org142f9ce">chardev.c</a></li>
|
|
<li><a href="#org0955cc2">Writing Modules for Multiple Kernel Versions</a></li>
|
|
</ul>
|
|
</li>
|
|
<li><a href="#org94acba2">The /proc File System</a>
|
|
<ul>
|
|
<li><a href="#orgbaaaee0">Read and Write a /proc File</a></li>
|
|
<li><a href="#org050c6d1">Manage /proc file with standard filesystem</a></li>
|
|
<li><a href="#orgf55e850">Manage /proc file with seq_file</a></li>
|
|
</ul>
|
|
</li>
|
|
<li><a href="#orgc2ebb44">sysfs: Interacting with your module</a></li>
|
|
<li><a href="#orgdd0bcef">Talking To Device Files</a></li>
|
|
<li><a href="#orgb0fbb3c">System Calls</a></li>
|
|
<li><a href="#orga2f4266">Blocking Processes and threads</a>
|
|
<ul>
|
|
<li><a href="#org85824d9">Sleep</a></li>
|
|
<li><a href="#orgca2cec5">Completions</a></li>
|
|
</ul>
|
|
</li>
|
|
<li><a href="#org06aaff5">Avoiding Collisions and Deadlocks</a>
|
|
<ul>
|
|
<li><a href="#orgb98d791">Mutex</a></li>
|
|
<li><a href="#orgb75c67b">Spinlocks</a></li>
|
|
<li><a href="#orgd4116f2">Read and write locks</a></li>
|
|
<li><a href="#org3a8a589">Atomic operations</a></li>
|
|
</ul>
|
|
</li>
|
|
<li><a href="#orgbb1c30e">Replacing Printks</a>
|
|
<ul>
|
|
<li><a href="#org2bb7a31">Replacing printk</a></li>
|
|
<li><a href="#org69a98da">Flashing keyboard LEDs</a></li>
|
|
</ul>
|
|
</li>
|
|
<li><a href="#org8a51e67">Scheduling Tasks</a>
|
|
<ul>
|
|
<li><a href="#org45c08b5">Tasklets</a></li>
|
|
<li><a href="#orgf6456ff">Work queues</a></li>
|
|
</ul>
|
|
</li>
|
|
<li><a href="#orgf85c716">Interrupt Handlers</a>
|
|
<ul>
|
|
<li><a href="#org15c7f9a">Interrupt Handlers</a></li>
|
|
<li><a href="#org4a7f40f">Detecting button presses</a></li>
|
|
<li><a href="#org5c9e9e3">Bottom Half</a></li>
|
|
</ul>
|
|
</li>
|
|
<li><a href="#org28f8ac7">Crypto</a>
|
|
<ul>
|
|
<li><a href="#org8ef480a">Hash functions</a></li>
|
|
<li><a href="#orgdc9f682">Symmetric key encryption</a></li>
|
|
</ul>
|
|
</li>
|
|
<li><a href="#orgcca0e8d">Standardising the interfaces: The Device Model</a></li>
|
|
<li><a href="#orga10b71d">Optimisations</a>
|
|
<ul>
|
|
<li><a href="#org25bd5bd">Likely and Unlikely conditions</a></li>
|
|
</ul>
|
|
</li>
|
|
<li><a href="#orga725d70">Common Pitfalls</a>
|
|
<ul>
|
|
<li><a href="#orgfff7611">Using standard libraries</a></li>
|
|
<li><a href="#org84bcc80">Disabling interrupts</a></li>
|
|
<li><a href="#orga55ec24">Sticking your head inside a large carnivore</a></li>
|
|
</ul>
|
|
</li>
|
|
<li><a href="#org93fe4b0">Where To Go From Here?</a></li>
|
|
</ul>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-org610de5f" class="outline-2">
|
|
<h2 id="org610de5f">Introduction</h2>
|
|
<div class="outline-text-2" id="text-org610de5f">
|
|
<p>
|
|
The Linux Kernel Module Programming Guide is a free book; you may reproduce and/or modify it under the terms of the Open Software License, version 3.0.
|
|
</p>
|
|
|
|
<p>
|
|
This book is distributed in the hope it will be useful, but without any warranty, without even the implied warranty of merchantability or fitness for a particular purpose.
|
|
</p>
|
|
|
|
<p>
|
|
The author encourages wide distribution of this book for personal or commercial use, provided the above copyright notice remains intact and the method adheres to the provisions of the Open Software License. In summary, you may copy and distribute this book free of charge or for a profit. No explicit permission is required from the author for reproduction of this book in any medium, physical or electronic.
|
|
</p>
|
|
|
|
<p>
|
|
Derivative works and translations of this document must be placed under the Open Software License, and the original copyright notice must remain intact. If you have contributed new material to this book, you must make the material and source code available for your revisions. Please make revisions and updates available directly to the document maintainer, Peter Jay Salzman <p@dirac.org>. This will allow for the merging of updates and provide consistent revisions to the Linux community.
|
|
</p>
|
|
|
|
<p>
|
|
If you publish or distribute this book commercially, donations, royalties, and/or printed copies are greatly appreciated by the author and the <a href="http://www.tldp.org">Linux Documentation Project</a> (LDP). Contributing in this way shows your support for free software and the LDP. If you have questions or comments, please contact the address above.
|
|
</p>
|
|
</div>
|
|
|
|
<div id="outline-container-org252dbd0" class="outline-3">
|
|
<h3 id="org252dbd0">Authorship</h3>
|
|
<div class="outline-text-3" id="text-org252dbd0">
|
|
<p>
|
|
The Linux Kernel Module Programming Guide was originally written for the 2.2 kernels by Ori Pomerantz. Eventually, Ori no longer had time to maintain the document. After all, the Linux kernel is a fast moving target. Peter Jay Salzman took over maintenance and updated it for the 2.4 kernels. Eventually, Peter no longer had time to follow developments with the 2.6 kernel, so Michael Burian became a co-maintainer to update the document for the 2.6 kernels. Bob Mottram updated the examples for 3.8 and later kernels, added the sysfs chapter and modified or updated other chapters.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-org7293619" class="outline-3">
|
|
<h3 id="org7293619">Versioning and Notes</h3>
|
|
<div class="outline-text-3" id="text-org7293619">
|
|
<p>
|
|
The Linux kernel is a moving target. There has always been a question whether the LKMPG should remove deprecated information or keep it around for historical sake. Michael Burian and I decided to create a new branch of the LKMPG for each new stable kernel version. So version LKMPG 4.9.x will address Linux kernel 4.9.x and LKMPG 2.6.x will address Linux kernel 2.6. No attempt will be made to archive historical information; a person wishing this information should read the appropriately versioned LKMPG.
|
|
</p>
|
|
|
|
<p>
|
|
The source code and discussions should apply to most architectures, but I can't promise anything. One exception is Chapter 12, Interrupt Handlers, which should not work on any architecture except for x86.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-org922de34" class="outline-3">
|
|
<h3 id="org922de34">Acknowledgements</h3>
|
|
<div class="outline-text-3" id="text-org922de34">
|
|
<p>
|
|
The following people have contributed corrections or good suggestions: Ignacio Martin, David Porter, Daniele Paolo Scarpazza, Dimo Velev, Francois Audeon, Horst Schirmeier, Bob Mottram and Roman Lakeev.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-orgbc46e96" class="outline-3">
|
|
<h3 id="orgbc46e96">What Is A Kernel Module?</h3>
|
|
<div class="outline-text-3" id="text-orgbc46e96">
|
|
<p>
|
|
So, you want to write a kernel module. You know C, you've written a few normal programs to run as processes, and now you want to get to where the real action is, to where a single wild pointer can wipe out your file system and a core dump means a reboot.
|
|
</p>
|
|
|
|
<p>
|
|
What exactly is a kernel module? Modules are pieces of code that can be loaded and unloaded into the kernel upon demand. They extend the functionality of the kernel without the need to reboot the system. For example, one type of module is the device driver, which allows the kernel to access hardware connected to the system. Without modules, we would have to build monolithic kernels and add new functionality directly into the kernel image. Besides having larger kernels, this has the disadvantage of requiring us to rebuild and reboot the kernel every time we want new functionality.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-org560454d" class="outline-3">
|
|
<h3 id="org560454d">Kernel module package</h3>
|
|
<div class="outline-text-3" id="text-org560454d">
|
|
<p>
|
|
Linux distros provide the commands <i>modprobe</i>, <i>insmod</i> and <i>depmod</i> within a package.
|
|
</p>
|
|
|
|
<p>
|
|
On Debian:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-sh">sudo apt-get install build-essential kmod
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
On Parabola:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-sh">sudo pacman -S gcc kmod
|
|
</code></pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-org559f5f0" class="outline-3">
|
|
<h3 id="org559f5f0">What Modules are in my Kernel?</h3>
|
|
<div class="outline-text-3" id="text-org559f5f0">
|
|
<p>
|
|
To discover what modules are already loaded within your current kernel use the command <b>lsmod</b>.
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-sh">sudo lsmod
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
Modules are stored within the file /proc/modules, so you can also see them with:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-sh">sudo cat /proc/modules
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
This can be a long list, and you might prefer to search for something particular. To search for the <i>fat</i> module:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-sh">sudo lsmod | grep fat
|
|
</code></pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-orgc2f4544" class="outline-3">
|
|
<h3 id="orgc2f4544">Do I need to download and compile the kernel?</h3>
|
|
<div class="outline-text-3" id="text-orgc2f4544">
|
|
<p>
|
|
For the purposes of following this guide you don't necessarily need to do that. However, it would be wise to run the examples within a test distro running on a virtual machine in order to avoid any possibility of messing up your system.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
<div id="outline-container-org9ccd372" class="outline-3">
|
|
<h3 id="org9ccd372">Before We Begin</h3>
|
|
<div class="outline-text-3" id="text-org9ccd372">
|
|
<p>
|
|
Before we delve into code, there are a few issues we need to cover. Everyone's system is different and everyone has their own groove. Getting your first "hello world" program to compile and load correctly can sometimes be a trick. Rest assured, after you get over the initial hurdle of doing it for the first time, it will be smooth sailing thereafter.
|
|
</p>
|
|
</div>
|
|
|
|
<ul class="org-ul">
|
|
<li><a id="orgf34a7cf"></a>Modversioning<br />
|
|
<div class="outline-text-5" id="text-orgf34a7cf">
|
|
<p>
|
|
A module compiled for one kernel won't load if you boot a different kernel unless you enable CONFIG_MODVERSIONS in the kernel. We won't go into module versioning until later in this guide. Until we cover modversions, the examples in the guide may not work if you're running a kernel with modversioning turned on. However, most stock Linux distro kernels come with it turned on. If you're having trouble loading the modules because of versioning errors, compile a kernel with modversioning turned off.
|
|
</p>
|
|
</div>
|
|
</li>
|
|
|
|
<li><a id="orgf23498b"></a>Using X<br />
|
|
<div class="outline-text-5" id="text-orgf23498b">
|
|
<p>
|
|
It is highly recommended that you type in, compile and load all the examples this guide discusses. It's also highly recommended you do this from a console. You should not be working on this stuff in X.
|
|
</p>
|
|
|
|
<p>
|
|
Modules can't print to the screen like printf() can, but they can log information and warnings, which ends up being printed on your screen, but only on a console. If you insmod a module from an xterm, the information and warnings will be logged, but only to your systemd journal. You won't see it unless you look through your journalctl. To have immediate access to this information, do all your work from the console.
|
|
</p>
|
|
</div>
|
|
</li>
|
|
</ul>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-org1e43e79" class="outline-2">
|
|
<h2 id="org1e43e79">Headers</h2>
|
|
<div class="outline-text-2" id="text-org1e43e79">
|
|
<p>
|
|
Before you can build anything you'll need to install the header files for your kernel. On Parabola GNU/Linux:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-sh">sudo pacman -S linux-libre-headers
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
On Debian:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-sh">sudo apt-get update
|
|
apt-cache search linux-headers-$(<span class="org-sh-quoted-exec">uname</span> -r)
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
This will tell you what kernel header files are available. Then for example:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-sh">sudo apt-get install kmod linux-headers-4.9.11-1-amd64
|
|
</code></pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div id="outline-container-org7db670c" class="outline-2">
|
|
<h2 id="org7db670c">Examples</h2>
|
|
<div class="outline-text-2" id="text-org7db670c">
|
|
<p>
|
|
All the examples from this document are available within the <i>examples</i> subdirectory. To test that they compile:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-sh"><span class="org-builtin">cd</span> examples
|
|
make
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
If there are any compile errors then you might have a more recent kernel version or need to install the corresponding kernel header files.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
<div id="outline-container-orgdac48b1" class="outline-2">
|
|
<h2 id="orgdac48b1">Hello World</h2>
|
|
<div class="outline-text-2" id="text-orgdac48b1">
|
|
</div>
|
|
<div id="outline-container-orgf7ef000" class="outline-3">
|
|
<h3 id="orgf7ef000">The Simplest Module</h3>
|
|
<div class="outline-text-3" id="text-orgf7ef000">
|
|
<p>
|
|
Most people learning programming start out with some sort of "<i>hello world</i>" example. I don't know what happens to people who break with this tradition, but I think it's safer not to find out. We'll start with a series of hello world programs that demonstrate the different aspects of the basics of writing a kernel module.
|
|
</p>
|
|
|
|
<p>
|
|
Here's the simplest module possible.
|
|
</p>
|
|
|
|
<p>
|
|
Make a test directory:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-sh">mkdir -p ~/develop/kernel/hello-1
|
|
<span class="org-builtin">cd</span> ~/develop/kernel/hello-1
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
Paste this into you favourite editor and save it as <b>hello-1.c</b>:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-c"><span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * hello-1.c - The simplest kernel module.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/module.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">Needed by all modules </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/kernel.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">Needed for KERN_INFO </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-type">int</span> <span class="org-function-name">init_module</span>(<span class="org-type">void</span>)
|
|
{
|
|
printk(KERN_INFO <span class="org-string">"Hello world 1.\n"</span>);
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * A non 0 return means init_module failed; module can't be loaded.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">return</span> 0;
|
|
}
|
|
|
|
<span class="org-type">void</span> <span class="org-function-name">cleanup_module</span>(<span class="org-type">void</span>)
|
|
{
|
|
printk(KERN_INFO <span class="org-string">"Goodbye world 1.\n"</span>);
|
|
}
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
Now you'll need a Makefile. If you copy and paste this change the indentation to use tabs, not spaces.
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-makefile"><span class="org-variable-name">obj-m</span> += hello-1.o
|
|
|
|
<span class="org-makefile-targets">all</span>:
|
|
make -C /lib/modules/$(<span class="org-variable-name">shell</span> uname -r)/build M=$(<span class="org-variable-name">PWD</span>) modules
|
|
|
|
<span class="org-makefile-targets">clean</span>:
|
|
make -C /lib/modules/$(<span class="org-variable-name">shell</span> uname -r)/build M=$(<span class="org-variable-name">PWD</span>) clean
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
And finally just:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-sh">make
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
If all goes smoothly you should then find that you have a compiled <b>hello-1.ko</b> module. You can find info on it with the command:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-sh">sudo modinfo hello-1.ko
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
At this point the command:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-sh">sudo lsmod | grep hello
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
should return nothing. You can try loading your shiny new module with:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-sh">sudo insmod hello-1.ko
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
The dash character will get converted to an underscore, so when you again try:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-sh">sudo lsmod | grep hello
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
you should now see your loaded module. It can be removed again with:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-sh">sudo rmmod hello_1
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
Notice that the dash was replaced by an underscore. To see what just happened in the logs:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-sh">journalctl --since <span class="org-string">"1 hour ago"</span> | grep kernel
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
You now know the basics of creating, compiling, installing and removing modules. Now for more of a description of how this module works.
|
|
</p>
|
|
|
|
<p>
|
|
Kernel modules must have at least two functions: a "start" (initialization) function called <b>init_module()</b> which is called when the module is insmoded into the kernel, and an "end" (cleanup) function called <b>cleanup_module()</b> which is called just before it is rmmoded. Actually, things have changed starting with kernel 2.3.13. You can now use whatever name you like for the
|
|
start and end functions of a module, and you'll learn how to do this in Section 2.3. In fact, the new method is the preferred method. However, many people still use init_module() and cleanup_module() for their start and end functions.
|
|
</p>
|
|
|
|
<p>
|
|
Typically, init_module() either registers a handler for something with the kernel, or it replaces one of the kernel functions with its own code (usually code to do something and then call the original function). The cleanup_module() function is supposed to undo whatever init_module() did, so the module can be unloaded safely.
|
|
</p>
|
|
|
|
<p>
|
|
Lastly, every kernel module needs to include linux/module.h. We needed to include <b>linux/kernel.h</b> only for the macro expansion for the printk() log level, KERN_ALERT, which you'll learn about in Section 2.1.1.
|
|
</p>
|
|
</div>
|
|
|
|
<ul class="org-ul">
|
|
<li><a id="orgd7aad54"></a>A point about coding style<br />
|
|
<div class="outline-text-5" id="text-orgd7aad54">
|
|
<p>
|
|
Another thing which may not be immediately obvious to anyone getting started with kernel programming is that indentation within your code should be using <b>tabs</b> and <b>not spaces</b>. It's one of the coding conventions of the kernel. You may not like it, but you'll need to get used to it if you ever submit a patch upstream.
|
|
</p>
|
|
</div>
|
|
</li>
|
|
<li><a id="orgd0c997a"></a>Introducing printk()<br />
|
|
<div class="outline-text-5" id="text-orgd0c997a">
|
|
<p>
|
|
Despite what you might think, <b>printk()</b> was not meant to communicate information to the user, even though we used it for exactly this purpose in hello-1! It happens to be a logging mechanism for the kernel, and is used to log information or give warnings. Therefore, each printk() statement comes with a priority, which is the <1> and KERN_ALERT you see. There are 8 priorities and the kernel has macros for them, so you don't have to use cryptic numbers, and you can view them (and their meanings) in <b>linux/kernel.h</b>. If you don't specify a priority level, the default priority, DEFAULT_MESSAGE_LOGLEVEL, will be used.
|
|
</p>
|
|
|
|
<p>
|
|
Take time to read through the priority macros. The header file also describes what each priority means. In practise, don't use number, like <4>. Always use the macro, like KERN_WARNING.
|
|
</p>
|
|
|
|
<p>
|
|
If the priority is less than int console_loglevel, the message is printed on your current terminal. If both syslogd and klogd are running, then the message will also get appended to the systemd journal, whether it got printed to the console or not. We use a high priority, like KERN_ALERT, to make sure the printk() messages get printed to your console rather than just logged to the journal. When you write real modules, you'll want to use priorities that are meaningful for the situation at hand.
|
|
</p>
|
|
</div>
|
|
</li>
|
|
|
|
<li><a id="orgf47890f"></a>About Compiling<br />
|
|
<div class="outline-text-5" id="text-orgf47890f">
|
|
<p>
|
|
Kernel modules need to be compiled a bit differently from regular userspace apps. Former kernel versions required us to care much about these settings, which are usually stored in Makefiles. Although hierarchically organized, many redundant settings accumulated in sublevel Makefiles and made them large and rather difficult to maintain. Fortunately, there is a new way of doing these things, called kbuild, and the build process for external loadable modules is now fully integrated into the standard kernel build mechanism. To learn more on how to compile modules which are not part of the official kernel (such as all the examples you'll find in this guide), see file <b>linux/Documentation/kbuild/modules.txt</b>.
|
|
</p>
|
|
|
|
<p>
|
|
Additional details about Makefiles for kernel modules are available in <b>linux/Documentation/kbuild/makefiles.txt</b>. Be sure to read this and the related files before starting to hack Makefiles. It'll probably save you lots of work.
|
|
</p>
|
|
|
|
<blockquote>
|
|
<p>
|
|
Here's another exercise for the reader. See that comment above the return statement in init_module()? Change the return value to something negative, recompile and load the module again. What happens?
|
|
</p>
|
|
</blockquote>
|
|
</div>
|
|
</li>
|
|
</ul>
|
|
</div>
|
|
|
|
<div id="outline-container-orgb73885a" class="outline-3">
|
|
<h3 id="orgb73885a">Hello and Goodbye</h3>
|
|
<div class="outline-text-3" id="text-orgb73885a">
|
|
<p>
|
|
In early kernel versions you had to use the <b>init_module</b> and <b>cleanup_module</b> functions, as in the first hello world example, but these days you can name those anything you want by using the <b>module_init</b> and <b>module_exit</b> macros. These macros are defined in <b>linux/init.h</b>. The only requirement is that your init and cleanup functions must be defined before calling the those macros, otherwise you'll get compilation errors. Here's an example of this technique:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-c"><span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * hello-2.c - Demonstrating the module_init() and module_exit() macros.</span>
|
|
<span class="org-comment"> * This is preferred over using init_module() and cleanup_module().</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/module.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">Needed by all modules </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/kernel.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">Needed for KERN_INFO </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/init.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">Needed for the macros </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-function-name">__init</span> hello_2_init(<span class="org-type">void</span>)
|
|
{
|
|
printk(KERN_INFO <span class="org-string">"Hello, world 2\n"</span>);
|
|
<span class="org-keyword">return</span> 0;
|
|
}
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">void</span> <span class="org-function-name">__exit</span> hello_2_exit(<span class="org-type">void</span>)
|
|
{
|
|
printk(KERN_INFO <span class="org-string">"Goodbye, world 2\n"</span>);
|
|
}
|
|
|
|
module_init(hello_2_init);
|
|
module_exit(hello_2_exit);
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
So now we have two real kernel modules under our belt. Adding another module is as simple as this:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-makefile"><span class="org-variable-name">obj-m</span> += hello-1.o
|
|
<span class="org-variable-name">obj-m</span> += hello-2.o
|
|
|
|
<span class="org-makefile-targets">all</span>:
|
|
make -C /lib/modules/$(<span class="org-variable-name">shell</span> uname -r)/build M=$(<span class="org-variable-name">PWD</span>) modules
|
|
|
|
<span class="org-makefile-targets">clean</span>:
|
|
make -C /lib/modules/$(<span class="org-variable-name">shell</span> uname -r)/build M=$(<span class="org-variable-name">PWD</span>) clean
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
Now have a look at linux/drivers/char/Makefile for a real world example. As you can see, some things get hardwired into the kernel (obj-y) but where are all those obj-m gone? Those familiar with shell scripts will easily be able to spot them. For those not, the obj-$(CONFIG_FOO) entries you see everywhere expand into obj-y or obj-m, depending on whether the CONFIG_FOO variable has been set to y or m. While we are at it, those were exactly the kind of variables that you have set in the linux/.config file, the last time when you said make menuconfig or something like that.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-org2bc20f2" class="outline-3">
|
|
<h3 id="org2bc20f2">The __init and __exit Macros</h3>
|
|
<div class="outline-text-3" id="text-org2bc20f2">
|
|
<p>
|
|
This demonstrates a feature of kernel 2.2 and later. Notice the change in the definitions of the init and cleanup functions. The <b>__init</b> macro causes the init function to be discarded and its memory freed once the init function finishes for built-in drivers, but not loadable modules. If you think about when the init function is invoked, this makes perfect sense.
|
|
</p>
|
|
|
|
<p>
|
|
There is also an <b>__initdata</b> which works similarly to <b>__init</b> but for init variables rather than functions.
|
|
</p>
|
|
|
|
<p>
|
|
The <b>__exit</b> macro causes the omission of the function when the module is built into the kernel, and like __init, has no effect for loadable modules. Again, if you consider when the cleanup function runs, this makes complete sense; built-in drivers don't need a cleanup function, while loadable modules do.
|
|
</p>
|
|
|
|
<p>
|
|
These macros are defined in <b>linux/init.h</b> and serve to free up kernel memory. When you boot your kernel and see something like Freeing unused kernel memory: 236k freed, this is precisely what the kernel is freeing.
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-c"><span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * hello-3.c - Illustrating the __init, __initdata and __exit macros.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/module.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">Needed by all modules </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/kernel.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">Needed for KERN_INFO </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/init.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">Needed for the macros </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-variable-name">hello3_data</span> __initdata = 3;
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-function-name">__init</span> hello_3_init(<span class="org-type">void</span>)
|
|
{
|
|
printk(KERN_INFO <span class="org-string">"Hello, world %d\n"</span>, hello3_data);
|
|
<span class="org-keyword">return</span> 0;
|
|
}
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">void</span> <span class="org-function-name">__exit</span> hello_3_exit(<span class="org-type">void</span>)
|
|
{
|
|
printk(KERN_INFO <span class="org-string">"Goodbye, world 3\n"</span>);
|
|
}
|
|
|
|
module_init(hello_3_init);
|
|
module_exit(hello_3_exit);
|
|
</code></pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-org26186d4" class="outline-3">
|
|
<h3 id="org26186d4">Licensing and Module Documentation</h3>
|
|
<div class="outline-text-3" id="text-org26186d4">
|
|
<p>
|
|
Honestly, who loads or even cares about proprietary modules? If you do then you might have seen something like this:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-txt"># insmod xxxxxx.o
|
|
Warning: loading xxxxxx.ko will taint the kernel: no license
|
|
See http://www.tux.org/lkml/#export-tainted for information about tainted modules
|
|
Module xxxxxx loaded, with warnings
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
You can use a few macros to indicate the license for your module. Some examples are "GPL", "GPL v2", "GPL and additional rights", "Dual BSD/GPL", "Dual MIT/GPL", "Dual MPL/GPL" and "Proprietary". They're defined within <b>linux/module.h</b>.
|
|
</p>
|
|
|
|
<p>
|
|
To reference what license you're using a macro is available called <b>MODULE_LICENSE</b>. This and a few other macros describing the module are illustrated in the below example.
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-c"><span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * hello-4.c - Demonstrates module documentation.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/module.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">Needed by all modules </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/kernel.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">Needed for KERN_INFO </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/init.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">Needed for the macros </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
MODULE_LICENSE(<span class="org-string">"GPL"</span>);
|
|
MODULE_AUTHOR(<span class="org-string">"Bob Mottram"</span>);
|
|
MODULE_DESCRIPTION(<span class="org-string">"A sample driver"</span>);
|
|
MODULE_SUPPORTED_DEVICE(<span class="org-string">"testdevice"</span>);
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-function-name">__init</span> init_hello_4(<span class="org-type">void</span>)
|
|
{
|
|
printk(KERN_INFO <span class="org-string">"Hello, world 4\n"</span>);
|
|
<span class="org-keyword">return</span> 0;
|
|
}
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">void</span> <span class="org-function-name">__exit</span> cleanup_hello_4(<span class="org-type">void</span>)
|
|
{
|
|
printk(KERN_INFO <span class="org-string">"Goodbye, world 4\n"</span>);
|
|
}
|
|
|
|
module_init(init_hello_4);
|
|
module_exit(cleanup_hello_4);
|
|
</code></pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-orgea77d95" class="outline-3">
|
|
<h3 id="orgea77d95">Passing Command Line Arguments to a Module</h3>
|
|
<div class="outline-text-3" id="text-orgea77d95">
|
|
<p>
|
|
Modules can take command line arguments, but not with the argc/argv you might be used to.
|
|
</p>
|
|
|
|
<p>
|
|
To allow arguments to be passed to your module, declare the variables that will take the values of the command line arguments as global and then use the module_param() macro, (defined in linux/moduleparam.h) to set the mechanism up. At runtime, insmod will fill the variables with any command line arguments that are given, like ./insmod mymodule.ko myvariable=5. The variable declarations and macros should be placed at the beginning of the module for clarity. The example code should clear up my admittedly lousy explanation.
|
|
</p>
|
|
|
|
<p>
|
|
The module_param() macro takes 3 arguments: the name of the variable, its type and permissions for the corresponding file in sysfs. Integer types can be signed as usual or unsigned. If you'd like to use arrays of integers or strings see module_param_array() and module_param_string().
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-c"><span class="org-type">int</span> <span class="org-variable-name">myint</span> = 3;
|
|
module_param(myint, <span class="org-type">int</span>, 0);
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
Arrays are supported too, but things are a bit different now than they were in the olden days. To keep track of the number of parameters you need to pass a pointer to a count variable as third parameter. At your option, you could also ignore the count and pass NULL instead. We show both possibilities here:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-c"><span class="org-type">int</span> <span class="org-variable-name">myintarray</span>[2];
|
|
module_param_array(myintarray, <span class="org-type">int</span>, <span class="org-constant">NULL</span>, 0); <span class="org-comment-delimiter">/* </span><span class="org-comment">not interested in count </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-type">short</span> <span class="org-variable-name">myshortarray</span>[4];
|
|
<span class="org-type">int</span> <span class="org-variable-name">count</span>;
|
|
module_parm_array(myshortarray, <span class="org-type">short</span>, &count, 0); <span class="org-comment-delimiter">/* </span><span class="org-comment">put count into "count" variable </span><span class="org-comment-delimiter">*/</span>
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
A good use for this is to have the module variable's default values set, like an port or IO address. If the variables contain the default values, then perform autodetection (explained elsewhere). Otherwise, keep the current value. This will be made clear later on.
|
|
</p>
|
|
|
|
<p>
|
|
Lastly, there's a macro function, <b>MODULE_PARM_DESC()</b>, that is used to document arguments that the module can take. It takes two parameters: a variable name and a free form string describing that variable.
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-c"><span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * hello-5.c - Demonstrates command line argument passing to a module.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/module.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/moduleparam.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/kernel.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/init.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/stat.h></span>
|
|
|
|
MODULE_LICENSE(<span class="org-string">"GPL"</span>);
|
|
MODULE_AUTHOR(<span class="org-string">"Peter Jay Salzman"</span>);
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">short</span> <span class="org-type">int</span> <span class="org-variable-name">myshort</span> = 1;
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-variable-name">myint</span> = 420;
|
|
<span class="org-keyword">static</span> <span class="org-type">long</span> <span class="org-type">int</span> <span class="org-variable-name">mylong</span> = 9999;
|
|
<span class="org-keyword">static</span> <span class="org-type">char</span> *<span class="org-variable-name">mystring</span> = <span class="org-string">"blah"</span>;
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-variable-name">myintArray</span>[2] = { -1, -1 };
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-variable-name">arr_argc</span> = 0;
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * module_param(foo, int, 0000)</span>
|
|
<span class="org-comment"> * The first param is the parameters name</span>
|
|
<span class="org-comment"> * The second param is it's data type</span>
|
|
<span class="org-comment"> * The final argument is the permissions bits,</span>
|
|
<span class="org-comment"> * for exposing parameters in sysfs (if non-zero) at a later stage.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
module_param(myshort, <span class="org-type">short</span>, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
|
|
MODULE_PARM_DESC(myshort, <span class="org-string">"A short integer"</span>);
|
|
module_param(myint, <span class="org-type">int</span>, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
|
|
MODULE_PARM_DESC(myint, <span class="org-string">"An integer"</span>);
|
|
module_param(mylong, <span class="org-type">long</span>, S_IRUSR);
|
|
MODULE_PARM_DESC(mylong, <span class="org-string">"A long integer"</span>);
|
|
module_param(mystring, charp, 0000);
|
|
MODULE_PARM_DESC(mystring, <span class="org-string">"A character string"</span>);
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * module_param_array(name, type, num, perm);</span>
|
|
<span class="org-comment"> * The first param is the parameter's (in this case the array's) name</span>
|
|
<span class="org-comment"> * The second param is the data type of the elements of the array</span>
|
|
<span class="org-comment"> * The third argument is a pointer to the variable that will store the number</span>
|
|
<span class="org-comment"> * of elements of the array initialized by the user at module loading time</span>
|
|
<span class="org-comment"> * The fourth argument is the permission bits</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
module_param_array(myintArray, <span class="org-type">int</span>, &arr_argc, 0000);
|
|
MODULE_PARM_DESC(myintArray, <span class="org-string">"An array of integers"</span>);
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-function-name">__init</span> hello_5_init(<span class="org-type">void</span>)
|
|
{
|
|
<span class="org-type">int</span> <span class="org-variable-name">i</span>;
|
|
printk(KERN_INFO <span class="org-string">"Hello, world 5\n=============\n"</span>);
|
|
printk(KERN_INFO <span class="org-string">"myshort is a short integer: %hd\n"</span>, myshort);
|
|
printk(KERN_INFO <span class="org-string">"myint is an integer: %d\n"</span>, myint);
|
|
printk(KERN_INFO <span class="org-string">"mylong is a long integer: %ld\n"</span>, mylong);
|
|
printk(KERN_INFO <span class="org-string">"mystring is a string: %s\n"</span>, mystring);
|
|
<span class="org-keyword">for</span> (i = 0; i < (<span class="org-keyword">sizeof</span> myintArray / <span class="org-keyword">sizeof</span> (<span class="org-type">int</span>)); i++)
|
|
{
|
|
printk(KERN_INFO <span class="org-string">"myintArray[%d] = %d\n"</span>, i, myintArray[i]);
|
|
}
|
|
printk(KERN_INFO <span class="org-string">"got %d arguments for myintArray.\n"</span>, arr_argc);
|
|
<span class="org-keyword">return</span> 0;
|
|
}
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">void</span> <span class="org-function-name">__exit</span> hello_5_exit(<span class="org-type">void</span>)
|
|
{
|
|
printk(KERN_INFO <span class="org-string">"Goodbye, world 5\n"</span>);
|
|
}
|
|
|
|
module_init(hello_5_init);
|
|
module_exit(hello_5_exit);
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
I would recommend playing around with this code:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-txt"># sudo insmod hello-5.ko mystring="bebop" mybyte=255 myintArray=-1
|
|
mybyte is an 8 bit integer: 255
|
|
myshort is a short integer: 1
|
|
myint is an integer: 20
|
|
mylong is a long integer: 9999
|
|
mystring is a string: bebop
|
|
myintArray is -1 and 420
|
|
|
|
# rmmod hello-5
|
|
Goodbye, world 5
|
|
|
|
# sudo insmod hello-5.ko mystring="supercalifragilisticexpialidocious" \
|
|
> mybyte=256 myintArray=-1,-1
|
|
mybyte is an 8 bit integer: 0
|
|
myshort is a short integer: 1
|
|
myint is an integer: 20
|
|
mylong is a long integer: 9999
|
|
mystring is a string: supercalifragilisticexpialidocious
|
|
myintArray is -1 and -1
|
|
|
|
# rmmod hello-5
|
|
Goodbye, world 5
|
|
|
|
# sudo insmod hello-5.ko mylong=hello
|
|
hello-5.o: invalid argument syntax for mylong: 'h'
|
|
</code></pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-org50373a3" class="outline-3">
|
|
<h3 id="org50373a3">Modules Spanning Multiple Files</h3>
|
|
<div class="outline-text-3" id="text-org50373a3">
|
|
<p>
|
|
Sometimes it makes sense to divide a kernel module between several source files.
|
|
</p>
|
|
|
|
<p>
|
|
Here's an example of such a kernel module.
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-c"><span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * start.c - Illustration of multi filed modules</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/kernel.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">We're doing kernel work </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/module.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">Specifically, a module </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-type">int</span> <span class="org-function-name">init_module</span>(<span class="org-type">void</span>)
|
|
{
|
|
printk(KERN_INFO <span class="org-string">"Hello, world - this is the kernel speaking\n"</span>);
|
|
<span class="org-keyword">return</span> 0;
|
|
}
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
The next file:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-c"><span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * stop.c - Illustration of multi filed modules</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/kernel.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">We're doing kernel work </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/module.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">Specifically, a module </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-type">void</span> <span class="org-function-name">cleanup_module</span>()
|
|
{
|
|
printk(KERN_INFO <span class="org-string">"Short is the life of a kernel module\n"</span>);
|
|
}
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
And finally, the makefile:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-makefile"><span class="org-variable-name">obj-m</span> += hello-1.o
|
|
<span class="org-variable-name">obj-m</span> += hello-2.o
|
|
<span class="org-variable-name">obj-m</span> += hello-3.o
|
|
<span class="org-variable-name">obj-m</span> += hello-4.o
|
|
<span class="org-variable-name">obj-m</span> += hello-5.o
|
|
<span class="org-variable-name">obj-m</span> += startstop.o
|
|
<span class="org-variable-name">startstop-objs</span> := start.o stop.o
|
|
|
|
<span class="org-makefile-targets">all</span>:
|
|
make -C /lib/modules/$(<span class="org-variable-name">shell</span> uname -r)/build M=$(<span class="org-variable-name">PWD</span>) modules
|
|
|
|
<span class="org-makefile-targets">clean</span>:
|
|
make -C /lib/modules/$(<span class="org-variable-name">shell</span> uname -r)/build M=$(<span class="org-variable-name">PWD</span>) clean
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
This is the complete makefile for all the examples we've seen so far. The first five lines are nothing special, but for the last example we'll need two lines. First we invent an object name for our combined module, second we tell make what object files are part of that module.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-org87541b0" class="outline-3">
|
|
<h3 id="org87541b0">Building modules for a precompiled kernel</h3>
|
|
<div class="outline-text-3" id="text-org87541b0">
|
|
<p>
|
|
Obviously, we strongly suggest you to recompile your kernel, so that you can enable a number of useful debugging features, such as forced module unloading (<b>MODULE_FORCE_UNLOAD</b>): when this option is enabled, you can force the kernel to unload a module even when it believes it is unsafe, via a <b>sudo rmmod -f module</b> command. This option can save you a lot of time and a number of reboots during the development of a module. If you don't want to recompile your kernel then you should consider running the examples within a test distro on a virtual machine. If you mess anything up then you can easily reboot or restore the VM.
|
|
</p>
|
|
|
|
<p>
|
|
There are a number of cases in which you may want to load your module into a precompiled running kernel, such as the ones shipped with common Linux distributions, or a kernel you have compiled in the past. In certain circumstances you could require to compile and insert a module into a running kernel which you are not allowed to recompile, or on a machine that you prefer not to reboot. If you can't think of a case that will force you to use modules for a precompiled kernel you might want to skip this and treat the rest of this chapter as a big footnote.
|
|
</p>
|
|
|
|
<p>
|
|
Now, if you just install a kernel source tree, use it to compile your kernel module and you try to insert your module into the kernel, in most cases you would obtain an error as follows:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-txt">insmod: error inserting 'poet_atkm.ko': -1 Invalid module format
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
Less cryptical information are logged to the systemd journal:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-txt">Jun 4 22:07:54 localhost kernel: poet_atkm: version magic '2.6.5-1.358custom 686
|
|
REGPARM 4KSTACKS gcc-3.3' should be '2.6.5-1.358 686 REGPARM 4KSTACKS gcc-3.3'
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
In other words, your kernel refuses to accept your module because version strings (more precisely, version magics) do not match. Incidentally, version magics are stored in the module object in the form of a static string, starting with vermagic:. Version data are inserted in your module when it is linked against the <b>init/vermagic.o</b> file. To inspect version magics and other strings stored in a given module, issue the modinfo module.ko command:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-txt"># sudo modinfo hello-4.ko
|
|
license: GPL
|
|
author: Bob Mottram <bob@freedombone.net>
|
|
description: A sample driver
|
|
vermagic: 4.9.11-1.358 amd64 REGPARM 4KSTACKS gcc-4.9.2
|
|
depends:
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
To overcome this problem we could resort to the <b>–force-vermagic</b> option, but this solution is potentially unsafe, and unquestionably inacceptable in production modules. Consequently, we want to compile our module in an environment which was identical to the one in which our precompiled kernel was built. How to do this, is the subject of the remainder of this chapter.
|
|
</p>
|
|
|
|
<p>
|
|
First of all, make sure that a kernel source tree is available, having exactly the same version as your current kernel. Then, find the configuration file which was used to compile your precompiled kernel. Usually, this is available in your current <i>boot directory, under a name like config-2.6.x. You may just want to copy it to your kernel source tree: *cp /boot/config-`uname -r` /usr/src/linux-`uname -r`</i>.config*.
|
|
</p>
|
|
|
|
<p>
|
|
Let's focus again on the previous error message: a closer look at the version magic strings suggests that, even with two configuration files which are exactly the same, a slight difference in the version magic could be possible, and it is sufficient to prevent insertion of the module into the kernel. That slight difference, namely the custom string which appears in the module's version magic and not in the kernel's one, is due to a modification with respect to the original, in the makefile that some distribution include. Then, examine your <b>/usr/src/linux/Makefile</b>, and make sure that the specified version information matches exactly the one used for your current kernel. For example, you makefile could start as follows:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-makefile"><span class="org-variable-name">VERSION</span> = 4
|
|
<span class="org-variable-name">PATCHLEVEL</span> = 7
|
|
<span class="org-variable-name">SUBLEVEL</span> = 4
|
|
<span class="org-variable-name">EXTRAVERSION</span> = -1.358custom
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
In this case, you need to restore the value of symbol <b>EXTRAVERSION</b> to -1.358. We suggest to keep a backup copy of the makefile used to compile your kernel available in <b>/lib/modules/4.9.11-1.358/build</b>. A simple <b>cp /lib/modules/`uname-r`/build/Makefile /usr/src/linux-`uname -r`</b> should suffice. Additionally, if you already started a kernel build with the previous (wrong) Makefile, you should also rerun make, or directly modify symbol UTS_RELEASE in file <b>/usr/src/linux-4.9.11/include/linux/version.h</b> according to contents of file <b>/lib/modules/4.9.11/build/include/linux/version.h</b>, or overwrite the latter with the first.
|
|
</p>
|
|
|
|
<p>
|
|
Now, please run make to update configuration and version headers and objects:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-txt"># make
|
|
CHK include/linux/version.h
|
|
UPD include/linux/version.h
|
|
SYMLINK include/asm -> include/asm-i386
|
|
SPLIT include/linux/autoconf.h -> include/config/*
|
|
HOSTCC scripts/basic/fixdep
|
|
HOSTCC scripts/basic/split-include
|
|
HOSTCC scripts/basic/docproc
|
|
HOSTCC scripts/conmakehash
|
|
HOSTCC scripts/kallsyms
|
|
CC scripts/empty.o
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
If you do not desire to actually compile the kernel, you can interrupt the build process (CTRL-C) just after the SPLIT line, because at that time, the files you need will be are ready. Now you can turn back to the directory of your module and compile it: It will be built exactly according your current kernel settings, and it will load into it without any errors.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-org2e995ae" class="outline-2">
|
|
<h2 id="org2e995ae">Preliminaries</h2>
|
|
<div class="outline-text-2" id="text-org2e995ae">
|
|
</div>
|
|
<div id="outline-container-org2c984aa" class="outline-3">
|
|
<h3 id="org2c984aa">How modules begin and end</h3>
|
|
<div class="outline-text-3" id="text-org2c984aa">
|
|
<p>
|
|
A program usually begins with a <b>main()</b> function, executes a bunch of instructions and terminates upon completion of those instructions. Kernel modules work a bit differently. A module always begin with either the init_module or the function you specify with module_init call. This is the entry function for modules; it tells the kernel what functionality the module provides and sets up the kernel to run the module's functions when they're needed. Once it does this, entry function returns and the module does nothing until the kernel wants to do something with the code that the module provides.
|
|
</p>
|
|
|
|
<p>
|
|
All modules end by calling either <b>cleanup_module</b> or the function you specify with the <b>module_exit</b> call. This is the exit function for modules; it undoes whatever entry function did. It unregisters the functionality that the entry function registered.
|
|
</p>
|
|
|
|
<p>
|
|
Every module must have an entry function and an exit function. Since there's more than one way to specify entry and exit functions, I'll try my best to use the terms `entry function' and `exit function', but if I slip and simply refer to them as init_module and cleanup_module, I think you'll know what I mean.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-org27d800d" class="outline-3">
|
|
<h3 id="org27d800d">Functions available to modules</h3>
|
|
<div class="outline-text-3" id="text-org27d800d">
|
|
<p>
|
|
Programmers use functions they don't define all the time. A prime example of this is <b>printf()</b>. You use these library functions which are provided by the standard C library, libc. The definitions for these functions don't actually enter your program until the linking stage, which insures that the code (for printf() for example) is available, and fixes the call instruction to point to that code.
|
|
</p>
|
|
|
|
<p>
|
|
Kernel modules are different here, too. In the hello world example, you might have noticed that we used a function, <b>printk()</b> but didn't include a standard I/O library. That's because modules are object files whose symbols get resolved upon insmod'ing. The definition for the symbols comes from the kernel itself; the only external functions you can use are the ones provided by the kernel. If you're curious about what symbols have been exported by your kernel, take a look at <b>/proc/kallsyms</b>.
|
|
</p>
|
|
|
|
<p>
|
|
One point to keep in mind is the difference between library functions and system calls. Library functions are higher level, run completely in user space and provide a more convenient interface for the programmer to the functions that do the real work — system calls. System calls run in kernel mode on the user's behalf and are provided by the kernel itself. The library function printf() may look like a very general printing function, but all it really does is format the data into strings and write the string data using the low-level system call write(), which then sends the data to standard output.
|
|
</p>
|
|
|
|
<p>
|
|
Would you like to see what system calls are made by printf()? It's easy! Compile the following program:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-c"><span class="org-preprocessor">#include</span> <span class="org-string"><stdio.h></span>
|
|
|
|
<span class="org-type">int</span> <span class="org-function-name">main</span>(<span class="org-type">void</span>)
|
|
{
|
|
printf(<span class="org-string">"hello"</span>);
|
|
<span class="org-keyword">return</span> 0;
|
|
}
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
with <b>gcc -Wall -o hello hello.c</b>. Run the exectable with <b>strace ./hello</b>. Are you impressed? Every line you see corresponds to a system call. <a href="https://strace.io/">strace</a> is a handy program that gives you details about what system calls a program is making, including which call is made, what its arguments are and what it returns. It's an invaluable tool for figuring out things like what files a program is trying to access. Towards the end, you'll see a line which looks like write (1, "hello", 5hello). There it is. The face behind the printf() mask. You may not be familiar with write, since most people use library functions for file I/O (like fopen, fputs, fclose). If that's the case, try looking at man 2 write. The 2nd man section is devoted to system calls (like kill() and read()). The 3rd man section is devoted to library calls, which you would probably be more familiar with (like cosh() and random()).
|
|
</p>
|
|
|
|
<p>
|
|
You can even write modules to replace the kernel's system calls, which we'll do shortly. Crackers often make use of this sort of thing for backdoors or trojans, but you can write your own modules to do more benign things, like have the kernel write Tee hee, that tickles! everytime someone tries to delete a file on your system.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-org2af6d40" class="outline-3">
|
|
<h3 id="org2af6d40">User Space vs Kernel Space</h3>
|
|
<div class="outline-text-3" id="text-org2af6d40">
|
|
<p>
|
|
A kernel is all about access to resources, whether the resource in question happens to be a video card, a hard drive or even memory. Programs often compete for the same resource. As I just saved this document, updatedb started updating the locate database. My vim session and updatedb are both using the hard drive concurrently. The kernel needs to keep things orderly, and not give users access to resources whenever they feel like it. To this end, a CPU can run in different modes. Each mode gives a different level of freedom to do what you want on the system. The Intel 80386 architecture had 4 of these modes, which were called rings. Unix uses only two rings; the highest ring (ring 0, also known as `supervisor mode' where everything is allowed to happen) and the lowest ring, which is called `user mode'.
|
|
</p>
|
|
|
|
<p>
|
|
Recall the discussion about library functions vs system calls. Typically, you use a library function in user mode. The library function calls one or more system calls, and these system calls execute on the library function's behalf, but do so in supervisor mode since they are part of the kernel itself. Once the system call completes its task, it returns and execution gets transfered back to user mode.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-org7de38e9" class="outline-3">
|
|
<h3 id="org7de38e9">Name Space</h3>
|
|
<div class="outline-text-3" id="text-org7de38e9">
|
|
<p>
|
|
When you write a small C program, you use variables which are convenient and make sense to the reader. If, on the other hand, you're writing routines which will be part of a bigger problem, any global variables you have are part of a community of other peoples' global variables; some of the variable names can clash. When a program has lots of global variables which aren't meaningful enough to be distinguished, you get namespace pollution. In large projects, effort must be made to remember reserved names, and to find ways to develop a scheme for naming unique variable names and symbols.
|
|
</p>
|
|
|
|
<p>
|
|
When writing kernel code, even the smallest module will be linked against the entire kernel, so this is definitely an issue. The best way to deal with this is to declare all your variables as static and to use a well-defined prefix for your symbols. By convention, all kernel prefixes are lowercase. If you don't want to declare everything as static, another option is to declare a symbol table and register it with a kernel. We'll get to this later.
|
|
</p>
|
|
|
|
<p>
|
|
The file <b>/proc/kallsyms</b> holds all the symbols that the kernel knows about and which are therefore accessible to your modules since they share the kernel's codespace.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-org0a073e1" class="outline-3">
|
|
<h3 id="org0a073e1">Code space</h3>
|
|
<div class="outline-text-3" id="text-org0a073e1">
|
|
<p>
|
|
Memory management is a very complicated subject and the majority of O'Reilly's "<i>Understanding The Linux Kernel</i>" exclusively covers memory management! We're not setting out to be experts on memory managements, but we do need to know a couple of facts to even begin worrying about writing real modules.
|
|
</p>
|
|
|
|
<p>
|
|
If you haven't thought about what a segfault really means, you may be surprised to hear that pointers don't actually point to memory locations. Not real ones, anyway. When a process is created, the kernel sets aside a portion of real physical memory and hands it to the process to use for its executing code, variables, stack, heap and other things which a computer scientist would know about. This memory begins with 0x00000000 and extends up to whatever it needs to be. Since the memory space for any two processes don't overlap, every process that can access a memory address, say 0xbffff978, would be accessing a different location in real physical memory! The processes would be accessing an index named 0xbffff978 which points to some kind of offset into the region of memory set aside for that particular process. For the most part, a process like our Hello, World program can't access the space of another process, although there are ways which we'll talk about later.
|
|
</p>
|
|
|
|
<p>
|
|
The kernel has its own space of memory as well. Since a module is code which can be dynamically inserted and removed in the kernel (as opposed to a semi-autonomous object), it shares the kernel's codespace rather than having its own. Therefore, if your module segfaults, the kernel segfaults. And if you start writing over data because of an off-by-one error, then you're trampling on kernel data (or code). This is even worse than it sounds, so try your best to be careful.
|
|
</p>
|
|
|
|
<p>
|
|
By the way, I would like to point out that the above discussion is true for any operating system which uses a monolithic kernel. This isn't quite the same thing as <i>"building all your modules into the kernel"</i>, although the idea is the same. There are things called microkernels which have modules which get their own codespace. The GNU Hurd and the Magenta kernel of Google Fuchsia are two examples of a microkernel.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-orgad8ccf5" class="outline-3">
|
|
<h3 id="orgad8ccf5">Device Drivers</h3>
|
|
<div class="outline-text-3" id="text-orgad8ccf5">
|
|
<p>
|
|
One class of module is the device driver, which provides functionality for hardware like a serial port. On unix, each piece of hardware is represented by a file located in /dev named a device file which provides the means to communicate with the hardware. The device driver provides the communication on behalf of a user program. So the es1370.o sound card device driver might connect the /dev/sound device file to the Ensoniq IS1370 sound card. A userspace program like mp3blaster can use /dev/sound without ever knowing what kind of sound card is installed.
|
|
</p>
|
|
</div>
|
|
|
|
<ul class="org-ul">
|
|
<li><a id="org4b813bb"></a>Major and Minor Numbers<br />
|
|
<div class="outline-text-5" id="text-org4b813bb">
|
|
<p>
|
|
Let's look at some device files. Here are device files which represent the first three partitions on the primary master IDE hard drive:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-sh"><span class="org-comment-delimiter"># </span><span class="org-comment">ls -l /dev/hda[1-3]</span>
|
|
brw-rw---- 1 root disk 3, 1 Jul 5 2000 /dev/hda1
|
|
brw-rw---- 1 root disk 3, 2 Jul 5 2000 /dev/hda2
|
|
brw-rw---- 1 root disk 3, 3 Jul 5 2000 /dev/hda3
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
Notice the column of numbers separated by a comma? The first number is called the device's major number. The second number is the minor number. The major number tells you which driver is used to access the hardware. Each driver is assigned a unique major number; all device files with the same major number are controlled by the same driver. All the above major numbers are 3, because they're all controlled by the same driver.
|
|
</p>
|
|
|
|
<p>
|
|
The minor number is used by the driver to distinguish between the various hardware it controls. Returning to the example above, although all three devices are handled by the same driver they have unique minor numbers because the driver sees them as being different pieces of hardware.
|
|
</p>
|
|
|
|
<p>
|
|
Devices are divided into two types: character devices and block devices. The difference is that block devices have a buffer for requests, so they can choose the best order in which to respond to the requests. This is important in the case of storage devices, where it's faster to read or write sectors which are close to each other, rather than those which are further apart. Another difference is that block devices can only accept input and return output in blocks (whose size can vary according to the device), whereas character devices are allowed to use as many or as few bytes as they like. Most devices in the world are character, because they don't need this type of buffering, and they don't operate with a fixed block size. You can tell whether a device file is for a block device or a character device by looking at the first character in the output of ls -l. If it's `b' then it's a block device, and if it's `c' then it's a character device. The devices you see above are block devices. Here are some character devices (the serial ports):
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-sh">crw-rw---- 1 root dial 4, 64 Feb 18 23:34 /dev/ttyS0
|
|
crw-r----- 1 root dial 4, 65 Nov 17 10:26 /dev/ttyS1
|
|
crw-rw---- 1 root dial 4, 66 Jul 5 2000 /dev/ttyS2
|
|
crw-rw---- 1 root dial 4, 67 Jul 5 2000 /dev/ttyS3
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
If you want to see which major numbers have been assigned, you can look at /usr/src/linux/Documentation/devices.txt.
|
|
</p>
|
|
|
|
<p>
|
|
When the system was installed, all of those device files were created by the mknod command. To create a new char device named `coffee' with major/minor number 12 and 2, simply do mknod /dev/coffee c 12 2. You don't have to put your device files into /dev, but it's done by convention. Linus put his device files in /dev, and so should you. However, when creating a device file for testing purposes, it's probably OK to place it in your working directory where you compile the kernel module. Just be sure to put it in the right place when you're done writing the device driver.
|
|
</p>
|
|
|
|
<p>
|
|
I would like to make a few last points which are implicit from the above discussion, but I'd like to make them explicit just in case. When a device file is accessed, the kernel uses the major number of the file to determine which driver should be used to handle the access. This means that the kernel doesn't really need to use or even know about the minor number. The driver itself is the only thing that cares about the minor number. It uses the minor number to distinguish between different pieces of hardware.
|
|
</p>
|
|
|
|
<p>
|
|
By the way, when I say `hardware', I mean something a bit more abstract than a PCI card that you can hold in your hand. Look at these two device files:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-sh">% ls -l /dev/fd0 /dev/fd0u1680
|
|
brwxrwxrwx 1 root floppy 2, 0 Jul 5 2000 /dev/fd0
|
|
brw-rw---- 1 root floppy 2, 44 Jul 5 2000 /dev/fd0u1680
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
By now you can look at these two device files and know instantly that they are block devices and are handled by same driver (block major 2). You might even be aware that these both represent your floppy drive, even if you only have one floppy drive. Why two files? One represents the floppy drive with 1.44 MB of storage. The other is the same floppy drive with 1.68 MB of storage, and corresponds to what some people call a `superformatted' disk. One that holds more data than a standard formatted floppy. So here's a case where two device files with different minor number actually represent the same piece of physical hardware. So just be aware that the word `hardware' in our discussion can mean something very abstract.
|
|
</p>
|
|
</div>
|
|
</li>
|
|
</ul>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-org15e4afe" class="outline-2">
|
|
<h2 id="org15e4afe">Character Device drivers</h2>
|
|
<div class="outline-text-2" id="text-org15e4afe">
|
|
</div>
|
|
<div id="outline-container-orgf3946e3" class="outline-3">
|
|
<h3 id="orgf3946e3">The file_operations Structure</h3>
|
|
<div class="outline-text-3" id="text-orgf3946e3">
|
|
<p>
|
|
The file_operations structure is defined in <b>/usr/include/linux/fs.h</b>, and holds pointers to functions defined by the driver that perform various operations on the device. Each field of the structure corresponds to the address of some function defined by the driver to handle a requested operation.
|
|
</p>
|
|
|
|
<p>
|
|
For example, every character driver needs to define a function that reads from the device. The file_operations structure holds the address of the module's function that performs that operation. Here is what the definition looks like for kernel 3.0:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-c"><span class="org-keyword">struct</span> <span class="org-type">file_operations</span> {
|
|
<span class="org-keyword">struct</span> <span class="org-type">module</span> *<span class="org-variable-name">owner</span>;
|
|
<span class="org-type">loff_t</span> (*<span class="org-function-name">llseek</span>) (<span class="org-keyword">struct</span> <span class="org-type">file</span> *, <span class="org-type">loff_t</span>, <span class="org-type">int</span>);
|
|
<span class="org-type">ssize_t</span> (*<span class="org-function-name">read</span>) (<span class="org-keyword">struct</span> <span class="org-type">file</span> *, <span class="org-type">char</span> <span class="org-variable-name">__user</span> *, <span class="org-type">size_t</span>, <span class="org-type">loff_t</span> *);
|
|
<span class="org-type">ssize_t</span> (*<span class="org-function-name">write</span>) (<span class="org-keyword">struct</span> <span class="org-type">file</span> *, <span class="org-keyword">const</span> <span class="org-type">char</span> <span class="org-variable-name">__user</span> *, <span class="org-type">size_t</span>, <span class="org-type">loff_t</span> *);
|
|
<span class="org-type">ssize_t</span> (*<span class="org-function-name">aio_read</span>) (<span class="org-keyword">struct</span> <span class="org-type">kiocb</span> *, <span class="org-keyword">const</span> <span class="org-keyword">struct</span> <span class="org-type">iovec</span> *, <span class="org-type">unsigned</span> <span class="org-type">long</span>, <span class="org-type">loff_t</span>);
|
|
<span class="org-type">ssize_t</span> (*<span class="org-function-name">aio_write</span>) (<span class="org-keyword">struct</span> <span class="org-type">kiocb</span> *, <span class="org-keyword">const</span> <span class="org-keyword">struct</span> <span class="org-type">iovec</span> *, <span class="org-type">unsigned</span> <span class="org-type">long</span>, <span class="org-type">loff_t</span>);
|
|
<span class="org-type">int</span> (*<span class="org-function-name">iterate</span>) (<span class="org-keyword">struct</span> <span class="org-type">file</span> *, <span class="org-keyword">struct</span> <span class="org-type">dir_context</span> *);
|
|
<span class="org-type">unsigned</span> <span class="org-type">int</span> (*<span class="org-function-name">poll</span>) (<span class="org-keyword">struct</span> <span class="org-type">file</span> *, <span class="org-keyword">struct</span> <span class="org-type">poll_table_struct</span> *);
|
|
<span class="org-type">long</span> (*<span class="org-function-name">unlocked_ioctl</span>) (<span class="org-keyword">struct</span> <span class="org-type">file</span> *, <span class="org-type">unsigned</span> <span class="org-type">int</span>, <span class="org-type">unsigned</span> <span class="org-type">long</span>);
|
|
<span class="org-type">long</span> (*<span class="org-function-name">compat_ioctl</span>) (<span class="org-keyword">struct</span> <span class="org-type">file</span> *, <span class="org-type">unsigned</span> <span class="org-type">int</span>, <span class="org-type">unsigned</span> <span class="org-type">long</span>);
|
|
<span class="org-type">int</span> (*<span class="org-function-name">mmap</span>) (<span class="org-keyword">struct</span> <span class="org-type">file</span> *, <span class="org-keyword">struct</span> <span class="org-type">vm_area_struct</span> *);
|
|
<span class="org-type">int</span> (*<span class="org-function-name">open</span>) (<span class="org-keyword">struct</span> <span class="org-type">inode</span> *, <span class="org-keyword">struct</span> <span class="org-type">file</span> *);
|
|
<span class="org-type">int</span> (*<span class="org-function-name">flush</span>) (<span class="org-keyword">struct</span> <span class="org-type">file</span> *, <span class="org-type">fl_owner_t</span> <span class="org-variable-name">id</span>);
|
|
<span class="org-type">int</span> (*<span class="org-function-name">release</span>) (<span class="org-keyword">struct</span> <span class="org-type">inode</span> *, <span class="org-keyword">struct</span> <span class="org-type">file</span> *);
|
|
<span class="org-type">int</span> (*<span class="org-function-name">fsync</span>) (<span class="org-keyword">struct</span> <span class="org-type">file</span> *, <span class="org-type">loff_t</span>, <span class="org-type">loff_t</span>, <span class="org-type">int</span> <span class="org-variable-name">datasync</span>);
|
|
<span class="org-type">int</span> (*<span class="org-function-name">aio_fsync</span>) (<span class="org-keyword">struct</span> <span class="org-type">kiocb</span> *, <span class="org-type">int</span> <span class="org-variable-name">datasync</span>);
|
|
<span class="org-type">int</span> (*<span class="org-function-name">fasync</span>) (<span class="org-type">int</span>, <span class="org-keyword">struct</span> <span class="org-type">file</span> *, <span class="org-type">int</span>);
|
|
<span class="org-type">int</span> (*<span class="org-function-name">lock</span>) (<span class="org-keyword">struct</span> <span class="org-type">file</span> *, <span class="org-type">int</span>, <span class="org-keyword">struct</span> <span class="org-type">file_lock</span> *);
|
|
<span class="org-type">ssize_t</span> (*<span class="org-function-name">sendpage</span>) (<span class="org-keyword">struct</span> <span class="org-type">file</span> *, <span class="org-keyword">struct</span> <span class="org-type">page</span> *, <span class="org-type">int</span>, <span class="org-type">size_t</span>, <span class="org-type">loff_t</span> *, <span class="org-type">int</span>);
|
|
<span class="org-type">unsigned</span> <span class="org-type">long</span> (*<span class="org-function-name">get_unmapped_area</span>)(<span class="org-keyword">struct</span> <span class="org-type">file</span> *, <span class="org-type">unsigned</span> <span class="org-type">long</span>, <span class="org-type">unsigned</span> <span class="org-type">long</span>, <span class="org-type">unsigned</span> <span class="org-type">long</span>, <span class="org-type">unsigned</span> <span class="org-type">long</span>);
|
|
<span class="org-type">int</span> (*<span class="org-function-name">check_flags</span>)(<span class="org-type">int</span>);
|
|
<span class="org-type">int</span> (*<span class="org-function-name">flock</span>) (<span class="org-keyword">struct</span> <span class="org-type">file</span> *, <span class="org-type">int</span>, <span class="org-keyword">struct</span> <span class="org-type">file_lock</span> *);
|
|
<span class="org-type">ssize_t</span> (*<span class="org-function-name">splice_write</span>)(<span class="org-keyword">struct</span> <span class="org-type">pipe_inode_info</span> *, <span class="org-keyword">struct</span> <span class="org-type">file</span> *, <span class="org-type">loff_t</span> *, <span class="org-type">size_t</span>, <span class="org-type">unsigned</span> <span class="org-type">int</span>);
|
|
<span class="org-type">ssize_t</span> (*<span class="org-function-name">splice_read</span>)(<span class="org-keyword">struct</span> <span class="org-type">file</span> *, <span class="org-type">loff_t</span> *, <span class="org-keyword">struct</span> <span class="org-type">pipe_inode_info</span> *, <span class="org-type">size_t</span>, <span class="org-type">unsigned</span> <span class="org-type">int</span>);
|
|
<span class="org-type">int</span> (*<span class="org-function-name">setlease</span>)(<span class="org-keyword">struct</span> <span class="org-type">file</span> *, <span class="org-type">long</span>, <span class="org-keyword">struct</span> <span class="org-type">file_lock</span> **);
|
|
<span class="org-type">long</span> (*<span class="org-function-name">fallocate</span>)(<span class="org-keyword">struct</span> <span class="org-type">file</span> *<span class="org-variable-name">file</span>, <span class="org-type">int</span> <span class="org-variable-name">mode</span>, <span class="org-type">loff_t</span> <span class="org-variable-name">offset</span>,
|
|
<span class="org-type">loff_t</span> <span class="org-variable-name">len</span>);
|
|
<span class="org-type">int</span> (*<span class="org-function-name">show_fdinfo</span>)(<span class="org-keyword">struct</span> <span class="org-type">seq_file</span> *<span class="org-variable-name">m</span>, <span class="org-keyword">struct</span> <span class="org-type">file</span> *<span class="org-variable-name">f</span>);
|
|
};
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
Some operations are not implemented by a driver. For example, a driver that handles a video card won't need to read from a directory structure. The corresponding entries in the file_operations structure should be set to NULL.
|
|
</p>
|
|
|
|
<p>
|
|
There is a gcc extension that makes assigning to this structure more convenient. You'll see it in modern drivers, and may catch you by surprise. This is what the new way of assigning to the structure looks like:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-c"><span class="org-keyword">struct</span> <span class="org-type">file_operations</span> <span class="org-variable-name">fops</span> = {
|
|
read: device_read,
|
|
write: device_write,
|
|
open: device_open,
|
|
release: device_release
|
|
};
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
However, there's also a C99 way of assigning to elements of a structure, and this is definitely preferred over using the GNU extension. The version of gcc the author used when writing this, 2.95, supports the new C99 syntax. You should use this syntax in case someone wants to port your driver. It will help with compatibility:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-c"><span class="org-keyword">struct</span> <span class="org-type">file_operations</span> <span class="org-variable-name">fops</span> = {
|
|
.read = device_read,
|
|
.write = device_write,
|
|
.open = device_open,
|
|
.release = device_release
|
|
};
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
The meaning is clear, and you should be aware that any member of the structure which you don't explicitly assign will be initialized to NULL by gcc.
|
|
</p>
|
|
|
|
<p>
|
|
An instance of struct file_operations containing pointers to functions that are used to implement read, write, open, … syscalls is commonly named fops.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-org4f5ee68" class="outline-3">
|
|
<h3 id="org4f5ee68">The file structure</h3>
|
|
<div class="outline-text-3" id="text-org4f5ee68">
|
|
<p>
|
|
Each device is represented in the kernel by a file structure, which is defined in <b>linux/fs.h</b>. Be aware that a file is a kernel level structure and never appears in a user space program. It's not the same thing as a <b>FILE</b>, which is defined by glibc and would never appear in a kernel space function. Also, its name is a bit misleading; it represents an abstract open `file', not a file on a disk, which is represented by a structure named inode.
|
|
</p>
|
|
|
|
<p>
|
|
An instance of struct file is commonly named filp. You'll also see it refered to as struct file file. Resist the temptation.
|
|
</p>
|
|
|
|
<p>
|
|
Go ahead and look at the definition of file. Most of the entries you see, like struct dentry aren't used by device drivers, and you can ignore them. This is because drivers don't fill file directly; they only use structures contained in file which are created elsewhere.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-org582dd8b" class="outline-3">
|
|
<h3 id="org582dd8b">Registering A Device</h3>
|
|
<div class="outline-text-3" id="text-org582dd8b">
|
|
<p>
|
|
As discussed earlier, char devices are accessed through device files, usually located in /dev. This is by convention. When writing a driver, it's OK to put the device file in your current directory. Just make sure you place it in /dev for a production driver. The major number tells you which driver handles which device file. The minor number is used only by the driver itself to differentiate which device it's operating on, just in case the driver handles more than one device.
|
|
</p>
|
|
|
|
<p>
|
|
Adding a driver to your system means registering it with the kernel. This is synonymous with assigning it a major number during the module's initialization. You do this by using the register_chrdev function, defined by linux/fs.h.
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-c"><span class="org-type">int</span> <span class="org-function-name">register_chrdev</span>(<span class="org-type">unsigned</span> <span class="org-type">int</span> <span class="org-variable-name">major</span>, <span class="org-keyword">const</span> <span class="org-type">char</span> *<span class="org-variable-name">name</span>, <span class="org-keyword">struct</span> <span class="org-type">file_operations</span> *<span class="org-variable-name">fops</span>);
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
where unsigned int major is the major number you want to request, <i>const char *name</i> is the name of the device as it'll appear in <b>/proc/devices</b> and <i>struct file_operations *fops</i> is a pointer to the file_operations table for your driver. A negative return value means the registration failed. Note that we didn't pass the minor number to register_chrdev. That's because the kernel doesn't care about the minor number; only our driver uses it.
|
|
</p>
|
|
|
|
<p>
|
|
Now the question is, how do you get a major number without hijacking one that's already in use? The easiest way would be to look through Documentation /devices.txt and pick an unused one. That's a bad way of doing things because you'll never be sure if the number you picked will be assigned later. The answer is that you can ask the kernel to assign you a dynamic major number.
|
|
</p>
|
|
|
|
<p>
|
|
If you pass a major number of 0 to register_chrdev, the return value will be the dynamically allocated major number. The downside is that you can't make a device file in advance, since you don't know what the major number will be. There are a couple of ways to do this. First, the driver itself can print the newly assigned number and we can make the device file by hand. Second, the newly registered device will have an entry in <b>/proc/devices</b>, and we can either make the device file by hand or write a shell script to read the file in and make the device file. The third method is we can have our driver make the the device file using the mknod system call after a successful registration and rm during the call to cleanup_module.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-orga4ee863" class="outline-3">
|
|
<h3 id="orga4ee863">Unregistering A Device</h3>
|
|
<div class="outline-text-3" id="text-orga4ee863">
|
|
<p>
|
|
We can't allow the kernel module to be rmmod'ed whenever root feels like it. If the device file is opened by a process and then we remove the kernel module, using the file would cause a call to the memory location where the appropriate function (read/write) used to be. If we're lucky, no other code was loaded there, and we'll get an ugly error message. If we're unlucky, another kernel module was loaded into the same location, which means a jump into the middle of another function within the kernel. The results of this would be impossible to predict, but they can't be very positive.
|
|
</p>
|
|
|
|
<p>
|
|
Normally, when you don't want to allow something, you return an error code (a negative number) from the function which is supposed to do it. With cleanup_module that's impossible because it's a void function. However, there's a counter which keeps track of how many processes are using your module. You can see what it's value is by looking at the 3rd field of <b>/proc/modules</b>. If this number isn't zero, rmmod will fail. Note that you don't have to check the counter from within cleanup_module because the check will be performed for you by the system call sys_delete_module, defined in <b>linux/module.c</b>. You shouldn't use this counter directly, but there are functions defined in <b>linux/module.h</b> which let you increase, decrease and display this counter:
|
|
</p>
|
|
|
|
<ul class="org-ul">
|
|
<li>try_module_get(THIS_MODULE): Increment the use count.</li>
|
|
<li>module_put(THIS_MODULE): Decrement the use count.</li>
|
|
</ul>
|
|
|
|
<p>
|
|
It's important to keep the counter accurate; if you ever do lose track of the correct usage count, you'll never be able to unload the module; it's now reboot time, boys and girls. This is bound to happen to you sooner or later during a module's development.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-org142f9ce" class="outline-3">
|
|
<h3 id="org142f9ce">chardev.c</h3>
|
|
<div class="outline-text-3" id="text-org142f9ce">
|
|
<p>
|
|
The next code sample creates a char driver named chardev. You can cat its device file.
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-bash">cat /proc/devices
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
(or open the file with a program) and the driver will put the number of times the device file has been read from into the file. We don't support writing to the file (like <b>echo "hi" > /dev/hello</b>), but catch these attempts and tell the user that the operation isn't supported. Don't worry if you don't see what we do with the data we read into the buffer; we don't do much with it. We simply read in the data and print a message acknowledging that we received it.
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-c"><span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * chardev.c: Creates a read-only char device that says how many times</span>
|
|
<span class="org-comment"> * you've read from the dev file</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/kernel.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/module.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/fs.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><asm/uaccess.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">for put_user </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Prototypes - this would normally go in a .h file</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-type">int</span> <span class="org-function-name">init_module</span>(<span class="org-type">void</span>);
|
|
<span class="org-type">void</span> <span class="org-function-name">cleanup_module</span>(<span class="org-type">void</span>);
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-function-name">device_open</span>(<span class="org-keyword">struct</span> <span class="org-type">inode</span> *, <span class="org-keyword">struct</span> <span class="org-type">file</span> *);
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-function-name">device_release</span>(<span class="org-keyword">struct</span> <span class="org-type">inode</span> *, <span class="org-keyword">struct</span> <span class="org-type">file</span> *);
|
|
<span class="org-keyword">static</span> <span class="org-type">ssize_t</span> <span class="org-function-name">device_read</span>(<span class="org-keyword">struct</span> <span class="org-type">file</span> *, <span class="org-type">char</span> *, <span class="org-type">size_t</span>, <span class="org-type">loff_t</span> *);
|
|
<span class="org-keyword">static</span> <span class="org-type">ssize_t</span> <span class="org-function-name">device_write</span>(<span class="org-keyword">struct</span> <span class="org-type">file</span> *, <span class="org-keyword">const</span> <span class="org-type">char</span> *, <span class="org-type">size_t</span>, <span class="org-type">loff_t</span> *);
|
|
|
|
<span class="org-preprocessor">#define</span> <span class="org-variable-name">SUCCESS</span> 0
|
|
<span class="org-preprocessor">#define</span> <span class="org-variable-name">DEVICE_NAME</span> <span class="org-string">"chardev"</span> <span class="org-comment-delimiter">/* </span><span class="org-comment">Dev name as it appears in /proc/devices </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#define</span> <span class="org-variable-name">BUF_LEN</span> 80 <span class="org-comment-delimiter">/* </span><span class="org-comment">Max length of the message from the device </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Global variables are declared as static, so are global within the file.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-variable-name">Major</span>; <span class="org-comment-delimiter">/* </span><span class="org-comment">Major number assigned to our device driver </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-variable-name">Device_Open</span> = 0; <span class="org-comment-delimiter">/* </span><span class="org-comment">Is device open?</span>
|
|
<span class="org-comment"> * Used to prevent multiple access to device </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">static</span> <span class="org-type">char</span> <span class="org-variable-name">msg</span>[BUF_LEN]; <span class="org-comment-delimiter">/* </span><span class="org-comment">The msg the device will give when asked </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">static</span> <span class="org-type">char</span> *<span class="org-variable-name">msg_Ptr</span>;
|
|
|
|
<span class="org-keyword">static</span> <span class="org-keyword">struct</span> <span class="org-type">file_operations</span> <span class="org-variable-name">fops</span> = {
|
|
.read = device_read,
|
|
.write = device_write,
|
|
.open = device_open,
|
|
.release = device_release
|
|
};
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * This function is called when the module is loaded</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-type">int</span> <span class="org-function-name">init_module</span>(<span class="org-type">void</span>)
|
|
{
|
|
Major = register_chrdev(0, DEVICE_NAME, &fops);
|
|
|
|
<span class="org-keyword">if</span> (Major < 0) {
|
|
printk(KERN_ALERT <span class="org-string">"Registering char device failed with %d\n"</span>, Major);
|
|
<span class="org-keyword">return</span> Major;
|
|
}
|
|
|
|
printk(KERN_INFO <span class="org-string">"I was assigned major number %d. To talk to\n"</span>, Major);
|
|
printk(KERN_INFO <span class="org-string">"the driver, create a dev file with\n"</span>);
|
|
printk(KERN_INFO <span class="org-string">"'mknod /dev/%s c %d 0'.\n"</span>, DEVICE_NAME, Major);
|
|
printk(KERN_INFO <span class="org-string">"Try various minor numbers. Try to cat and echo to\n"</span>);
|
|
printk(KERN_INFO <span class="org-string">"the device file.\n"</span>);
|
|
printk(KERN_INFO <span class="org-string">"Remove the device file and module when done.\n"</span>);
|
|
|
|
<span class="org-keyword">return</span> SUCCESS;
|
|
}
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * This function is called when the module is unloaded</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-type">void</span> <span class="org-function-name">cleanup_module</span>(<span class="org-type">void</span>)
|
|
{
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Unregister the device</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
unregister_chrdev(Major, DEVICE_NAME);
|
|
}
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Methods</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Called when a process tries to open the device file, like</span>
|
|
<span class="org-comment"> * "cat /dev/mycharfile"</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-function-name">device_open</span>(<span class="org-keyword">struct</span> <span class="org-type">inode</span> *<span class="org-variable-name">inode</span>, <span class="org-keyword">struct</span> <span class="org-type">file</span> *<span class="org-variable-name">file</span>)
|
|
{
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-variable-name">counter</span> = 0;
|
|
|
|
<span class="org-keyword">if</span> (Device_Open)
|
|
<span class="org-keyword">return</span> -EBUSY;
|
|
|
|
Device_Open++;
|
|
sprintf(msg, <span class="org-string">"I already told you %d times Hello world!\n"</span>, counter++);
|
|
msg_Ptr = msg;
|
|
try_module_get(THIS_MODULE);
|
|
|
|
<span class="org-keyword">return</span> SUCCESS;
|
|
}
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Called when a process closes the device file.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-function-name">device_release</span>(<span class="org-keyword">struct</span> <span class="org-type">inode</span> *<span class="org-variable-name">inode</span>, <span class="org-keyword">struct</span> <span class="org-type">file</span> *<span class="org-variable-name">file</span>)
|
|
{
|
|
Device_Open--; <span class="org-comment-delimiter">/* </span><span class="org-comment">We're now ready for our next caller </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Decrement the usage count, or else once you opened the file, you'll</span>
|
|
<span class="org-comment"> * never get get rid of the module.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
module_put(THIS_MODULE);
|
|
|
|
<span class="org-keyword">return</span> SUCCESS;
|
|
}
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Called when a process, which already opened the dev file, attempts to</span>
|
|
<span class="org-comment"> * read from it.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">static</span> <span class="org-type">ssize_t</span> <span class="org-function-name">device_read</span>(<span class="org-keyword">struct</span> <span class="org-type">file</span> *<span class="org-variable-name">filp</span>, <span class="org-comment-delimiter">/* </span><span class="org-comment">see include/linux/fs.h </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-type">char</span> *<span class="org-variable-name">buffer</span>, <span class="org-comment-delimiter">/* </span><span class="org-comment">buffer to fill with data </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-type">size_t</span> <span class="org-variable-name">length</span>, <span class="org-comment-delimiter">/* </span><span class="org-comment">length of the buffer </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-type">loff_t</span> * <span class="org-variable-name">offset</span>)
|
|
{
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Number of bytes actually written to the buffer</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-type">int</span> <span class="org-variable-name">bytes_read</span> = 0;
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * If we're at the end of the message,</span>
|
|
<span class="org-comment"> * return 0 signifying end of file</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">if</span> (*msg_Ptr == 0)
|
|
<span class="org-keyword">return</span> 0;
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Actually put the data into the buffer</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">while</span> (length && *msg_Ptr) {
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * The buffer is in the user data segment, not the kernel</span>
|
|
<span class="org-comment"> * segment so "*" assignment won't work. We have to use</span>
|
|
<span class="org-comment"> * put_user which copies data from the kernel data segment to</span>
|
|
<span class="org-comment"> * the user data segment.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
put_user(*(msg_Ptr++), buffer++);
|
|
|
|
length--;
|
|
bytes_read++;
|
|
}
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Most read functions return the number of bytes put into the buffer</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">return</span> bytes_read;
|
|
}
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Called when a process writes to dev file: echo "hi" > /dev/hello</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">static</span> <span class="org-type">ssize_t</span> <span class="org-function-name">device_write</span>(<span class="org-keyword">struct</span> <span class="org-type">file</span> *<span class="org-variable-name">filp</span>,
|
|
<span class="org-keyword">const</span> <span class="org-type">char</span> *<span class="org-variable-name">buff</span>,
|
|
<span class="org-type">size_t</span> <span class="org-variable-name">len</span>,
|
|
<span class="org-type">loff_t</span> * <span class="org-variable-name">off</span>)
|
|
{
|
|
printk(KERN_ALERT <span class="org-string">"Sorry, this operation isn't supported.\n"</span>);
|
|
<span class="org-keyword">return</span> -EINVAL;
|
|
}
|
|
</code></pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-org0955cc2" class="outline-3">
|
|
<h3 id="org0955cc2">Writing Modules for Multiple Kernel Versions</h3>
|
|
<div class="outline-text-3" id="text-org0955cc2">
|
|
<p>
|
|
The system calls, which are the major interface the kernel shows to the processes, generally stay the same across versions. A new system call may be added, but usually the old ones will behave exactly like they used to. This is necessary for backward compatibility – a new kernel version is not supposed to break regular processes. In most cases, the device files will also remain the same. On the other hand, the internal interfaces within the kernel can and do change between versions.
|
|
</p>
|
|
|
|
<p>
|
|
The Linux kernel versions are divided between the stable versions (n.$<$even number\(>\).m) and the development versions (n.$<$odd number\(>\).m). The development versions include all the cool new ideas, including those which will be considered a mistake, or reimplemented, in the next version. As a result, you can't trust the interface to remain the same in those versions (which is why I don't bother to support them in this book, it's too much work and it would become dated too quickly). In the stable versions, on the other hand, we can expect the interface to remain the same regardless of the bug fix version (the m number).
|
|
</p>
|
|
|
|
<p>
|
|
There are differences between different kernel versions, and if you want to support multiple kernel versions, you'll find yourself having to code conditional compilation directives. The way to do this to compare the macro LINUX_VERSION_CODE to the macro KERNEL_VERSION. In version a.b.c of the kernel, the value of this macro would be \(2^{16}a+2^{8}b+c\).
|
|
</p>
|
|
|
|
<p>
|
|
While previous versions of this guide showed how you can write backward compatible code with such constructs in great detail, we decided to break with this tradition for the better. People interested in doing such might now use a LKMPG with a version matching to their kernel. We decided to version the LKMPG like the kernel, at least as far as major and minor number are concerned. We use the patchlevel for our own versioning so use LKMPG version 2.4.x for kernels 2.4.x, use LKMPG version 2.6.x for kernels 2.6.x and so on. Also make sure that you always use current, up to date versions of both, kernel and guide.
|
|
</p>
|
|
|
|
<p>
|
|
You might already have noticed that recent kernels look different. In case you haven't they look like 2.6.x.y now. The meaning of the first three items basically stays the same, but a subpatchlevel has been added and will indicate security fixes till the next stable patchlevel is out. So people can choose between a stable tree with security updates and use the latest kernel as developer tree. Search the kernel mailing list archives if you're interested in the full story.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-org94acba2" class="outline-2">
|
|
<h2 id="org94acba2">The /proc File System</h2>
|
|
<div class="outline-text-2" id="text-org94acba2">
|
|
<p>
|
|
In Linux, there is an additional mechanism for the kernel and kernel modules to send information to processes — the <b>/proc</b> file system. Originally designed to allow easy access to information about processes (hence the name), it is now used by every bit of the kernel which has something interesting to report, such as <b>/proc/modules</b> which provides the list of modules and <b>/proc/meminfo</b> which stats memory usage statistics.
|
|
</p>
|
|
|
|
<p>
|
|
The method to use the proc file system is very similar to the one used with device drivers — a structure is created with all the information needed for the <b>/proc</b> file, including pointers to any handler functions (in our case there is only one, the one called when somebody attempts to read from the <b>/proc</b> file). Then, init_module registers the structure with the kernel and cleanup_module unregisters it.
|
|
</p>
|
|
|
|
<p>
|
|
Normal file systems are located on a disk, rather than just in memory (which is where <b>/proc</b> is), and in that case the inode number is a pointer to a disk location where the file's index-node (inode for short) is located. The inode contains information about the file, for example the file's permissions, together with a pointer to the disk location or locations where the file's data can be found.
|
|
</p>
|
|
|
|
<p>
|
|
Because we don't get called when the file is opened or closed, there's nowhere for us to put try_module_get and try_module_put in this module, and if the file is opened and then the module is removed, there's no way to avoid the consequences.
|
|
</p>
|
|
|
|
<p>
|
|
Here a simple example showing how to use a <b>/proc</b> file. This is the HelloWorld for the <b>/proc</b> filesystem. There are three parts: create the file <b><i>proc</i> helloworld</b> in the function init_module, return a value (and a buffer) when the file <b>/proc/helloworld</b> is read in the callback function <b>procfile_read</b>, and delete the file <b>/proc/helloworld</b> in the function cleanup_module.
|
|
</p>
|
|
|
|
<p>
|
|
The <b>/proc/helloworld</b> is created when the module is loaded with the function <b>proc_create</b>. The return value is a <b>struct proc_dir_entry</b> , and it will be used to configure the file <b>/proc/helloworld</b> (for example, the owner of this file). A null return value means that the creation has failed.
|
|
</p>
|
|
|
|
<p>
|
|
Each time, everytime the file <b>/proc/helloworld</b> is read, the function <b>procfile_read</b> is called. Two parameters of this function are very important: the buffer (the first parameter) and the offset (the third one). The content of the buffer will be returned to the application which read it (for example the cat command). The offset is the current position in the file. If the return value of the function isn't null, then this function is called again. So be careful with this function, if it never returns zero, the read function is called endlessly.
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-txt"># cat /proc/helloworld
|
|
HelloWorld!
|
|
</code></pre>
|
|
</div>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-c"><span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> procfs1.c</span>
|
|
<span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/module.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/kernel.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/proc_fs.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><asm/uaccess.h></span>
|
|
|
|
<span class="org-preprocessor">#define</span> <span class="org-variable-name">procfs_name</span> <span class="org-string">"helloworld"</span>
|
|
|
|
<span class="org-keyword">struct</span> <span class="org-type">proc_dir_entry</span> *<span class="org-variable-name">Our_Proc_File</span>;
|
|
|
|
|
|
<span class="org-type">ssize_t</span> <span class="org-function-name">procfile_read</span>(<span class="org-keyword">struct</span> <span class="org-type">file</span> *<span class="org-variable-name">filePointer</span>,<span class="org-type">char</span> *<span class="org-variable-name">buffer</span>,
|
|
<span class="org-type">size_t</span> <span class="org-variable-name">buffer_length</span>, <span class="org-type">loff_t</span> * <span class="org-variable-name">offset</span>)
|
|
{
|
|
<span class="org-type">int</span> <span class="org-variable-name">ret</span>=0;
|
|
<span class="org-keyword">if</span>(strlen(buffer) ==0) {
|
|
printk(KERN_INFO <span class="org-string">"procfile read %s\n"</span>,filePointer->f_path.dentry->d_name.name);
|
|
ret=copy_to_user(buffer,<span class="org-string">"HelloWorld!\n"</span>,<span class="org-keyword">sizeof</span>(<span class="org-string">"HelloWorld!\n"</span>));
|
|
ret=<span class="org-keyword">sizeof</span>(<span class="org-string">"HelloWorld!\n"</span>);
|
|
}
|
|
<span class="org-keyword">return</span> ret;
|
|
|
|
}
|
|
|
|
<span class="org-keyword">static</span> <span class="org-keyword">const</span> <span class="org-keyword">struct</span> <span class="org-type">file_operations</span> <span class="org-variable-name">proc_file_fops</span> = {
|
|
.owner = THIS_MODULE,
|
|
.read = procfile_read,
|
|
};
|
|
|
|
<span class="org-type">int</span> <span class="org-function-name">init_module</span>()
|
|
{
|
|
Our_Proc_File = proc_create(procfs_name,0644,<span class="org-constant">NULL</span>,&proc_file_fops);
|
|
<span class="org-keyword">if</span>(<span class="org-constant">NULL</span>==Our_Proc_File) {
|
|
proc_remove(Our_Proc_File);
|
|
printk(KERN_ALERT <span class="org-string">"Error:Could not initialize /proc/%s\n"</span>,procfs_name);
|
|
<span class="org-keyword">return</span> -ENOMEM;
|
|
}
|
|
|
|
printk(KERN_INFO <span class="org-string">"/proc/%s created\n"</span>, procfs_name);
|
|
<span class="org-keyword">return</span> 0;
|
|
}
|
|
|
|
<span class="org-type">void</span> <span class="org-function-name">cleanup_module</span>()
|
|
{
|
|
proc_remove(Our_Proc_File);
|
|
printk(KERN_INFO <span class="org-string">"/proc/%s removed\n"</span>, procfs_name);
|
|
}
|
|
</code></pre>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-orgbaaaee0" class="outline-3">
|
|
<h3 id="orgbaaaee0">Read and Write a /proc File</h3>
|
|
<div class="outline-text-3" id="text-orgbaaaee0">
|
|
<p>
|
|
We have seen a very simple example for a /proc file where we only read the file /proc/helloworld. It's also possible to write in a /proc file. It works the same way as read, a function is called when the /proc file is written. But there is a little difference with read, data comes from user, so you have to import data from user space to kernel space (with copy_from_user or get_user)
|
|
</p>
|
|
|
|
<p>
|
|
The reason for copy_from_user or get_user is that Linux memory (on Intel architecture, it may be different under some other processors) is segmented. This means that a pointer, by itself, does not reference a unique location in memory, only a location in a memory segment, and you need to know which memory segment it is to be able to use it. There is one memory segment for the kernel, and one for each of the processes.
|
|
</p>
|
|
|
|
<p>
|
|
The only memory segment accessible to a process is its own, so when writing regular programs to run as processes, there's no need to worry about segments. When you write a kernel module, normally you want to access the kernel memory segment, which is handled automatically by the system. However, when the content of a memory buffer needs to be passed between the currently running process and the kernel, the kernel function receives a pointer to the memory buffer which is in the process segment. The put_user and get_user macros allow you to access that memory. These functions handle only one caracter, you can handle several caracters with copy_to_user and copy_from_user. As the buffer (in read or write function) is in kernel space, for write function you need to import data because it comes from user space, but not for the read function because data is already in kernel space.
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-c"><span class="org-doc">/**</span>
|
|
<span class="org-doc"> * procfs2.c - create a "file" in /proc</span>
|
|
<span class="org-doc"> *</span>
|
|
<span class="org-doc"> */</span>
|
|
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/module.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">Specifically, a module </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/kernel.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">We're doing kernel work </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/proc_fs.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">Necessary because we use the proc fs </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><asm/uaccess.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">for copy_from_user </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-preprocessor">#define</span> <span class="org-variable-name">PROCFS_MAX_SIZE</span> 1024
|
|
<span class="org-preprocessor">#define</span> <span class="org-variable-name">PROCFS_NAME</span> <span class="org-string">"buffer1k"</span>
|
|
|
|
<span class="org-doc">/**</span>
|
|
<span class="org-doc"> * This structure hold information about the /proc file</span>
|
|
<span class="org-doc"> *</span>
|
|
<span class="org-doc"> */</span>
|
|
<span class="org-keyword">static</span> <span class="org-keyword">struct</span> <span class="org-type">proc_dir_entry</span> *<span class="org-variable-name">Our_Proc_File</span>;
|
|
|
|
<span class="org-doc">/**</span>
|
|
<span class="org-doc"> * The buffer used to store character for this module</span>
|
|
<span class="org-doc"> *</span>
|
|
<span class="org-doc"> */</span>
|
|
<span class="org-keyword">static</span> <span class="org-type">char</span> <span class="org-variable-name">procfs_buffer</span>[PROCFS_MAX_SIZE];
|
|
|
|
<span class="org-doc">/**</span>
|
|
<span class="org-doc"> * The size of the buffer</span>
|
|
<span class="org-doc"> *</span>
|
|
<span class="org-doc"> */</span>
|
|
<span class="org-keyword">static</span> <span class="org-type">unsigned</span> <span class="org-type">long</span> <span class="org-variable-name">procfs_buffer_size</span> = 0;
|
|
|
|
<span class="org-doc">/**</span>
|
|
<span class="org-doc"> * This function is called then the /proc file is read</span>
|
|
<span class="org-doc"> *</span>
|
|
<span class="org-doc"> */</span>
|
|
<span class="org-type">ssize_t</span> <span class="org-function-name">procfile_read</span>(<span class="org-keyword">struct</span> <span class="org-type">file</span> *<span class="org-variable-name">filePointer</span>,<span class="org-type">char</span> *<span class="org-variable-name">buffer</span>,
|
|
<span class="org-type">size_t</span> <span class="org-variable-name">buffer_length</span>, <span class="org-type">loff_t</span> * <span class="org-variable-name">offset</span>)
|
|
{
|
|
<span class="org-type">int</span> <span class="org-variable-name">ret</span>=0;
|
|
<span class="org-keyword">if</span>(strlen(buffer) ==0) {
|
|
printk(KERN_INFO <span class="org-string">"procfile read %s\n"</span>,filePointer->f_path.dentry->d_name.name);
|
|
ret=copy_to_user(buffer,<span class="org-string">"HelloWorld!\n"</span>,<span class="org-keyword">sizeof</span>(<span class="org-string">"HelloWorld!\n"</span>));
|
|
ret=<span class="org-keyword">sizeof</span>(<span class="org-string">"HelloWorld!\n"</span>);
|
|
}
|
|
<span class="org-keyword">return</span> ret;
|
|
}
|
|
|
|
|
|
<span class="org-doc">/**</span>
|
|
<span class="org-doc"> * This function is called with the /proc file is written</span>
|
|
<span class="org-doc"> *</span>
|
|
<span class="org-doc"> */</span>
|
|
<span class="org-keyword">static</span> <span class="org-type">ssize_t</span> <span class="org-function-name">procfile_write</span>(<span class="org-keyword">struct</span> <span class="org-type">file</span> *<span class="org-variable-name">file</span>, <span class="org-keyword">const</span> <span class="org-type">char</span> *<span class="org-variable-name">buff</span>,
|
|
<span class="org-type">size_t</span> <span class="org-variable-name">len</span>, <span class="org-type">loff_t</span> *<span class="org-variable-name">off</span>)
|
|
{
|
|
procfs_buffer_size = len;
|
|
<span class="org-keyword">if</span> (procfs_buffer_size > PROCFS_MAX_SIZE)
|
|
procfs_buffer_size = PROCFS_MAX_SIZE;
|
|
|
|
<span class="org-keyword">if</span> (copy_from_user(procfs_buffer, buff, procfs_buffer_size))
|
|
<span class="org-keyword">return</span> -EFAULT;
|
|
|
|
procfs_buffer[procfs_buffer_size] = <span class="org-string">'\0'</span>;
|
|
<span class="org-keyword">return</span> procfs_buffer_size;
|
|
}
|
|
|
|
<span class="org-keyword">static</span> <span class="org-keyword">const</span> <span class="org-keyword">struct</span> <span class="org-type">file_operations</span> <span class="org-variable-name">proc_file_fops</span> = {
|
|
.owner = THIS_MODULE,
|
|
.read = procfile_read,
|
|
.write = procfile_write,
|
|
};
|
|
|
|
<span class="org-doc">/**</span>
|
|
<span class="org-doc"> *This function is called when the module is loaded</span>
|
|
<span class="org-doc"> *</span>
|
|
<span class="org-doc"> */</span>
|
|
<span class="org-type">int</span> <span class="org-function-name">init_module</span>()
|
|
{
|
|
Our_Proc_File = proc_create(PROCFS_NAME,0644,<span class="org-constant">NULL</span>,&proc_file_fops);
|
|
<span class="org-keyword">if</span>(<span class="org-constant">NULL</span>==Our_Proc_File) {
|
|
proc_remove(Our_Proc_File);
|
|
printk(KERN_ALERT <span class="org-string">"Error:Could not initialize /proc/%s\n"</span>,PROCFS_NAME);
|
|
<span class="org-keyword">return</span> -ENOMEM;
|
|
}
|
|
|
|
printk(KERN_INFO <span class="org-string">"/proc/%s created\n"</span>, PROCFS_NAME);
|
|
<span class="org-keyword">return</span> 0;
|
|
}
|
|
|
|
<span class="org-doc">/**</span>
|
|
<span class="org-doc"> *This function is called when the module is unloaded</span>
|
|
<span class="org-doc"> *</span>
|
|
<span class="org-doc"> */</span>
|
|
<span class="org-type">void</span> <span class="org-function-name">cleanup_module</span>()
|
|
{
|
|
proc_remove(Our_Proc_File);
|
|
printk(KERN_INFO <span class="org-string">"/proc/%s removed\n"</span>, PROCFS_NAME);
|
|
}
|
|
</code></pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-org050c6d1" class="outline-3">
|
|
<h3 id="org050c6d1">Manage /proc file with standard filesystem</h3>
|
|
<div class="outline-text-3" id="text-org050c6d1">
|
|
<p>
|
|
We have seen how to read and write a /proc file with the /proc interface. But it's also possible to manage /proc file with inodes. The main concern is to use advanced functions, like permissions.
|
|
</p>
|
|
|
|
<p>
|
|
In Linux, there is a standard mechanism for file system registration. Since every file system has to have its own functions to handle inode and file operations, there is a special structure to hold pointers to all those functions, struct <b>inode_operations</b>, which includes a pointer to struct file_operations.
|
|
</p>
|
|
|
|
<p>
|
|
The difference between file and inode operations is that file operations deal with the file itself whereas inode operations deal with ways of referencing the file, such as creating links to it.
|
|
</p>
|
|
|
|
<p>
|
|
In /proc, whenever we register a new file, we're allowed to specify which struct inode_operations will be used to access to it. This is the mechanism we use, a struct inode_operations which includes a pointer to a struct file_operations which includes pointers to our procfs_read and procfs_write functions.
|
|
</p>
|
|
|
|
<p>
|
|
Another interesting point here is the module_permission function. This function is called whenever a process tries to do something with the /proc file, and it can decide whether to allow access or not. Right now it is only based on the operation and the uid of the current user (as available in current, a pointer to a structure which includes information on the currently running process), but it could be based on anything we like, such as what other processes are doing with the same file, the time of day, or the last input we received.
|
|
</p>
|
|
|
|
<p>
|
|
It's important to note that the standard roles of read and write are reversed in the kernel. Read functions are used for output, whereas write functions are used for input. The reason for that is that read and write refer to the user's point of view — if a process reads something from the kernel, then the kernel needs to output it, and if a process writes something to the kernel, then the kernel receives it as input.
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-c"><span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> procfs3.c</span>
|
|
<span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/kernel.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/module.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/proc_fs.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/sched.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><asm/uaccess.h></span>
|
|
|
|
<span class="org-preprocessor">#define</span> <span class="org-variable-name">PROCFS_MAX_SIZE</span> 2048
|
|
<span class="org-preprocessor">#define</span> <span class="org-variable-name">PROCFS_ENTRY_FILENAME</span> <span class="org-string">"buffer2k"</span>
|
|
|
|
<span class="org-keyword">struct</span> <span class="org-type">proc_dir_entry</span> *<span class="org-variable-name">Our_Proc_File</span>;
|
|
<span class="org-keyword">static</span> <span class="org-type">char</span> <span class="org-variable-name">procfs_buffer</span>[PROCFS_MAX_SIZE];
|
|
<span class="org-keyword">static</span> <span class="org-type">unsigned</span> <span class="org-type">long</span> <span class="org-variable-name">procfs_buffer_size</span> = 0;
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">ssize_t</span> <span class="org-function-name">procfs_read</span>(<span class="org-keyword">struct</span> <span class="org-type">file</span> *<span class="org-variable-name">filp</span>, <span class="org-type">char</span> *<span class="org-variable-name">buffer</span>,
|
|
<span class="org-type">size_t</span> <span class="org-variable-name">length</span>, <span class="org-type">loff_t</span> *<span class="org-variable-name">offset</span>)
|
|
{
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-variable-name">finished</span> = 0;
|
|
<span class="org-keyword">if</span>(finished)
|
|
{
|
|
printk(KERN_DEBUG <span class="org-string">"procfs_read: END\n"</span>);
|
|
finished = 0;
|
|
<span class="org-keyword">return</span> 0;
|
|
}
|
|
finished = 1;
|
|
<span class="org-keyword">if</span>(copy_to_user(buffer, procfs_buffer, procfs_buffer_size))
|
|
<span class="org-keyword">return</span> -EFAULT;
|
|
printk(KERN_DEBUG <span class="org-string">"procfs_read: read %lu bytes\n"</span>, procfs_buffer_size);
|
|
<span class="org-keyword">return</span> procfs_buffer_size;
|
|
}
|
|
<span class="org-keyword">static</span> <span class="org-type">ssize_t</span> <span class="org-function-name">procfs_write</span>(<span class="org-keyword">struct</span> <span class="org-type">file</span> *<span class="org-variable-name">file</span>, <span class="org-keyword">const</span> <span class="org-type">char</span> *<span class="org-variable-name">buffer</span>,
|
|
<span class="org-type">size_t</span> <span class="org-variable-name">len</span>, <span class="org-type">loff_t</span> *<span class="org-variable-name">off</span>)
|
|
{
|
|
<span class="org-keyword">if</span>(len>PROCFS_MAX_SIZE)
|
|
procfs_buffer_size = PROCFS_MAX_SIZE;
|
|
<span class="org-keyword">else</span>
|
|
procfs_buffer_size = len;
|
|
<span class="org-keyword">if</span>(copy_from_user(procfs_buffer, buffer, procfs_buffer_size))
|
|
<span class="org-keyword">return</span> -EFAULT;
|
|
printk(KERN_DEBUG <span class="org-string">"procfs_write: write %lu bytes\n"</span>, procfs_buffer_size);
|
|
<span class="org-keyword">return</span> procfs_buffer_size;
|
|
}
|
|
<span class="org-type">int</span> <span class="org-function-name">procfs_open</span>(<span class="org-keyword">struct</span> <span class="org-type">inode</span> *<span class="org-variable-name">inode</span>, <span class="org-keyword">struct</span> <span class="org-type">file</span> *<span class="org-variable-name">file</span>)
|
|
{
|
|
try_module_get(THIS_MODULE);
|
|
<span class="org-keyword">return</span> 0;
|
|
}
|
|
<span class="org-type">int</span> <span class="org-function-name">procfs_close</span>(<span class="org-keyword">struct</span> <span class="org-type">inode</span> *<span class="org-variable-name">inode</span>, <span class="org-keyword">struct</span> <span class="org-type">file</span> *<span class="org-variable-name">file</span>)
|
|
{
|
|
module_put(THIS_MODULE);
|
|
<span class="org-keyword">return</span> 0;
|
|
}
|
|
|
|
<span class="org-keyword">static</span> <span class="org-keyword">struct</span> <span class="org-type">file_operations</span> <span class="org-variable-name">File_Ops_4_Our_Proc_File</span> = {
|
|
.read = procfs_read,
|
|
.write = procfs_write,
|
|
.open = procfs_open,
|
|
.release = procfs_close,
|
|
};
|
|
|
|
<span class="org-type">int</span> <span class="org-function-name">init_module</span>()
|
|
{
|
|
Our_Proc_File = proc_create(PROCFS_ENTRY_FILENAME, 0644, <span class="org-constant">NULL</span>,&File_Ops_4_Our_Proc_File);
|
|
<span class="org-keyword">if</span>(Our_Proc_File == <span class="org-constant">NULL</span>)
|
|
{
|
|
remove_proc_entry(PROCFS_ENTRY_FILENAME, <span class="org-constant">NULL</span>);
|
|
printk(KERN_DEBUG <span class="org-string">"Error: Could not initialize /proc/%s\n"</span>, PROCFS_ENTRY_FILENAME);
|
|
<span class="org-keyword">return</span> -ENOMEM;
|
|
}
|
|
proc_set_size(Our_Proc_File, 80);
|
|
proc_set_user(Our_Proc_File, GLOBAL_ROOT_UID, GLOBAL_ROOT_GID);
|
|
|
|
printk(KERN_DEBUG <span class="org-string">"/proc/%s created\n"</span>, PROCFS_ENTRY_FILENAME);
|
|
<span class="org-keyword">return</span> 0;
|
|
}
|
|
<span class="org-type">void</span> <span class="org-function-name">cleanup_module</span>()
|
|
{
|
|
remove_proc_entry(PROCFS_ENTRY_FILENAME, <span class="org-constant">NULL</span>);
|
|
printk(KERN_DEBUG <span class="org-string">"/proc/%s removed\n"</span>, PROCFS_ENTRY_FILENAME);
|
|
}
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
Still hungry for procfs examples? Well, first of all keep in mind, there are rumors around, claiming that procfs is on it's way out, consider using sysfs instead. Second, if you really can't get enough, there's a highly recommendable bonus level for procfs below linux/Documentation/DocBook/ . Use make help in your toplevel kernel directory for instructions about how to convert it into your favourite format. Example: make htmldocs . Consider using this mechanism, in case you want to document something kernel related yourself.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-orgf55e850" class="outline-3">
|
|
<h3 id="orgf55e850">Manage /proc file with seq_file</h3>
|
|
<div class="outline-text-3" id="text-orgf55e850">
|
|
<p>
|
|
As we have seen, writing a /proc file may be quite "complex". So to help
|
|
people writting /proc file, there is an API named seq_file that helps
|
|
formating a /proc file for output. It's based on sequence, which is composed of 3 functions: start(), next(), and stop(). The seq_file API starts a sequence when a user read the /proc file.
|
|
</p>
|
|
|
|
<p>
|
|
A sequence begins with the call of the function start(). If the return is a
|
|
non NULL value, the function next() is called. This function is an iterator, the goal is to go thought all the data. Each time next() is called, the function show() is also called. It writes data values in the buffer read by the user. The function next() is called until it returns NULL. The sequence ends when next() returns NULL, then the function stop() is called.
|
|
</p>
|
|
|
|
<p>
|
|
BE CARREFUL: when a sequence is finished, another one starts. That means that at the end of function stop(), the function start() is called again. This loop finishes when the function start() returns NULL. You can see a scheme of this in the figure "How seq_file works".
|
|
</p>
|
|
|
|
|
|
<div class="figure">
|
|
<p><img src="img/seq_file.png" alt="seq_file.png" />
|
|
</p>
|
|
</div>
|
|
|
|
<table border="2" cellspacing="0" cellpadding="6" rules="groups" frame="hsides">
|
|
|
|
|
|
<tbody>
|
|
<tr>
|
|
</tr>
|
|
</tbody>
|
|
</table>
|
|
<p>
|
|
Seq_file provides basic functions for file_operations, as seq_read, seq_lseek, and some others. But nothing to write in the /proc file. Of course, you can still use the same way as in the previous example.
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-c"><span class="org-doc">/**</span>
|
|
<span class="org-doc"> * procfs4.c - create a "file" in /proc</span>
|
|
<span class="org-doc"> * This program uses the seq_file library to manage the /proc file.</span>
|
|
<span class="org-doc"> *</span>
|
|
<span class="org-doc"> */</span>
|
|
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/kernel.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">We're doing kernel work </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/module.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">Specifically, a module </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/proc_fs.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">Necessary because we use proc fs </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/seq_file.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">for seq_file </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-preprocessor">#define</span> <span class="org-variable-name">PROC_NAME</span> <span class="org-string">"iter"</span>
|
|
|
|
MODULE_AUTHOR(<span class="org-string">"Philippe Reynes"</span>);
|
|
MODULE_LICENSE(<span class="org-string">"GPL"</span>);
|
|
|
|
<span class="org-doc">/**</span>
|
|
<span class="org-doc"> * This function is called at the beginning of a sequence.</span>
|
|
<span class="org-doc"> * ie, when:</span>
|
|
<span class="org-doc"> * - the /proc file is read (first time)</span>
|
|
<span class="org-doc"> * - after the function stop (end of sequence)</span>
|
|
<span class="org-doc"> *</span>
|
|
<span class="org-doc"> */</span>
|
|
<span class="org-keyword">static</span> <span class="org-type">void</span> *<span class="org-function-name">my_seq_start</span>(<span class="org-keyword">struct</span> <span class="org-type">seq_file</span> *<span class="org-variable-name">s</span>, <span class="org-type">loff_t</span> *<span class="org-variable-name">pos</span>)
|
|
{
|
|
<span class="org-keyword">static</span> <span class="org-type">unsigned</span> <span class="org-type">long</span> <span class="org-variable-name">counter</span> = 0;
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">beginning a new sequence ? </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">if</span> ( *pos == 0 ) {
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">yes => return a non null value to begin the sequence </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">return</span> &counter;
|
|
}
|
|
<span class="org-keyword">else</span> {
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">no => it's the end of the sequence, return end to stop reading </span><span class="org-comment-delimiter">*/</span>
|
|
*pos = 0;
|
|
<span class="org-keyword">return</span> <span class="org-constant">NULL</span>;
|
|
}
|
|
}
|
|
|
|
<span class="org-doc">/**</span>
|
|
<span class="org-doc"> * This function is called after the beginning of a sequence.</span>
|
|
<span class="org-doc"> * It's called untill the return is NULL (this ends the sequence).</span>
|
|
<span class="org-doc"> *</span>
|
|
<span class="org-doc"> */</span>
|
|
<span class="org-keyword">static</span> <span class="org-type">void</span> *<span class="org-function-name">my_seq_next</span>(<span class="org-keyword">struct</span> <span class="org-type">seq_file</span> *<span class="org-variable-name">s</span>, <span class="org-type">void</span> *<span class="org-variable-name">v</span>, <span class="org-type">loff_t</span> *<span class="org-variable-name">pos</span>)
|
|
{
|
|
<span class="org-type">unsigned</span> <span class="org-type">long</span> *<span class="org-variable-name">tmp_v</span> = (<span class="org-type">unsigned</span> <span class="org-type">long</span> *)v;
|
|
(*tmp_v)++;
|
|
(*pos)++;
|
|
<span class="org-keyword">return</span> <span class="org-constant">NULL</span>;
|
|
}
|
|
|
|
<span class="org-doc">/**</span>
|
|
<span class="org-doc"> * This function is called at the end of a sequence</span>
|
|
<span class="org-doc"> *</span>
|
|
<span class="org-doc"> */</span>
|
|
<span class="org-keyword">static</span> <span class="org-type">void</span> <span class="org-function-name">my_seq_stop</span>(<span class="org-keyword">struct</span> <span class="org-type">seq_file</span> *<span class="org-variable-name">s</span>, <span class="org-type">void</span> *<span class="org-variable-name">v</span>)
|
|
{
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">nothing to do, we use a static value in start() </span><span class="org-comment-delimiter">*/</span>
|
|
}
|
|
|
|
<span class="org-doc">/**</span>
|
|
<span class="org-doc"> * This function is called for each "step" of a sequence</span>
|
|
<span class="org-doc"> *</span>
|
|
<span class="org-doc"> */</span>
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-function-name">my_seq_show</span>(<span class="org-keyword">struct</span> <span class="org-type">seq_file</span> *<span class="org-variable-name">s</span>, <span class="org-type">void</span> *<span class="org-variable-name">v</span>)
|
|
{
|
|
<span class="org-type">loff_t</span> *<span class="org-variable-name">spos</span> = (<span class="org-type">loff_t</span> *) v;
|
|
|
|
seq_printf(s, <span class="org-string">"%Ld\n"</span>, *spos);
|
|
<span class="org-keyword">return</span> 0;
|
|
}
|
|
|
|
<span class="org-doc">/**</span>
|
|
<span class="org-doc"> * This structure gather "function" to manage the sequence</span>
|
|
<span class="org-doc"> *</span>
|
|
<span class="org-doc"> */</span>
|
|
<span class="org-keyword">static</span> <span class="org-keyword">struct</span> <span class="org-type">seq_operations</span> <span class="org-variable-name">my_seq_ops</span> = {
|
|
.start = my_seq_start,
|
|
.next = my_seq_next,
|
|
.stop = my_seq_stop,
|
|
.show = my_seq_show
|
|
};
|
|
|
|
<span class="org-doc">/**</span>
|
|
<span class="org-doc"> * This function is called when the /proc file is open.</span>
|
|
<span class="org-doc"> *</span>
|
|
<span class="org-doc"> */</span>
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-function-name">my_open</span>(<span class="org-keyword">struct</span> <span class="org-type">inode</span> *<span class="org-variable-name">inode</span>, <span class="org-keyword">struct</span> <span class="org-type">file</span> *<span class="org-variable-name">file</span>)
|
|
{
|
|
<span class="org-keyword">return</span> seq_open(file, &my_seq_ops);
|
|
};
|
|
|
|
<span class="org-doc">/**</span>
|
|
<span class="org-doc"> * This structure gather "function" that manage the /proc file</span>
|
|
<span class="org-doc"> *</span>
|
|
<span class="org-doc"> */</span>
|
|
<span class="org-keyword">static</span> <span class="org-keyword">struct</span> <span class="org-type">file_operations</span> <span class="org-variable-name">my_file_ops</span> = {
|
|
.owner = THIS_MODULE,
|
|
.open = my_open,
|
|
.read = seq_read,
|
|
.llseek = seq_lseek,
|
|
.release = seq_release
|
|
};
|
|
|
|
|
|
<span class="org-doc">/**</span>
|
|
<span class="org-doc"> * This function is called when the module is loaded</span>
|
|
<span class="org-doc"> *</span>
|
|
<span class="org-doc"> */</span>
|
|
<span class="org-type">int</span> <span class="org-function-name">init_module</span>(<span class="org-type">void</span>)
|
|
{
|
|
<span class="org-keyword">struct</span> <span class="org-type">proc_dir_entry</span> *<span class="org-variable-name">entry</span>;
|
|
|
|
entry = proc_create(PROC_NAME, 0, <span class="org-constant">NULL</span>, &my_file_ops);
|
|
<span class="org-keyword">if</span>(entry == <span class="org-constant">NULL</span>)
|
|
{
|
|
remove_proc_entry(PROC_NAME, <span class="org-constant">NULL</span>);
|
|
printk(KERN_DEBUG <span class="org-string">"Error: Could not initialize /proc/%s\n"</span>, PROC_NAME);
|
|
<span class="org-keyword">return</span> -ENOMEM;
|
|
}
|
|
|
|
<span class="org-keyword">return</span> 0;
|
|
}
|
|
|
|
<span class="org-doc">/**</span>
|
|
<span class="org-doc"> * This function is called when the module is unloaded.</span>
|
|
<span class="org-doc"> *</span>
|
|
<span class="org-doc"> */</span>
|
|
<span class="org-type">void</span> <span class="org-function-name">cleanup_module</span>(<span class="org-type">void</span>)
|
|
{
|
|
remove_proc_entry(PROC_NAME, <span class="org-constant">NULL</span>);
|
|
printk(KERN_DEBUG <span class="org-string">"/proc/%s removed\n"</span>, PROC_NAME);
|
|
}
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
If you want more information, you can read this web page:
|
|
</p>
|
|
|
|
<ul class="org-ul">
|
|
<li><a href="http://lwn.net/Articles/22355/">http://lwn.net/Articles/22355/</a></li>
|
|
|
|
<li><a href="http://www.kernelnewbies.org/documents/seq_file_howto.txt">http://www.kernelnewbies.org/documents/seq_file_howto.txt</a></li>
|
|
</ul>
|
|
|
|
|
|
<p>
|
|
You can also read the code of fs/seq_file.c in the linux kernel.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-orgc2ebb44" class="outline-2">
|
|
<h2 id="orgc2ebb44">sysfs: Interacting with your module</h2>
|
|
<div class="outline-text-2" id="text-orgc2ebb44">
|
|
<p>
|
|
<i>sysfs</i> allows you to interact with the running kernel from userspace by reading or setting variables inside of modules. This can be useful for debugging purposes, or just as an interface for applications or scripts. You can find sysfs directories and files under the <i>sys</i> directory on your system.
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-bash">ls -l /sys
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
An example of a hello world module which includes the creation of a variable accessible via sysfs is given below.
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-c"><span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * hello-sysfs.c sysfs example</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/module.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/printk.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/kobject.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/sysfs.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/init.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/fs.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/string.h></span>
|
|
|
|
MODULE_LICENSE(<span class="org-string">"GPL"</span>);
|
|
MODULE_AUTHOR(<span class="org-string">"Bob Mottram"</span>);
|
|
|
|
<span class="org-keyword">static</span> <span class="org-keyword">struct</span> <span class="org-type">kobject</span> *<span class="org-variable-name">mymodule</span>;
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">the variable you want to be able to change </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-variable-name">myvariable</span> = 0;
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">ssize_t</span> <span class="org-function-name">myvariable_show</span>(<span class="org-keyword">struct</span> <span class="org-type">kobject</span> *<span class="org-variable-name">kobj</span>,
|
|
<span class="org-keyword">struct</span> <span class="org-type">kobj_attribute</span> *<span class="org-variable-name">attr</span>,
|
|
<span class="org-type">char</span> *<span class="org-variable-name">buf</span>)
|
|
{
|
|
<span class="org-keyword">return</span> sprintf(buf, <span class="org-string">"%d\n"</span>, myvariable);
|
|
}
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">ssize_t</span> <span class="org-function-name">myvariable_store</span>(<span class="org-keyword">struct</span> <span class="org-type">kobject</span> *<span class="org-variable-name">kobj</span>,
|
|
<span class="org-keyword">struct</span> <span class="org-type">kobj_attribute</span> *<span class="org-variable-name">attr</span>,
|
|
<span class="org-type">char</span> *<span class="org-variable-name">buf</span>, <span class="org-type">size_t</span> <span class="org-variable-name">count</span>)
|
|
{
|
|
sscanf(buf, <span class="org-string">"%du"</span>, &myvariable);
|
|
<span class="org-keyword">return</span> count;
|
|
}
|
|
|
|
|
|
<span class="org-keyword">static</span> <span class="org-keyword">struct</span> <span class="org-type">kobj_attribute</span> <span class="org-variable-name">myvariable_attribute</span> =
|
|
__ATTR(myvariable, 0660, myvariable_show,
|
|
(<span class="org-type">void</span>*)myvariable_store);
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-function-name">__init</span> mymodule_init (<span class="org-type">void</span>)
|
|
{
|
|
<span class="org-type">int</span> <span class="org-variable-name">error</span> = 0;
|
|
|
|
printk(KERN_INFO <span class="org-string">"mymodule: initialised\n"</span>);
|
|
|
|
mymodule =
|
|
kobject_create_and_add(<span class="org-string">"mymodule"</span>, kernel_kobj);
|
|
<span class="org-keyword">if</span> (<span class="org-negation-char">!</span>mymodule)
|
|
<span class="org-keyword">return</span> -ENOMEM;
|
|
|
|
error = sysfs_create_file(mymodule, &myvariable_attribute.attr);
|
|
<span class="org-keyword">if</span> (error) {
|
|
printk(KERN_INFO <span class="org-string">"failed to create the myvariable file "</span> \
|
|
<span class="org-string">"in /sys/kernel/mymodule\n"</span>);
|
|
}
|
|
|
|
<span class="org-keyword">return</span> error;
|
|
}
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">void</span> <span class="org-function-name">__exit</span> mymodule_exit (<span class="org-type">void</span>)
|
|
{
|
|
printk(KERN_INFO <span class="org-string">"mymodule: Exit success\n"</span>);
|
|
kobject_put(mymodule);
|
|
}
|
|
|
|
module_init(mymodule_init);
|
|
module_exit(mymodule_exit);
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
Make and install the module:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-sh">make
|
|
sudo insmod hello-sysfs.ko
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
Check that it exists:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-sh">sudo lsmod | grep hello_sysfs
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
What is the current value of <i>myvariable</i> ?
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-sh">cat /sys/kernel/mymodule/myvariable
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
Set the value of <i>myvariable</i> and check that it changed.
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-sh"><span class="org-builtin">echo</span> <span class="org-string">"32"</span> > /sys/kernel/mymodule/myvariable
|
|
cat /sys/kernel/mymodule/myvariable
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
Finally, remove the test module:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-sh">sudo rmmod hello_sysfs
|
|
</code></pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-orgdd0bcef" class="outline-2">
|
|
<h2 id="orgdd0bcef">Talking To Device Files</h2>
|
|
<div class="outline-text-2" id="text-orgdd0bcef">
|
|
<p>
|
|
Device files are supposed to represent physical devices. Most physical devices are used for output as well as input, so there has to be some mechanism for device drivers in the kernel to get the output to send to the device from processes. This is done by opening the device file for output and writing to it, just like writing to a file. In the following example, this is implemented by device_write.
|
|
</p>
|
|
|
|
<p>
|
|
This is not always enough. Imagine you had a serial port connected to a modem (even if you have an internal modem, it is still implemented from the CPU's perspective as a serial port connected to a modem, so you don't have to tax your imagination too hard). The natural thing to do would be to use the device file to write things to the modem (either modem commands or data to be sent through the phone line) and read things from the modem (either responses for commands or the data received through the phone line). However, this leaves open the question of what to do when you need to talk to the serial port itself, for example to send the rate at which data is sent and received.
|
|
</p>
|
|
|
|
<p>
|
|
The answer in Unix is to use a special function called <b>ioctl</b> (short for Input Output ConTroL). Every device can have its own ioctl commands, which can be read ioctl's (to send information from a process to the kernel), write ioctl's (to return information to a process), both or neither. Notice here the roles of read and write are reversed again, so in ioctl's read is to send information to the kernel and write is to receive information from the kernel.
|
|
</p>
|
|
|
|
<p>
|
|
The ioctl function is called with three parameters: the file descriptor of the appropriate device file, the ioctl number, and a parameter, which is of type long so you can use a cast to use it to pass anything. You won't be able to pass a structure this way, but you will be able to pass a pointer to the structure.
|
|
</p>
|
|
|
|
<p>
|
|
The ioctl number encodes the major device number, the type of the ioctl, the command, and the type of the parameter. This ioctl number is usually created by a macro call (_IO, _IOR, _IOW or _IOWR — depending on the type) in a header file. This header file should then be included both by the programs which will use ioctl (so they can generate the appropriate ioctl's) and by the kernel module (so it can understand it). In the example below, the header file is chardev.h and the program which uses it is ioctl.c.
|
|
</p>
|
|
|
|
<p>
|
|
If you want to use ioctls in your own kernel modules, it is best to receive an official ioctl assignment, so if you accidentally get somebody else's ioctls, or if they get yours, you'll know something is wrong. For more information, consult the kernel source tree at Documentation/ioctl-number.txt.
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-c"><span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * chardev2.c - Create an input/output character device</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/kernel.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">We're doing kernel work </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/module.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">Specifically, a module </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/fs.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><asm/uaccess.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">for get_user and put_user </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-preprocessor">#include</span> <span class="org-string">"chardev.h"</span>
|
|
<span class="org-preprocessor">#define</span> <span class="org-variable-name">SUCCESS</span> 0
|
|
<span class="org-preprocessor">#define</span> <span class="org-variable-name">DEVICE_NAME</span> <span class="org-string">"char_dev"</span>
|
|
<span class="org-preprocessor">#define</span> <span class="org-variable-name">BUF_LEN</span> 80
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Is the device open right now? Used to prevent</span>
|
|
<span class="org-comment"> * concurent access into the same device</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-variable-name">Device_Open</span> = 0;
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * The message the device will give when asked</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">static</span> <span class="org-type">char</span> <span class="org-variable-name">Message</span>[BUF_LEN];
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * How far did the process reading the message get?</span>
|
|
<span class="org-comment"> * Useful if the message is larger than the size of the</span>
|
|
<span class="org-comment"> * buffer we get to fill in device_read.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">static</span> <span class="org-type">char</span> *<span class="org-variable-name">Message_Ptr</span>;
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * This is called whenever a process attempts to open the device file</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-function-name">device_open</span>(<span class="org-keyword">struct</span> <span class="org-type">inode</span> *<span class="org-variable-name">inode</span>, <span class="org-keyword">struct</span> <span class="org-type">file</span> *<span class="org-variable-name">file</span>)
|
|
{
|
|
<span class="org-preprocessor">#ifdef</span> DEBUG
|
|
printk(KERN_INFO <span class="org-string">"device_open(%p)\n"</span>, file);
|
|
<span class="org-preprocessor">#endif</span>
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * We don't want to talk to two processes at the same time</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">if</span> (Device_Open)
|
|
<span class="org-keyword">return</span> -EBUSY;
|
|
|
|
Device_Open++;
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Initialize the message</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
Message_Ptr = Message;
|
|
try_module_get(THIS_MODULE);
|
|
<span class="org-keyword">return</span> SUCCESS;
|
|
}
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-function-name">device_release</span>(<span class="org-keyword">struct</span> <span class="org-type">inode</span> *<span class="org-variable-name">inode</span>, <span class="org-keyword">struct</span> <span class="org-type">file</span> *<span class="org-variable-name">file</span>)
|
|
{
|
|
<span class="org-preprocessor">#ifdef</span> DEBUG
|
|
printk(KERN_INFO <span class="org-string">"device_release(%p,%p)\n"</span>, inode, file);
|
|
<span class="org-preprocessor">#endif</span>
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * We're now ready for our next caller</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
Device_Open--;
|
|
|
|
module_put(THIS_MODULE);
|
|
<span class="org-keyword">return</span> SUCCESS;
|
|
}
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * This function is called whenever a process which has already opened the</span>
|
|
<span class="org-comment"> * device file attempts to read from it.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">static</span> <span class="org-type">ssize_t</span> <span class="org-function-name">device_read</span>(<span class="org-keyword">struct</span> <span class="org-type">file</span> *<span class="org-variable-name">file</span>, <span class="org-comment-delimiter">/* </span><span class="org-comment">see include/linux/fs.h </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-type">char</span> <span class="org-variable-name">__user</span> * buffer, <span class="org-comment-delimiter">/* </span><span class="org-comment">buffer to be</span>
|
|
<span class="org-comment"> * filled with data </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-type">size_t</span> <span class="org-variable-name">length</span>, <span class="org-comment-delimiter">/* </span><span class="org-comment">length of the buffer </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-type">loff_t</span> * <span class="org-variable-name">offset</span>)
|
|
{
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Number of bytes actually written to the buffer</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-type">int</span> <span class="org-variable-name">bytes_read</span> = 0;
|
|
|
|
<span class="org-preprocessor">#ifdef</span> DEBUG
|
|
printk(KERN_INFO <span class="org-string">"device_read(%p,%p,%d)\n"</span>, file, buffer, length);
|
|
<span class="org-preprocessor">#endif</span>
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * If we're at the end of the message, return 0</span>
|
|
<span class="org-comment"> * (which signifies end of file)</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">if</span> (*Message_Ptr == 0)
|
|
<span class="org-keyword">return</span> 0;
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Actually put the data into the buffer</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">while</span> (length && *Message_Ptr) {
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Because the buffer is in the user data segment,</span>
|
|
<span class="org-comment"> * not the kernel data segment, assignment wouldn't</span>
|
|
<span class="org-comment"> * work. Instead, we have to use put_user which</span>
|
|
<span class="org-comment"> * copies data from the kernel data segment to the</span>
|
|
<span class="org-comment"> * user data segment.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
put_user(*(Message_Ptr++), buffer++);
|
|
length--;
|
|
bytes_read++;
|
|
}
|
|
|
|
<span class="org-preprocessor">#ifdef</span> DEBUG
|
|
printk(KERN_INFO <span class="org-string">"Read %d bytes, %d left\n"</span>, bytes_read, length);
|
|
<span class="org-preprocessor">#endif</span>
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Read functions are supposed to return the number</span>
|
|
<span class="org-comment"> * of bytes actually inserted into the buffer</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">return</span> bytes_read;
|
|
}
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * This function is called when somebody tries to</span>
|
|
<span class="org-comment"> * write into our device file.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">static</span> <span class="org-type">ssize_t</span>
|
|
<span class="org-function-name">device_write</span>(<span class="org-keyword">struct</span> <span class="org-type">file</span> *<span class="org-variable-name">file</span>,
|
|
<span class="org-keyword">const</span> <span class="org-type">char</span> <span class="org-variable-name">__user</span> * buffer, <span class="org-type">size_t</span> <span class="org-variable-name">length</span>, <span class="org-type">loff_t</span> * <span class="org-variable-name">offset</span>)
|
|
{
|
|
<span class="org-type">int</span> <span class="org-variable-name">i</span>;
|
|
|
|
<span class="org-preprocessor">#ifdef</span> DEBUG
|
|
printk(KERN_INFO <span class="org-string">"device_write(%p,%s,%d)"</span>, file, buffer, length);
|
|
<span class="org-preprocessor">#endif</span>
|
|
|
|
<span class="org-keyword">for</span> (i = 0; i < length && i < BUF_LEN; i++)
|
|
get_user(Message[i], buffer + i);
|
|
|
|
Message_Ptr = Message;
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Again, return the number of input characters used</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">return</span> i;
|
|
}
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * This function is called whenever a process tries to do an ioctl on our</span>
|
|
<span class="org-comment"> * device file. We get two extra parameters (additional to the inode and file</span>
|
|
<span class="org-comment"> * structures, which all device functions get): the number of the ioctl called</span>
|
|
<span class="org-comment"> * and the parameter given to the ioctl function.</span>
|
|
<span class="org-comment"> *</span>
|
|
<span class="org-comment"> * If the ioctl is write or read/write (meaning output is returned to the</span>
|
|
<span class="org-comment"> * calling process), the ioctl call returns the output of this function.</span>
|
|
<span class="org-comment"> *</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-type">long</span> <span class="org-function-name">device_ioctl</span>(<span class="org-keyword">struct</span> <span class="org-type">file</span> *<span class="org-variable-name">file</span>, <span class="org-comment-delimiter">/* </span><span class="org-comment">ditto </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-type">unsigned</span> <span class="org-type">int</span> <span class="org-variable-name">ioctl_num</span>, <span class="org-comment-delimiter">/* </span><span class="org-comment">number and param for ioctl </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-type">unsigned</span> <span class="org-type">long</span> <span class="org-variable-name">ioctl_param</span>)
|
|
{
|
|
<span class="org-type">int</span> <span class="org-variable-name">i</span>;
|
|
<span class="org-type">char</span> *<span class="org-variable-name">temp</span>;
|
|
<span class="org-type">char</span> <span class="org-variable-name">ch</span>;
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Switch according to the ioctl called</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">switch</span> (ioctl_num) {
|
|
<span class="org-keyword">case</span> IOCTL_SET_MSG:
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Receive a pointer to a message (in user space) and set that</span>
|
|
<span class="org-comment"> * to be the device's message. Get the parameter given to</span>
|
|
<span class="org-comment"> * ioctl by the process.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
temp = (<span class="org-type">char</span> *)ioctl_param;
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Find the length of the message</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
get_user(ch, temp);
|
|
<span class="org-keyword">for</span> (i = 0; ch && i < BUF_LEN; i++, temp++)
|
|
get_user(ch, temp);
|
|
|
|
device_write(file, (<span class="org-type">char</span> *)ioctl_param, i, 0);
|
|
<span class="org-keyword">break</span>;
|
|
|
|
<span class="org-keyword">case</span> IOCTL_GET_MSG:
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Give the current message to the calling process -</span>
|
|
<span class="org-comment"> * the parameter we got is a pointer, fill it.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
i = device_read(file, (<span class="org-type">char</span> *)ioctl_param, 99, 0);
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Put a zero at the end of the buffer, so it will be</span>
|
|
<span class="org-comment"> * properly terminated</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
put_user(<span class="org-string">'\0'</span>, (<span class="org-type">char</span> *)ioctl_param + i);
|
|
<span class="org-keyword">break</span>;
|
|
|
|
<span class="org-keyword">case</span> IOCTL_GET_NTH_BYTE:
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * This ioctl is both input (ioctl_param) and</span>
|
|
<span class="org-comment"> * output (the return value of this function)</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">return</span> Message[ioctl_param];
|
|
<span class="org-keyword">break</span>;
|
|
}
|
|
|
|
<span class="org-keyword">return</span> SUCCESS;
|
|
}
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">Module Declarations </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * This structure will hold the functions to be called</span>
|
|
<span class="org-comment"> * when a process does something to the device we</span>
|
|
<span class="org-comment"> * created. Since a pointer to this structure is kept in</span>
|
|
<span class="org-comment"> * the devices table, it can't be local to</span>
|
|
<span class="org-comment"> * init_module. NULL is for unimplemented functions.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">struct</span> <span class="org-type">file_operations</span> <span class="org-variable-name">Fops</span> = {
|
|
.read = device_read,
|
|
.write = device_write,
|
|
.unlocked_ioctl = device_ioctl,
|
|
.open = device_open,
|
|
.release = device_release, <span class="org-comment-delimiter">/* </span><span class="org-comment">a.k.a. close </span><span class="org-comment-delimiter">*/</span>
|
|
};
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Initialize the module - Register the character device</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-type">int</span> <span class="org-function-name">init_module</span>()
|
|
{
|
|
<span class="org-type">int</span> <span class="org-variable-name">ret_val</span>;
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Register the character device (atleast try)</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
ret_val = register_chrdev(MAJOR_NUM, DEVICE_NAME, &Fops);
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Negative values signify an error</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">if</span> (ret_val < 0) {
|
|
printk(KERN_ALERT <span class="org-string">"%s failed with %d\n"</span>,
|
|
<span class="org-string">"Sorry, registering the character device "</span>, ret_val);
|
|
<span class="org-keyword">return</span> ret_val;
|
|
}
|
|
|
|
printk(KERN_INFO <span class="org-string">"%s The major device number is %d.\n"</span>,
|
|
<span class="org-string">"Registeration is a success"</span>, MAJOR_NUM);
|
|
printk(KERN_INFO <span class="org-string">"If you want to talk to the device driver,\n"</span>);
|
|
printk(KERN_INFO <span class="org-string">"you'll have to create a device file. \n"</span>);
|
|
printk(KERN_INFO <span class="org-string">"We suggest you use:\n"</span>);
|
|
printk(KERN_INFO <span class="org-string">"mknod %s c %d 0\n"</span>, DEVICE_FILE_NAME, MAJOR_NUM);
|
|
printk(KERN_INFO <span class="org-string">"The device file name is important, because\n"</span>);
|
|
printk(KERN_INFO <span class="org-string">"the ioctl program assumes that's the\n"</span>);
|
|
printk(KERN_INFO <span class="org-string">"file you'll use.\n"</span>);
|
|
|
|
<span class="org-keyword">return</span> 0;
|
|
}
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Cleanup - unregister the appropriate file from /proc</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-type">void</span> <span class="org-function-name">cleanup_module</span>()
|
|
{
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Unregister the device</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
unregister_chrdev(MAJOR_NUM, DEVICE_NAME);
|
|
}
|
|
</code></pre>
|
|
</div>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-c"><span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * chardev.h - the header file with the ioctl definitions.</span>
|
|
<span class="org-comment"> *</span>
|
|
<span class="org-comment"> * The declarations here have to be in a header file, because</span>
|
|
<span class="org-comment"> * they need to be known both to the kernel module</span>
|
|
<span class="org-comment"> * (in chardev.c) and the process calling ioctl (ioctl.c)</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-preprocessor">#if</span><span class="org-negation-char"><span class="org-preprocessor">n</span></span><span class="org-preprocessor">def</span> CHARDEV_H
|
|
<span class="org-preprocessor">#define</span> <span class="org-variable-name">CHARDEV_H</span>
|
|
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/ioctl.h></span>
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * The major device number. We can't rely on dynamic</span>
|
|
<span class="org-comment"> * registration any more, because ioctls need to know</span>
|
|
<span class="org-comment"> * it.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#define</span> <span class="org-variable-name">MAJOR_NUM</span> 100
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Set the message of the device driver</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#define</span> <span class="org-variable-name">IOCTL_SET_MSG</span> _IOW(MAJOR_NUM, 0, <span class="org-type">char</span> *)
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * _IOW means that we're creating an ioctl command</span>
|
|
<span class="org-comment"> * number for passing information from a user process</span>
|
|
<span class="org-comment"> * to the kernel module.</span>
|
|
<span class="org-comment"> *</span>
|
|
<span class="org-comment"> * The first arguments, MAJOR_NUM, is the major device</span>
|
|
<span class="org-comment"> * number we're using.</span>
|
|
<span class="org-comment"> *</span>
|
|
<span class="org-comment"> * The second argument is the number of the command</span>
|
|
<span class="org-comment"> * (there could be several with different meanings).</span>
|
|
<span class="org-comment"> *</span>
|
|
<span class="org-comment"> * The third argument is the type we want to get from</span>
|
|
<span class="org-comment"> * the process to the kernel.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Get the message of the device driver</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#define</span> <span class="org-variable-name">IOCTL_GET_MSG</span> _IOR(MAJOR_NUM, 1, <span class="org-type">char</span> *)
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * This IOCTL is used for output, to get the message</span>
|
|
<span class="org-comment"> * of the device driver. However, we still need the</span>
|
|
<span class="org-comment"> * buffer to place the message in to be input,</span>
|
|
<span class="org-comment"> * as it is allocated by the process.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Get the n'th byte of the message</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#define</span> <span class="org-variable-name">IOCTL_GET_NTH_BYTE</span> _IOWR(MAJOR_NUM, 2, <span class="org-type">int</span>)
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * The IOCTL is used for both input and output. It</span>
|
|
<span class="org-comment"> * receives from the user a number, n, and returns</span>
|
|
<span class="org-comment"> * Message[n].</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * The name of the device file</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#define</span> <span class="org-variable-name">DEVICE_FILE_NAME</span> <span class="org-string">"char_dev"</span>
|
|
|
|
<span class="org-preprocessor">#endif</span>
|
|
</code></pre>
|
|
</div>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-c"><span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * ioctl.c - the process to use ioctl's to control the kernel module</span>
|
|
<span class="org-comment"> *</span>
|
|
<span class="org-comment"> * Until now we could have used cat for input and output. But now</span>
|
|
<span class="org-comment"> * we need to do ioctl's, which require writing our own process.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * device specifics, such as ioctl numbers and the</span>
|
|
<span class="org-comment"> * major device file.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string">"../chardev.h"</span>
|
|
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><stdio.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><stdlib.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><fcntl.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">open </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><unistd.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">exit </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><sys/ioctl.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">ioctl </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Functions for the ioctl calls</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-type">int</span> <span class="org-function-name">ioctl_set_msg</span>(<span class="org-type">int</span> <span class="org-variable-name">file_desc</span>, <span class="org-type">char</span> *<span class="org-variable-name">message</span>)
|
|
{
|
|
<span class="org-type">int</span> <span class="org-variable-name">ret_val</span>;
|
|
|
|
ret_val = ioctl(file_desc, IOCTL_SET_MSG, message);
|
|
|
|
<span class="org-keyword">if</span> (ret_val < 0) {
|
|
printf(<span class="org-string">"ioctl_set_msg failed:%d\n"</span>, ret_val);
|
|
exit(-1);
|
|
}
|
|
<span class="org-keyword">return</span> 0;
|
|
}
|
|
|
|
<span class="org-type">int</span> <span class="org-function-name">ioctl_get_msg</span>(<span class="org-type">int</span> <span class="org-variable-name">file_desc</span>)
|
|
{
|
|
<span class="org-type">int</span> <span class="org-variable-name">ret_val</span>;
|
|
<span class="org-type">char</span> <span class="org-variable-name">message</span>[100];
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Warning - this is dangerous because we don't tell</span>
|
|
<span class="org-comment"> * the kernel how far it's allowed to write, so it</span>
|
|
<span class="org-comment"> * might overflow the buffer. In a real production</span>
|
|
<span class="org-comment"> * program, we would have used two ioctls - one to tell</span>
|
|
<span class="org-comment"> * the kernel the buffer length and another to give</span>
|
|
<span class="org-comment"> * it the buffer to fill</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
ret_val = ioctl(file_desc, IOCTL_GET_MSG, message);
|
|
|
|
<span class="org-keyword">if</span> (ret_val < 0) {
|
|
printf(<span class="org-string">"ioctl_get_msg failed:%d\n"</span>, ret_val);
|
|
exit(-1);
|
|
}
|
|
|
|
printf(<span class="org-string">"get_msg message:%s\n"</span>, message);
|
|
<span class="org-keyword">return</span> 0;
|
|
}
|
|
|
|
<span class="org-type">int</span> <span class="org-function-name">ioctl_get_nth_byte</span>(<span class="org-type">int</span> <span class="org-variable-name">file_desc</span>)
|
|
{
|
|
<span class="org-type">int</span> <span class="org-variable-name">i</span>;
|
|
<span class="org-type">char</span> <span class="org-variable-name">c</span>;
|
|
|
|
printf(<span class="org-string">"get_nth_byte message:"</span>);
|
|
|
|
i = 0;
|
|
<span class="org-keyword">do</span> {
|
|
c = ioctl(file_desc, IOCTL_GET_NTH_BYTE, i++);
|
|
|
|
<span class="org-keyword">if</span> (c < 0) {
|
|
printf(<span class="org-string">"ioctl_get_nth_byte failed at the %d'th byte:\n"</span>,
|
|
i);
|
|
exit(-1);
|
|
}
|
|
|
|
putchar(c);
|
|
} <span class="org-keyword">while</span> (c != 0);
|
|
putchar(<span class="org-string">'\n'</span>);
|
|
<span class="org-keyword">return</span> 0;
|
|
}
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Main - Call the ioctl functions</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-type">int</span> <span class="org-function-name">main</span>()
|
|
{
|
|
<span class="org-type">int</span> <span class="org-variable-name">file_desc</span>, <span class="org-variable-name">ret_val</span>;
|
|
<span class="org-type">char</span> *<span class="org-variable-name">msg</span> = <span class="org-string">"Message passed by ioctl\n"</span>;
|
|
|
|
file_desc = open(DEVICE_FILE_NAME, 0);
|
|
<span class="org-keyword">if</span> (file_desc < 0) {
|
|
printf(<span class="org-string">"Can't open device file: %s\n"</span>, DEVICE_FILE_NAME);
|
|
exit(-1);
|
|
}
|
|
|
|
ioctl_get_nth_byte(file_desc);
|
|
ioctl_get_msg(file_desc);
|
|
ioctl_set_msg(file_desc, msg);
|
|
|
|
close(file_desc);
|
|
<span class="org-keyword">return</span> 0;
|
|
}
|
|
</code></pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-orgb0fbb3c" class="outline-2">
|
|
<h2 id="orgb0fbb3c">System Calls</h2>
|
|
<div class="outline-text-2" id="text-orgb0fbb3c">
|
|
<p>
|
|
So far, the only thing we've done was to use well defined kernel mechanisms to register <b>/proc</b> files and device handlers. This is fine if you want to do something the kernel programmers thought you'd want, such as write a device driver. But what if you want to do something unusual, to change the behavior of the system in some way? Then, you're mostly on your own.
|
|
</p>
|
|
|
|
<p>
|
|
If you're not being sensible and using a virtual machine then this is where kernel programming can become hazardous. While writing the example below, I killed the <b>open()</b> system call. This meant I couldn't open any files, I couldn't run any programs, and I couldn't shutdown the system. I had to restart the virtual machine. No important files got anihilated, but if I was doing this on some live mission critical system then that could have been a possible outcome. To ensure you don't lose any files, even within a test environment, please run <b>sync</b> right before you do the <b>insmod</b> and the <b>rmmod</b>.
|
|
</p>
|
|
|
|
<p>
|
|
Forget about <b>/proc</b> files, forget about device files. They're just minor details. Minutiae in the vast expanse of the universe. The real process to kernel communication mechanism, the one used by all processes, is <i>system calls</i>. When a process requests a service from the kernel (such as opening a file, forking to a new process, or requesting more memory), this is the mechanism used. If you want to change the behaviour of the kernel in interesting ways, this is the place to do it. By the way, if you want to see which system calls a program uses, run <b>strace <arguments></b>.
|
|
</p>
|
|
|
|
<p>
|
|
In general, a process is not supposed to be able to access the kernel. It can't access kernel memory and it can't call kernel functions. The hardware of the CPU enforces this (that's the reason why it's called `protected mode' or 'page protection').
|
|
</p>
|
|
|
|
<p>
|
|
System calls are an exception to this general rule. What happens is that the process fills the registers with the appropriate values and then calls a special instruction which jumps to a previously defined location in the kernel (of course, that location is readable by user processes, it is not writable by them). Under Intel CPUs, this is done by means of interrupt 0x80. The hardware knows that once you jump to this location, you are no longer running in restricted user mode, but as the operating system kernel — and therefore you're allowed to do whatever you want.
|
|
</p>
|
|
|
|
<p>
|
|
The location in the kernel a process can jump to is called system_call. The procedure at that location checks the system call number, which tells the kernel what service the process requested. Then, it looks at the table of system calls (sys_call_table) to see the address of the kernel function to call. Then it calls the function, and after it returns, does a few system checks and then return back to the process (or to a different process, if the process time ran out). If you want to read this code, it's at the source file arch/$<$architecture$>$/kernel/entry.S, after the line ENTRY(system_call).
|
|
</p>
|
|
|
|
<p>
|
|
So, if we want to change the way a certain system call works, what we need to do is to write our own function to implement it (usually by adding a bit of our own code, and then calling the original function) and then change the pointer at sys_call_table to point to our function. Because we might be removed later and we don't want to leave the system in an unstable state, it's important for cleanup_module to restore the table to its original state.
|
|
</p>
|
|
|
|
<p>
|
|
The source code here is an example of such a kernel module. We want to "spy" on a certain user, and to printk() a message whenever that user opens a file. Towards this end, we replace the system call to open a file with our own function, called <b>our_sys_open</b>. This function checks the uid (user's id) of the current process, and if it's equal to the uid we spy on, it calls printk() to display the name of the file to be opened. Then, either way, it calls the original open() function with the same parameters, to actually open the file.
|
|
</p>
|
|
|
|
<p>
|
|
The <b>init_module</b> function replaces the appropriate location in <b>sys_call_table</b> and keeps the original pointer in a variable. The cleanup_module function uses that variable to restore everything back to normal. This approach is dangerous, because of the possibility of two kernel modules changing the same system call. Imagine we have two kernel modules, A and B. A's open system call will be A_open and B's will be B_open. Now, when A is inserted into the kernel, the system call is replaced with A_open, which will call the original sys_open when it's done. Next, B is inserted into the kernel, which replaces the system call with B_open, which will call what it thinks is the original system call, A_open, when it's done.
|
|
</p>
|
|
|
|
<p>
|
|
Now, if B is removed first, everything will be well — it will simply restore the system call to A_open, which calls the original. However, if A is removed and then B is removed, the system will crash. A's removal will restore the system call to the original, sys_open, cutting B out of the loop. Then, when B is removed, it will restore the system call to what it thinks is the original, <b>A_open</b>, which is no longer in memory. At first glance, it appears we could solve this particular problem by checking if the system call is equal to our open function and if so not changing it at all (so that B won't change the system call when it's removed), but that will cause an even worse problem. When A is removed, it sees that the system call was changed to <b>B_open</b> so that it is no longer pointing to <b>A_open</b>, so it won't restore it to <b>sys_open</b> before it is removed from memory. Unfortunately, <b>B_open</b> will still try to call <b>A_open</b> which is no longer there, so that even without removing B the system would crash.
|
|
</p>
|
|
|
|
<p>
|
|
Note that all the related problems make syscall stealing unfeasiable for production use. In order to keep people from doing potential harmful things <b>sys_call_table</b> is no longer exported. This means, if you want to do something more than a mere dry run of this example, you will have to patch your current kernel in order to have sys_call_table exported. In the example directory you will find a README and the patch. As you can imagine, such modifications are not to be taken lightly. Do not try this on valueable systems (ie systems that you do not own - or cannot restore easily). You'll need to get the complete sourcecode of this guide as a tarball in order to get the patch and the README. Depending on your kernel version, you might even need to hand apply the patch. Still here? Well, so is this chapter. If Wyle E. Coyote was a kernel hacker, this would be the first thing he'd try. ;)
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-c"><span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * syscall.c</span>
|
|
<span class="org-comment"> *</span>
|
|
<span class="org-comment"> * System call "stealing" sample.</span>
|
|
<span class="org-comment"> *</span>
|
|
<span class="org-comment"> * Disables page protection at a processor level by</span>
|
|
<span class="org-comment"> * changing the 16th bit in the cr0 register (could be Intel specific)</span>
|
|
<span class="org-comment"> *</span>
|
|
<span class="org-comment"> * Based on example by Peter Jay Salzman and</span>
|
|
<span class="org-comment"> * https://bbs.archlinux.org/viewtopic.php?id=139406</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/module.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/kernel.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/syscalls.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/delay.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><asm/paravirt.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/moduleparam.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">which will have params </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/unistd.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">The list of system calls </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * For the current (process) structure, we need</span>
|
|
<span class="org-comment"> * this to know who the current user is.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/sched.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><asm/uaccess.h></span>
|
|
|
|
<span class="org-type">unsigned</span> <span class="org-type">long</span> **<span class="org-variable-name">sys_call_table</span>;
|
|
<span class="org-type">unsigned</span> <span class="org-type">long</span> <span class="org-variable-name">original_cr0</span>;
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * UID we want to spy on - will be filled from the</span>
|
|
<span class="org-comment"> * command line</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-variable-name">uid</span>;
|
|
module_param(uid, <span class="org-type">int</span>, 0644);
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * A pointer to the original system call. The reason</span>
|
|
<span class="org-comment"> * we keep this, rather than call the original function</span>
|
|
<span class="org-comment"> * (sys_open), is because somebody else might have</span>
|
|
<span class="org-comment"> * replaced the system call before us. Note that this</span>
|
|
<span class="org-comment"> * is not 100% safe, because if another module</span>
|
|
<span class="org-comment"> * replaced sys_open before us, then when we're inserted</span>
|
|
<span class="org-comment"> * we'll call the function in that module - and it</span>
|
|
<span class="org-comment"> * might be removed before we are.</span>
|
|
<span class="org-comment"> *</span>
|
|
<span class="org-comment"> * Another reason for this is that we can't get sys_open.</span>
|
|
<span class="org-comment"> * It's a static variable, so it is not exported.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
asmlinkage <span class="org-type">int</span> (*<span class="org-function-name">original_call</span>) (<span class="org-keyword">const</span> <span class="org-type">char</span> *, <span class="org-type">int</span>, <span class="org-type">int</span>);
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * The function we'll replace sys_open (the function</span>
|
|
<span class="org-comment"> * called when you call the open system call) with. To</span>
|
|
<span class="org-comment"> * find the exact prototype, with the number and type</span>
|
|
<span class="org-comment"> * of arguments, we find the original function first</span>
|
|
<span class="org-comment"> * (it's at fs/open.c).</span>
|
|
<span class="org-comment"> *</span>
|
|
<span class="org-comment"> * In theory, this means that we're tied to the</span>
|
|
<span class="org-comment"> * current version of the kernel. In practice, the</span>
|
|
<span class="org-comment"> * system calls almost never change (it would wreck havoc</span>
|
|
<span class="org-comment"> * and require programs to be recompiled, since the system</span>
|
|
<span class="org-comment"> * calls are the interface between the kernel and the</span>
|
|
<span class="org-comment"> * processes).</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
asmlinkage <span class="org-type">int</span> <span class="org-function-name">our_sys_open</span>(<span class="org-keyword">const</span> <span class="org-type">char</span> *<span class="org-variable-name">filename</span>, <span class="org-type">int</span> <span class="org-variable-name">flags</span>, <span class="org-type">int</span> <span class="org-variable-name">mode</span>)
|
|
{
|
|
<span class="org-type">int</span> <span class="org-variable-name">i</span> = 0;
|
|
<span class="org-type">char</span> <span class="org-variable-name">ch</span>;
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Report the file, if relevant</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
printk(<span class="org-string">"Opened file by %d: "</span>, uid);
|
|
<span class="org-keyword">do</span> {
|
|
get_user(ch, filename + i);
|
|
i++;
|
|
printk(<span class="org-string">"%c"</span>, ch);
|
|
} <span class="org-keyword">while</span> (ch != 0);
|
|
printk(<span class="org-string">"\n"</span>);
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Call the original sys_open - otherwise, we lose</span>
|
|
<span class="org-comment"> * the ability to open files</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">return</span> original_call(filename, flags, mode);
|
|
}
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">unsigned</span> <span class="org-type">long</span> **<span class="org-function-name">aquire_sys_call_table</span>(<span class="org-type">void</span>)
|
|
{
|
|
<span class="org-type">unsigned</span> <span class="org-type">long</span> <span class="org-type">int</span> <span class="org-variable-name">offset</span> = PAGE_OFFSET;
|
|
<span class="org-type">unsigned</span> <span class="org-type">long</span> **<span class="org-variable-name">sct</span>;
|
|
|
|
<span class="org-keyword">while</span> (offset < ULLONG_MAX) {
|
|
sct = (<span class="org-type">unsigned</span> <span class="org-type">long</span> **)offset;
|
|
|
|
<span class="org-keyword">if</span> (sct[__NR_close] == (<span class="org-type">unsigned</span> <span class="org-type">long</span> *) sys_close)
|
|
<span class="org-keyword">return</span> sct;
|
|
|
|
offset += <span class="org-keyword">sizeof</span>(<span class="org-type">void</span> *);
|
|
}
|
|
|
|
<span class="org-keyword">return</span> <span class="org-constant">NULL</span>;
|
|
}
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-function-name">__init</span> syscall_start(<span class="org-type">void</span>)
|
|
{
|
|
<span class="org-keyword">if</span>(<span class="org-negation-char">!</span>(sys_call_table = aquire_sys_call_table()))
|
|
<span class="org-keyword">return</span> -1;
|
|
|
|
original_cr0 = read_cr0();
|
|
|
|
write_cr0(original_cr0 & ~0x00010000);
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">keep track of the original open function </span><span class="org-comment-delimiter">*/</span>
|
|
original_call = (<span class="org-type">void</span>*)sys_call_table[__NR_open];
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">use our open function instead </span><span class="org-comment-delimiter">*/</span>
|
|
sys_call_table[__NR_open] = (<span class="org-type">unsigned</span> <span class="org-type">long</span> *)our_sys_open;
|
|
|
|
write_cr0(original_cr0);
|
|
|
|
printk(KERN_INFO <span class="org-string">"Spying on UID:%d\n"</span>, uid);
|
|
|
|
<span class="org-keyword">return</span> 0;
|
|
}
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">void</span> <span class="org-function-name">__exit</span> syscall_end(<span class="org-type">void</span>)
|
|
{
|
|
<span class="org-keyword">if</span>(<span class="org-negation-char">!</span>sys_call_table) {
|
|
<span class="org-keyword">return</span>;
|
|
}
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Return the system call back to normal</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">if</span> (sys_call_table[__NR_open] != (<span class="org-type">unsigned</span> <span class="org-type">long</span> *)our_sys_open) {
|
|
printk(KERN_ALERT <span class="org-string">"Somebody else also played with the "</span>);
|
|
printk(KERN_ALERT <span class="org-string">"open system call\n"</span>);
|
|
printk(KERN_ALERT <span class="org-string">"The system may be left in "</span>);
|
|
printk(KERN_ALERT <span class="org-string">"an unstable state.\n"</span>);
|
|
}
|
|
|
|
write_cr0(original_cr0 & ~0x00010000);
|
|
sys_call_table[__NR_open] = (<span class="org-type">unsigned</span> <span class="org-type">long</span> *)original_call;
|
|
write_cr0(original_cr0);
|
|
|
|
msleep(2000);
|
|
}
|
|
|
|
module_init(syscall_start);
|
|
module_exit(syscall_end);
|
|
|
|
MODULE_LICENSE(<span class="org-string">"GPL"</span>);
|
|
</code></pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-orga2f4266" class="outline-2">
|
|
<h2 id="orga2f4266">Blocking Processes and threads</h2>
|
|
<div class="outline-text-2" id="text-orga2f4266">
|
|
</div>
|
|
<div id="outline-container-org85824d9" class="outline-3">
|
|
<h3 id="org85824d9">Sleep</h3>
|
|
<div class="outline-text-3" id="text-org85824d9">
|
|
<p>
|
|
What do you do when somebody asks you for something you can't do right away? If you're a human being and you're bothered by a human being, the only thing you can say is: "<i>Not right now, I'm busy. Go away!</i>". But if you're a kernel module and you're bothered by a process, you have another possibility. You can put the process to sleep until you can service it. After all, processes are being put to sleep by the kernel and woken up all the time (that's the way multiple processes appear to run on the same time on a single CPU).
|
|
</p>
|
|
|
|
<p>
|
|
This kernel module is an example of this. The file (called <b>/proc/sleep</b>) can only be opened by a single process at a time. If the file is already open, the kernel module calls wait_event_interruptible. The easiest way to keep a file open is to open it with:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-bash">tail -f
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
This function changes the status of the task (a task is the kernel data structure which holds information about a process and the system call it's in, if any) to <b>TASK_INTERRUPTIBLE</b>, which means that the task will not run until it is woken up somehow, and adds it to WaitQ, the queue of tasks waiting to access the file. Then, the function calls the scheduler to context switch to a different process, one which has some use for the CPU.
|
|
</p>
|
|
|
|
<p>
|
|
When a process is done with the file, it closes it, and module_close is called. That function wakes up all the processes in the queue (there's no mechanism to only wake up one of them). It then returns and the process which just closed the file can continue to run. In time, the scheduler decides that that process has had enough and gives control of the CPU to another process. Eventually, one of the processes which was in the queue will be given control of the CPU by the scheduler. It starts at the point right after the call to <b>module_interruptible_sleep_on</b>.
|
|
</p>
|
|
|
|
<p>
|
|
This means that the process is still in kernel mode - as far as the process is concerned, it issued the open system call and the system call hasn't returned yet. The process doesn't know somebody else used the CPU for most of the time between the moment it issued the call and the moment it returned.
|
|
</p>
|
|
|
|
<p>
|
|
It can then proceed to set a global variable to tell all the other processes that the file is still open and go on with its life. When the other processes get a piece of the CPU, they'll see that global variable and go back to sleep.
|
|
</p>
|
|
|
|
<p>
|
|
So we'll use tail -f to keep the file open in the background, while trying to access it with another process (again in the background, so that we need not switch to a different vt). As soon as the first background process is killed with kill %1 , the second is woken up, is able to access the file and finally terminates.
|
|
</p>
|
|
|
|
<p>
|
|
To make our life more interesting, <b>module_close</b> doesn't have a monopoly on waking up the processes which wait to access the file. A signal, such as <i>Ctrl +c</i> (<b>SIGINT</b>) can also wake up a process. This is because we used <b>module_interruptible_sleep_on</b>. We could have used <b>module_sleep_on</b> instead, but that would have resulted in extremely angry users whose <i>Ctrl+c</i>'s are ignored.
|
|
</p>
|
|
|
|
<p>
|
|
In that case, we want to return with <b>-EINTR</b> immediately. This is important so users can, for example, kill the process before it receives the file.
|
|
</p>
|
|
|
|
<p>
|
|
There is one more point to remember. Some times processes don't want to sleep, they want either to get what they want immediately, or to be told it cannot be done. Such processes use the <b>O_NONBLOCK</b> flag when opening the file. The kernel is supposed to respond by returning with the error code <b>-EAGAIN</b> from operations which would otherwise block, such as opening the file in this example. The program cat_noblock, available in the source directory for this chapter, can be used to open a file with <b>O_NONBLOCK</b>.
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-sh">hostname:~/lkmpg-examples/09-BlockingProcesses# insmod sleep.ko
|
|
hostname:~/lkmpg-examples/09-BlockingProcesses# cat_noblock /proc/sleep
|
|
Last input:
|
|
hostname:~/lkmpg-examples/09-BlockingProcesses# tail -f /proc/sleep &
|
|
Last input:
|
|
Last input:
|
|
Last input:
|
|
Last input:
|
|
Last input:
|
|
Last input:
|
|
Last input:
|
|
tail: /proc/sleep: file truncated
|
|
[1] 6540
|
|
hostname:~/lkmpg-examples/09-BlockingProcesses# cat_noblock /proc/sleep
|
|
Open would block
|
|
hostname:~/lkmpg-examples/09-BlockingProcesses# kill %1
|
|
[1]+ Terminated tail -f /proc/sleep
|
|
hostname:~/lkmpg-examples/09-BlockingProcesses# cat_noblock /proc/sleep
|
|
Last input:
|
|
hostname:~/lkmpg-examples/09-BlockingProcesses#
|
|
</code></pre>
|
|
</div>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-c"><span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * sleep.c - create a /proc file, and if several processes try to open it at</span>
|
|
<span class="org-comment"> * the same time, put all but one to sleep</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/kernel.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">We're doing kernel work </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/module.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">Specifically, a module </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/proc_fs.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">Necessary because we use proc fs </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/sched.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">For putting processes to sleep and</span>
|
|
<span class="org-comment"> waking them up </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><asm/uaccess.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">for get_user and put_user </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * The module's file functions</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Here we keep the last message received, to prove that we can process our</span>
|
|
<span class="org-comment"> * input</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#define</span> <span class="org-variable-name">MESSAGE_LENGTH</span> 80
|
|
<span class="org-keyword">static</span> <span class="org-type">char</span> Message[MESSAGE_LENGTH];
|
|
|
|
<span class="org-keyword">static</span> <span class="org-keyword">struct</span> <span class="org-type">proc_dir_entry</span> *<span class="org-variable-name">Our_Proc_File</span>;
|
|
<span class="org-preprocessor">#define</span> <span class="org-variable-name">PROC_ENTRY_FILENAME</span> <span class="org-string">"sleep"</span>
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Since we use the file operations struct, we can't use the special proc</span>
|
|
<span class="org-comment"> * output provisions - we have to use a standard read function, which is this</span>
|
|
<span class="org-comment"> * function</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">static</span> <span class="org-type">ssize_t</span> <span class="org-function-name">module_output</span>(<span class="org-keyword">struct</span> <span class="org-type">file</span> *<span class="org-variable-name">file</span>, <span class="org-comment-delimiter">/* </span><span class="org-comment">see include/linux/fs.h </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-type">char</span> *<span class="org-variable-name">buf</span>, <span class="org-comment-delimiter">/* </span><span class="org-comment">The buffer to put data to</span>
|
|
<span class="org-comment"> (in the user segment) </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-type">size_t</span> <span class="org-variable-name">len</span>, <span class="org-comment-delimiter">/* </span><span class="org-comment">The length of the buffer </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-type">loff_t</span> * <span class="org-variable-name">offset</span>)
|
|
{
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-variable-name">finished</span> = 0;
|
|
<span class="org-type">int</span> <span class="org-variable-name">i</span>;
|
|
<span class="org-type">char</span> <span class="org-variable-name">message</span>[MESSAGE_LENGTH + 30];
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Return 0 to signify end of file - that we have nothing</span>
|
|
<span class="org-comment"> * more to say at this point.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">if</span> (finished) {
|
|
finished = 0;
|
|
<span class="org-keyword">return</span> 0;
|
|
}
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * If you don't understand this by now, you're hopeless as a kernel</span>
|
|
<span class="org-comment"> * programmer.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
sprintf(message, <span class="org-string">"Last input:%s\n"</span>, Message);
|
|
<span class="org-keyword">for</span> (i = 0; i < len && message[i]; i++)
|
|
put_user(message[i], buf + i);
|
|
|
|
finished = 1;
|
|
<span class="org-keyword">return</span> i; <span class="org-comment-delimiter">/* </span><span class="org-comment">Return the number of bytes "read" </span><span class="org-comment-delimiter">*/</span>
|
|
}
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * This function receives input from the user when the user writes to the /proc</span>
|
|
<span class="org-comment"> * file.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">static</span> <span class="org-type">ssize_t</span> <span class="org-function-name">module_input</span>(<span class="org-keyword">struct</span> <span class="org-type">file</span> *<span class="org-variable-name">file</span>, <span class="org-comment-delimiter">/* </span><span class="org-comment">The file itself </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">const</span> <span class="org-type">char</span> *<span class="org-variable-name">buf</span>, <span class="org-comment-delimiter">/* </span><span class="org-comment">The buffer with input </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-type">size_t</span> <span class="org-variable-name">length</span>, <span class="org-comment-delimiter">/* </span><span class="org-comment">The buffer's length </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-type">loff_t</span> * <span class="org-variable-name">offset</span>) <span class="org-comment-delimiter">/* </span><span class="org-comment">offset to file - ignore </span><span class="org-comment-delimiter">*/</span>
|
|
{
|
|
<span class="org-type">int</span> <span class="org-variable-name">i</span>;
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Put the input into Message, where module_output will later be</span>
|
|
<span class="org-comment"> * able to use it</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">for</span> (i = 0; i < MESSAGE_LENGTH - 1 && i < length; i++)
|
|
get_user(Message[i], buf + i);
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * we want a standard, zero terminated string</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
Message[i] = <span class="org-string">'\0'</span>;
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * We need to return the number of input characters used</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">return</span> i;
|
|
}
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * 1 if the file is currently open by somebody</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-type">int</span> <span class="org-variable-name">Already_Open</span> = 0;
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Queue of processes who want our file</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
DECLARE_WAIT_QUEUE_HEAD(WaitQ);
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Called when the /proc file is opened</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-function-name">module_open</span>(<span class="org-keyword">struct</span> <span class="org-type">inode</span> *<span class="org-variable-name">inode</span>, <span class="org-keyword">struct</span> <span class="org-type">file</span> *<span class="org-variable-name">file</span>)
|
|
{
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * If the file's flags include O_NONBLOCK, it means the process doesn't</span>
|
|
<span class="org-comment"> * want to wait for the file. In this case, if the file is already</span>
|
|
<span class="org-comment"> * open, we should fail with -EAGAIN, meaning "you'll have to try</span>
|
|
<span class="org-comment"> * again", instead of blocking a process which would rather stay awake.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">if</span> ((file->f_flags & O_NONBLOCK) && Already_Open)
|
|
<span class="org-keyword">return</span> -EAGAIN;
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * This is the correct place for try_module_get(THIS_MODULE) because</span>
|
|
<span class="org-comment"> * if a process is in the loop, which is within the kernel module,</span>
|
|
<span class="org-comment"> * the kernel module must not be removed.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
try_module_get(THIS_MODULE);
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * If the file is already open, wait until it isn't</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-keyword">while</span> (Already_Open) {
|
|
<span class="org-type">int</span> <span class="org-variable-name">i</span>, <span class="org-variable-name">is_sig</span> = 0;
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * This function puts the current process, including any system</span>
|
|
<span class="org-comment"> * calls, such as us, to sleep. Execution will be resumed right</span>
|
|
<span class="org-comment"> * after the function call, either because somebody called</span>
|
|
<span class="org-comment"> * wake_up(&WaitQ) (only module_close does that, when the file</span>
|
|
<span class="org-comment"> * is closed) or when a signal, such as Ctrl-C, is sent</span>
|
|
<span class="org-comment"> * to the process</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
wait_event_interruptible(WaitQ, <span class="org-negation-char">!</span>Already_Open);
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * If we woke up because we got a signal we're not blocking,</span>
|
|
<span class="org-comment"> * return -EINTR (fail the system call). This allows processes</span>
|
|
<span class="org-comment"> * to be killed or stopped.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Emmanuel Papirakis:</span>
|
|
<span class="org-comment"> *</span>
|
|
<span class="org-comment"> * This is a little update to work with 2.2.*. Signals now are contained in</span>
|
|
<span class="org-comment"> * two words (64 bits) and are stored in a structure that contains an array of</span>
|
|
<span class="org-comment"> * two unsigned longs. We now have to make 2 checks in our if.</span>
|
|
<span class="org-comment"> *</span>
|
|
<span class="org-comment"> * Ori Pomerantz:</span>
|
|
<span class="org-comment"> *</span>
|
|
<span class="org-comment"> * Nobody promised me they'll never use more than 64 bits, or that this book</span>
|
|
<span class="org-comment"> * won't be used for a version of Linux with a word size of 16 bits. This code</span>
|
|
<span class="org-comment"> * would work in any case.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">for</span> (i = 0; i < _NSIG_WORDS && <span class="org-negation-char">!</span>is_sig; i++)
|
|
is_sig =
|
|
current->pending.signal.sig[i] & ~current->
|
|
blocked.sig[i];
|
|
|
|
<span class="org-keyword">if</span> (is_sig) {
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * It's important to put module_put(THIS_MODULE) here,</span>
|
|
<span class="org-comment"> * because for processes where the open is interrupted</span>
|
|
<span class="org-comment"> * there will never be a corresponding close. If we</span>
|
|
<span class="org-comment"> * don't decrement the usage count here, we will be</span>
|
|
<span class="org-comment"> * left with a positive usage count which we'll have no</span>
|
|
<span class="org-comment"> * way to bring down to zero, giving us an immortal</span>
|
|
<span class="org-comment"> * module, which can only be killed by rebooting</span>
|
|
<span class="org-comment"> * the machine.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
module_put(THIS_MODULE);
|
|
<span class="org-keyword">return</span> -EINTR;
|
|
}
|
|
}
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * If we got here, Already_Open must be zero</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Open the file</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
Already_Open = 1;
|
|
<span class="org-keyword">return</span> 0; <span class="org-comment-delimiter">/* </span><span class="org-comment">Allow the access </span><span class="org-comment-delimiter">*/</span>
|
|
}
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Called when the /proc file is closed</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-type">int</span> <span class="org-function-name">module_close</span>(<span class="org-keyword">struct</span> <span class="org-type">inode</span> *<span class="org-variable-name">inode</span>, <span class="org-keyword">struct</span> <span class="org-type">file</span> *<span class="org-variable-name">file</span>)
|
|
{
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Set Already_Open to zero, so one of the processes in the WaitQ will</span>
|
|
<span class="org-comment"> * be able to set Already_Open back to one and to open the file. All</span>
|
|
<span class="org-comment"> * the other processes will be called when Already_Open is back to one,</span>
|
|
<span class="org-comment"> * so they'll go back to sleep.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
Already_Open = 0;
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Wake up all the processes in WaitQ, so if anybody is waiting for the</span>
|
|
<span class="org-comment"> * file, they can have it.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
wake_up(&WaitQ);
|
|
|
|
module_put(THIS_MODULE);
|
|
|
|
<span class="org-keyword">return</span> 0; <span class="org-comment-delimiter">/* </span><span class="org-comment">success </span><span class="org-comment-delimiter">*/</span>
|
|
}
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Structures to register as the /proc file, with pointers to all the relevant</span>
|
|
<span class="org-comment"> * functions.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * File operations for our proc file. This is where we place pointers to all</span>
|
|
<span class="org-comment"> * the functions called when somebody tries to do something to our file. NULL</span>
|
|
<span class="org-comment"> * means we don't want to deal with something.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">static</span> <span class="org-keyword">struct</span> <span class="org-type">file_operations</span> <span class="org-variable-name">File_Ops_4_Our_Proc_File</span> = {
|
|
.read = module_output, <span class="org-comment-delimiter">/* </span><span class="org-comment">"read" from the file </span><span class="org-comment-delimiter">*/</span>
|
|
.write = module_input, <span class="org-comment-delimiter">/* </span><span class="org-comment">"write" to the file </span><span class="org-comment-delimiter">*/</span>
|
|
.open = module_open, <span class="org-comment-delimiter">/* </span><span class="org-comment">called when the /proc file is opened </span><span class="org-comment-delimiter">*/</span>
|
|
.release = module_close, <span class="org-comment-delimiter">/* </span><span class="org-comment">called when it's closed </span><span class="org-comment-delimiter">*/</span>
|
|
};
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Module initialization and cleanup</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Initialize the module - register the proc file</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-type">int</span> <span class="org-function-name">init_module</span>()
|
|
{
|
|
Our_Proc_File = proc_create(PROC_ENTRY_FILENAME, 0644, <span class="org-constant">NULL</span>, &File_Ops_4_Our_Proc_File);
|
|
<span class="org-keyword">if</span>(Our_Proc_File == <span class="org-constant">NULL</span>)
|
|
{
|
|
remove_proc_entry(PROC_ENTRY_FILENAME, <span class="org-constant">NULL</span>);
|
|
printk(KERN_DEBUG <span class="org-string">"Error: Could not initialize /proc/%s\n"</span>, PROC_ENTRY_FILENAME);
|
|
<span class="org-keyword">return</span> -ENOMEM;
|
|
}
|
|
proc_set_size(Our_Proc_File, 80);
|
|
proc_set_user(Our_Proc_File, GLOBAL_ROOT_UID, GLOBAL_ROOT_GID);
|
|
|
|
printk(KERN_INFO <span class="org-string">"/proc/test created\n"</span>);
|
|
|
|
<span class="org-keyword">return</span> 0;
|
|
}
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Cleanup - unregister our file from /proc. This could get dangerous if</span>
|
|
<span class="org-comment"> * there are still processes waiting in WaitQ, because they are inside our</span>
|
|
<span class="org-comment"> * open function, which will get unloaded. I'll explain how to avoid removal</span>
|
|
<span class="org-comment"> * of a kernel module in such a case in chapter 10.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-type">void</span> <span class="org-function-name">cleanup_module</span>()
|
|
{
|
|
remove_proc_entry(PROC_ENTRY_FILENAME, <span class="org-constant">NULL</span>);
|
|
printk(KERN_DEBUG <span class="org-string">"/proc/%s removed\n"</span>, PROC_ENTRY_FILENAME);
|
|
}
|
|
</code></pre>
|
|
</div>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-c"><span class="org-comment-delimiter">/* </span><span class="org-comment">cat_noblock.c - open a file and display its contents, but exit rather than</span>
|
|
<span class="org-comment"> * wait for input </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">Copyright (C) 1998 by Ori Pomerantz </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><stdio.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">standard I/O </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><fcntl.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">for open </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><unistd.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">for read </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><stdlib.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">for exit </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><errno.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">for errno </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-preprocessor">#define</span> <span class="org-variable-name">MAX_BYTES</span> 1024*4
|
|
|
|
|
|
<span class="org-type">int</span> <span class="org-function-name">main</span>(<span class="org-type">int</span> <span class="org-variable-name">argc</span>, <span class="org-type">char</span> *<span class="org-variable-name">argv</span>[])
|
|
{
|
|
<span class="org-type">int</span> <span class="org-variable-name">fd</span>; <span class="org-comment-delimiter">/* </span><span class="org-comment">The file descriptor for the file to read </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-type">size_t</span> <span class="org-variable-name">bytes</span>; <span class="org-comment-delimiter">/* </span><span class="org-comment">The number of bytes read </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-type">char</span> <span class="org-variable-name">buffer</span>[MAX_BYTES]; <span class="org-comment-delimiter">/* </span><span class="org-comment">The buffer for the bytes </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">Usage </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">if</span> (argc != 2) {
|
|
printf(<span class="org-string">"Usage: %s <filename>\n"</span>, argv[0]);
|
|
puts(<span class="org-string">"Reads the content of a file, but doesn't wait for input"</span>);
|
|
exit(-1);
|
|
}
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">Open the file for reading in non blocking mode </span><span class="org-comment-delimiter">*/</span>
|
|
fd = open(argv[1], O_RDONLY | O_NONBLOCK);
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">If open failed </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">if</span> (fd == -1) {
|
|
<span class="org-keyword">if</span> (errno = EAGAIN)
|
|
puts(<span class="org-string">"Open would block"</span>);
|
|
<span class="org-keyword">else</span>
|
|
puts(<span class="org-string">"Open failed"</span>);
|
|
exit(-1);
|
|
}
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">Read the file and output its contents </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">do</span> {
|
|
<span class="org-type">int</span> <span class="org-variable-name">i</span>;
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">Read characters from the file </span><span class="org-comment-delimiter">*/</span>
|
|
bytes = read(fd, buffer, MAX_BYTES);
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">If there's an error, report it and die </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">if</span> (bytes == -1) {
|
|
<span class="org-keyword">if</span> (errno = EAGAIN)
|
|
puts(<span class="org-string">"Normally I'd block, but you told me not to"</span>);
|
|
<span class="org-keyword">else</span>
|
|
puts(<span class="org-string">"Another read error"</span>);
|
|
exit(-1);
|
|
}
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">Print the characters </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">if</span> (bytes > 0) {
|
|
<span class="org-keyword">for</span>(i=0; i<bytes; i++)
|
|
putchar(buffer[i]);
|
|
}
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">While there are no errors and the file isn't over </span><span class="org-comment-delimiter">*/</span>
|
|
} <span class="org-keyword">while</span> (bytes > 0);
|
|
<span class="org-keyword">return</span> 0;
|
|
}
|
|
</code></pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-orgca2cec5" class="outline-3">
|
|
<h3 id="orgca2cec5">Completions</h3>
|
|
<div class="outline-text-3" id="text-orgca2cec5">
|
|
<p>
|
|
Sometimes one thing should happen before another within a module having multiple threads. Rather than using <b>/proc/sleep</b> commands the kernel has another way to do this which allows timeouts or interrupts to also happen.
|
|
</p>
|
|
|
|
<p>
|
|
In the following example two threads are started, but one needs to start before another.
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-C"><span class="org-preprocessor">#include</span> <span class="org-string"><linux/init.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/module.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/kernel.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/kthread.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/completion.h></span>
|
|
|
|
<span class="org-keyword">static</span> <span class="org-keyword">struct</span> {
|
|
<span class="org-keyword">struct</span> <span class="org-type">completion</span> <span class="org-variable-name">crank_comp</span>;
|
|
<span class="org-keyword">struct</span> <span class="org-type">completion</span> <span class="org-variable-name">flywheel_comp</span>;
|
|
} <span class="org-variable-name">machine</span>;
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-function-name">machine_crank_thread</span>(<span class="org-type">void</span>* <span class="org-variable-name">arg</span>)
|
|
{
|
|
printk(<span class="org-string">"Turn the crank\n"</span>);
|
|
|
|
complete_all(&machine.crank_comp);
|
|
complete_and_exit(&machine.crank_comp, 0);
|
|
}
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-function-name">machine_flywheel_spinup_thread</span>(<span class="org-type">void</span>* <span class="org-variable-name">arg</span>)
|
|
{
|
|
wait_for_completion(&machine.crank_comp);
|
|
|
|
printk(<span class="org-string">"Flywheel spins up\n"</span>);
|
|
|
|
complete_all(&machine.flywheel_comp);
|
|
complete_and_exit(&machine.flywheel_comp, 0);
|
|
}
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-function-name">completions_init</span>(<span class="org-type">void</span>)
|
|
{
|
|
<span class="org-keyword">struct</span> <span class="org-type">task_struct</span>* <span class="org-variable-name">crank_thread</span>;
|
|
<span class="org-keyword">struct</span> <span class="org-type">task_struct</span>* <span class="org-variable-name">flywheel_thread</span>;
|
|
|
|
printk(<span class="org-string">"completions example\n"</span>);
|
|
|
|
init_completion(&machine.crank_comp);
|
|
init_completion(&machine.flywheel_comp);
|
|
|
|
crank_thread =
|
|
kthread_create(machine_crank_thread,
|
|
<span class="org-constant">NULL</span>, <span class="org-string">"KThread Crank"</span>);
|
|
<span class="org-keyword">if</span> (IS_ERR(crank_thread))
|
|
<span class="org-keyword">goto</span> <span class="org-constant">ERROR_THREAD_1</span>;
|
|
|
|
flywheel_thread =
|
|
kthread_create(machine_flywheel_spinup_thread,
|
|
<span class="org-constant">NULL</span>, <span class="org-string">"KThread Flywheel"</span>);
|
|
<span class="org-keyword">if</span> (IS_ERR(flywheel_thread))
|
|
<span class="org-keyword">goto</span> <span class="org-constant">ERROR_THREAD_2</span>;
|
|
|
|
wake_up_process(flywheel_thread);
|
|
wake_up_process(crank_thread);
|
|
|
|
<span class="org-keyword">return</span> 0;
|
|
|
|
<span class="org-constant">ERROR_THREAD_2</span>:
|
|
kthread_stop(crank_thread);
|
|
<span class="org-constant">ERROR_THREAD_1</span>:
|
|
|
|
<span class="org-keyword">return</span> -1;
|
|
}
|
|
|
|
<span class="org-type">void</span> <span class="org-function-name">completions_exit</span>(<span class="org-type">void</span>)
|
|
{
|
|
wait_for_completion(&machine.crank_comp);
|
|
wait_for_completion(&machine.flywheel_comp);
|
|
|
|
printk(<span class="org-string">"completions exit\n"</span>);
|
|
}
|
|
|
|
module_init(completions_init);
|
|
module_exit(completions_exit);
|
|
|
|
MODULE_AUTHOR(<span class="org-string">"Bob Mottram"</span>);
|
|
MODULE_DESCRIPTION(<span class="org-string">"Completions example"</span>);
|
|
MODULE_LICENSE(<span class="org-string">"GPL"</span>);
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
The <i>machine</i> structure stores the completion states for the two threads. At the exit point of each thread the respective completion state is updated, and <i>wait_for_completion</i> is used by the flywheel thread to ensure that it doesn't begin prematurely.
|
|
</p>
|
|
|
|
<p>
|
|
So even though <i>flywheel_thread</i> is started first you should notice if you load this module and run <i>dmesg</i> that turning the crank always happens first because the flywheel thread waits for it to complete.
|
|
</p>
|
|
|
|
<p>
|
|
There are other variations upon the <i>wait_for_completion</i> function, which include timeouts or being interrupted, but this basic mechanism is enough for many common situations without adding a lot of complexity.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-org06aaff5" class="outline-2">
|
|
<h2 id="org06aaff5">Avoiding Collisions and Deadlocks</h2>
|
|
<div class="outline-text-2" id="text-org06aaff5">
|
|
<p>
|
|
If processes running on different CPUs or in different threads try to access the same memory then it's possible that strange things can happen or your system can lock up. To avoid this various types of mutual exclusion kernel functions are available. These indicate if a section of code is "locked" or "unlocked" so that simultaneous attempts to run it can't happen.
|
|
</p>
|
|
</div>
|
|
<div id="outline-container-orgb98d791" class="outline-3">
|
|
<h3 id="orgb98d791">Mutex</h3>
|
|
<div class="outline-text-3" id="text-orgb98d791">
|
|
<p>
|
|
You can use kernel mutexes (mutual exclusions) in much the same manner that you might deploy them in userland. This may be all that's needed to avoid collisions in most cases.
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-C"><span class="org-preprocessor">#include</span> <span class="org-string"><linux/kernel.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/module.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/init.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/mutex.h></span>
|
|
|
|
DEFINE_MUTEX(mymutex);
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-function-name">example_mutex_init</span>(<span class="org-type">void</span>)
|
|
{
|
|
<span class="org-type">int</span> <span class="org-variable-name">ret</span>;
|
|
|
|
printk(<span class="org-string">"example_mutex init\n"</span>);
|
|
|
|
ret = mutex_trylock(&mymutex);
|
|
<span class="org-keyword">if</span> (ret != 0) {
|
|
printk(<span class="org-string">"mutex is locked\n"</span>);
|
|
|
|
<span class="org-keyword">if</span> (mutex_is_locked(&mymutex) == 0)
|
|
printk(<span class="org-string">"The mutex failed to lock!\n"</span>);
|
|
|
|
mutex_unlock(&mymutex);
|
|
printk(<span class="org-string">"mutex is unlocked\n"</span>);
|
|
}
|
|
<span class="org-keyword">else</span>
|
|
printk(<span class="org-string">"Failed to lock\n"</span>);
|
|
|
|
<span class="org-keyword">return</span> 0;
|
|
}
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">void</span> <span class="org-function-name">example_mutex_exit</span>(<span class="org-type">void</span>)
|
|
{
|
|
printk(<span class="org-string">"example_mutex exit\n"</span>);
|
|
}
|
|
|
|
module_init(example_mutex_init);
|
|
module_exit(example_mutex_exit);
|
|
|
|
MODULE_AUTHOR(<span class="org-string">"Bob Mottram"</span>);
|
|
MODULE_DESCRIPTION(<span class="org-string">"Mutex example"</span>);
|
|
MODULE_LICENSE(<span class="org-string">"GPL"</span>);
|
|
</code></pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div id="outline-container-orgb75c67b" class="outline-3">
|
|
<h3 id="orgb75c67b">Spinlocks</h3>
|
|
<div class="outline-text-3" id="text-orgb75c67b">
|
|
<p>
|
|
As the name suggests, spinlocks lock up the CPU that the code is running on, taking 100% of its resources. Because of this you should only use the spinlock mechanism around code which is likely to take no more than a few milliseconds to run and so won't noticably slow anything down from the user's point of view.
|
|
</p>
|
|
|
|
<p>
|
|
The example here is <i>"irq safe"</i> in that if interrupts happen during the lock then they won't be forgotten and will activate when the unlock happens, using the <i>flags</i> variable to retain their state.
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-C"><span class="org-preprocessor">#include</span> <span class="org-string"><linux/kernel.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/module.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/init.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/spinlock.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/interrupt.h></span>
|
|
|
|
DEFINE_SPINLOCK(sl_static);
|
|
<span class="org-type">spinlock_t</span> <span class="org-variable-name">sl_dynamic</span>;
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">void</span> <span class="org-function-name">example_spinlock_static</span>(<span class="org-type">void</span>)
|
|
{
|
|
<span class="org-type">unsigned</span> <span class="org-type">long</span> <span class="org-variable-name">flags</span>;
|
|
|
|
spin_lock_irqsave(&sl_static, flags);
|
|
printk(<span class="org-string">"Locked static spinlock\n"</span>);
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">Do something or other safely.</span>
|
|
<span class="org-comment"> Because this uses 100% CPU time this</span>
|
|
<span class="org-comment"> code should take no more than a few</span>
|
|
<span class="org-comment"> milliseconds to run </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
spin_unlock_irqrestore(&sl_static, flags);
|
|
printk(<span class="org-string">"Unlocked static spinlock\n"</span>);
|
|
}
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">void</span> <span class="org-function-name">example_spinlock_dynamic</span>(<span class="org-type">void</span>)
|
|
{
|
|
<span class="org-type">unsigned</span> <span class="org-type">long</span> <span class="org-variable-name">flags</span>;
|
|
|
|
spin_lock_init(&sl_dynamic);
|
|
spin_lock_irqsave(&sl_dynamic, flags);
|
|
printk(<span class="org-string">"Locked dynamic spinlock\n"</span>);
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">Do something or other safely.</span>
|
|
<span class="org-comment"> Because this uses 100% CPU time this</span>
|
|
<span class="org-comment"> code should take no more than a few</span>
|
|
<span class="org-comment"> milliseconds to run </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
spin_unlock_irqrestore(&sl_dynamic, flags);
|
|
printk(<span class="org-string">"Unlocked dynamic spinlock\n"</span>);
|
|
}
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-function-name">example_spinlock_init</span>(<span class="org-type">void</span>)
|
|
{
|
|
printk(<span class="org-string">"example spinlock started\n"</span>);
|
|
|
|
example_spinlock_static();
|
|
example_spinlock_dynamic();
|
|
|
|
<span class="org-keyword">return</span> 0;
|
|
}
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">void</span> <span class="org-function-name">example_spinlock_exit</span>(<span class="org-type">void</span>)
|
|
{
|
|
printk(<span class="org-string">"example spinlock exit\n"</span>);
|
|
}
|
|
|
|
module_init(example_spinlock_init);
|
|
module_exit(example_spinlock_exit);
|
|
|
|
MODULE_AUTHOR(<span class="org-string">"Bob Mottram"</span>);
|
|
MODULE_DESCRIPTION(<span class="org-string">"Spinlock example"</span>);
|
|
MODULE_LICENSE(<span class="org-string">"GPL"</span>);
|
|
</code></pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-orgd4116f2" class="outline-3">
|
|
<h3 id="orgd4116f2">Read and write locks</h3>
|
|
<div class="outline-text-3" id="text-orgd4116f2">
|
|
<p>
|
|
Read and write locks are specialised kinds of spinlocks so that you can exclusively read from something or write to something. Like the earlier spinlocks example the one below shows an "irq safe" situation in which if other functions were triggered from irqs which might also read and write to whatever you are concerned with then they wouldn't disrupt the logic. As before it's a good idea to keep anything done within the lock as short as possible so that it doesn't hang up the system and cause users to start revolting against the tyranny of your module.
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-C"><span class="org-preprocessor">#include</span> <span class="org-string"><linux/kernel.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/module.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/interrupt.h></span>
|
|
|
|
DEFINE_RWLOCK(myrwlock);
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">void</span> <span class="org-function-name">example_read_lock</span>(<span class="org-type">void</span>)
|
|
{
|
|
<span class="org-type">unsigned</span> <span class="org-type">long</span> <span class="org-variable-name">flags</span>;
|
|
|
|
read_lock_irqsave(&myrwlock, flags);
|
|
printk(<span class="org-string">"Read Locked\n"</span>);
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">Read from something </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
read_unlock_irqrestore(&myrwlock, flags);
|
|
printk(<span class="org-string">"Read Unlocked\n"</span>);
|
|
}
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">void</span> <span class="org-function-name">example_write_lock</span>(<span class="org-type">void</span>)
|
|
{
|
|
<span class="org-type">unsigned</span> <span class="org-type">long</span> <span class="org-variable-name">flags</span>;
|
|
|
|
write_lock_irqsave(&myrwlock, flags);
|
|
printk(<span class="org-string">"Write Locked\n"</span>);
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">Write to something </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
write_unlock_irqrestore(&myrwlock, flags);
|
|
printk(<span class="org-string">"Write Unlocked\n"</span>);
|
|
}
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-function-name">example_rwlock_init</span>(<span class="org-type">void</span>)
|
|
{
|
|
printk(<span class="org-string">"example_rwlock started\n"</span>);
|
|
|
|
example_read_lock();
|
|
example_write_lock();
|
|
|
|
<span class="org-keyword">return</span> 0;
|
|
}
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">void</span> <span class="org-function-name">example_rwlock_exit</span>(<span class="org-type">void</span>)
|
|
{
|
|
printk(<span class="org-string">"example_rwlock exit\n"</span>);
|
|
}
|
|
|
|
module_init(example_rwlock_init);
|
|
module_exit(example_rwlock_exit);
|
|
|
|
MODULE_AUTHOR(<span class="org-string">"Bob Mottram"</span>);
|
|
MODULE_DESCRIPTION(<span class="org-string">"Read/Write locks example"</span>);
|
|
MODULE_LICENSE(<span class="org-string">"GPL"</span>);
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
Of course if you know for sure that there are no functions triggered by irqs which could possibly interfere with your logic then you can use the simpler <i>read_lock(&myrwlock)</i> and <i>read_unlock(&myrwlock)</i> or the corresponding write functions.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
<div id="outline-container-org3a8a589" class="outline-3">
|
|
<h3 id="org3a8a589">Atomic operations</h3>
|
|
<div class="outline-text-3" id="text-org3a8a589">
|
|
<p>
|
|
If you're doing simple arithmetic: adding, subtracting or bitwise operations then there's another way in the multi-CPU and multi-hyperthreaded world to stop other parts of the system from messing with your mojo. By using atomic operations you can be confident that your addition, subtraction or bit flip did actually happen and wasn't overwritten by some other shenanigans. An example is shown below.
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-C"><span class="org-preprocessor">#include</span> <span class="org-string"><linux/kernel.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/module.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/interrupt.h></span>
|
|
|
|
<span class="org-preprocessor">#define</span> <span class="org-variable-name">BYTE_TO_BINARY_PATTERN</span> <span class="org-string">"%c%c%c%c%c%c%c%c"</span>
|
|
<span class="org-preprocessor">#define</span> <span class="org-function-name">BYTE_TO_BINARY</span>(<span class="org-variable-name">byte</span>) \
|
|
(byte & 0x80 ? <span class="org-string">'1'</span> : <span class="org-string">'0'</span>), \
|
|
(byte & 0x40 ? <span class="org-string">'1'</span> : <span class="org-string">'0'</span>), \
|
|
(byte & 0x20 ? <span class="org-string">'1'</span> : <span class="org-string">'0'</span>), \
|
|
(byte & 0x10 ? <span class="org-string">'1'</span> : <span class="org-string">'0'</span>), \
|
|
(byte & 0x08 ? <span class="org-string">'1'</span> : <span class="org-string">'0'</span>), \
|
|
(byte & 0x04 ? <span class="org-string">'1'</span> : <span class="org-string">'0'</span>), \
|
|
(byte & 0x02 ? <span class="org-string">'1'</span> : <span class="org-string">'0'</span>), \
|
|
(byte & 0x01 ? <span class="org-string">'1'</span> : <span class="org-string">'0'</span>)
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">void</span> <span class="org-function-name">atomic_add_subtract</span>(<span class="org-type">void</span>)
|
|
{
|
|
<span class="org-type">atomic_t</span> <span class="org-variable-name">debbie</span>;
|
|
<span class="org-type">atomic_t</span> <span class="org-variable-name">chris</span> = ATOMIC_INIT(50);
|
|
|
|
atomic_set(&debbie, 45);
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">subtract one </span><span class="org-comment-delimiter">*/</span>
|
|
atomic_dec(&debbie);
|
|
|
|
atomic_add(7, &debbie);
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">add one </span><span class="org-comment-delimiter">*/</span>
|
|
atomic_inc(&debbie);
|
|
|
|
printk(<span class="org-string">"chris: %d, debbie: %d\n"</span>,
|
|
atomic_read(&chris), atomic_read(&debbie));
|
|
}
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">void</span> <span class="org-function-name">atomic_bitwise</span>(<span class="org-type">void</span>)
|
|
{
|
|
<span class="org-type">unsigned</span> <span class="org-type">long</span> <span class="org-variable-name">word</span> = 0;
|
|
|
|
printk(<span class="org-string">"Bits 0: "</span>BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));
|
|
set_bit(3, &word);
|
|
set_bit(5, &word);
|
|
printk(<span class="org-string">"Bits 1: "</span>BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));
|
|
clear_bit(5, &word);
|
|
printk(<span class="org-string">"Bits 2: "</span>BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));
|
|
change_bit(3, &word);
|
|
|
|
printk(<span class="org-string">"Bits 3: "</span>BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));
|
|
<span class="org-keyword">if</span> (test_and_set_bit(3, &word))
|
|
printk(<span class="org-string">"wrong\n"</span>);
|
|
printk(<span class="org-string">"Bits 4: "</span>BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));
|
|
|
|
word = 255;
|
|
printk(<span class="org-string">"Bits 5: "</span>BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));
|
|
}
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-function-name">example_atomic_init</span>(<span class="org-type">void</span>)
|
|
{
|
|
printk(<span class="org-string">"example_atomic started\n"</span>);
|
|
|
|
atomic_add_subtract();
|
|
atomic_bitwise();
|
|
|
|
<span class="org-keyword">return</span> 0;
|
|
}
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">void</span> <span class="org-function-name">example_atomic_exit</span>(<span class="org-type">void</span>)
|
|
{
|
|
printk(<span class="org-string">"example_atomic exit\n"</span>);
|
|
}
|
|
|
|
module_init(example_atomic_init);
|
|
module_exit(example_atomic_exit);
|
|
|
|
MODULE_AUTHOR(<span class="org-string">"Bob Mottram"</span>);
|
|
MODULE_DESCRIPTION(<span class="org-string">"Atomic operations example"</span>);
|
|
MODULE_LICENSE(<span class="org-string">"GPL"</span>);
|
|
</code></pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div id="outline-container-orgbb1c30e" class="outline-2">
|
|
<h2 id="orgbb1c30e">Replacing Printks</h2>
|
|
<div class="outline-text-2" id="text-orgbb1c30e">
|
|
</div>
|
|
<div id="outline-container-org2bb7a31" class="outline-3">
|
|
<h3 id="org2bb7a31">Replacing printk</h3>
|
|
<div class="outline-text-3" id="text-org2bb7a31">
|
|
<p>
|
|
In Section 1.2.1.2, I said that X and kernel module programming don't mix. That's true for developing kernel modules, but in actual use, you want to be able to send messages to whichever tty the command to load the module came from.
|
|
</p>
|
|
|
|
<p>
|
|
"tty" is an abbreviation of <i>teletype</i>: originally a combination keyboard-printer used to communicate with a Unix system, and today an abstraction for the text stream used for a Unix program, whether it's a physical terminal, an xterm on an X display, a network connection used with ssh, etc.
|
|
</p>
|
|
|
|
<p>
|
|
The way this is done is by using current, a pointer to the currently running task, to get the current task's tty structure. Then, we look inside that tty structure to find a pointer to a string write function, which we use to write a string to the tty.
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-c"><span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * print_string.c - Send output to the tty we're running on, regardless if it's</span>
|
|
<span class="org-comment"> * through X11, telnet, etc. We do this by printing the string to the tty</span>
|
|
<span class="org-comment"> * associated with the current task.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/kernel.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/module.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/init.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/sched.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">For current </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/tty.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">For the tty declarations </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/version.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">For LINUX_VERSION_CODE </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
MODULE_LICENSE(<span class="org-string">"GPL"</span>);
|
|
MODULE_AUTHOR(<span class="org-string">"Peter Jay Salzman"</span>);
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">void</span> <span class="org-function-name">print_string</span>(<span class="org-type">char</span> *<span class="org-variable-name">str</span>)
|
|
{
|
|
<span class="org-keyword">struct</span> <span class="org-type">tty_struct</span> *<span class="org-variable-name">my_tty</span>;
|
|
<span class="org-keyword">const</span> <span class="org-keyword">struct</span> <span class="org-type">tty_operations</span> *<span class="org-variable-name">ttyops</span>;
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * tty struct went into signal struct in 2.6.6</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#if</span> ( LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,5) )
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * The tty for the current task</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
my_tty = current->tty;
|
|
<span class="org-preprocessor">#else</span>
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * The tty for the current task, for 2.6.6+ kernels</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
my_tty = get_current_tty();
|
|
<span class="org-preprocessor">#endif</span>
|
|
ttyops = my_tty->driver->ops;
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * If my_tty is NULL, the current task has no tty you can print to</span>
|
|
<span class="org-comment"> * (ie, if it's a daemon). If so, there's nothing we can do.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">if</span> (my_tty != <span class="org-constant">NULL</span>) {
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * my_tty->driver is a struct which holds the tty's functions,</span>
|
|
<span class="org-comment"> * one of which (write) is used to write strings to the tty.</span>
|
|
<span class="org-comment"> * It can be used to take a string either from the user's or</span>
|
|
<span class="org-comment"> * kernel's memory segment.</span>
|
|
<span class="org-comment"> *</span>
|
|
<span class="org-comment"> * The function's 1st parameter is the tty to write to,</span>
|
|
<span class="org-comment"> * because the same function would normally be used for all</span>
|
|
<span class="org-comment"> * tty's of a certain type. The 2nd parameter controls</span>
|
|
<span class="org-comment"> * whether the function receives a string from kernel</span>
|
|
<span class="org-comment"> * memory (false, 0) or from user memory (true, non zero).</span>
|
|
<span class="org-comment"> * BTW: this param has been removed in Kernels > 2.6.9</span>
|
|
<span class="org-comment"> * The (2nd) 3rd parameter is a pointer to a string.</span>
|
|
<span class="org-comment"> * The (3rd) 4th parameter is the length of the string.</span>
|
|
<span class="org-comment"> *</span>
|
|
<span class="org-comment"> * As you will see below, sometimes it's necessary to use</span>
|
|
<span class="org-comment"> * preprocessor stuff to create code that works for different</span>
|
|
<span class="org-comment"> * kernel versions. The (naive) approach we've taken here</span>
|
|
<span class="org-comment"> * does not scale well. The right way to deal with this</span>
|
|
<span class="org-comment"> * is described in section 2 of</span>
|
|
<span class="org-comment"> * linux/Documentation/SubmittingPatches</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
(ttyops->write) (my_tty, <span class="org-comment-delimiter">/* </span><span class="org-comment">The tty itself </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#if</span> ( LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,9) )
|
|
0, <span class="org-comment-delimiter">/* </span><span class="org-comment">Don't take the string</span>
|
|
<span class="org-comment"> from user space </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#endif</span>
|
|
str, <span class="org-comment-delimiter">/* </span><span class="org-comment">String </span><span class="org-comment-delimiter">*/</span>
|
|
strlen(str)); <span class="org-comment-delimiter">/* </span><span class="org-comment">Length </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * ttys were originally hardware devices, which (usually)</span>
|
|
<span class="org-comment"> * strictly followed the ASCII standard. In ASCII, to move to</span>
|
|
<span class="org-comment"> * a new line you need two characters, a carriage return and a</span>
|
|
<span class="org-comment"> * line feed. On Unix, the ASCII line feed is used for both</span>
|
|
<span class="org-comment"> * purposes - so we can't just use \n, because it wouldn't have</span>
|
|
<span class="org-comment"> * a carriage return and the next line will start at the</span>
|
|
<span class="org-comment"> * column right after the line feed.</span>
|
|
<span class="org-comment"> *</span>
|
|
<span class="org-comment"> * This is why text files are different between Unix and</span>
|
|
<span class="org-comment"> * MS Windows. In CP/M and derivatives, like MS-DOS and</span>
|
|
<span class="org-comment"> * MS Windows, the ASCII standard was strictly adhered to,</span>
|
|
<span class="org-comment"> * and therefore a newline requirs both a LF and a CR.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-preprocessor">#if</span> ( LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,9) )
|
|
(ttyops->write) (my_tty, 0, <span class="org-string">"\015\012"</span>, 2);
|
|
<span class="org-preprocessor">#else</span>
|
|
(ttyops->write) (my_tty, <span class="org-string">"\015\012"</span>, 2);
|
|
<span class="org-preprocessor">#endif</span>
|
|
}
|
|
}
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-function-name">__init</span> print_string_init(<span class="org-type">void</span>)
|
|
{
|
|
print_string(<span class="org-string">"The module has been inserted. Hello world!"</span>);
|
|
<span class="org-keyword">return</span> 0;
|
|
}
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">void</span> <span class="org-function-name">__exit</span> print_string_exit(<span class="org-type">void</span>)
|
|
{
|
|
print_string(<span class="org-string">"The module has been removed. Farewell world!"</span>);
|
|
}
|
|
|
|
module_init(print_string_init);
|
|
module_exit(print_string_exit);
|
|
</code></pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-org69a98da" class="outline-3">
|
|
<h3 id="org69a98da">Flashing keyboard LEDs</h3>
|
|
<div class="outline-text-3" id="text-org69a98da">
|
|
<p>
|
|
In certain conditions, you may desire a simpler and more direct way to communicate to the external world. Flashing keyboard LEDs can be such a solution: It is an immediate way to attract attention or to display a status condition. Keyboard LEDs are present on every hardware, they are always visible, they do not need any setup, and their use is rather simple and non-intrusive, compared to writing to a tty or a file.
|
|
</p>
|
|
|
|
<p>
|
|
The following source code illustrates a minimal kernel module which, when loaded, starts blinking the keyboard LEDs until it is unloaded.
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-c"><span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * kbleds.c - Blink keyboard leds until the module is unloaded.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/module.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/init.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/vt_kern.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">for fg_console </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/tty.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">For fg_console, MAX_NR_CONSOLES </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/kd.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">For KDSETLED </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/vt.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/console_struct.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">For vc_cons </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
MODULE_DESCRIPTION(<span class="org-string">"Example module illustrating the use of Keyboard LEDs."</span>);
|
|
MODULE_AUTHOR(<span class="org-string">"Daniele Paolo Scarpazza"</span>);
|
|
MODULE_LICENSE(<span class="org-string">"GPL"</span>);
|
|
|
|
<span class="org-keyword">struct</span> <span class="org-type">timer_list</span> <span class="org-variable-name">my_timer</span>;
|
|
<span class="org-keyword">struct</span> <span class="org-type">tty_driver</span> *<span class="org-variable-name">my_driver</span>;
|
|
<span class="org-type">char</span> <span class="org-variable-name">kbledstatus</span> = 0;
|
|
|
|
<span class="org-preprocessor">#define</span> <span class="org-variable-name">BLINK_DELAY</span> HZ/5
|
|
<span class="org-preprocessor">#define</span> <span class="org-variable-name">ALL_LEDS_ON</span> 0x07
|
|
<span class="org-preprocessor">#define</span> <span class="org-variable-name">RESTORE_LEDS</span> 0xFF
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Function my_timer_func blinks the keyboard LEDs periodically by invoking</span>
|
|
<span class="org-comment"> * command KDSETLED of ioctl() on the keyboard driver. To learn more on virtual</span>
|
|
<span class="org-comment"> * terminal ioctl operations, please see file:</span>
|
|
<span class="org-comment"> * /usr/src/linux/drivers/char/vt_ioctl.c, function vt_ioctl().</span>
|
|
<span class="org-comment"> *</span>
|
|
<span class="org-comment"> * The argument to KDSETLED is alternatively set to 7 (thus causing the led</span>
|
|
<span class="org-comment"> * mode to be set to LED_SHOW_IOCTL, and all the leds are lit) and to 0xFF</span>
|
|
<span class="org-comment"> * (any value above 7 switches back the led mode to LED_SHOW_FLAGS, thus</span>
|
|
<span class="org-comment"> * the LEDs reflect the actual keyboard status). To learn more on this,</span>
|
|
<span class="org-comment"> * please see file:</span>
|
|
<span class="org-comment"> * /usr/src/linux/drivers/char/keyboard.c, function setledstate().</span>
|
|
<span class="org-comment"> *</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">void</span> <span class="org-function-name">my_timer_func</span>(<span class="org-type">unsigned</span> <span class="org-type">long</span> <span class="org-variable-name">ptr</span>)
|
|
{
|
|
<span class="org-type">unsigned</span> <span class="org-type">long</span> *<span class="org-variable-name">pstatus</span> = (<span class="org-type">unsigned</span> <span class="org-type">long</span> *)ptr;
|
|
<span class="org-keyword">struct</span> <span class="org-type">tty_struct</span>* <span class="org-variable-name">t</span> = vc_cons[fg_console].d->port.tty;
|
|
|
|
<span class="org-keyword">if</span> (*pstatus == ALL_LEDS_ON)
|
|
*pstatus = RESTORE_LEDS;
|
|
<span class="org-keyword">else</span>
|
|
*pstatus = ALL_LEDS_ON;
|
|
|
|
(my_driver->ops->ioctl) (t, KDSETLED, *pstatus);
|
|
|
|
my_timer.expires = jiffies + BLINK_DELAY;
|
|
add_timer(&my_timer);
|
|
}
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-function-name">__init</span> kbleds_init(<span class="org-type">void</span>)
|
|
{
|
|
<span class="org-type">int</span> <span class="org-variable-name">i</span>;
|
|
|
|
printk(KERN_INFO <span class="org-string">"kbleds: loading\n"</span>);
|
|
printk(KERN_INFO <span class="org-string">"kbleds: fgconsole is %x\n"</span>, fg_console);
|
|
<span class="org-keyword">for</span> (i = 0; i < MAX_NR_CONSOLES; i++) {
|
|
<span class="org-keyword">if</span> (<span class="org-negation-char">!</span>vc_cons[i].d)
|
|
<span class="org-keyword">break</span>;
|
|
printk(KERN_INFO <span class="org-string">"poet_atkm: console[%i/%i] #%i, tty %lx\n"</span>, i,
|
|
MAX_NR_CONSOLES, vc_cons[i].d->vc_num,
|
|
(<span class="org-type">unsigned</span> <span class="org-type">long</span>)vc_cons[i].d->port.tty);
|
|
}
|
|
printk(KERN_INFO <span class="org-string">"kbleds: finished scanning consoles\n"</span>);
|
|
|
|
my_driver = vc_cons[fg_console].d->port.tty->driver;
|
|
printk(KERN_INFO <span class="org-string">"kbleds: tty driver magic %x\n"</span>, my_driver->magic);
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Set up the LED blink timer the first time</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
init_timer(&my_timer);
|
|
my_timer.function = my_timer_func;
|
|
my_timer.data = (<span class="org-type">unsigned</span> <span class="org-type">long</span>)&kbledstatus;
|
|
my_timer.expires = jiffies + BLINK_DELAY;
|
|
add_timer(&my_timer);
|
|
|
|
<span class="org-keyword">return</span> 0;
|
|
}
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">void</span> <span class="org-function-name">__exit</span> kbleds_cleanup(<span class="org-type">void</span>)
|
|
{
|
|
printk(KERN_INFO <span class="org-string">"kbleds: unloading...\n"</span>);
|
|
del_timer(&my_timer);
|
|
(my_driver->ops->ioctl) (vc_cons[fg_console].d->port.tty,
|
|
KDSETLED, RESTORE_LEDS);
|
|
}
|
|
|
|
module_init(kbleds_init);
|
|
module_exit(kbleds_cleanup);
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
If none of the examples in this chapter fit your debugging needs there might yet be some other tricks to try. Ever wondered what CONFIG_LL_DEBUG in make menuconfig is good for? If you activate that you get low level access to the serial port. While this might not sound very powerful by itself, you can patch kernel/printk.c or any other essential syscall to use printascii, thus makeing it possible to trace virtually everything what your code does over a serial line. If you find yourself porting the kernel to some new and former unsupported architecture this is usually amongst the first things that should be implemented. Logging over a netconsole might also be worth a try.
|
|
</p>
|
|
|
|
<p>
|
|
While you have seen lots of stuff that can be used to aid debugging here, there are some things to be aware of. Debugging is almost always intrusive. Adding debug code can change the situation enough to make the bug seem to dissappear. Thus you should try to keep debug code to a minimum and make sure it does not show up in production code.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-org8a51e67" class="outline-2">
|
|
<h2 id="org8a51e67">Scheduling Tasks</h2>
|
|
<div class="outline-text-2" id="text-org8a51e67">
|
|
<p>
|
|
There are two main ways of running tasks: tasklets and work queues. Tasklets are a quick and easy way of scheduling a single function to be run, for example when triggered from an interrupt, whereas work queues are more complicated but also better suited to running multiple things in a sequence.
|
|
</p>
|
|
</div>
|
|
|
|
<div id="outline-container-org45c08b5" class="outline-3">
|
|
<h3 id="org45c08b5">Tasklets</h3>
|
|
<div class="outline-text-3" id="text-org45c08b5">
|
|
<p>
|
|
Here's an example tasklet module. The <i>tasklet_fn</i> function runs for a few seconds and in the mean time execution of the <i>example_tasklet_init</i> function continues to the exit point.
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-C"><span class="org-preprocessor">#include</span> <span class="org-string"><linux/kernel.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/module.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/delay.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/interrupt.h></span>
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">void</span> <span class="org-function-name">tasklet_fn</span>(<span class="org-type">unsigned</span> <span class="org-type">long</span> <span class="org-variable-name">data</span>)
|
|
{
|
|
printk(<span class="org-string">"Example tasklet starts\n"</span>);
|
|
mdelay(5000);
|
|
printk(<span class="org-string">"Example tasklet ends\n"</span>);
|
|
}
|
|
|
|
DECLARE_TASKLET(mytask, tasklet_fn, 0L);
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-function-name">example_tasklet_init</span>(<span class="org-type">void</span>)
|
|
{
|
|
printk(<span class="org-string">"tasklet example init\n"</span>);
|
|
tasklet_schedule(&mytask);
|
|
mdelay(200);
|
|
printk(<span class="org-string">"Example tasklet init continues...\n"</span>);
|
|
<span class="org-keyword">return</span> 0;
|
|
}
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">void</span> <span class="org-function-name">example_tasklet_exit</span>(<span class="org-type">void</span>)
|
|
{
|
|
printk(<span class="org-string">"tasklet example exit\n"</span>);
|
|
tasklet_kill(&mytask);
|
|
}
|
|
|
|
module_init(example_tasklet_init);
|
|
module_exit(example_tasklet_exit);
|
|
|
|
MODULE_AUTHOR(<span class="org-string">"Bob Mottram"</span>);
|
|
MODULE_DESCRIPTION(<span class="org-string">"Tasklet example"</span>);
|
|
MODULE_LICENSE(<span class="org-string">"GPL"</span>);
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
So with this example loaded <i>dmesg</i> should show:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-bash">tasklet example init
|
|
Example tasklet starts
|
|
Example tasklet init continues...
|
|
Example tasklet ends
|
|
</code></pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div id="outline-container-orgf6456ff" class="outline-3">
|
|
<h3 id="orgf6456ff">Work queues</h3>
|
|
<div class="outline-text-3" id="text-orgf6456ff">
|
|
<p>
|
|
Very often, we have "housekeeping" tasks which have to be done at a certain time, or every so often. If the task is to be done by a process, we do it by putting it in the crontab file. If the task is to be done by a kernel module, we have two possibilities. The first is to put a process in the crontab file which will wake up the module by a system call when necessary, for example by opening a file. This is terribly inefficient, however – we run a new process off of crontab, read a new executable to memory, and all this just to wake up a kernel module which is in memory anyway.
|
|
</p>
|
|
|
|
<p>
|
|
Instead of doing that, we can create a function that will be called once for every timer interrupt. The way we do this is we create a task, held in a workqueue_struct structure, which will hold a pointer to the function. Then, we use queue_delayed_work to put that task on a task list called my_workqueue , which is the list of tasks to be executed on the next timer interrupt. Because we want the function to keep on being executed, we need to put it back on my_workqueue whenever it is called, for the next timer interrupt.
|
|
</p>
|
|
|
|
<p>
|
|
There's one more point we need to remember here. When a module is removed by rmmod, first its reference count is checked. If it is zero, module_cleanup is called. Then, the module is removed from memory with all its functions. Things need to be shut down properly, or bad things will happen. See the code below how this can be done in a safe way.
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-c"><span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * sched.c - schedule a function to be called on every timer interrupt.</span>
|
|
<span class="org-comment"> *</span>
|
|
<span class="org-comment"> * Copyright (C) 2001 by Peter Jay Salzman</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * The necessary header files</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Standard in kernel modules</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/kernel.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">We're doing kernel work </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/module.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">Specifically, a module </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/proc_fs.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">Necessary because we use the proc fs </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/workqueue.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">We schedule tasks here </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/sched.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">We need to put ourselves to sleep</span>
|
|
<span class="org-comment"> and wake up later </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/init.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">For __init and __exit </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/interrupt.h></span> <span class="org-comment-delimiter">/* </span><span class="org-comment">For irqreturn_t </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-keyword">struct</span> <span class="org-type">proc_dir_entry</span> *Our_Proc_File;
|
|
<span class="org-preprocessor">#define</span> <span class="org-variable-name">PROC_ENTRY_FILENAME</span> <span class="org-string">"sched"</span>
|
|
<span class="org-preprocessor">#define</span> <span class="org-variable-name">MY_WORK_QUEUE_NAME</span> <span class="org-string">"WQsched.c"</span>
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * some work_queue related functions</span>
|
|
<span class="org-comment"> * are just available to GPL licensed Modules</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
MODULE_LICENSE(<span class="org-string">"GPL"</span>);
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * The number of times the timer interrupt has been called so far</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-variable-name">TimerIntrpt</span> = 0;
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">void</span> <span class="org-function-name">intrpt_routine</span>(<span class="org-keyword">struct</span> <span class="org-type">work_struct</span> *<span class="org-variable-name">work</span>);
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-variable-name">die</span> = 0; <span class="org-comment-delimiter">/* </span><span class="org-comment">set this to 1 for shutdown </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * The work queue structure for this task, from workqueue.h</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">static</span> <span class="org-keyword">struct</span> <span class="org-type">workqueue_struct</span> *<span class="org-variable-name">my_workqueue</span>;
|
|
|
|
<span class="org-keyword">static</span> <span class="org-keyword">struct</span> <span class="org-type">delayed_work</span> <span class="org-variable-name">Task</span>;
|
|
<span class="org-keyword">static</span> <span class="org-function-name">DECLARE_DELAYED_WORK</span>(Task, intrpt_routine);
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * This function will be called on every timer interrupt. Notice the void*</span>
|
|
<span class="org-comment"> * pointer - task functions can be used for more than one purpose, each time</span>
|
|
<span class="org-comment"> * getting a different parameter.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">static</span> <span class="org-type">void</span> <span class="org-function-name">intrpt_routine</span>(<span class="org-keyword">struct</span> <span class="org-type">work_struct</span> *<span class="org-variable-name">work</span>)
|
|
{
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Increment the counter</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
TimerIntrpt++;
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * If cleanup wants us to die</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">if</span> (die == 0)
|
|
queue_delayed_work(my_workqueue, &Task, 100);
|
|
}
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Put data into the proc fs file.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-type">int</span>
|
|
<span class="org-function-name">procfile_read</span>(<span class="org-type">char</span> *<span class="org-variable-name">buffer</span>,
|
|
<span class="org-type">char</span> **<span class="org-variable-name">buffer_location</span>,
|
|
<span class="org-type">off_t</span> <span class="org-variable-name">offset</span>, <span class="org-type">int</span> <span class="org-variable-name">buffer_length</span>, <span class="org-type">int</span> *<span class="org-variable-name">eof</span>, <span class="org-type">void</span> *<span class="org-variable-name">data</span>)
|
|
{
|
|
<span class="org-type">int</span> <span class="org-variable-name">len</span>; <span class="org-comment-delimiter">/* </span><span class="org-comment">The number of bytes actually used </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * It's static so it will still be in memory</span>
|
|
<span class="org-comment"> * when we leave this function</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">static</span> <span class="org-type">char</span> <span class="org-variable-name">my_buffer</span>[80];
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * We give all of our information in one go, so if anybody asks us</span>
|
|
<span class="org-comment"> * if we have more information the answer should always be no.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">if</span> (offset > 0)
|
|
<span class="org-keyword">return</span> 0;
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Fill the buffer and get its length</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
len = sprintf(my_buffer, <span class="org-string">"Timer called %d times so far\n"</span>, TimerIntrpt);
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Tell the function which called us where the buffer is</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
*buffer_location = my_buffer;
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Return the length</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">return</span> len;
|
|
}
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Initialize the module - register the proc file</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-type">int</span> <span class="org-function-name">__init</span> init_module()
|
|
{
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Create our /proc file</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
Our_Proc_File = proc_create(PROC_ENTRY_FILENAME, 0644, <span class="org-constant">NULL</span>, <span class="org-constant">NULL</span>);
|
|
|
|
<span class="org-keyword">if</span> (Our_Proc_File == <span class="org-constant">NULL</span>) {
|
|
remove_proc_entry(PROC_ENTRY_FILENAME, <span class="org-constant">NULL</span>);
|
|
printk(KERN_ALERT <span class="org-string">"Error: Could not initialize /proc/%s\n"</span>,
|
|
PROC_ENTRY_FILENAME);
|
|
<span class="org-keyword">return</span> -ENOMEM;
|
|
}
|
|
proc_set_size(Our_Proc_File, 80);
|
|
proc_set_user(Our_Proc_File, GLOBAL_ROOT_UID, GLOBAL_ROOT_GID);
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Put the task in the work_timer task queue, so it will be executed at</span>
|
|
<span class="org-comment"> * next timer interrupt</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
my_workqueue = create_workqueue(MY_WORK_QUEUE_NAME);
|
|
queue_delayed_work(my_workqueue, &Task, 100);
|
|
|
|
printk(KERN_INFO <span class="org-string">"/proc/%s created\n"</span>, PROC_ENTRY_FILENAME);
|
|
|
|
<span class="org-keyword">return</span> 0;
|
|
}
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Cleanup</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-type">void</span> <span class="org-function-name">__exit</span> cleanup_module()
|
|
{
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Unregister our /proc file</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
remove_proc_entry(PROC_ENTRY_FILENAME, <span class="org-constant">NULL</span>);
|
|
printk(KERN_INFO <span class="org-string">"/proc/%s removed\n"</span>, PROC_ENTRY_FILENAME);
|
|
|
|
die = 1; <span class="org-comment-delimiter">/* </span><span class="org-comment">keep intrp_routine from queueing itself </span><span class="org-comment-delimiter">*/</span>
|
|
cancel_delayed_work(&Task); <span class="org-comment-delimiter">/* </span><span class="org-comment">no "new ones" </span><span class="org-comment-delimiter">*/</span>
|
|
flush_workqueue(my_workqueue); <span class="org-comment-delimiter">/* </span><span class="org-comment">wait till all "old ones" finished </span><span class="org-comment-delimiter">*/</span>
|
|
destroy_workqueue(my_workqueue);
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * Sleep until intrpt_routine is called one last time. This is</span>
|
|
<span class="org-comment"> * necessary, because otherwise we'll deallocate the memory holding</span>
|
|
<span class="org-comment"> * intrpt_routine and Task while work_timer still references them.</span>
|
|
<span class="org-comment"> * Notice that here we don't allow signals to interrupt us.</span>
|
|
<span class="org-comment"> *</span>
|
|
<span class="org-comment"> * Since WaitQ is now not NULL, this automatically tells the interrupt</span>
|
|
<span class="org-comment"> * routine it's time to die.</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
}
|
|
</code></pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-orgf85c716" class="outline-2">
|
|
<h2 id="orgf85c716">Interrupt Handlers</h2>
|
|
<div class="outline-text-2" id="text-orgf85c716">
|
|
</div>
|
|
<div id="outline-container-org15c7f9a" class="outline-3">
|
|
<h3 id="org15c7f9a">Interrupt Handlers</h3>
|
|
<div class="outline-text-3" id="text-org15c7f9a">
|
|
<p>
|
|
Except for the last chapter, everything we did in the kernel so far we've done as a response to a process asking for it, either by dealing with a special file, sending an ioctl(), or issuing a system call. But the job of the kernel isn't just to respond to process requests. Another job, which is every bit as important, is to speak to the hardware connected to the machine.
|
|
</p>
|
|
|
|
<p>
|
|
There are two types of interaction between the CPU and the rest of the computer's hardware. The first type is when the CPU gives orders to the hardware, the other is when the hardware needs to tell the CPU something. The second, called interrupts, is much harder to implement because it has to be dealt with when convenient for the hardware, not the CPU. Hardware devices typically have a very small amount of RAM, and if you don't read their information when available, it is lost.
|
|
</p>
|
|
|
|
<p>
|
|
Under Linux, hardware interrupts are called IRQ's (Interrupt ReQuests). There are two types of IRQ's, short and long. A short IRQ is one which is expected to take a very short period of time, during which the rest of the machine will be blocked and no other interrupts will be handled. A long IRQ is one which can take longer, and during which other interrupts may occur (but not interrupts from the same device). If at all possible, it's better to declare an interrupt handler to be long.
|
|
</p>
|
|
|
|
<p>
|
|
When the CPU receives an interrupt, it stops whatever it's doing (unless it's processing a more important interrupt, in which case it will deal with this one only when the more important one is done), saves certain parameters on the stack and calls the interrupt handler. This means that certain things are not allowed in the interrupt handler itself, because the system is in an unknown state. The solution to this problem is for the interrupt handler to do what needs to be done immediately, usually read something from the hardware or send something to the hardware, and then schedule the handling of the new information at a later time (this is called the "bottom half") and return. The kernel is then guaranteed to call the bottom half as soon as possible – and when it does, everything allowed in kernel modules will be allowed.
|
|
</p>
|
|
|
|
<p>
|
|
The way to implement this is to call <b>request_irq()</b> to get your interrupt handler called when the relevant IRQ is received.
|
|
</p>
|
|
|
|
<p>
|
|
In practice IRQ handling can be a bit more complex. Hardware is often designed in a way that chains two interrupt controllers, so that all the IRQs from interrupt controller B are cascaded to a certain IRQ from interrupt controller A. Of course that requires that the kernel finds out which IRQ it really was afterwards and that adds overhead. Other architectures offer some special, very low overhead, so called "fast IRQ" or FIQs. To take advantage of them requires handlers to be written in assembler, so they do not really fit into the kernel. They can be made to work similar to the others, but after that procedure, they're no longer any faster than "common" IRQs. SMP enabled kernels running on systems with more than one processor need to solve another truckload of problems. It's not enough to know if a certain IRQs has happend, it's also important for what CPU(s) it was for. People still interested in more details, might want to do a web search for "APIC" now ;)
|
|
</p>
|
|
|
|
<p>
|
|
This function receives the IRQ number, the name of the function, flags, a name for /proc/interrupts and a parameter to pass to the interrupt handler. Usually there is a certain number of IRQs available. How many IRQs there are is hardware-dependent. The flags can include SA_SHIRQ to indicate you're willing to share the IRQ with other interrupt handlers (usually because a number of hardware devices sit on the same IRQ) and SA_INTERRUPT to indicate this is a fast interrupt. This function will only succeed if there isn't already a handler on this IRQ, or if you're both willing to share.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-org4a7f40f" class="outline-3">
|
|
<h3 id="org4a7f40f">Detecting button presses</h3>
|
|
<div class="outline-text-3" id="text-org4a7f40f">
|
|
<p>
|
|
Many popular single board computers, such as Raspberry Pis or Beagleboards, have a bunch of GPIO pins. Attaching buttons to those and then having a button press do something is a classic case in which you might need to use interrupts so that instead of having the CPU waste time and battery power polling for a change in input state it's better for the input to trigger the CPU to then run a particular handling function.
|
|
</p>
|
|
|
|
<p>
|
|
Here's an example where buttons are connected to GPIO numbers 17 and 18 and an LED is connected to GPIO 4. You can change those numbers to whatever is appropriate for your board.
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-c"><span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * intrpt.c - Handling GPIO with interrupts</span>
|
|
<span class="org-comment"> *</span>
|
|
<span class="org-comment"> * Copyright (C) 2017 by Bob Mottram</span>
|
|
<span class="org-comment"> * Based upon the Rpi example by Stefan Wendler (devnull@kaltpost.de)</span>
|
|
<span class="org-comment"> * from:</span>
|
|
<span class="org-comment"> * https://github.com/wendlers/rpi-kmod-samples</span>
|
|
<span class="org-comment"> *</span>
|
|
<span class="org-comment"> * Press one button to turn on a LED and another to turn it off</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/module.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/kernel.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/gpio.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/interrupt.h></span>
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-variable-name">button_irqs</span>[] = { -1, -1 };
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">Define GPIOs for LEDs.</span>
|
|
<span class="org-comment"> Change the numbers for the GPIO on your board. </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">static</span> <span class="org-keyword">struct</span> <span class="org-type">gpio</span> <span class="org-variable-name">leds</span>[] = {
|
|
{ 4, GPIOF_OUT_INIT_LOW, <span class="org-string">"LED 1"</span> }
|
|
};
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">Define GPIOs for BUTTONS</span>
|
|
<span class="org-comment"> Change the numbers for the GPIO on your board. </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">static</span> <span class="org-keyword">struct</span> <span class="org-type">gpio</span> <span class="org-variable-name">buttons</span>[] = {
|
|
{ 17, GPIOF_IN, <span class="org-string">"LED 1 ON BUTTON"</span> },
|
|
{ 18, GPIOF_IN, <span class="org-string">"LED 1 OFF BUTTON"</span> }
|
|
};
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * interrupt function triggered when a button is pressed</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">static</span> <span class="org-type">irqreturn_t</span> <span class="org-function-name">button_isr</span>(<span class="org-type">int</span> <span class="org-variable-name">irq</span>, <span class="org-type">void</span> *<span class="org-variable-name">data</span>)
|
|
{
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">first button </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">if</span> (irq == button_irqs[0] && <span class="org-negation-char">!</span>gpio_get_value(leds[0].gpio))
|
|
gpio_set_value(leds[0].gpio, 1);
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">second button </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">else</span> <span class="org-keyword">if</span>(irq == button_irqs[1] && gpio_get_value(leds[0].gpio))
|
|
gpio_set_value(leds[0].gpio, 0);
|
|
|
|
<span class="org-keyword">return</span> IRQ_HANDLED;
|
|
}
|
|
|
|
<span class="org-type">int</span> <span class="org-function-name">init_module</span>()
|
|
{
|
|
<span class="org-type">int</span> <span class="org-variable-name">ret</span> = 0;
|
|
|
|
printk(KERN_INFO <span class="org-string">"%s\n"</span>, __func__);
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">register LED gpios </span><span class="org-comment-delimiter">*/</span>
|
|
ret = gpio_request_array(leds, ARRAY_SIZE(leds));
|
|
|
|
<span class="org-keyword">if</span> (ret) {
|
|
printk(KERN_ERR <span class="org-string">"Unable to request GPIOs for LEDs: %d\n"</span>, ret);
|
|
<span class="org-keyword">return</span> ret;
|
|
}
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">register BUTTON gpios </span><span class="org-comment-delimiter">*/</span>
|
|
ret = gpio_request_array(buttons, ARRAY_SIZE(buttons));
|
|
|
|
<span class="org-keyword">if</span> (ret) {
|
|
printk(KERN_ERR <span class="org-string">"Unable to request GPIOs for BUTTONs: %d\n"</span>, ret);
|
|
<span class="org-keyword">goto</span> <span class="org-constant">fail1</span>;
|
|
}
|
|
|
|
printk(KERN_INFO <span class="org-string">"Current button1 value: %d\n"</span>,
|
|
gpio_get_value(buttons[0].gpio));
|
|
|
|
ret = gpio_to_irq(buttons[0].gpio);
|
|
|
|
<span class="org-keyword">if</span> (ret < 0) {
|
|
printk(KERN_ERR <span class="org-string">"Unable to request IRQ: %d\n"</span>, ret);
|
|
<span class="org-keyword">goto</span> <span class="org-constant">fail2</span>;
|
|
}
|
|
|
|
button_irqs[0] = ret;
|
|
|
|
printk(KERN_INFO <span class="org-string">"Successfully requested BUTTON1 IRQ # %d\n"</span>,
|
|
button_irqs[0]);
|
|
|
|
ret = request_irq(button_irqs[0], button_isr,
|
|
IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING,
|
|
<span class="org-string">"gpiomod#button1"</span>, <span class="org-constant">NULL</span>);
|
|
|
|
<span class="org-keyword">if</span> (ret) {
|
|
printk(KERN_ERR <span class="org-string">"Unable to request IRQ: %d\n"</span>, ret);
|
|
<span class="org-keyword">goto</span> <span class="org-constant">fail2</span>;
|
|
}
|
|
|
|
|
|
ret = gpio_to_irq(buttons[1].gpio);
|
|
|
|
<span class="org-keyword">if</span> (ret < 0) {
|
|
printk(KERN_ERR <span class="org-string">"Unable to request IRQ: %d\n"</span>, ret);
|
|
<span class="org-keyword">goto</span> <span class="org-constant">fail2</span>;
|
|
}
|
|
|
|
button_irqs[1] = ret;
|
|
|
|
printk(KERN_INFO <span class="org-string">"Successfully requested BUTTON2 IRQ # %d\n"</span>,
|
|
button_irqs[1]);
|
|
|
|
ret = request_irq(button_irqs[1], button_isr,
|
|
IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING,
|
|
<span class="org-string">"gpiomod#button2"</span>, <span class="org-constant">NULL</span>);
|
|
|
|
<span class="org-keyword">if</span> (ret) {
|
|
printk(KERN_ERR <span class="org-string">"Unable to request IRQ: %d\n"</span>, ret);
|
|
<span class="org-keyword">goto</span> <span class="org-constant">fail3</span>;
|
|
}
|
|
|
|
<span class="org-keyword">return</span> 0;
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">cleanup what has been setup so far </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-constant">fail3</span>:
|
|
free_irq(button_irqs[0], <span class="org-constant">NULL</span>);
|
|
|
|
<span class="org-constant">fail2</span>:
|
|
gpio_free_array(buttons, ARRAY_SIZE(leds));
|
|
|
|
<span class="org-constant">fail1</span>:
|
|
gpio_free_array(leds, ARRAY_SIZE(leds));
|
|
|
|
<span class="org-keyword">return</span> ret;
|
|
}
|
|
|
|
<span class="org-type">void</span> <span class="org-function-name">cleanup_module</span>()
|
|
{
|
|
<span class="org-type">int</span> <span class="org-variable-name">i</span>;
|
|
|
|
printk(KERN_INFO <span class="org-string">"%s\n"</span>, __func__);
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">free irqs </span><span class="org-comment-delimiter">*/</span>
|
|
free_irq(button_irqs[0], <span class="org-constant">NULL</span>);
|
|
free_irq(button_irqs[1], <span class="org-constant">NULL</span>);
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">turn all LEDs off </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">for</span> (i = 0; i < ARRAY_SIZE(leds); i++)
|
|
gpio_set_value(leds[i].gpio, 0);
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">unregister </span><span class="org-comment-delimiter">*/</span>
|
|
gpio_free_array(leds, ARRAY_SIZE(leds));
|
|
gpio_free_array(buttons, ARRAY_SIZE(buttons));
|
|
}
|
|
|
|
MODULE_LICENSE(<span class="org-string">"GPL"</span>);
|
|
MODULE_AUTHOR(<span class="org-string">"Bob Mottram"</span>);
|
|
MODULE_DESCRIPTION(<span class="org-string">"Handle some GPIO interrupts"</span>);
|
|
</code></pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-org5c9e9e3" class="outline-3">
|
|
<h3 id="org5c9e9e3">Bottom Half</h3>
|
|
<div class="outline-text-3" id="text-org5c9e9e3">
|
|
<p>
|
|
Suppose you want to do a bunch of stuff inside of an interrupt routine. A common way to do that without rendering the interrupt unavailable for a significant duration is to combine it with a tasklet. This pushes the bulk of the work off into the scheduler.
|
|
</p>
|
|
|
|
<p>
|
|
The example below modifies the previous example to also run an additional task when an interrupt is triggered.
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-C"><span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * bottomhalf.c - Top and bottom half interrupt handling</span>
|
|
<span class="org-comment"> *</span>
|
|
<span class="org-comment"> * Copyright (C) 2017 by Bob Mottram</span>
|
|
<span class="org-comment"> * Based upon the Rpi example by Stefan Wendler (devnull@kaltpost.de)</span>
|
|
<span class="org-comment"> * from:</span>
|
|
<span class="org-comment"> * https://github.com/wendlers/rpi-kmod-samples</span>
|
|
<span class="org-comment"> *</span>
|
|
<span class="org-comment"> * Press one button to turn on a LED and another to turn it off</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/module.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/kernel.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/gpio.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/delay.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/interrupt.h></span>
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-variable-name">button_irqs</span>[] = { -1, -1 };
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">Define GPIOs for LEDs.</span>
|
|
<span class="org-comment"> Change the numbers for the GPIO on your board. </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">static</span> <span class="org-keyword">struct</span> <span class="org-type">gpio</span> <span class="org-variable-name">leds</span>[] = {
|
|
{ 4, GPIOF_OUT_INIT_LOW, <span class="org-string">"LED 1"</span> }
|
|
};
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">Define GPIOs for BUTTONS</span>
|
|
<span class="org-comment"> Change the numbers for the GPIO on your board. </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">static</span> <span class="org-keyword">struct</span> <span class="org-type">gpio</span> <span class="org-variable-name">buttons</span>[] = {
|
|
{ 17, GPIOF_IN, <span class="org-string">"LED 1 ON BUTTON"</span> },
|
|
{ 18, GPIOF_IN, <span class="org-string">"LED 1 OFF BUTTON"</span> }
|
|
};
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">Tasklet containing some non-trivial amount of processing </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">static</span> <span class="org-type">void</span> <span class="org-function-name">bottomhalf_tasklet_fn</span>(<span class="org-type">unsigned</span> <span class="org-type">long</span> <span class="org-variable-name">data</span>)
|
|
{
|
|
printk(<span class="org-string">"Bottom half tasklet starts\n"</span>);
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">do something which takes a while </span><span class="org-comment-delimiter">*/</span>
|
|
mdelay(500);
|
|
printk(<span class="org-string">"Bottom half tasklet ends\n"</span>);
|
|
}
|
|
|
|
DECLARE_TASKLET(buttontask, bottomhalf_tasklet_fn, 0L);
|
|
|
|
<span class="org-comment-delimiter">/*</span>
|
|
<span class="org-comment"> * interrupt function triggered when a button is pressed</span>
|
|
<span class="org-comment"> </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">static</span> <span class="org-type">irqreturn_t</span> <span class="org-function-name">button_isr</span>(<span class="org-type">int</span> <span class="org-variable-name">irq</span>, <span class="org-type">void</span> *<span class="org-variable-name">data</span>)
|
|
{
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">Do something quickly right now </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">if</span> (irq == button_irqs[0] && <span class="org-negation-char">!</span>gpio_get_value(leds[0].gpio))
|
|
gpio_set_value(leds[0].gpio, 1);
|
|
<span class="org-keyword">else</span> <span class="org-keyword">if</span>(irq == button_irqs[1] && gpio_get_value(leds[0].gpio))
|
|
gpio_set_value(leds[0].gpio, 0);
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">Do the rest at leisure via the scheduler </span><span class="org-comment-delimiter">*/</span>
|
|
tasklet_schedule(&buttontask);
|
|
|
|
<span class="org-keyword">return</span> IRQ_HANDLED;
|
|
}
|
|
|
|
<span class="org-type">int</span> <span class="org-function-name">init_module</span>()
|
|
{
|
|
<span class="org-type">int</span> <span class="org-variable-name">ret</span> = 0;
|
|
|
|
printk(KERN_INFO <span class="org-string">"%s\n"</span>, __func__);
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">register LED gpios </span><span class="org-comment-delimiter">*/</span>
|
|
ret = gpio_request_array(leds, ARRAY_SIZE(leds));
|
|
|
|
<span class="org-keyword">if</span> (ret) {
|
|
printk(KERN_ERR <span class="org-string">"Unable to request GPIOs for LEDs: %d\n"</span>, ret);
|
|
<span class="org-keyword">return</span> ret;
|
|
}
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">register BUTTON gpios </span><span class="org-comment-delimiter">*/</span>
|
|
ret = gpio_request_array(buttons, ARRAY_SIZE(buttons));
|
|
|
|
<span class="org-keyword">if</span> (ret) {
|
|
printk(KERN_ERR <span class="org-string">"Unable to request GPIOs for BUTTONs: %d\n"</span>, ret);
|
|
<span class="org-keyword">goto</span> <span class="org-constant">fail1</span>;
|
|
}
|
|
|
|
printk(KERN_INFO <span class="org-string">"Current button1 value: %d\n"</span>,
|
|
gpio_get_value(buttons[0].gpio));
|
|
|
|
ret = gpio_to_irq(buttons[0].gpio);
|
|
|
|
<span class="org-keyword">if</span> (ret < 0) {
|
|
printk(KERN_ERR <span class="org-string">"Unable to request IRQ: %d\n"</span>, ret);
|
|
<span class="org-keyword">goto</span> <span class="org-constant">fail2</span>;
|
|
}
|
|
|
|
button_irqs[0] = ret;
|
|
|
|
printk(KERN_INFO <span class="org-string">"Successfully requested BUTTON1 IRQ # %d\n"</span>,
|
|
button_irqs[0]);
|
|
|
|
ret = request_irq(button_irqs[0], button_isr,
|
|
IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING,
|
|
<span class="org-string">"gpiomod#button1"</span>, <span class="org-constant">NULL</span>);
|
|
|
|
<span class="org-keyword">if</span> (ret) {
|
|
printk(KERN_ERR <span class="org-string">"Unable to request IRQ: %d\n"</span>, ret);
|
|
<span class="org-keyword">goto</span> <span class="org-constant">fail2</span>;
|
|
}
|
|
|
|
|
|
ret = gpio_to_irq(buttons[1].gpio);
|
|
|
|
<span class="org-keyword">if</span> (ret < 0) {
|
|
printk(KERN_ERR <span class="org-string">"Unable to request IRQ: %d\n"</span>, ret);
|
|
<span class="org-keyword">goto</span> <span class="org-constant">fail2</span>;
|
|
}
|
|
|
|
button_irqs[1] = ret;
|
|
|
|
printk(KERN_INFO <span class="org-string">"Successfully requested BUTTON2 IRQ # %d\n"</span>,
|
|
button_irqs[1]);
|
|
|
|
ret = request_irq(button_irqs[1], button_isr,
|
|
IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING,
|
|
<span class="org-string">"gpiomod#button2"</span>, <span class="org-constant">NULL</span>);
|
|
|
|
<span class="org-keyword">if</span> (ret) {
|
|
printk(KERN_ERR <span class="org-string">"Unable to request IRQ: %d\n"</span>, ret);
|
|
<span class="org-keyword">goto</span> <span class="org-constant">fail3</span>;
|
|
}
|
|
|
|
<span class="org-keyword">return</span> 0;
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">cleanup what has been setup so far </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-constant">fail3</span>:
|
|
free_irq(button_irqs[0], <span class="org-constant">NULL</span>);
|
|
|
|
<span class="org-constant">fail2</span>:
|
|
gpio_free_array(buttons, ARRAY_SIZE(leds));
|
|
|
|
<span class="org-constant">fail1</span>:
|
|
gpio_free_array(leds, ARRAY_SIZE(leds));
|
|
|
|
<span class="org-keyword">return</span> ret;
|
|
}
|
|
|
|
<span class="org-type">void</span> <span class="org-function-name">cleanup_module</span>()
|
|
{
|
|
<span class="org-type">int</span> <span class="org-variable-name">i</span>;
|
|
|
|
printk(KERN_INFO <span class="org-string">"%s\n"</span>, __func__);
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">free irqs </span><span class="org-comment-delimiter">*/</span>
|
|
free_irq(button_irqs[0], <span class="org-constant">NULL</span>);
|
|
free_irq(button_irqs[1], <span class="org-constant">NULL</span>);
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">turn all LEDs off </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">for</span> (i = 0; i < ARRAY_SIZE(leds); i++)
|
|
gpio_set_value(leds[i].gpio, 0);
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">unregister </span><span class="org-comment-delimiter">*/</span>
|
|
gpio_free_array(leds, ARRAY_SIZE(leds));
|
|
gpio_free_array(buttons, ARRAY_SIZE(buttons));
|
|
}
|
|
|
|
MODULE_LICENSE(<span class="org-string">"GPL"</span>);
|
|
MODULE_AUTHOR(<span class="org-string">"Bob Mottram"</span>);
|
|
MODULE_DESCRIPTION(<span class="org-string">"Interrupt with top and bottom half"</span>);
|
|
</code></pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div id="outline-container-org28f8ac7" class="outline-2">
|
|
<h2 id="org28f8ac7">Crypto</h2>
|
|
<div class="outline-text-2" id="text-org28f8ac7">
|
|
<p>
|
|
At the dawn of the internet everybody trusted everybody completely…but that didn't work out so well. When this guide was originally written it was a more innocent era in which almost nobody actually gave a damn about crypto - least of all kernel developers. That's certainly no longer the case now. To handle crypto stuff the kernel has its own API enabling common methods of encryption, decryption and your favourite hash functions.
|
|
</p>
|
|
</div>
|
|
|
|
<div id="outline-container-org8ef480a" class="outline-3">
|
|
<h3 id="org8ef480a">Hash functions</h3>
|
|
<div class="outline-text-3" id="text-org8ef480a">
|
|
<p>
|
|
Calculating and checking the hashes of things is a common operation. Here is a demonstration of how to calculate a sha256 hash within a kernel module.
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-C"><span class="org-preprocessor">#include</span> <span class="org-string"><linux/module.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><crypto/internal/hash.h></span>
|
|
|
|
<span class="org-preprocessor">#define</span> <span class="org-variable-name">SHA256_LENGTH</span> (256/8)
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">void</span> <span class="org-function-name">show_hash_result</span>(<span class="org-type">char</span> * <span class="org-variable-name">plaintext</span>, <span class="org-type">char</span> * <span class="org-variable-name">hash_sha256</span>)
|
|
{
|
|
<span class="org-type">int</span> <span class="org-variable-name">i</span>;
|
|
<span class="org-type">char</span> <span class="org-variable-name">str</span>[SHA256_LENGTH*2 + 1];
|
|
|
|
printk(<span class="org-string">"sha256 test for string: \"%s\"\n"</span>, plaintext);
|
|
<span class="org-keyword">for</span> (i = 0; i < SHA256_LENGTH ; i++)
|
|
sprintf(&str[i*2],<span class="org-string">"%02x"</span>, (<span class="org-type">unsigned</span> <span class="org-type">char</span>)hash_sha256[i]);
|
|
str[i*2] = 0;
|
|
printk(<span class="org-string">"%s\n"</span>, str);
|
|
}
|
|
|
|
<span class="org-type">int</span> <span class="org-function-name">cryptosha256_init</span>(<span class="org-type">void</span>)
|
|
{
|
|
<span class="org-type">char</span> * <span class="org-variable-name">plaintext</span> = <span class="org-string">"This is a test"</span>;
|
|
<span class="org-type">char</span> <span class="org-variable-name">hash_sha256</span>[SHA256_LENGTH];
|
|
<span class="org-keyword">struct</span> <span class="org-type">crypto_shash</span> *<span class="org-variable-name">sha256</span>;
|
|
<span class="org-keyword">struct</span> <span class="org-type">shash_desc</span> *<span class="org-variable-name">shash</span>;
|
|
|
|
sha256 = crypto_alloc_shash(<span class="org-string">"sha256"</span>, 0, 0);
|
|
<span class="org-keyword">if</span> (IS_ERR(sha256))
|
|
<span class="org-keyword">return</span> -1;
|
|
|
|
shash =
|
|
kmalloc(<span class="org-keyword">sizeof</span>(<span class="org-keyword">struct</span> <span class="org-type">shash_desc</span>) + crypto_shash_descsize(sha256),
|
|
GFP_KERNEL);
|
|
<span class="org-keyword">if</span> (<span class="org-negation-char">!</span>shash)
|
|
<span class="org-keyword">return</span> -ENOMEM;
|
|
|
|
shash->tfm = sha256;
|
|
shash->flags = 0;
|
|
|
|
<span class="org-keyword">if</span> (crypto_shash_init(shash))
|
|
<span class="org-keyword">return</span> -1;
|
|
|
|
<span class="org-keyword">if</span> (crypto_shash_update(shash, plaintext, strlen(plaintext)))
|
|
<span class="org-keyword">return</span> -1;
|
|
|
|
<span class="org-keyword">if</span> (crypto_shash_final(shash, hash_sha256))
|
|
<span class="org-keyword">return</span> -1;
|
|
|
|
kfree(shash);
|
|
crypto_free_shash(sha256);
|
|
|
|
show_hash_result(plaintext, hash_sha256);
|
|
|
|
<span class="org-keyword">return</span> 0;
|
|
}
|
|
|
|
<span class="org-type">void</span> <span class="org-function-name">cryptosha256_exit</span>(<span class="org-type">void</span>)
|
|
{
|
|
}
|
|
|
|
module_init(cryptosha256_init);
|
|
module_exit(cryptosha256_exit);
|
|
|
|
MODULE_AUTHOR(<span class="org-string">"Bob Mottram"</span>);
|
|
MODULE_DESCRIPTION(<span class="org-string">"sha256 hash test"</span>);
|
|
MODULE_LICENSE(<span class="org-string">"GPL"</span>);
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
Make and install the module:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-sh">make
|
|
sudo insmod cryptosha256.ko
|
|
dmesg
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
And you should see that the hash was calculated for the test string.
|
|
</p>
|
|
|
|
<p>
|
|
Finally, remove the test module:
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-sh">sudo rmmod cryptosha256
|
|
</code></pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div id="outline-container-orgdc9f682" class="outline-3">
|
|
<h3 id="orgdc9f682">Symmetric key encryption</h3>
|
|
<div class="outline-text-3" id="text-orgdc9f682">
|
|
<p>
|
|
Here is an example of symmetrically encrypting a string using the AES algorithm and a password.
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-C"><span class="org-preprocessor">#include</span> <span class="org-string"><crypto/internal/skcipher.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/module.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/crypto.h></span>
|
|
|
|
<span class="org-preprocessor">#define</span> <span class="org-variable-name">SYMMETRIC_KEY_LENGTH</span> 32
|
|
<span class="org-preprocessor">#define</span> <span class="org-variable-name">CIPHER_BLOCK_SIZE</span> 16
|
|
|
|
<span class="org-keyword">struct</span> <span class="org-type">tcrypt_result</span> {
|
|
<span class="org-keyword">struct</span> <span class="org-type">completion</span> <span class="org-variable-name">completion</span>;
|
|
<span class="org-type">int</span> <span class="org-variable-name">err</span>;
|
|
};
|
|
|
|
<span class="org-keyword">struct</span> <span class="org-type">skcipher_def</span> {
|
|
<span class="org-keyword">struct</span> <span class="org-type">scatterlist</span> <span class="org-variable-name">sg</span>;
|
|
<span class="org-keyword">struct</span> <span class="org-type">crypto_skcipher</span> * <span class="org-variable-name">tfm</span>;
|
|
<span class="org-keyword">struct</span> <span class="org-type">skcipher_request</span> * <span class="org-variable-name">req</span>;
|
|
<span class="org-keyword">struct</span> <span class="org-type">tcrypt_result</span> <span class="org-variable-name">result</span>;
|
|
<span class="org-type">char</span> * <span class="org-variable-name">scratchpad</span>;
|
|
<span class="org-type">char</span> * <span class="org-variable-name">ciphertext</span>;
|
|
<span class="org-type">char</span> * <span class="org-variable-name">ivdata</span>;
|
|
};
|
|
|
|
<span class="org-keyword">static</span> <span class="org-keyword">struct</span> <span class="org-type">skcipher_def</span> <span class="org-variable-name">sk</span>;
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">void</span> <span class="org-function-name">test_skcipher_finish</span>(<span class="org-keyword">struct</span> <span class="org-type">skcipher_def</span> * <span class="org-variable-name">sk</span>)
|
|
{
|
|
<span class="org-keyword">if</span> (sk->tfm)
|
|
crypto_free_skcipher(sk->tfm);
|
|
<span class="org-keyword">if</span> (sk->req)
|
|
skcipher_request_free(sk->req);
|
|
<span class="org-keyword">if</span> (sk->ivdata)
|
|
kfree(sk->ivdata);
|
|
<span class="org-keyword">if</span> (sk->scratchpad)
|
|
kfree(sk->scratchpad);
|
|
<span class="org-keyword">if</span> (sk->ciphertext)
|
|
kfree(sk->ciphertext);
|
|
}
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-function-name">test_skcipher_result</span>(<span class="org-keyword">struct</span> <span class="org-type">skcipher_def</span> * <span class="org-variable-name">sk</span>, <span class="org-type">int</span> <span class="org-variable-name">rc</span>)
|
|
{
|
|
<span class="org-keyword">switch</span> (rc) {
|
|
<span class="org-keyword">case</span> 0:
|
|
<span class="org-keyword">break</span>;
|
|
<span class="org-keyword">case</span> -EINPROGRESS:
|
|
<span class="org-keyword">case</span> -EBUSY:
|
|
rc = wait_for_completion_interruptible(
|
|
&sk->result.completion);
|
|
<span class="org-keyword">if</span> (<span class="org-negation-char">!</span>rc && <span class="org-negation-char">!</span>sk->result.err) {
|
|
reinit_completion(&sk->result.completion);
|
|
<span class="org-keyword">break</span>;
|
|
}
|
|
<span class="org-keyword">default</span>:
|
|
printk(<span class="org-string">"skcipher encrypt returned with %d result %d\n"</span>,
|
|
rc, sk->result.err);
|
|
<span class="org-keyword">break</span>;
|
|
}
|
|
|
|
init_completion(&sk->result.completion);
|
|
|
|
<span class="org-keyword">return</span> rc;
|
|
}
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">void</span> <span class="org-function-name">test_skcipher_callback</span>(<span class="org-keyword">struct</span> <span class="org-type">crypto_async_request</span> *<span class="org-variable-name">req</span>, <span class="org-type">int</span> <span class="org-variable-name">error</span>)
|
|
{
|
|
<span class="org-keyword">struct</span> <span class="org-type">tcrypt_result</span> *<span class="org-variable-name">result</span> = req->data;
|
|
<span class="org-type">int</span> <span class="org-variable-name">ret</span>;
|
|
|
|
<span class="org-keyword">if</span> (error == -EINPROGRESS)
|
|
<span class="org-keyword">return</span>;
|
|
|
|
result->err = error;
|
|
complete(&result->completion);
|
|
printk(<span class="org-string">"Encryption finished successfully\n"</span>);
|
|
}
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-function-name">test_skcipher_encrypt</span>(<span class="org-type">char</span> * <span class="org-variable-name">plaintext</span>, <span class="org-type">char</span> * <span class="org-variable-name">password</span>,
|
|
<span class="org-keyword">struct</span> <span class="org-type">skcipher_def</span> * <span class="org-variable-name">sk</span>)
|
|
{
|
|
<span class="org-type">int</span> <span class="org-variable-name">ret</span> = -EFAULT;
|
|
<span class="org-type">unsigned</span> <span class="org-type">char</span> <span class="org-variable-name">key</span>[SYMMETRIC_KEY_LENGTH];
|
|
|
|
<span class="org-keyword">if</span> (<span class="org-negation-char">!</span>sk->tfm) {
|
|
sk->tfm = crypto_alloc_skcipher(<span class="org-string">"cbc-aes-aesni"</span>, 0, 0);
|
|
<span class="org-keyword">if</span> (IS_ERR(sk->tfm)) {
|
|
printk(<span class="org-string">"could not allocate skcipher handle\n"</span>);
|
|
<span class="org-keyword">return</span> PTR_ERR(sk->tfm);
|
|
}
|
|
}
|
|
|
|
<span class="org-keyword">if</span> (<span class="org-negation-char">!</span>sk->req) {
|
|
sk->req = skcipher_request_alloc(sk->tfm, GFP_KERNEL);
|
|
<span class="org-keyword">if</span> (<span class="org-negation-char">!</span>sk->req) {
|
|
printk(<span class="org-string">"could not allocate skcipher request\n"</span>);
|
|
ret = -ENOMEM;
|
|
<span class="org-keyword">goto</span> <span class="org-constant">out</span>;
|
|
}
|
|
}
|
|
|
|
skcipher_request_set_callback(sk->req, CRYPTO_TFM_REQ_MAY_BACKLOG,
|
|
test_skcipher_callback,
|
|
&sk->result);
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">clear the key </span><span class="org-comment-delimiter">*/</span>
|
|
memset((<span class="org-type">void</span>*)key,<span class="org-string">'\0'</span>,SYMMETRIC_KEY_LENGTH);
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">Use the world's favourite password </span><span class="org-comment-delimiter">*/</span>
|
|
sprintf((<span class="org-type">char</span>*)key,<span class="org-string">"%s"</span>,password);
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">AES 256 with given symmetric key </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-keyword">if</span> (crypto_skcipher_setkey(sk->tfm, key, SYMMETRIC_KEY_LENGTH)) {
|
|
printk(<span class="org-string">"key could not be set\n"</span>);
|
|
ret = -EAGAIN;
|
|
<span class="org-keyword">goto</span> <span class="org-constant">out</span>;
|
|
}
|
|
printk(<span class="org-string">"Symmetric key: %s\n"</span>, key);
|
|
printk(<span class="org-string">"Plaintext: %s\n"</span>, plaintext);
|
|
|
|
<span class="org-keyword">if</span> (<span class="org-negation-char">!</span>sk->ivdata) {
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">see https://en.wikipedia.org/wiki/Initialization_vector </span><span class="org-comment-delimiter">*/</span>
|
|
sk->ivdata = kmalloc(CIPHER_BLOCK_SIZE, GFP_KERNEL);
|
|
<span class="org-keyword">if</span> (<span class="org-negation-char">!</span>sk->ivdata) {
|
|
printk(<span class="org-string">"could not allocate ivdata\n"</span>);
|
|
<span class="org-keyword">goto</span> <span class="org-constant">out</span>;
|
|
}
|
|
get_random_bytes(sk->ivdata, CIPHER_BLOCK_SIZE);
|
|
}
|
|
|
|
<span class="org-keyword">if</span> (<span class="org-negation-char">!</span>sk->scratchpad) {
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">The text to be encrypted </span><span class="org-comment-delimiter">*/</span>
|
|
sk->scratchpad = kmalloc(CIPHER_BLOCK_SIZE, GFP_KERNEL);
|
|
<span class="org-keyword">if</span> (<span class="org-negation-char">!</span>sk->scratchpad) {
|
|
printk(<span class="org-string">"could not allocate scratchpad\n"</span>);
|
|
<span class="org-keyword">goto</span> <span class="org-constant">out</span>;
|
|
}
|
|
}
|
|
sprintf((<span class="org-type">char</span>*)sk->scratchpad,<span class="org-string">"%s"</span>,plaintext);
|
|
|
|
sg_init_one(&sk->sg, sk->scratchpad, CIPHER_BLOCK_SIZE);
|
|
skcipher_request_set_crypt(sk->req, &sk->sg, &sk->sg,
|
|
CIPHER_BLOCK_SIZE, sk->ivdata);
|
|
init_completion(&sk->result.completion);
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">encrypt data </span><span class="org-comment-delimiter">*/</span>
|
|
ret = crypto_skcipher_encrypt(sk->req);
|
|
ret = test_skcipher_result(sk, ret);
|
|
<span class="org-keyword">if</span> (ret)
|
|
<span class="org-keyword">goto</span> <span class="org-constant">out</span>;
|
|
|
|
printk(<span class="org-string">"Encryption request successful\n"</span>);
|
|
|
|
<span class="org-constant">out</span>:
|
|
<span class="org-keyword">return</span> ret;
|
|
}
|
|
|
|
<span class="org-type">int</span> <span class="org-function-name">cryptoapi_init</span>(<span class="org-type">void</span>)
|
|
{
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">The world's favourite password </span><span class="org-comment-delimiter">*/</span>
|
|
<span class="org-type">char</span> * <span class="org-variable-name">password</span> = <span class="org-string">"password123"</span>;
|
|
|
|
sk.tfm = <span class="org-constant">NULL</span>;
|
|
sk.req = <span class="org-constant">NULL</span>;
|
|
sk.scratchpad = <span class="org-constant">NULL</span>;
|
|
sk.ciphertext = <span class="org-constant">NULL</span>;
|
|
sk.ivdata = <span class="org-constant">NULL</span>;
|
|
|
|
test_skcipher_encrypt(<span class="org-string">"Testing"</span>, password, &sk);
|
|
<span class="org-keyword">return</span> 0;
|
|
}
|
|
|
|
<span class="org-type">void</span> <span class="org-function-name">cryptoapi_exit</span>(<span class="org-type">void</span>)
|
|
{
|
|
test_skcipher_finish(&sk);
|
|
}
|
|
|
|
module_init(cryptoapi_init);
|
|
module_exit(cryptoapi_exit);
|
|
|
|
MODULE_AUTHOR(<span class="org-string">"Bob Mottram"</span>);
|
|
MODULE_DESCRIPTION(<span class="org-string">"Symmetric key encryption example"</span>);
|
|
MODULE_LICENSE(<span class="org-string">"GPL"</span>);
|
|
</code></pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div id="outline-container-orgcca0e8d" class="outline-2">
|
|
<h2 id="orgcca0e8d">Standardising the interfaces: The Device Model</h2>
|
|
<div class="outline-text-2" id="text-orgcca0e8d">
|
|
<p>
|
|
Up to this point we've seen all kinds of modules doing all kinds of things, but there was no consistency in their interfaces with the rest of the kernel. To impose some consistency such that there is at minimum a standardised way to start, suspend and resume a device a device model was added. An example is show below, and you can use this as a template to add your own suspend, resume or other interface functions.
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-C"><span class="org-preprocessor">#include</span> <span class="org-string"><linux/kernel.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/module.h></span>
|
|
<span class="org-preprocessor">#include</span> <span class="org-string"><linux/platform_device.h></span>
|
|
|
|
<span class="org-keyword">struct</span> <span class="org-type">devicemodel_data</span> {
|
|
<span class="org-type">char</span> *<span class="org-variable-name">greeting</span>;
|
|
<span class="org-type">int</span> <span class="org-variable-name">number</span>;
|
|
};
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-function-name">devicemodel_probe</span>(<span class="org-keyword">struct</span> <span class="org-type">platform_device</span> *<span class="org-variable-name">dev</span>)
|
|
{
|
|
<span class="org-keyword">struct</span> <span class="org-type">devicemodel_data</span> *<span class="org-variable-name">pd</span> = (<span class="org-keyword">struct</span> <span class="org-type">devicemodel_data</span> *)(dev->dev.platform_data);
|
|
|
|
printk(<span class="org-string">"devicemodel probe\n"</span>);
|
|
printk(<span class="org-string">"devicemodel greeting: %s; %d\n"</span>, pd->greeting, pd->number);
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">Your device initialisation code </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-keyword">return</span> 0;
|
|
}
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-function-name">devicemodel_remove</span>(<span class="org-keyword">struct</span> <span class="org-type">platform_device</span> *<span class="org-variable-name">dev</span>)
|
|
{
|
|
printk(<span class="org-string">"devicemodel example removed\n"</span>);
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">Your device removal code </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-keyword">return</span> 0;
|
|
}
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-function-name">devicemodel_suspend</span>(<span class="org-keyword">struct</span> <span class="org-type">device</span> *<span class="org-variable-name">dev</span>)
|
|
{
|
|
printk(<span class="org-string">"devicemodel example suspend\n"</span>);
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">Your device suspend code </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-keyword">return</span> 0;
|
|
}
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-function-name">devicemodel_resume</span>(<span class="org-keyword">struct</span> <span class="org-type">device</span> *<span class="org-variable-name">dev</span>)
|
|
{
|
|
printk(<span class="org-string">"devicemodel example resume\n"</span>);
|
|
|
|
<span class="org-comment-delimiter">/* </span><span class="org-comment">Your device resume code </span><span class="org-comment-delimiter">*/</span>
|
|
|
|
<span class="org-keyword">return</span> 0;
|
|
}
|
|
|
|
<span class="org-keyword">static</span> <span class="org-keyword">const</span> <span class="org-keyword">struct</span> <span class="org-type">dev_pm_ops</span> <span class="org-variable-name">devicemodel_pm_ops</span> =
|
|
{
|
|
.suspend = devicemodel_suspend,
|
|
.resume = devicemodel_resume,
|
|
.poweroff = devicemodel_suspend,
|
|
.freeze = devicemodel_suspend,
|
|
.thaw = devicemodel_resume,
|
|
.restore = devicemodel_resume
|
|
};
|
|
|
|
<span class="org-keyword">static</span> <span class="org-keyword">struct</span> <span class="org-type">platform_driver</span> <span class="org-variable-name">devicemodel_driver</span> = {
|
|
.driver = {
|
|
.name = <span class="org-string">"devicemodel_example"</span>,
|
|
.owner = THIS_MODULE,
|
|
.pm = &devicemodel_pm_ops,
|
|
},
|
|
.probe = devicemodel_probe,
|
|
.remove = devicemodel_remove,
|
|
};
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">int</span> <span class="org-function-name">devicemodel_init</span>(<span class="org-type">void</span>)
|
|
{
|
|
<span class="org-type">int</span> <span class="org-variable-name">ret</span>;
|
|
|
|
printk(<span class="org-string">"devicemodel init\n"</span>);
|
|
|
|
ret = platform_driver_register(&devicemodel_driver);
|
|
|
|
<span class="org-keyword">if</span> (ret) {
|
|
printk(KERN_ERR <span class="org-string">"Unable to register driver\n"</span>);
|
|
<span class="org-keyword">return</span> ret;
|
|
}
|
|
|
|
<span class="org-keyword">return</span> 0;
|
|
}
|
|
|
|
<span class="org-keyword">static</span> <span class="org-type">void</span> <span class="org-function-name">devicemodel_exit</span>(<span class="org-type">void</span>)
|
|
{
|
|
printk(<span class="org-string">"devicemodel exit\n"</span>);
|
|
platform_driver_unregister(&devicemodel_driver);
|
|
}
|
|
|
|
MODULE_LICENSE(<span class="org-string">"GPL"</span>);
|
|
MODULE_AUTHOR(<span class="org-string">"Bob Mottram"</span>);
|
|
MODULE_DESCRIPTION(<span class="org-string">"Linux Device Model example"</span>);
|
|
|
|
module_init(devicemodel_init);
|
|
module_exit(devicemodel_exit);
|
|
</code></pre>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div id="outline-container-orga10b71d" class="outline-2">
|
|
<h2 id="orga10b71d">Optimisations</h2>
|
|
<div class="outline-text-2" id="text-orga10b71d">
|
|
</div>
|
|
<div id="outline-container-org25bd5bd" class="outline-3">
|
|
<h3 id="org25bd5bd">Likely and Unlikely conditions</h3>
|
|
<div class="outline-text-3" id="text-org25bd5bd">
|
|
<p>
|
|
Sometimes you might want your code to run as quickly as possible, especially if it's handling an interrupt or doing something which might cause noticible latency. If your code contains boolean conditions and if you know that the conditions are almost always likely to evaluate as either <i>true</i> or <i>false</i>, then you can allow the compiler to optimise for this using the <i>likely</i> and <i>unlikely</i> macros.
|
|
</p>
|
|
|
|
<p>
|
|
For example, when allocating memory you're almost always expecting this to succeed.
|
|
</p>
|
|
|
|
<div class="org-src-container">
|
|
<pre><code class="src src-C">bvl = bvec_alloc(gfp_mask, nr_iovecs, &idx);
|
|
<span class="org-keyword">if</span> (unlikely(<span class="org-negation-char">!</span>bvl)) {
|
|
mempool_free(bio, bio_pool);
|
|
bio = <span class="org-constant">NULL</span>;
|
|
<span class="org-keyword">goto</span> <span class="org-constant">out</span>;
|
|
}
|
|
</code></pre>
|
|
</div>
|
|
|
|
<p>
|
|
When the <i>unlikely</i> macro is used the compiler alters its machine instruction output so that it continues along the false branch and only jumps if the condition is true. That avoids flushing the processor pipeline. The opposite happens if you use the <i>likely</i> macro.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div id="outline-container-orga725d70" class="outline-2">
|
|
<h2 id="orga725d70">Common Pitfalls</h2>
|
|
<div class="outline-text-2" id="text-orga725d70">
|
|
<p>
|
|
Before I send you on your way to go out into the world and write kernel modules, there are a few things I need to warn you about. If I fail to warn you and something bad happens, please report the problem to me for a full refund of the amount I was paid for your copy of the book.
|
|
</p>
|
|
</div>
|
|
|
|
<div id="outline-container-orgfff7611" class="outline-3">
|
|
<h3 id="orgfff7611">Using standard libraries</h3>
|
|
<div class="outline-text-3" id="text-orgfff7611">
|
|
<p>
|
|
You can't do that. In a kernel module you can only use kernel functions, which are the functions you can see in /proc/kallsyms.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-org84bcc80" class="outline-3">
|
|
<h3 id="org84bcc80">Disabling interrupts</h3>
|
|
<div class="outline-text-3" id="text-org84bcc80">
|
|
<p>
|
|
You might need to do this for a short time and that is OK, but if you don't enable them afterwards, your system will be stuck and you'll have to power it off.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-orga55ec24" class="outline-3">
|
|
<h3 id="orga55ec24">Sticking your head inside a large carnivore</h3>
|
|
<div class="outline-text-3" id="text-orga55ec24">
|
|
<p>
|
|
I probably don't have to warn you about this, but I figured I will anyway, just in case.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<div id="outline-container-org93fe4b0" class="outline-2">
|
|
<h2 id="org93fe4b0">Where To Go From Here?</h2>
|
|
<div class="outline-text-2" id="text-org93fe4b0">
|
|
<p>
|
|
I could easily have squeezed a few more chapters into this book. I could have added a chapter about creating new file systems, or about adding new protocol stacks (as if there's a need for that – you'd have to dig underground to find a protocol stack not supported by Linux). I could have added explanations of the kernel mechanisms we haven't touched upon, such as bootstrapping or the disk interface.
|
|
</p>
|
|
|
|
<p>
|
|
However, I chose not to. My purpose in writing this book was to provide initiation into the mysteries of kernel module programming and to teach the common techniques for that purpose. For people seriously interested in kernel programming, I recommend <a href="https://kernelnewbies.org">kernelnewbies.org</a> and the <i>Documentation</i> subdirectory within the kernel source code which isn't always easy to understand but can be a starting point for further investigation. Also, as Linus said, the best way to learn the kernel is to read the source code yourself.
|
|
</p>
|
|
|
|
<p>
|
|
If you're interested in more examples of short kernel modules then searching on sites such as Github and Gitlab is a good way to start, although there is a lot of duplication of older LKMPG examples which may not compile with newer kernel versions. You will also be able to find examples of the use of kernel modules to attack or compromise systems or exfiltrate data and those can be useful for thinking about how to defend systems and learning about existing security mechanisms within the kernel.
|
|
</p>
|
|
|
|
<p>
|
|
I hope I have helped you in your quest to become a better programmer, or at least to have fun through technology. And, if you do write useful kernel modules, I hope you publish them under the GPL, so I can use them too.
|
|
</p>
|
|
|
|
<p>
|
|
If you'd like to contribute to this guide, notice anything glaringly wrong, or just want to add extra sarcastic remarks perhaps involving monkeys or some other kind of animal then please file an issue or even better submit a pull request at <a href="https://github.com/bashrc/LKMPG">https://github.com/bashrc/LKMPG</a>.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
<div id="postamble" class="status">
|
|
|
|
<style type="text/css">
|
|
.back-to-top {
|
|
position: fixed;
|
|
bottom: 2em;
|
|
right: 0px;
|
|
text-decoration: none;
|
|
color: #000000;
|
|
background-color: rgba(235, 235, 235, 0.80);
|
|
font-size: 12px;
|
|
padding: 1em;
|
|
display: none;
|
|
}
|
|
|
|
.back-to-top:hover {
|
|
background-color: rgba(135, 135, 135, 0.50);
|
|
}
|
|
</style>
|
|
|
|
<div class="back-to-top">
|
|
<a href="#top">Back to top</a> | <a href="mailto:bob@freedombone.net">E-mail me</a>
|
|
</div>
|
|
</div>
|
|
</body>
|
|
</html>
|