How to Get Your Change Into the Linux Kernel
or
Care And Operation Of Your Linus Torvalds For a person or company who wishes to submit a change to the Linux
kernel, the process can sometimes be daunting if you're not familiar
with "the system." This text is a collection of suggestions which
can greatly increase the chances of your change being accepted. Read Documentation/SubmitChecklist for a list of items to check
before submitting code. If you are submitting a driver, also read
Documentation/SubmittingDrivers. --------------------------------------------
SECTION 1 - CREATING AND SENDING YOUR CHANGE
-------------------------------------------- 1) "diff -up"
------------ Use "diff -up" or "diff -uprN" to create patches. All changes to the Linux kernel occur in the form of patches, as
generated by diff(1). When creating your patch, make sure to create it
in "unified diff" format, as supplied by the '-u' argument to diff(1).
Also, please use the '-p' argument which shows which C function each
change is in - that makes the resultant diff a lot easier to read.
Patches should be based in the root kernel source directory,
not in any lower subdirectory. To create a patch for a single file, it is often sufficient to do: SRCTREE= linux-2.6
MYFILE= drivers/net/mydriver.c cd $SRCTREE
cp $MYFILE $MYFILE.orig
vi $MYFILE # make your change
cd ..
diff -up $SRCTREE/$MYFILE{.orig,} > /tmp/patch To create a patch for multiple files, you should unpack a "vanilla",
or unmodified kernel source tree, and generate a diff against your
own source tree. For example: MYSRC= /devel/linux-2.6 tar xvfz linux-2.6.12.tar.gz
mv linux-2.6.12 linux-2.6.12-vanilla
diff -uprN -X linux-2.6.12-vanilla/Documentation/dontdiff \
linux-2.6.12-vanilla $MYSRC > /tmp/patch "dontdiff" is a list of files which are generated by the kernel during
the build process, and should be ignored in any diff(1)-generated
patch. The "dontdiff" file is included in the kernel tree in
2.6.12 and later. Make sure your patch does not include any extra files which do not
belong in a patch submission. Make sure to review your patch -after-
generated it with diff(1), to ensure accuracy. If your changes produce a lot of deltas, you may want to look into
splitting them into individual patches which modify things in
logical stages. This will facilitate easier reviewing by other
kernel developers, very important if you want your patch accepted.
There are a number of scripts which can aid in this: Quilt:
http://savannah.nongnu.org/projects/quilt Andrew Morton's patch scripts:
http://userweb.kernel.org/~akpm/stuff/patch-scripts.tar.gz
Instead of these scripts, quilt is the recommended patch management
tool (see above). 2) Describe your changes. Describe the technical detail of the change(s) your patch includes. Be as specific as possible. The WORST descriptions possible include
things like "update driver X", "bug fix for driver X", or "this patch
includes updates for subsystem X. Please apply." The maintainer will thank you if you write your patch description in a
form which can be easily pulled into Linux's source code management
system, git, as a "commit log". See #15, below. If your description starts to get long, that's a sign that you probably
need to split up your patch. See #3, next. When you submit or resubmit a patch or patch series, include the
complete patch description and justification for it. Don't just
say that this is version N of the patch (series). Don't expect the
patch merger to refer back to earlier patch versions or referenced
URLs to find the patch description and put that into the patch.
I.e., the patch (series) and its description should be self-contained.
This benefits both the patch merger(s) and reviewers. Some reviewers
probably didn't even receive earlier versions of the patch. If the patch fixes a logged bug entry, refer to that bug entry by
number and URL. If you want to refer to a specific commit, don't just refer to the
SHA-1 ID of the commit. Please also include the oneline summary of
the commit, to make it easier for reviewers to know what it is about.
Example: Commit e21d2170f36602ae2708 ("video: remove unnecessary
platform_set_drvdata()") removed the unnecessary
platform_set_drvdata(), but left the variable "dev" unused,
delete it. 3) Separate your changes. Separate _logical changes_ into a single patch file. For example, if your changes include both bug fixes and performance
enhancements for a single driver, separate those changes into two
or more patches. If your changes include an API update, and a new
driver which uses that new API, separate those into two patches. On the other hand, if you make a single change to numerous files,
group those changes into a single patch. Thus a single logical change
is contained within a single patch. If one patch depends on another patch in order for a change to be
complete, that is OK. Simply note "this patch depends on patch X"
in your patch description. If you cannot condense your patch set into a smaller set of patches,
then only post say 15 or so at a time(那么一次只发出,比如15个patch)and wait for review and integration. 4) Style check your changes. Check your patch for basic style violations, details of which can be
found in Documentation/CodingStyle. Failure to do so simply wastes
the reviewers time and will get your patch rejected, probably
without even being read. At a minimum you should check your patches with the patch style
checker prior to submission (scripts/checkpatch.pl). You should
be able to justify all violations that remain in your patch. 5) Select e-mail destination. Look through the MAINTAINERS file and the source code, and determine
if your change applies to a specific subsystem of the kernel, with
an assigned maintainer. If so, e-mail that person. The script
scripts/get_maintainer.pl can be very useful at this step. If no maintainer is listed, or the maintainer does not respond, send
your patch to the primary Linux kernel developer's mailing list,
linux-kernel@vger.kernel.org. Most kernel developers monitor this
e-mail list, and can comment on your changes. Do not send more than 15 patches at once to the vger mailing lists!!! Linus Torvalds is the final arbiter of all changes accepted into the
Linux kernel. His e-mail address is <torvalds@linux-foundation.org>.
He gets a lot of e-mail, so typically you should do your best to -avoid-
sending him e-mail. Patches which are bug fixes, are "obvious" changes, or similarly
require little discussion should be sent or CC'd to Linus. Patches
which require discussion or do not have a clear advantage should
usually be sent first to linux-kernel. Only after the patch is
discussed should the patch then be submitted to Linus. 6) Select your CC (e-mail carbon copy) list. Unless you have a reason NOT to do so, CC linux-kernel@vger.kernel.org. Other kernel developers besides Linus need to be aware of your change,
so that they may comment on it and offer code review and suggestions.
linux-kernel is the primary Linux kernel developer mailing list.
Other mailing lists are available for specific subsystems, such as
USB, framebuffer devices, the VFS, the SCSI subsystem, etc. See the
MAINTAINERS file for a mailing list that relates specifically to
your change. Majordomo lists of VGER.KERNEL.ORG at:
<http://vger.kernel.org/vger-lists.html> If changes affect userland-kernel interfaces, please send
the MAN-PAGES maintainer (as listed in the MAINTAINERS file)
a man-pages patch, or at least a notification of the change,
so that some information makes its way into the manual pages. Even if the maintainer did not respond in step #5, make sure to ALWAYS
copy the maintainer when you change their code. For small patches you may want to CC the Trivial Patch Monkey
trivial@kernel.org which collects "trivial" patches. Have a look
into the MAINTAINERS file for its current manager.
Trivial patches must qualify for one of the following rules:
Spelling fixes in documentation
Spelling fixes which could break grep(1)
Warning fixes (cluttering with useless warnings is bad)
Compilation fixes (only if they are actually correct)
Runtime fixes (only if they actually fix things)
Removing use of deprecated functions/macros (eg. check_region)
Contact detail and documentation fixes
Non-portable code replaced by portable code (even in arch-specific,
since people copy, as long as it's trivial)
Any fix by the author/maintainer of the file (ie. patch monkey
in re-transmission mode) 7) No MIME, no links, no compression, no attachments. Just plain text. Linus and other kernel developers need to be able to read and comment
on the changes you are submitting. It is important for a kernel
developer to be able to "quote" your changes, using standard e-mail
tools, so that they may comment on specific portions of your code. For this reason, all patches should be submitting e-mail "inline".
WARNING: Be wary of your editor's word-wrap corrupting your patch,
if you choose to cut-n-paste your patch. Do not attach the patch as a MIME attachment, compressed or not.
Many popular e-mail applications will not always transmit a MIME
attachment as plain text, making it impossible to comment on your
code. A MIME attachment also takes Linus a bit more time to process,
decreasing the likelihood of your MIME-attached change being accepted. Exception: If your mailer is mangling patches then someone may ask
you to re-send them using MIME. See Documentation/email-clients.txt for hints about configuring
your e-mail client so that it sends your patches untouched. 8) E-mail size. When sending patches to Linus, always follow step #7. Large changes are not appropriate for mailing lists, and some
maintainers. If your patch, uncompressed, exceeds 300 kB in size,
it is preferred that you store your patch on an Internet-accessible
server, and provide instead a URL (link) pointing to your patch. 9) Name your kernel version. It is important to note, either in the subject line or in the patch
description, the kernel version to which this patch applies. If the patch does not apply cleanly to the latest kernel version,
Linus will not apply it. 10) Don't get discouraged. Re-submit. After you have submitted your change, be patient and wait. If Linus
likes your change and applies it, it will appear in the next version
of the kernel that he releases. However, if your change doesn't appear in the next version of the
kernel, there could be any number of reasons. It's YOUR job to
narrow down those reasons, correct what was wrong, and submit your
updated change. It is quite common for Linus to "drop" your patch without comment.
That's the nature of the system. If he drops your patch, it could be
due to
* Your patch did not apply cleanly to the latest kernel version.
* Your patch was not sufficiently discussed on linux-kernel.
* A style issue (see section 2).
* An e-mail formatting issue (re-read this section).
* A technical problem with your change.
* He gets tons of e-mail, and yours got lost in the shuffle.
* You are being annoying. When in doubt, solicit comments on linux-kernel mailing list. 11) Include PATCH in the subject Due to high e-mail traffic to Linus, and to linux-kernel, it is common
convention to prefix your subject line with [PATCH]. This lets Linus
and other kernel developers more easily distinguish patches from other
e-mail discussions. 12) Sign your work To improve tracking of who did what, especially with patches that can
percolate to their final resting place in the kernel through several
layers of maintainers, we've introduced a "sign-off" procedure on
patches that are being emailed around. The sign-off is a simple line at the end of the explanation for the
patch, which certifies that you wrote it or otherwise have the right to
pass it on as an open-source patch. The rules are pretty simple: if you
can certify the below: Developer's Certificate of Origin 1.1 By making a contribution to this project, I certify that: (a) The contribution was created in whole or in part by me and I
have the right to submit it under the open source license
indicated in the file; or (b) The contribution is based upon previous work that, to the best
of my knowledge, is covered under an appropriate open source
license and I have the right under that license to submit that
work with modifications, whether created in whole or in part
by me, under the same open source license (unless I am
permitted to submit under a different license), as indicated
in the file; or (c) The contribution was provided directly to me by some other
person who certified (a), (b) or (c) and I have not modified
it. (d) I understand and agree that this project and the contribution
are public and that a record of the contribution (including all
personal information I submit with it, including my sign-off) is
maintained indefinitely and may be redistributed consistent with
this project or the open source license(s) involved. then you just add a line saying Signed-off-by: Random J Developer <random@developer.example.org> using your real name (sorry, no pseudonyms or anonymous contributions.) Some people also put extra tags at the end. They'll just be ignored for
now, but you can do this to mark internal company procedures or just
point out some special detail about the sign-off. If you are a subsystem or branch maintainer, sometimes you need to slightly
modify patches you receive in order to merge them, because the code is not
exactly the same in your tree and the submitters'. If you stick strictly to
rule (c), you should ask the submitter to rediff, but this is a totally
counter-productive waste of time and energy. Rule (b) allows you to adjust
the code, but then it is very impolite to change one submitter's code and
make him endorse your bugs. To solve this problem, it is recommended that
you add a line between the last Signed-off-by header and yours, indicating
the nature of your changes. While there is nothing mandatory about this, it
seems like prepending the description with your mail and/or name, all
enclosed in square brackets, is noticeable enough to make it obvious that
you are responsible for last-minute changes. Example : Signed-off-by: Random J Developer <random@developer.example.org>
[lucky@maintainer.example.org: struct foo moved from foo.c to foo.h]
Signed-off-by: Lucky K Maintainer <lucky@maintainer.example.org> This practise is particularly helpful if you maintain a stable branch and
want at the same time to credit the author, track changes, merge the fix,
and protect the submitter from complaints. Note that under no circumstances
can you change the author's identity (the From header), as it is the one
which appears in the changelog. Special note to back-porters: It seems to be a common and useful practise
to insert an indication of the origin of a patch at the top of the commit
message (just after the subject line) to facilitate tracking. For instance,
here's what we see in 2.6-stable : Date: Tue May 13 19:10:30 2008 +0000 SCSI: libiscsi regression in 2.6.25: fix nop timer handling commit 4cf1043593db6a337f10e006c23c69e5fc93e722 upstream And here's what appears in 2.4 : Date: Tue May 13 22:12:27 2008 +0200 wireless, airo: waitbusy() won't delay [backport of 2.6 commit b7acbdfbd1f277c1eb23f344f899cfa4cd0bf36a] Whatever the format, this information provides a valuable help to people
tracking your trees, and to people trying to trouble-shoot bugs in your
tree. 13) When to use Acked-by: and Cc: The Signed-off-by: tag indicates that the signer was involved in the
development of the patch, or that he/she was in the patch's delivery path. If a person was not directly involved in the preparation or handling of a
patch but wishes to signify and record their approval of it then they can
arrange to have an Acked-by: line added to the patch's changelog. Acked-by: is often used by the maintainer of the affected code when that
maintainer neither contributed to nor forwarded the patch. Acked-by: is not as formal as Signed-off-by:. It is a record that the acker
has at least reviewed the patch and has indicated acceptance. Hence patch
mergers will sometimes manually convert an acker's "yep, looks good to me"
into an Acked-by:. Acked-by: does not necessarily indicate acknowledgement of the entire patch.
For example, if a patch affects multiple subsystems and has an Acked-by: from
one subsystem maintainer then this usually indicates acknowledgement of just
the part which affects that maintainer's code. Judgement should be used here.
When in doubt people should refer to the original discussion in the mailing
list archives. If a person has had the opportunity to comment on a patch, but has not
provided such comments, you may optionally add a "Cc:" tag to the patch.
This is the only tag which might be added without an explicit action by the
person it names. This tag documents that potentially interested parties
have been included in the discussion 14) Using Reported-by:, Tested-by:, Reviewed-by: and Suggested-by: If this patch fixes a problem reported by somebody else, consider adding a
Reported-by: tag to credit the reporter for their contribution. Please
note that this tag should not be added without the reporter's permission,
especially if the problem was not reported in a public forum. That said,
if we diligently credit our bug reporters, they will, hopefully, be
inspired to help us again in the future. A Tested-by: tag indicates that the patch has been successfully tested (in
some environment) by the person named. This tag informs maintainers that
some testing has been performed, provides a means to locate testers for
future patches, and ensures credit for the testers. Reviewed-by:, instead, indicates that the patch has been reviewed and found
acceptable according to the Reviewer's Statement: Reviewer's statement of oversight By offering my Reviewed-by: tag, I state that: (a) I have carried out a technical review of this patch to
evaluate its appropriateness and readiness for inclusion into
the mainline kernel. (b) Any problems, concerns, or questions relating to the patch
have been communicated back to the submitter. I am satisfied
with the submitter's response to my comments. (c) While there may be things that could be improved with this
submission, I believe that it is, at this time, (1) a
worthwhile modification to the kernel, and (2) free of known
issues which would argue against its inclusion. (d) While I have reviewed the patch and believe it to be sound, I
do not (unless explicitly stated elsewhere) make any
warranties or guarantees that it will achieve its stated
purpose or function properly in any given situation. A Reviewed-by tag is a statement of opinion that the patch is an
appropriate modification of the kernel without any remaining serious
technical issues. Any interested reviewer (who has done the work) can
offer a Reviewed-by tag for a patch. This tag serves to give credit to
reviewers and to inform maintainers of the degree of review which has been
done on the patch. Reviewed-by: tags, when supplied by reviewers known to
understand the subject area and to perform thorough reviews, will normally
increase the likelihood of your patch getting into the kernel. A Suggested-by: tag indicates that the patch idea is suggested by the person
named and ensures credit to the person for the idea. Please note that this
tag should not be added without the reporter's permission, especially if the
idea was not posted in a public forum. That said, if we diligently credit our
idea reporters, they will, hopefully, be inspired to help us again in the
future. 15) The canonical patch format The canonical patch subject line is: Subject: [PATCH 001/123] subsystem: summary phrase The canonical patch message body contains the following: - A "from" line specifying the patch author. - An empty line. - The body of the explanation, which will be copied to the
permanent changelog to describe this patch. - The "Signed-off-by:" lines, described above, which will
also go in the changelog. - A marker line containing simply "---". - Any additional comments not suitable for the changelog. - The actual patch (diff output). The Subject line format makes it very easy to sort the emails
alphabetically by subject line - pretty much any email reader will
support that - since because the sequence number is zero-padded,
the numerical and alphabetic sort is the same. The "subsystem" in the email's Subject should identify which
area or subsystem of the kernel is being patched. The "summary phrase" in the email's Subject should concisely
describe the patch which that email contains. The "summary
phrase" should not be a filename. Do not use the same "summary
phrase" for every patch in a whole patch series (where a "patch
series" is an ordered sequence of multiple, related patches). Bear in mind that the "summary phrase" of your email becomes a
globally-unique identifier for that patch. It propagates all the way
into the git changelog. The "summary phrase" may later be used in
developer discussions which refer to the patch. People will want to
google for the "summary phrase" to read discussion regarding that
patch. It will also be the only thing that people may quickly see
when, two or three months later, they are going through perhaps
thousands of patches using tools such as "gitk" or "git log
--oneline". For these reasons, the "summary" must be no more than 70-75
characters, and it must describe both what the patch changes, as well
as why the patch might be necessary. It is challenging to be both
succinct and descriptive, but that is what a well-written summary
should do. The "summary phrase" may be prefixed by tags enclosed in square
brackets: "Subject: [PATCH tag] <summary phrase>". The tags are not
considered part of the summary phrase, but describe how the patch
should be treated. Common tags might include a version descriptor if
the multiple versions of the patch have been sent out in response to
comments (i.e., "v1, v2, v3"), or "RFC" to indicate a request for
comments. If there are four patches in a patch series the individual
patches may be numbered like this: 1/4, 2/4, 3/4, 4/4. This assures
that developers understand the order in which the patches should be
applied and that they have reviewed or applied all of the patches in
the patch series. A couple of example Subjects: Subject: [patch 2/5] ext2: improve scalability of bitmap searching
Subject: [PATCHv2 001/207] x86: fix eflags tracking The "from" line must be the very first line in the message body,
and has the form: From: Original Author <author@example.com> The "from" line specifies who will be credited as the author of the
patch in the permanent changelog. If the "from" line is missing,
then the "From:" line from the email header will be used to determine
the patch author in the changelog. The explanation body will be committed to the permanent source
changelog, so should make sense to a competent reader who has long
since forgotten the immediate details of the discussion that might
have led to this patch. Including symptoms of the failure which the
patch addresses (kernel log messages, oops messages, etc.) is
especially useful for people who might be searching the commit logs
looking for the applicable patch. If a patch fixes a compile failure,
it may not be necessary to include _all_ of the compile failures; just
enough that it is likely that someone searching for the patch can find
it. As in the "summary phrase", it is important to be both succinct as
well as descriptive. The "---" marker line serves the essential purpose of marking for patch
handling tools where the changelog message ends. One good use for the additional comments after the "---" marker is for
a diffstat, to show what files have changed, and the number of
inserted and deleted lines per file. A diffstat is especially useful
on bigger patches. Other comments relevant only to the moment or the
maintainer, not suitable for the permanent changelog, should also go
here. A good example of such comments might be "patch changelogs"
which describe what has changed between the v1 and v2 version of the
patch. If you are going to include a diffstat after the "---" marker, please
use diffstat options "-p 1 -w 70" so that filenames are listed from
the top of the kernel source tree and don't use too much horizontal
space (easily fit in 80 columns, maybe with some indentation). See more details on the proper patch format in the following
references. 16) Sending "git pull" requests (from Linus emails) Please write the git repo address and branch name alone on the same line
so that I can't even by mistake pull from the wrong branch, and so
that a triple-click just selects the whole thing. So the proper format is something along the lines of: "Please pull from git://jdelvare.pck.nerim.net/jdelvare-2.6 i2c-for-linus to get these changes:" so that I don't have to hunt-and-peck for the address and inevitably
get it wrong (actually, I've only gotten it wrong a few times, and
checking against the diffstat tells me when I get it wrong, but I'm
just a lot more comfortable when I don't have to "look for" the right
thing to pull, and double-check that I have the right branch-name). Please use "git diff -M --stat --summary" to generate the diffstat:
the -M enables rename detection, and the summary enables a summary of
new/deleted or renamed files. With rename detection, the statistics are rather different [...]
because git will notice that a fair number of the changes are renames. -----------------------------------
SECTION 2 - HINTS, TIPS, AND TRICKS
----------------------------------- This section lists many of the common "rules" associated with code
submitted to the kernel. There are always exceptions... but you must
have a really good reason for doing so. You could probably call this
section Linus Computer Science 101. 1) Read Documentation/CodingStyle Nuff said. If your code deviates too much from this, it is likely
to be rejected without further review, and without comment. One significant exception is when moving code from one file to
another -- in this case you should not modify the moved code at all in
the same patch which moves it. This clearly delineates the act of
moving the code and your changes. This greatly aids review of the
actual differences and allows tools to better track the history of
the code itself. Check your patches with the patch style checker prior to submission
(scripts/checkpatch.pl). The style checker should be viewed as
a guide not as the final word. If your code looks better with
a violation then its probably best left alone. The checker reports at three levels:
- ERROR: things that are very likely to be wrong
- WARNING: things requiring careful review
- CHECK: things requiring thought You should be able to justify all violations that remain in your
patch. 2) #ifdefs are ugly Code cluttered with ifdefs is difficult to read and maintain. Don't do
it. Instead, put your ifdefs in a header, and conditionally define
'static inline' functions, or macros, which are used in the code.
Let the compiler optimize away the "no-op" case. Simple example, of poor code: dev = alloc_etherdev (sizeof(struct funky_private));
if (!dev)
return -ENODEV;
#ifdef CONFIG_NET_FUNKINESS
init_funky_net(dev);
#endif Cleaned-up example: (in header)
#ifndef CONFIG_NET_FUNKINESS
static inline void init_funky_net (struct net_device *d) {}
#endif (in the code itself)
dev = alloc_etherdev (sizeof(struct funky_private));
if (!dev)
return -ENODEV;
init_funky_net(dev); 3) 'static inline' is better than a macro Static inline functions are greatly preferred over macros.
They provide type safety, have no length limitations, no formatting
limitations, and under gcc they are as cheap as macros. Macros should only be used for cases where a static inline is clearly
suboptimal [there are a few, isolated cases of this in fast paths],
or where it is impossible to use a static inline function [such as
string-izing]. 'static inline' is preferred over 'static __inline__', 'extern inline',
and 'extern __inline__'. 4) Don't over-design. Don't try to anticipate nebulous future cases which may or may not
be useful: "Make it as simple as you can, and no simpler." ----------------------
SECTION 3 - REFERENCES
---------------------- Andrew Morton, "The perfect patch" (tpp).
<http://userweb.kernel.org/~akpm/stuff/tpp.txt> Jeff Garzik, "Linux kernel patch submission format".
<http://linux.yyz.us/patch-format.html> Greg Kroah-Hartman, "How to piss off a kernel subsystem maintainer".
<http://www.kroah.com/log/linux/maintainer.html>
<http://www.kroah.com/log/linux/maintainer-02.html>
<http://www.kroah.com/log/linux/maintainer-03.html>
<http://www.kroah.com/log/linux/maintainer-04.html>
<http://www.kroah.com/log/linux/maintainer-05.html> NO!!!! No more huge patch bombs to linux-kernel@vger.kernel.org people!
<http://marc.theaimsgroup.com/?l=linux-kernel&m=112112749912944&w=2> Kernel Documentation/CodingStyle:
<http://users.sosdg.org/~qiyong/lxr/source/Documentation/CodingStyle> Linus Torvalds's mail on the canonical patch format:
<http://lkml.org/lkml/2005/4/7/183> Andi Kleen, "On submitting kernel patches"
Some strategies to get difficult or controversial changes in.
http://halobates.de/on-submitting-patches.pdf --
Linux Kernel patch submission checklist
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Here are some basic things that developers should do if they want to see their
kernel patch submissions accepted more quickly. These are all above and beyond the documentation that is provided in
Documentation/SubmittingPatches and elsewhere regarding submitting Linux
kernel patches. 1: If you use a facility then #include the file that defines/declares
that facility. Don't depend on other header files pulling in ones
that you use. 2: Builds cleanly with applicable or modified CONFIG options =y, =m, and
=n. No gcc warnings/errors, no linker warnings/errors. 2b: Passes allnoconfig, allmodconfig 2c: Builds successfully when using O=builddir 3: Builds on multiple CPU architectures by using local cross-compile tools
or some other build farm. 4: ppc64 is a good architecture for cross-compilation checking because it
tends to use `unsigned long' for 64-bit quantities. 5: Check your patch for general style as detailed in
Documentation/CodingStyle. Check for trivial violations with the
patch style checker prior to submission (scripts/checkpatch.pl).
You should be able to justify all violations that remain in
your patch. 6: Any new or modified CONFIG options don't muck up the config menu. 7: All new Kconfig options have help text. 8: Has been carefully reviewed with respect to relevant Kconfig
combinations. This is very hard to get right with testing -- brainpower
pays off here. 9: Check cleanly with sparse. 10: Use 'make checkstack' and 'make namespacecheck' and fix any problems
that they find. Note: checkstack does not point out problems explicitly,
but any one function that uses more than 512 bytes on the stack is a
candidate for change. 11: Include kernel-doc to document global kernel APIs. (Not required for
static functions, but OK there also.) Use 'make htmldocs' or 'make
mandocs' to check the kernel-doc and fix any issues. 12: Has been tested with CONFIG_PREEMPT, CONFIG_DEBUG_PREEMPT,
CONFIG_DEBUG_SLAB, CONFIG_DEBUG_PAGEALLOC, CONFIG_DEBUG_MUTEXES,
CONFIG_DEBUG_SPINLOCK, CONFIG_DEBUG_ATOMIC_SLEEP, CONFIG_PROVE_RCU
and CONFIG_DEBUG_OBJECTS_RCU_HEAD all simultaneously enabled. 13: Has been build- and runtime tested with and without CONFIG_SMP and
CONFIG_PREEMPT. 14: If the patch affects IO/Disk, etc: has been tested with and without
CONFIG_LBDAF. 15: All codepaths have been exercised with all lockdep features enabled. 16: All new /proc entries are documented under Documentation/ 17: All new kernel boot parameters are documented in
Documentation/kernel-parameters.txt. 18: All new module parameters are documented with MODULE_PARM_DESC() 19: All new userspace interfaces are documented in Documentation/ABI/.
See Documentation/ABI/README for more information.
Patches that change userspace interfaces should be CCed to
linux-api@vger.kernel.org. 20: Check that it all passes `make headers_check'. 21: Has been checked with injection of at least slab and page-allocation
failures. See Documentation/fault-injection/. If the new code is substantial, addition of subsystem-specific fault
injection might be appropriate. 22: Newly-added code has been compiled with `gcc -W' (use "make
EXTRA_CFLAGS=-W"). This will generate lots of noise, but is good for
finding bugs like "warning: comparison between signed and unsigned". 23: Tested after it has been merged into the -mm patchset to make sure
that it still works with all of the other queued patches and various
changes in the VM, VFS, and other subsystems. 24: All memory barriers {e.g., barrier(), rmb(), wmb()} need a comment in the
source code that explains the logic of what they are doing and why. 25: If any ioctl's are added by the patch, then also update
Documentation/ioctl/ioctl-number.txt. 26: If your modified source code depends on or uses any of the kernel
APIs or features that are related to the following kconfig symbols,
then test multiple builds with the related kconfig symbols disabled
and/or =m (if that option is available) [not all of these at the
same time, just various/random combinations of them]: CONFIG_SMP, CONFIG_SYSFS, CONFIG_PROC_FS, CONFIG_INPUT, CONFIG_PCI,
CONFIG_BLOCK, CONFIG_PM, CONFIG_MAGIC_SYSRQ,
CONFIG_NET, CONFIG_INET=n (but latter with CONFIG_NET=y)
		Linux kernel coding style

This is a short document describing the preferred coding style for the
linux kernel. Coding style is very personal, and I won't _force_ my
views on anybody, but this is what goes for anything that I have to be
able to maintain, and I'd prefer it for most other things too. Please
at least consider the points made here. First off, I'd suggest printing out a copy of the GNU coding standards,
and NOT read it. Burn them, it's a great symbolic gesture. Anyway, here goes: Chapter 1: Indentation Tabs are 8 characters, and thus indentations are also 8 characters.
There are heretic movements that try to make indentations 4 (or even 2!)
characters deep, and that is akin to trying to define the value of PI to
be 3. Rationale: The whole idea behind indentation is to clearly define where
a block of control starts and ends. Especially when you've been looking
at your screen for 20 straight hours, you'll find it a lot easier to see
how the indentation works if you have large indentations. Now, some people will claim that having 8-character indentations makes
the code move too far to the right, and makes it hard to read on a
80-character terminal screen. The answer to that is that if you need
more than 3 levels of indentation, you're screwed anyway, and should fix
your program. In short, 8-char indents make things easier to read, and have the added
benefit of warning you when you're nesting your functions too deep.
Heed that warning. The preferred way to ease multiple indentation levels in a switch statement is
to align the "switch" and its subordinate "case" labels in the same column
instead of "double-indenting" the "case" labels. E.g.: switch (suffix) {
case 'G':
case 'g':
mem <<= 30;
break;
case 'M':
case 'm':
mem <<= 20;
break;
case 'K':
case 'k':
mem <<= 10;
/* fall through */
default:
break;
} Don't put multiple statements on a single line unless you have
something to hide: if (condition) do_this;
do_something_everytime; Don't put multiple assignments on a single line either. Kernel coding style
is super simple. Avoid tricky expressions. Outside of comments, documentation and except in Kconfig, spaces are never
used for indentation, and the above example is deliberately broken. Get a decent editor and don't leave whitespace at the end of lines. Chapter 2: Breaking long lines and strings Coding style is all about readability and maintainability using commonly
available tools. The limit on the length of lines is 80 columns and this is a strongly
preferred limit. Statements longer than 80 columns will be broken into sensible chunks, unless
exceeding 80 columns significantly increases readability and does not hide
information. Descendants are always substantially shorter than the parent and
are placed substantially to the right. The same applies to function headers
with a long argument list. However, never break user-visible strings such as
printk messages, because that breaks the ability to grep for them. Chapter 3: Placing Braces and Spaces The other issue that always comes up in C styling is the placement of
braces. Unlike the indent size, there are few technical reasons to
choose one placement strategy over the other, but the preferred way, as
shown to us by the prophets Kernighan and Ritchie, is to put the opening
brace last on the line, and put the closing brace first, thusly: if (x is true) {
we do y
} This applies to all non-function statement blocks (if, switch, for,
while, do). E.g.: switch (action) {
case KOBJ_ADD:
return "add";
case KOBJ_REMOVE:
return "remove";
case KOBJ_CHANGE:
return "change";
default:
return NULL;
} However, there is one special case, namely functions: they have the
opening brace at the beginning of the next line, thus: int function(int x)
{
body of function
} Heretic people all over the world have claimed that this inconsistency
is ... well ... inconsistent, but all right-thinking people know that
(a) K&R are _right_ and (b) K&R are right. Besides, functions are
special anyway (you can't nest them in C). Note that the closing brace is empty on a line of its own, _except_ in
the cases where it is followed by a continuation of the same statement,
ie a "while" in a do-statement or an "else" in an if-statement, like
this: do {
body of do-loop
} while (condition); and if (x == y) {
..
} else if (x > y) {
...
} else {
....
} Rationale: K&R. Also, note that this brace-placement also minimizes the number of empty
(or almost empty) lines, without any loss of readability. Thus, as the
supply of new-lines on your screen is not a renewable resource (think
25-line terminal screens here), you have more empty lines to put
comments on. Do not unnecessarily use braces where a single statement will do. if (condition)
action(); and if (condition)
do_this();
else
do_that(); This does not apply if only one branch of a conditional statement is a single
statement; in the latter case use braces in both branches: if (condition) {
do_this();
do_that();
} else {
otherwise();
} 3.1: Spaces Linux kernel style for use of spaces depends (mostly) on
function-versus-keyword usage. Use a space after (most) keywords. The
notable exceptions are sizeof, typeof, alignof, and __attribute__, which look
somewhat like functions (and are usually used with parentheses in Linux,
although they are not required in the language, as in: "sizeof info" after
"struct fileinfo info;" is declared). So use a space after these keywords:
if, switch, case, for, do, while
but not with sizeof, typeof, alignof, or __attribute__. E.g.,
s = sizeof(struct file); Do not add spaces around (inside) parenthesized expressions. This example is
*bad*: s = sizeof( struct file ); When declaring pointer data or a function that returns a pointer type, the
preferred use of '*' is adjacent to the data name or function name and not
adjacent to the type name. Examples: char *linux_banner;
unsigned long long memparse(char *ptr, char **retptr);
char *match_strdup(substring_t *s); Use one space around (on each side of) most binary and ternary operators,
such as any of these: = + - < > * / % | & ^ <= >= == != ? : but no space after unary operators:
& * + - ~ ! sizeof typeof alignof __attribute__ defined no space before the postfix increment & decrement unary operators:
++ -- no space after the prefix increment & decrement unary operators:
++ -- and no space around the '.' and "->" structure member operators. Do not leave trailing whitespace at the ends of lines. Some editors with
"smart" indentation will insert whitespace at the beginning of new lines as
appropriate, so you can start typing the next line of code right away.
However, some such editors do not remove the whitespace if you end up not
putting a line of code there, such as if you leave a blank line. As a result,
you end up with lines containing trailing whitespace. Git will warn you about patches that introduce trailing whitespace, and can
optionally strip the trailing whitespace for you; however, if applying a series
of patches, this may make later patches in the series fail by changing their
context lines. Chapter 4: Naming C is a Spartan language, and so should your naming be. Unlike Modula-2
and Pascal programmers, C programmers do not use cute names like
ThisVariableIsATemporaryCounter. A C programmer would call that
variable "tmp", which is much easier to write, and not the least more
difficult to understand. HOWEVER, while mixed-case names are frowned upon, descriptive names for
global variables are a must. To call a global function "foo" is a
shooting offense. GLOBAL variables (to be used only if you _really_ need them) need to
have descriptive names, as do global functions. If you have a function
that counts the number of active users, you should call that
"count_active_users()" or similar, you should _not_ call it "cntusr()". Encoding the type of a function into the name (so-called Hungarian
notation) is brain damaged - the compiler knows the types anyway and can
check those, and it only confuses the programmer. No wonder MicroSoft
makes buggy programs. LOCAL variable names should be short, and to the point. If you have
some random integer loop counter, it should probably be called "i".
Calling it "loop_counter" is non-productive, if there is no chance of it
being mis-understood. Similarly, "tmp" can be just about any type of
variable that is used to hold a temporary value. If you are afraid to mix up your local variable names, you have another
problem, which is called the function-growth-hormone-imbalance syndrome.
See chapter 6 (Functions). Chapter 5: Typedefs Please don't use things like "vps_t". It's a _mistake_ to use typedef for structures and pointers. When you see a vps_t a; in the source, what does it mean? In contrast, if it says struct virtual_container *a; you can actually tell what "a" is. Lots of people think that typedefs "help readability". Not so. They are
useful only for: (a) totally opaque objects (where the typedef is actively used to _hide_
what the object is). Example: "pte_t" etc. opaque objects that you can only access using
the proper accessor functions. NOTE! Opaqueness and "accessor functions" are not good in themselves.
The reason we have them for things like pte_t etc. is that there
really is absolutely _zero_ portably accessible information there. (b) Clear integer types, where the abstraction _helps_ avoid confusion
whether it is "int" or "long". u8/u16/u32 are perfectly fine typedefs, although they fit into
category (d) better than here. NOTE! Again - there needs to be a _reason_ for this. If something is
"unsigned long", then there's no reason to do typedef unsigned long myflags_t; but if there is a clear reason for why it under certain circumstances
might be an "unsigned int" and under other configurations might be
"unsigned long", then by all means go ahead and use a typedef. (c) when you use sparse to literally create a _new_ type for
type-checking. (d) New types which are identical to standard C99 types, in certain
exceptional circumstances. Although it would only take a short amount of time for the eyes and
brain to become accustomed to the standard types like 'uint32_t',
some people object to their use anyway. Therefore, the Linux-specific 'u8/u16/u32/u64' types and their
signed equivalents which are identical to standard types are
permitted -- although they are not mandatory in new code of your
own. When editing existing code which already uses one or the other set
of types, you should conform to the existing choices in that code. (e) Types safe for use in userspace. In certain structures which are visible to userspace, we cannot
require C99 types and cannot use the 'u32' form above. Thus, we
use __u32 and similar types in all structures which are shared
with userspace. Maybe there are other cases too, but the rule should basically be to NEVER
EVER use a typedef unless you can clearly match one of those rules. In general, a pointer, or a struct that has elements that can reasonably
be directly accessed should _never_ be a typedef. Chapter 6: Functions Functions should be short and sweet, and do just one thing. They should
fit on one or two screenfuls of text (the ISO/ANSI screen size is 80x24,
as we all know), and do one thing and do that well. The maximum length of a function is inversely proportional to the
complexity and indentation level of that function. So, if you have a
conceptually simple function that is just one long (but simple)
case-statement, where you have to do lots of small things for a lot of
different cases, it's OK to have a longer function. However, if you have a complex function, and you suspect that a
less-than-gifted first-year high-school student might not even
understand what the function is all about, you should adhere to the
maximum limits all the more closely. Use helper functions with
descriptive names (you can ask the compiler to in-line them if you think
it's performance-critical, and it will probably do a better job of it
than you would have done). Another measure of the function is the number of local variables. They
shouldn't exceed 5-10, or you're doing something wrong. Re-think the
function, and split it into smaller pieces. A human brain can
generally easily keep track of about 7 different things, anything more
and it gets confused. You know you're brilliant, but maybe you'd like
to understand what you did 2 weeks from now. In source files, separate functions with one blank line. If the function is
exported, the EXPORT* macro for it should follow immediately after the closing
function brace line. E.g.: int system_is_up(void)
{
return system_state == SYSTEM_RUNNING;
}
EXPORT_SYMBOL(system_is_up); In function prototypes, include parameter names with their data types.
Although this is not required by the C language, it is preferred in Linux
because it is a simple way to add valuable information for the reader. Chapter 7: Centralized exiting of functions Albeit deprecated by some people, the equivalent of the goto statement is
used frequently by compilers in form of the unconditional jump instruction. The goto statement comes in handy when a function exits from multiple
locations and some common work such as cleanup has to be done. If there is no
cleanup needed then just return directly. The rationale is: - unconditional statements are easier to understand and follow
- nesting is reduced
- errors by not updating individual exit points when making
modifications are prevented
- saves the compiler work to optimize redundant code away ;) int fun(int a)
{
int result = 0;
char *buffer = kmalloc(SIZE); if (buffer == NULL)
return -ENOMEM; if (condition1) {
while (loop1) {
...
}
result = 1;
goto out;
}
...
out:
kfree(buffer);
return result;
} Chapter 8: Commenting Comments are good, but there is also a danger of over-commenting. NEVER
try to explain HOW your code works in a comment: it's much better to
write the code so that the _working_ is obvious, and it's a waste of
time to explain badly written code. Generally, you want your comments to tell WHAT your code does, not HOW.
Also, try to avoid putting comments inside a function body: if the
function is so complex that you need to separately comment parts of it,
you should probably go back to chapter 6 for a while. You can make
small comments to note or warn about something particularly clever (or
ugly), but try to avoid excess. Instead, put the comments at the head
of the function, telling people what it does, and possibly WHY it does
it. When commenting the kernel API functions, please use the kernel-doc format.
See the files Documentation/kernel-doc-nano-HOWTO.txt and scripts/kernel-doc
for details. Linux style for comments is the C89 "/* ... */" style.
Don't use C99-style "// ..." comments. The preferred style for long (multi-line) comments is: /*
* This is the preferred style for multi-line
* comments in the Linux kernel source code.
* Please use it consistently.
*
* Description: A column of asterisks on the left side,
* with beginning and ending almost-blank lines.
*/ For files in net/ and drivers/net/ the preferred style for long (multi-line)
comments is a little different. /* The preferred comment style for files in net/ and drivers/net
* looks like this.
*
* It is nearly the same as the generally preferred comment style,
* but there is no initial almost-blank line.
*/ It's also important to comment data, whether they are basic types or derived
types. To this end, use just one data declaration per line (no commas for
multiple data declarations). This leaves you room for a small comment on each
item, explaining its use. Chapter 9: You've made a mess of it That's OK, we all do. You've probably been told by your long-time Unix
user helper that "GNU emacs" automatically formats the C sources for
you, and you've noticed that yes, it does do that, but the defaults it
uses are less than desirable (in fact, they are worse than random
typing - an infinite number of monkeys typing into GNU emacs would never
make a good program). So, you can either get rid of GNU emacs, or change it to use saner
values. To do the latter, you can stick the following in your .emacs file: (defun c-lineup-arglist-tabs-only (ignored)
"Line up argument lists by tabs, not spaces"
(let* ((anchor (c-langelem-pos c-syntactic-element))
(column (c-langelem-2nd-pos c-syntactic-element))
(offset (- (1+ column) anchor))
(steps (floor offset c-basic-offset)))
(* (max steps 1)
c-basic-offset))) (add-hook 'c-mode-common-hook
(lambda ()
;; Add kernel style
(c-add-style
"linux-tabs-only"
'("linux" (c-offsets-alist
(arglist-cont-nonempty
c-lineup-gcc-asm-reg
c-lineup-arglist-tabs-only)))))) (add-hook 'c-mode-hook
(lambda ()
(let ((filename (buffer-file-name)))
;; Enable kernel mode for the appropriate files
(when (and filename
(string-match (expand-file-name "~/src/linux-trees")
filename))
(setq indent-tabs-mode t)
(c-set-style "linux-tabs-only"))))) This will make emacs go better with the kernel coding style for C
files below ~/src/linux-trees. But even if you fail in getting emacs to do sane formatting, not
everything is lost: use "indent". Now, again, GNU indent has the same brain-dead settings that GNU emacs
has, which is why you need to give it a few command line options.
However, that's not too bad, because even the makers of GNU indent
recognize the authority of K&R (the GNU people aren't evil, they are
just severely misguided in this matter), so you just give indent the
options "-kr -i8" (stands for "K&R, 8 character indents"), or use
"scripts/Lindent", which indents in the latest style. "indent" has a lot of options, and especially when it comes to comment
re-formatting you may want to take a look at the man page. But
remember: "indent" is not a fix for bad programming. Chapter 10: Kconfig configuration files For all of the Kconfig* configuration files throughout the source tree,
the indentation is somewhat different. Lines under a "config" definition
are indented with one tab, while help text is indented an additional two
spaces. Example: config AUDIT
bool "Auditing support"
depends on NET
help
Enable auditing infrastructure that can be used with another
kernel subsystem, such as SELinux (which requires this for
logging of avc messages output). Does not do system-call
auditing without CONFIG_AUDITSYSCALL. Seriously dangerous features (such as write support for certain
filesystems) should advertise this prominently in their prompt string: config ADFS_FS_RW
bool "ADFS write support (DANGEROUS)"
depends on ADFS_FS
... For full documentation on the configuration files, see the file
Documentation/kbuild/kconfig-language.txt. Chapter 11: Data structures Data structures that have visibility outside the single-threaded
environment they are created and destroyed in should always have
reference counts. In the kernel, garbage collection doesn't exist (and
outside the kernel garbage collection is slow and inefficient), which
means that you absolutely _have_ to reference count all your uses. Reference counting means that you can avoid locking, and allows multiple
users to have access to the data structure in parallel - and not having
to worry about the structure suddenly going away from under them just
because they slept or did something else for a while. Note that locking is _not_ a replacement for reference counting.
Locking is used to keep data structures coherent, while reference
counting is a memory management technique. Usually both are needed, and
they are not to be confused with each other. Many data structures can indeed have two levels of reference counting,
when there are users of different "classes". The subclass count counts
the number of subclass users, and decrements the global count just once
when the subclass count goes to zero. Examples of this kind of "multi-level-reference-counting" can be found in
memory management ("struct mm_struct": mm_users and mm_count), and in
filesystem code ("struct super_block": s_count and s_active). Remember: if another thread can find your data structure, and you don't
have a reference count on it, you almost certainly have a bug. Chapter 12: Macros, Enums and RTL Names of macros defining constants and labels in enums are capitalized. #define CONSTANT 0x12345 Enums are preferred when defining several related constants. CAPITALIZED macro names are appreciated but macros resembling functions
may be named in lower case. Generally, inline functions are preferable to macros resembling functions. Macros with multiple statements should be enclosed in a do - while block: #define macrofun(a, b, c) \
do { \
if (a == 5) \
do_this(b, c); \
} while (0) Things to avoid when using macros: 1) macros that affect control flow: #define FOO(x) \
do { \
if (blah(x) < 0) \
return -EBUGGERED; \
} while(0) is a _very_ bad idea. It looks like a function call but exits the "calling"
function; don't break the internal parsers of those who will read the code. 2) macros that depend on having a local variable with a magic name: #define FOO(val) bar(index, val) might look like a good thing, but it's confusing as hell when one reads the
code and it's prone to breakage from seemingly innocent changes. 3) macros with arguments that are used as l-values: FOO(x) = y; will
bite you if somebody e.g. turns FOO into an inline function. 4) forgetting about precedence: macros defining constants using expressions
must enclose the expression in parentheses. Beware of similar issues with
macros using parameters. #define CONSTANT 0x4000
#define CONSTEXP (CONSTANT | 3) The cpp manual deals with macros exhaustively. The gcc internals manual also
covers RTL which is used frequently with assembly language in the kernel. Chapter 13: Printing kernel messages Kernel developers like to be seen as literate. Do mind the spelling
of kernel messages to make a good impression. Do not use crippled
words like "dont"; use "do not" or "don't" instead. Make the messages
concise, clear, and unambiguous. Kernel messages do not have to be terminated with a period. Printing numbers in parentheses (%d) adds no value and should be avoided. There are a number of driver model diagnostic macros in <linux/device.h>
which you should use to make sure messages are matched to the right device
and driver, and are tagged with the right level: dev_err(), dev_warn(),
dev_info(), and so forth. For messages that aren't associated with a
particular device, <linux/printk.h> defines pr_debug() and pr_info(). Coming up with good debugging messages can be quite a challenge; and once
you have them, they can be a huge help for remote troubleshooting. Such
messages should be compiled out when the DEBUG symbol is not defined (that
is, by default they are not included). When you use dev_dbg() or pr_debug(),
that's automatic. Many subsystems have Kconfig options to turn on -DDEBUG.
A related convention uses VERBOSE_DEBUG to add dev_vdbg() messages to the
ones already enabled by DEBUG. Chapter 14: Allocating memory The kernel provides the following general purpose memory allocators:
kmalloc(), kzalloc(), kmalloc_array(), kcalloc(), vmalloc(), and
vzalloc(). Please refer to the API documentation for further information
about them. The preferred form for passing a size of a struct is the following: p = kmalloc(sizeof(*p), ...); The alternative form where struct name is spelled out hurts readability and
introduces an opportunity for a bug when the pointer variable type is changed
but the corresponding sizeof that is passed to a memory allocator is not. Casting the return value which is a void pointer is redundant. The conversion
from void pointer to any other pointer type is guaranteed by the C programming
language. The preferred form for allocating an array is the following: p = kmalloc_array(n, sizeof(...), ...); The preferred form for allocating a zeroed array is the following: p = kcalloc(n, sizeof(...), ...); Both forms check for overflow on the allocation size n * sizeof(...),
and return NULL if that occurred. Chapter 15: The inline disease There appears to be a common misperception that gcc has a magic "make me
faster" speedup option called "inline". While the use of inlines can be
appropriate (for example as a means of replacing macros, see Chapter 12), it
very often is not. Abundant use of the inline keyword leads to a much bigger
kernel, which in turn slows the system as a whole down, due to a bigger
icache footprint for the CPU and simply because there is less memory
available for the pagecache. Just think about it; a pagecache miss causes a
disk seek, which easily takes 5 milliseconds. There are a LOT of cpu cycles
that can go into these 5 milliseconds. A reasonable rule of thumb is to not put inline at functions that have more
than 3 lines of code in them. An exception to this rule are the cases where
a parameter is known to be a compiletime constant, and as a result of this
constantness you *know* the compiler will be able to optimize most of your
function away at compile time. For a good example of this later case, see
the kmalloc() inline function. Often people argue that adding inline to functions that are static and used
only once is always a win since there is no space tradeoff. While this is
technically correct, gcc is capable of inlining these automatically without
help, and the maintenance issue of removing the inline when a second user
appears outweighs the potential value of the hint that tells gcc to do
something it would have done anyway. Chapter 16: Function return values and names Functions can return values of many different kinds, and one of the
most common is a value indicating whether the function succeeded or
failed. Such a value can be represented as an error-code integer
(-Exxx = failure, 0 = success) or a "succeeded" boolean (0 = failure,
non-zero = success). Mixing up these two sorts of representations is a fertile source of
difficult-to-find bugs. If the C language included a strong distinction
between integers and booleans then the compiler would find these mistakes
for us... but it doesn't. To help prevent such bugs, always follow this
convention: If the name of a function is an action or an imperative command,
the function should return an error-code integer. If the name
is a predicate, the function should return a "succeeded" boolean. For example, "add work" is a command, and the add_work() function returns 0
for success or -EBUSY for failure. In the same way, "PCI device present" is
a predicate, and the pci_dev_present() function returns 1 if it succeeds in
finding a matching device or 0 if it doesn't. All EXPORTed functions must respect this convention, and so should all
public functions. Private (static) functions need not, but it is
recommended that they do. Functions whose return value is the actual result of a computation, rather
than an indication of whether the computation succeeded, are not subject to
this rule. Generally they indicate failure by returning some out-of-range
result. Typical examples would be functions that return pointers; they use
NULL or the ERR_PTR mechanism to report failure. Chapter 17: Don't re-invent the kernel macros The header file include/linux/kernel.h contains a number of macros that
you should use, rather than explicitly coding some variant of them yourself.
For example, if you need to calculate the length of an array, take advantage
of the macro #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) Similarly, if you need to calculate the size of some structure member, use #define FIELD_SIZEOF(t, f) (sizeof(((t*)0)->f)) There are also min() and max() macros that do strict type checking if you
need them. Feel free to peruse that header file to see what else is already
defined that you shouldn't reproduce in your code. Chapter 18: Editor modelines and other cruft Some editors can interpret configuration information embedded in source files,
indicated with special markers. For example, emacs interprets lines marked
like this: -*- mode: c -*- Or like this: /*
Local Variables:
compile-command: "gcc -DMAGIC_DEBUG_FLAG foo.c"
End:
*/ Vim interprets markers that look like this: /* vim:set sw=8 noet */ Do not include any of these in source files. People have their own personal
editor configurations, and your source files should not override them. This
includes markers for indentation and mode configuration. People may use their
own custom mode, or may have some other magic method for making indentation
work correctly. Chapter 19: Inline assembly In architecture-specific code, you may need to use inline assembly to interface
with CPU or platform functionality. Don't hesitate to do so when necessary.
However, don't use inline assembly gratuitously when C can do the job. You can
and should poke hardware from C when possible. Consider writing simple helper functions that wrap common bits of inline
assembly, rather than repeatedly writing them with slight variations. Remember
that inline assembly can use C parameters. Large, non-trivial assembly functions should go in .S files, with corresponding
C prototypes defined in C header files. The C prototypes for assembly
functions should use "asmlinkage". You may need to mark your asm statement as volatile, to prevent GCC from
removing it if GCC doesn't notice any side effects. You don't always need to
do so, though, and doing so unnecessarily can limit optimization. When writing a single inline assembly statement containing multiple
instructions, put each instruction on a separate line in a separate quoted
string, and end each string except the last with \n\t to properly indent the
next instruction in the assembly output: asm ("magic %reg1, #42\n\t"
"more_magic %reg2, %reg3"
: /* outputs */ : /* inputs */ : /* clobbers */); Appendix I: References The C Programming Language, Second Edition
by Brian W. Kernighan and Dennis M. Ritchie.
Prentice Hall, Inc., 1988.
ISBN 0-13-110362-8 (paperback), 0-13-110370-9 (hardback).
URL: http://cm.bell-labs.com/cm/cs/cbook/ The Practice of Programming
by Brian W. Kernighan and Rob Pike.
Addison-Wesley, Inc., 1999.
ISBN 0-201-61586-X.
URL: http://cm.bell-labs.com/cm/cs/tpop/ GNU manuals - where in compliance with K&R and this text - for cpp, gcc,
gcc internals and indent, all available from http://www.gnu.org/manual/ WG14 is the international standardization working group for the programming
language C, URL: http://www.open-std.org/JTC1/SC22/WG14/ Kernel CodingStyle, by greg@kroah.com at OLS 2002:
http://www.kroah.com/linux/talks/ols_2002_kernel_codingstyle_talk/html/

SubmittingPatches, SubmitChecklist and CodingStyle的更多相关文章

  1. [转] Linux内核代码风格 CodingStyle [CH]

    from:http://blog.csdn.net/jiang_dlut/article/details/8163731 中文版维护者: 张乐 Zhang Le <r0bertz@gentoo. ...

  2. linux-kernel/CodingStyle

    https://www.kernel.org/doc/Documentation/zh_CN/CodingStyle Chinese translated version of Documentati ...

  3. Linux内核学习之道

    来自:http://blog.chinaunix.net/uid-26258259-id-3783679.html 内核文档 内核代码中包含有大量的文档,这些文档对于学习理解内核有着不可估量的价值,记 ...

  4. 如何切入 Linux 内核源代码

    Makefile不是Make Love 从前在学校,混了四年,没有学到任何东西,每天就是逃课,上网,玩游戏,睡觉.毕业的时候,人家跟我说Makefile我完全不知,但是一说Make Love我就来劲了 ...

  5. Linux内核学习方法

    Makefile不是Make Love 从前在学校,混了四年,没有学到任何东西,每天就是逃课,上网,玩游戏,睡觉.毕业的时候,人家跟我说Makefile我完全不知,但是一说Make Love我就来劲了 ...

  6. LINUX 内核调试基础+编程基础

    http://blog.chinaunix.net/uid-20564848-id-73208.html 内核文档:[root@localhost Documentation]# pwd /usr/s ...

  7. 十天学Linux内核之第十天---总结篇(kconfig和Makefile & 讲不出再见)

    原文:十天学Linux内核之第十天---总结篇(kconfig和Makefile & 讲不出再见) 非常开心能够和大家一起分享这些,让我受益匪浅,感激之情也溢于言表,,code monkey的 ...

  8. 24小时学通Linux内核总结篇(kconfig和Makefile & 讲不出再见)

    非常开心能够和大家一起分享这些,让我受益匪浅,感激之情也溢于言表,,code monkey的话少,没办法煽情了,,,,,,,冬天的风,吹得伤怀,倒叙往事,褪成空白~学校的人越来越少了,就像那年我们小年 ...

  9. Linux内核(5) - 内核学习的相关资源

    “世界上最缺的不是金钱,而是资源.”当我在一份报纸上看到这句大大标题时,我的第一反应是——作者一定是个自然环保主义者,然后我在羞愧得反省自身的同时油然生出一股对这样的无产主义理想者无比崇敬的情绪来. ...

随机推荐

  1. 让Android软键盘默认进入英文键盘

    今天在做一个功能的 时候,需要输入法软键盘弹出后,需要进入英文输入界面. 可以通过设置EditText的输入类型为EMAIL来实现.     //将输入法切换到英文     edit.setInput ...

  2. BZOJ2324 [ZJOI2011]营救皮卡丘 【费用流】

    题目 皮卡丘被火箭队用邪恶的计谋抢走了!这三个坏家伙还给小智留下了赤果果的挑衅!为了皮卡丘,也为了正义,小智和他的朋友们义不容辞的踏上了营救皮卡丘的道路. 火箭队一共有N个据点,据点之间存在M条双向道 ...

  3. django前端渲染多对多关系(比如一本书的作者有哪些)

    自己遇到的问题是,前端渲染不出多对多关系,咨询Yuan后解决,特此记录. urls.py from django.conf.urls import url from book import views ...

  4. 【BZOJ4555】【TJOI2016】【HEOI2016】求和 (第二类斯特林数+NTT卷积)

    Description 在2016年,佳媛姐姐刚刚学习了第二类斯特林数,非常开心. 现在他想计算这样一个函数的值: $$f(n)=\sum_{i=0}^n\sum_{j=0}^i S(i,j)\tim ...

  5. Bzoj3747 [POI1015] Kinoman

    Description 共有m部电影,编号为1~m,第i部电影的好看值为w[i]. 在n天之中(从1~n编号)每天会放映一部电影,第i天放映的是第f[i]部. 你可以选择l,r(1<=l< ...

  6. CAR_TUNE_VALUE 校準

    CAR_TUNE_VALUE 是用來校準 流過電池上的電流 與 系統偵測到的電流 的一致性, 假電 若您是使用假電, 請拔除零件, 僅留下必要元件,如thermal電阻,ID 電阻, 減少量測 fue ...

  7. HDU 2767:Proving Equivalences(强连通)

    题意: 一个有向图,问最少加几条边,能让它强连通 方法: 1:tarjan 缩点 2:采用如下构造法: 缩点后的图找到所有头结点和尾结点,那么,可以这么构造:把所有的尾结点连一条边到头结点,就必然可以 ...

  8. Java通过开启线程池实现多线程

    计算1..100  和1...200 的和,使用线程池开启两个线程 调用Executors类的newFixedThreadPool方法参数是线程池容纳的线程数量 这里是2 返回的对象是 Executo ...

  9. Drupal 有用的模块

    投票模块drigg https://www.drupal.org/project/drigg

  10. 微信小程序 之三元运算符代替wx:if 来解决背景图片显示隐藏

    最近在开发一个小程序项目时,碰到一个问题, 在一个多条件单项选择中,为选中条件添加一个选中状态,选中状态为灰色背景,但是这个背景要用到背景图片 大家都知道在小程序 中wxss是无法读到本地图标资源,只 ...